mirror of
https://github.com/D-Modem/WebOne-go.git
synced 2026-11-28 12:38:05 -08:00
Port WebOne 0.19.0 to Go
A Go translation of WebOne (github.com/atauenis/webone, commit e940b43), the HTTP 1.x proxy that lets old browsers use today's web: config loader with sets of edits and .NET regular expressions, the HTTP/1.0-1.1 server with keep-alive, HTTPS fetching and patching, code pages, the CONNECT proxy (MITM, pass-through, non-HTTP tunnels), the CA and site certificates (MD5/SHA-1 signing included), internal and error pages, Web Archive fallback, converters, web FTP client and online video. WebOne's licence, configuration files and html pages are kept. Go-only options: SslCaDirectory signs with the D-Modem BBS's proxy sub-CA (or its root), SslTrustOwnCA, and DnsServer. README lists the differences: no SSL 2.0/3.0 in Go's TLS, and the upstream bugs fixed on purpose. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B82eRRH4kntyPfrY1bFWC3
This commit is contained in:
271 files changed
+11967
-1
No files matched your search
@@ -0,0 +1,144 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/rx"
|
||||
)
|
||||
|
||||
// activexCabURL emulates Microsoft's ActiveX codebase search server
|
||||
// (activex.microsoft.com/objects/ocget.dll) from [ActiveXGallery]: the URL
|
||||
// of a component by CLSID or MIME type; "" to ask the real service; "404"
|
||||
// when the installed component is up to date (HttpTransit.GetActiveXCabUrl).
|
||||
func (t *transit) activexCabURL() string {
|
||||
var clsid, version, mime, lang string
|
||||
var hasCLSID, hasVer, hasMime bool
|
||||
if cl := t.req.Header.Get("Content-Length"); cl != "" && cl != "0" {
|
||||
data, _ := io.ReadAll(t.req.Body)
|
||||
t.req.Body = bytes.NewReader(data)
|
||||
body := strings.ToUpper(string(data))
|
||||
if g := rx.FindGroups(`CLSID=\{(.*)\}`, body); g != nil {
|
||||
clsid, hasCLSID = g[1], true
|
||||
}
|
||||
if g := rx.FindGroups(`VERSION=(.*)`, body); g != nil {
|
||||
version, hasVer = g[1], true
|
||||
}
|
||||
if g := rx.FindGroups(`MIMETYPE=(.*)`, body); g != nil {
|
||||
mime, hasMime = g[1], true
|
||||
}
|
||||
} else {
|
||||
q := strings.ToUpper("?" + t.url.RawQuery)
|
||||
if g := rx.FindGroups(`CLSID=%7(.*)%7`, q); g != nil {
|
||||
clsid, hasCLSID = g[1], true
|
||||
}
|
||||
if g := rx.FindGroups(`VERSION=(.*)`, q); g != nil {
|
||||
version, hasVer = g[1], true
|
||||
}
|
||||
if g := rx.FindGroups(`MIMETYPE=(.*)`, q); g != nil {
|
||||
mime, hasMime = g[1], true
|
||||
}
|
||||
}
|
||||
if al := t.req.Header.Get("Accept-Language"); al != "" {
|
||||
if g := rx.FindGroups(`[a-zA-Z]*`, al); g != nil {
|
||||
lang = strings.ToUpper(g[0])
|
||||
}
|
||||
}
|
||||
if !hasCLSID && !hasMime {
|
||||
t.dump("--OCGET Emulation: Request not understood, unknown syntax.--")
|
||||
t.log.Printf("OCGET Emulation: missing search terms.")
|
||||
return ""
|
||||
}
|
||||
if hasVer {
|
||||
version = strings.ReplaceAll(version, ",", ".")
|
||||
}
|
||||
db := t.cfg.ActivexGalleryCLSIDs
|
||||
codebase, found := "", false
|
||||
lookup := func(key string) bool {
|
||||
if _, ok := db[key]; !ok {
|
||||
return false
|
||||
}
|
||||
if hasVer {
|
||||
if reported, ok := parseDotVersion(version); ok {
|
||||
if latest, ok := db[key+",LATEST"]; ok {
|
||||
if lv, ok := parseDotVersion(latest); ok && cmpVersion(reported, lv) >= 0 {
|
||||
return true // up to date
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, ok := db[key+","+lang]; ok {
|
||||
key += "," + lang
|
||||
}
|
||||
codebase, found = db[key], true
|
||||
return false
|
||||
}
|
||||
if hasCLSID && lookup(clsid) {
|
||||
return "404"
|
||||
}
|
||||
if hasMime && lookup(mime) {
|
||||
return "404"
|
||||
}
|
||||
|
||||
report := "something"
|
||||
if hasCLSID {
|
||||
report = clsid
|
||||
}
|
||||
if hasMime {
|
||||
report = mime
|
||||
}
|
||||
if hasVer {
|
||||
report += ";version=" + version
|
||||
}
|
||||
if lang != "" {
|
||||
report += ";language=" + lang
|
||||
}
|
||||
if found {
|
||||
t.dump("--OCGET Emulation: " + report + " is " + codebase + ".--")
|
||||
t.log.Printf("OCGET Emulation: found codebase for %s, return 302.", report)
|
||||
return codebase
|
||||
}
|
||||
t.dump("--OCGET Emulation: using real Microsoft service for " + report + ".--")
|
||||
t.log.Printf("OCGET Emulation: no codebase for %s, use real service.", report)
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseDotVersion parses a .NET Version ("1.2", "1.2.3.4").
|
||||
func parseDotVersion(s string) ([]int, bool) {
|
||||
parts := strings.Split(strings.TrimSpace(s), ".")
|
||||
if len(parts) < 2 || len(parts) > 4 {
|
||||
return nil, false
|
||||
}
|
||||
out := make([]int, len(parts))
|
||||
for i, p := range parts {
|
||||
n, err := strconv.Atoi(p)
|
||||
if err != nil || n < 0 {
|
||||
return nil, false
|
||||
}
|
||||
out[i] = n
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
// cmpVersion compares versions as .NET does: a missing part is less than
|
||||
// any number.
|
||||
func cmpVersion(a, b []int) int {
|
||||
for i := 0; i < 4; i++ {
|
||||
x, y := -1, -1
|
||||
if i < len(a) {
|
||||
x = a[i]
|
||||
}
|
||||
if i < len(b) {
|
||||
y = b[i]
|
||||
}
|
||||
if x != y {
|
||||
if x < y {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/logx"
|
||||
"github.com/D-Modem/webone-go/internal/rx"
|
||||
)
|
||||
|
||||
// bufConn is a connection whose first bytes may already sit in a reader.
|
||||
type bufConn struct {
|
||||
net.Conn
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
func (c *bufConn) Read(p []byte) (int, error) { return c.r.Read(p) }
|
||||
|
||||
// connect handles CONNECT host:port (the HTTPS proxy part of
|
||||
// ProcessTransit, with HttpSecureServer, HttpSecurePassthroughServer,
|
||||
// HttpSecureNonHttpServer and HttpSecureNonHttpDecryptServer).
|
||||
func (t *transit) connect() {
|
||||
raw := t.req.RawURL
|
||||
if !strings.Contains(raw, ":") {
|
||||
t.log.Printf(" Invalid CONNECT target: %s", raw)
|
||||
t.sendError(400, "Invalid request. Correct format is <pre>CONNECT example.com:443 HTTP/1.1</pre>")
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case rx.AnyMatches(raw, t.cfg.ConnectPassThrough):
|
||||
t.connectPassThrough()
|
||||
case t.cfg.NonHttpSslDecrypt[raw] != "":
|
||||
t.connectDecrypt(t.cfg.NonHttpSslDecrypt[raw])
|
||||
case strings.HasSuffix(raw, ":443"):
|
||||
t.connectSecure()
|
||||
default:
|
||||
t.connectNonHttp(containsAny(strings.ToLower(raw), t.cfg.NonHttpSslServers))
|
||||
}
|
||||
}
|
||||
|
||||
// established answers "200 Connection established" and gives the
|
||||
// connection over to the tunnel.
|
||||
func (t *transit) established(via bool) net.Conn {
|
||||
w := t.resp
|
||||
w.SetVersion(1, 1)
|
||||
w.Status = 200
|
||||
w.StatusMessage = "Connection established"
|
||||
if via {
|
||||
w.Header.Add("Via", "1.1 WebOne/"+t.cfg.Vars.Value("WOVer"))
|
||||
}
|
||||
w.Header.Set("Connection", "Keep-Alive")
|
||||
w.KeepAlive = true
|
||||
w.SendHeaders(Version)
|
||||
t.hijacked = true
|
||||
return &bufConn{Conn: t.req.conn, r: t.req.br}
|
||||
}
|
||||
|
||||
// onlyHTTPS refuses a tunnel to a port other than 443.
|
||||
func (t *transit) onlyHTTPS() {
|
||||
const msg = "This proxy is performing only HTTP and HTTPS tunneling."
|
||||
t.resp.SetVersion(1, 1)
|
||||
t.resp.KeepAlive = false
|
||||
t.resp.Header.Set("Connection", "Close")
|
||||
t.sendBytes(502, "text/plain", []byte(msg))
|
||||
t.log.Printf("<Not a HTTPS CONNECT, goodbye.")
|
||||
}
|
||||
|
||||
// sslDisabled answers a secure CONNECT when SslEnable is off.
|
||||
func (t *transit) sslDisabled() {
|
||||
t.log.Printf("<Secure CONNECT is disabled.")
|
||||
html := "<HTML><HEAD><TITLE>WebOne: SSL is not supported</TITLE></HEAD>" +
|
||||
"<BODY><P>Incoming HTTPS connections support is disabled on this server.</P>" + t.s.infoString() + "</BODY></HTML>"
|
||||
if b, err := os.ReadFile(filepath.Join(t.cfg.ContentDirectory, "Err-SslDisabled.htm")); err == nil {
|
||||
html = string(b)
|
||||
}
|
||||
t.resp.SetVersion(1, 1)
|
||||
t.sendBytes(501, "text/html", []byte(html))
|
||||
}
|
||||
|
||||
func (t *transit) sslAvailable() bool { return t.cfg.SslEnable && t.s.CA != nil }
|
||||
|
||||
// connectSecure is the HTTPS proxy: the proxy answers TLS with a
|
||||
// certificate for the host and handles the requests inside the tunnel as
|
||||
// any other (HttpSecureServer).
|
||||
func (t *transit) connectSecure() {
|
||||
if !t.sslAvailable() {
|
||||
t.sslDisabled()
|
||||
return
|
||||
}
|
||||
host := t.req.RawURL[:strings.LastIndexByte(t.req.RawURL, ':')]
|
||||
cfg, err := t.s.tlsFor(host)
|
||||
if err != nil {
|
||||
t.log.Printf(" Cannot made SSL connection: %v", err)
|
||||
t.sendError(501, "Sorry, an error occured on creating client SSL tunnel: "+err.Error())
|
||||
return
|
||||
}
|
||||
c := t.established(true)
|
||||
tc := tls.Server(c, cfg)
|
||||
tc.SetDeadline(time.Now().Add(time.Minute))
|
||||
if err := tc.Handshake(); err != nil {
|
||||
t.log.Printf("!SSL Handshake failed: %s", handshakeError(err))
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
tc.SetDeadline(time.Time{})
|
||||
st := tc.ConnectionState()
|
||||
log := logx.New()
|
||||
log.Printf(">SSL %s: %s with %s", host, tls.VersionName(st.Version), tls.CipherSuiteName(st.CipherSuite))
|
||||
t.s.handleConn(tc, bufio.NewReaderSize(tc, 16*1024), true, host, log)
|
||||
tc.Close()
|
||||
log.Printf("<Close SSL.")
|
||||
}
|
||||
|
||||
// handshakeError makes Go's TLS errors say what old clients do wrong.
|
||||
func handshakeError(err error) string {
|
||||
msg := err.Error()
|
||||
if strings.Contains(msg, "unsupported SSLv2 handshake") || strings.Contains(msg, "oversized record") {
|
||||
return msg + " (the client speaks SSL 2.0 or 3.0, which this proxy cannot)"
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
// connectPassThrough connects the client straight to the server
|
||||
// (HttpSecurePassthroughServer).
|
||||
func (t *transit) connectPassThrough() {
|
||||
raw := t.req.RawURL
|
||||
if !strings.HasSuffix(raw, ":443") && !t.cfg.AllowNonHttpsCONNECT {
|
||||
t.onlyHTTPS()
|
||||
return
|
||||
}
|
||||
c := t.established(false)
|
||||
t.log.Printf(">Passthrough: %s", raw)
|
||||
remote, err := t.s.up.dialer.Dial("tcp", raw)
|
||||
if err != nil {
|
||||
t.log.Printf(" PT Connection failed: %v.", err)
|
||||
io.WriteString(c, "The proxy server is unable to connect pass-though: "+err.Error()+"\r\n")
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
t.log.Printf(" PT tunnel established.")
|
||||
pipe(c, remote)
|
||||
t.log.Printf(" PT connection to %s closed.", raw)
|
||||
}
|
||||
|
||||
// connectNonHttp is a tunnel to some other protocol, decrypting the
|
||||
// client's TLS and re-encrypting to the server when useTLS
|
||||
// (HttpSecureNonHttpServer).
|
||||
func (t *transit) connectNonHttp(useTLS bool) {
|
||||
if !t.cfg.AllowNonHttpsCONNECT {
|
||||
t.onlyHTTPS()
|
||||
return
|
||||
}
|
||||
target := t.req.RawURL
|
||||
parts := strings.Split(target, ":")
|
||||
if len(parts) != 2 {
|
||||
t.sendError(400, "Invalid `domain:port` pair supplied for CONNECT method.")
|
||||
return
|
||||
}
|
||||
if _, err := strconv.Atoi(parts[1]); err != nil {
|
||||
t.sendError(400, "Invalid port number supplied for CONNECT method.")
|
||||
return
|
||||
}
|
||||
var cfg *tls.Config
|
||||
if useTLS && t.sslAvailable() {
|
||||
var err error
|
||||
if cfg, err = t.s.tlsFor(parts[0]); err != nil {
|
||||
t.log.Printf(" Cannot made SSL connection: %v", err)
|
||||
t.sendError(501, "Sorry, an error occured on creating client SSL tunnel: "+err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
c := t.established(false)
|
||||
t.log.Printf(">Non-HTTP: %s", target)
|
||||
defer c.Close()
|
||||
if containsAny(target, t.cfg.UrlBlackList) {
|
||||
t.log.Printf(" Blacklisted target, goodbye.")
|
||||
return
|
||||
}
|
||||
if len(t.cfg.UrlWhiteList) > 0 && !containsAny(target, t.cfg.UrlWhiteList) {
|
||||
t.log.Printf(" Non-allowed target, goodbye.")
|
||||
return
|
||||
}
|
||||
for src, dst := range t.cfg.NonHttpConnectRedirect {
|
||||
if strings.Contains(t.req.RawURL, src) {
|
||||
target = dst
|
||||
t.log.Printf(" Redirect connection to %s.", dst)
|
||||
}
|
||||
}
|
||||
if useTLS {
|
||||
if cfg == nil {
|
||||
t.log.Printf("<SSL is disabled, goodbye.")
|
||||
return
|
||||
}
|
||||
tc := tls.Server(c, cfg)
|
||||
if err := tc.Handshake(); err != nil {
|
||||
t.log.Printf("!SSL client handshake failed: %s", handshakeError(err))
|
||||
return
|
||||
}
|
||||
c = tc
|
||||
}
|
||||
remote, err := t.s.up.dialer.Dial("tcp", target)
|
||||
if err == nil && useTLS {
|
||||
rc := tls.Client(remote, t.upstreamTLS(parts[0]))
|
||||
if err = rc.Handshake(); err != nil {
|
||||
remote.Close()
|
||||
}
|
||||
remote = rc
|
||||
}
|
||||
if err != nil {
|
||||
t.log.Printf(" Connection failed: %v.", err)
|
||||
io.WriteString(c, "The proxy server is unable to connect: "+err.Error()+"\r\n")
|
||||
return
|
||||
}
|
||||
if useTLS {
|
||||
t.log.Printf(" Secure tunnel established.")
|
||||
} else {
|
||||
t.log.Printf(" Tunnel established.")
|
||||
}
|
||||
pipe(c, remote)
|
||||
t.log.Printf(" Connection to %s closed.", t.req.RawURL)
|
||||
}
|
||||
|
||||
// connectDecrypt is a plain tunnel from the client that the proxy
|
||||
// encrypts toward the server (HttpSecureNonHttpDecryptServer).
|
||||
func (t *transit) connectDecrypt(server string) {
|
||||
if !t.cfg.AllowNonHttpsCONNECT {
|
||||
t.onlyHTTPS()
|
||||
return
|
||||
}
|
||||
host := server
|
||||
if i := strings.LastIndexByte(server, ':'); i >= 0 {
|
||||
host = server[:i]
|
||||
}
|
||||
c := t.established(false)
|
||||
defer c.Close()
|
||||
t.log.Printf(">Decrypt: %s", server)
|
||||
remote, err := t.s.up.dialer.Dial("tcp", server)
|
||||
if err == nil {
|
||||
t.log.Printf(" D tunnel connected.")
|
||||
rc := tls.Client(remote, t.upstreamTLS(host))
|
||||
if err = rc.Handshake(); err != nil {
|
||||
remote.Close()
|
||||
}
|
||||
remote = rc
|
||||
}
|
||||
if err != nil {
|
||||
t.log.Printf(" D connection failed: %v.", err)
|
||||
io.WriteString(c, "The proxy server is unable to connect with decryption: "+err.Error()+"\r\n")
|
||||
return
|
||||
}
|
||||
t.log.Printf(" D tunnel established.")
|
||||
pipe(c, remote)
|
||||
t.log.Printf(" D connection to %s closed.", t.req.RawURL)
|
||||
}
|
||||
|
||||
// upstreamTLS is the TLS client configuration toward a server.
|
||||
func (t *transit) upstreamTLS(host string) *tls.Config {
|
||||
c := t.s.up.tlsCfg.Clone()
|
||||
c.ServerName = host
|
||||
return c
|
||||
}
|
||||
|
||||
// pipe copies both ways until one side ends, then closes both.
|
||||
func pipe(a, b net.Conn) {
|
||||
var once sync.Once
|
||||
done := make(chan struct{})
|
||||
closeBoth := func() {
|
||||
once.Do(func() {
|
||||
a.Close()
|
||||
b.Close()
|
||||
close(done)
|
||||
})
|
||||
}
|
||||
go func() { io.Copy(b, a); closeBoth() }()
|
||||
go func() { io.Copy(a, b); closeBoth() }()
|
||||
<-done
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/certs"
|
||||
"github.com/D-Modem/webone-go/internal/config"
|
||||
"github.com/D-Modem/webone-go/internal/rx"
|
||||
)
|
||||
|
||||
// runConverter runs a [Converters] program on in (nil when the program
|
||||
// downloads srcURL itself) and gives its output, with the output's length
|
||||
// when it is known (Converter.Run).
|
||||
func (s *Server) runConverter(cv config.Converter, log logger, in io.ReadCloser, arg1, arg2, destType, srcURL string) (io.ReadCloser, int64, error) {
|
||||
if cv.SelfDownload && (in != nil || srcURL == "") {
|
||||
if in != nil {
|
||||
in.Close()
|
||||
}
|
||||
return nil, -1, errors.New("The converter " + cv.Executable + " can only download the content self")
|
||||
}
|
||||
if srcURL == "" {
|
||||
srcURL = "http://webone.github.io/index.htm"
|
||||
}
|
||||
if destType == "" {
|
||||
destType = "tmp"
|
||||
}
|
||||
rnd := strconv.FormatUint(uint64(rand.Uint32()), 10)
|
||||
srcTmp := filepath.Join(s.cfg.TemporaryDirectory, "convert-"+rnd+".orig.tmp")
|
||||
dstTmp := filepath.Join(s.cfg.TemporaryDirectory, "convert-"+rnd+".conv."+destType)
|
||||
cleanup := func() {
|
||||
os.Remove(srcTmp)
|
||||
os.Remove(dstTmp)
|
||||
}
|
||||
|
||||
if !cv.UseStdin && !cv.SelfDownload {
|
||||
f, err := os.Create(srcTmp)
|
||||
if err != nil {
|
||||
in.Close()
|
||||
return nil, -1, err
|
||||
}
|
||||
_, err = io.Copy(f, in)
|
||||
f.Close()
|
||||
in.Close()
|
||||
in = nil
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, -1, err
|
||||
}
|
||||
}
|
||||
|
||||
line := s.processURIMasks(cv.CommandLine, srcURL, false, nil)
|
||||
line = strings.NewReplacer(
|
||||
"%SRC%", srcTmp, "%ARG1%", arg1, "%DEST%", dstTmp, "%ARG2%", arg2,
|
||||
"%DESTEXT%", destType, "%SRCURL%", srcURL,
|
||||
).Replace(line)
|
||||
cmd := exec.Command(cv.Executable, certs.SplitArgs(line)...)
|
||||
cmd.Stderr = os.Stderr
|
||||
log.Printf(" Converting: %s %s...", cv.Executable, line)
|
||||
|
||||
var stdin io.WriteCloser
|
||||
var err error
|
||||
if cv.UseStdin && in != nil {
|
||||
if stdin, err = cmd.StdinPipe(); err != nil {
|
||||
in.Close()
|
||||
return nil, -1, err
|
||||
}
|
||||
}
|
||||
feed := func() {
|
||||
if stdin != nil {
|
||||
go func() {
|
||||
io.Copy(stdin, in)
|
||||
stdin.Close()
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
if cv.UseStdout {
|
||||
out, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, -1, err
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
if in != nil {
|
||||
in.Close()
|
||||
}
|
||||
cleanup()
|
||||
return nil, -1, err
|
||||
}
|
||||
feed()
|
||||
return &procReader{r: out, cmd: cmd, in: in, cleanup: cleanup}, -1, nil
|
||||
}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
if in != nil {
|
||||
in.Close()
|
||||
}
|
||||
cleanup()
|
||||
return nil, -1, err
|
||||
}
|
||||
feed()
|
||||
err = cmd.Wait()
|
||||
if in != nil {
|
||||
in.Close()
|
||||
}
|
||||
f, ferr := os.Open(dstTmp)
|
||||
if ferr != nil {
|
||||
cleanup()
|
||||
if err != nil {
|
||||
return nil, -1, err
|
||||
}
|
||||
return nil, -1, ferr
|
||||
}
|
||||
// WebOne leaves the files for a minute, then removes them
|
||||
time.AfterFunc(time.Minute, cleanup)
|
||||
st, _ := f.Stat()
|
||||
return f, st.Size(), nil
|
||||
}
|
||||
|
||||
// procReader is a converter's standard output; closing it stops the
|
||||
// converter and removes its temporary files.
|
||||
type procReader struct {
|
||||
r io.ReadCloser
|
||||
cmd *exec.Cmd
|
||||
in io.Closer
|
||||
cleanup func()
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (p *procReader) Read(b []byte) (int, error) { return p.r.Read(b) }
|
||||
|
||||
func (p *procReader) Close() error {
|
||||
p.once.Do(func() {
|
||||
if p.in != nil {
|
||||
p.in.Close()
|
||||
}
|
||||
p.cmd.Process.Kill()
|
||||
p.cmd.Wait()
|
||||
p.cleanup()
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) converter(name string) (config.Converter, bool) {
|
||||
for _, c := range s.cfg.Converters {
|
||||
if c.Executable == name {
|
||||
return c, true
|
||||
}
|
||||
}
|
||||
return config.Converter{}, false
|
||||
}
|
||||
|
||||
// convertResponse converts the server's response on the fly with an
|
||||
// AddConverting rule.
|
||||
func (t *transit) convertResponse(name, dest, arg1, arg2, contentType, srcContentType string) {
|
||||
cv, ok := t.s.converter(name)
|
||||
if !ok {
|
||||
t.op.RespBody.Close()
|
||||
t.sendError(503, "<big>Converter "<b>"+name+"</b>" is unknown</big>.<br>"+
|
||||
"<p>This converter is not well listed in configuration file.</p>"+
|
||||
`<p>See <a href="http://github.com/atauenis/webone/wiki">WebOne wiki</a> for help on this.</p>`)
|
||||
return
|
||||
}
|
||||
var in io.ReadCloser = t.op.RespBody
|
||||
if cv.SelfDownload {
|
||||
in.Close()
|
||||
in = nil
|
||||
}
|
||||
out, n, err := t.s.runConverter(cv, t.log, in, arg1, arg2, dest, t.urlString())
|
||||
if err != nil {
|
||||
t.log.Printf(" On-fly converter error: %v", err)
|
||||
t.sendError(502, "<p><big><b>Converter error</b>: "+err.Error()+"</big></p>"+
|
||||
"Source URL: "+t.urlString()+"<br>Utility: "+name+"<br>"+
|
||||
"Mode: seamless from '"+srcContentType+"' to '"+contentType+"'")
|
||||
return
|
||||
}
|
||||
t.sendStream(out, contentType, n, 200)
|
||||
}
|
||||
|
||||
// localFile finds a file of the proxy (logo.webp ...): as given, or next
|
||||
// to the program.
|
||||
func localFile(name string) (string, error) {
|
||||
if _, err := os.Stat(name); err == nil {
|
||||
return name, nil
|
||||
}
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
p := filepath.Join(filepath.Dir(exe), name)
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("No such file: " + name)
|
||||
}
|
||||
|
||||
// imageMagickTest converts WebOne's logo to GIF (/!imagemagicktest.gif).
|
||||
func (t *transit) imageMagickTest() {
|
||||
for _, cv := range t.cfg.Converters {
|
||||
if cv.Executable == "convert" && !cv.SelfDownload {
|
||||
p, err := localFile("logo.webp")
|
||||
if err == nil {
|
||||
var f *os.File
|
||||
if f, err = os.Open(p); err == nil {
|
||||
var out io.ReadCloser
|
||||
var n int64
|
||||
out, n, err = t.s.runConverter(cv, t.log, f, "", "", "gif", "https://github.com/atauenis/webone/")
|
||||
if err == nil {
|
||||
t.sendStream(out, "image/gif", n, 200)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
t.sendError(502, "<p><big><b>Converter error</b>: "+err.Error()+"</big></p>")
|
||||
return
|
||||
}
|
||||
}
|
||||
t.sendInfoPage("WebOne: ImageMagick error", "Error",
|
||||
"<p>ImageMagick's <b>convert</b> utility is not properly registered in <b>[Converters]</b> section of proxy configuration.</p>"+
|
||||
"<p>Make sure that the line is present in <code>[Converters]</code> section of configuration: <code>convert %SRC% %ARG1% %DESTEXT%:- %ARG2%</code></p>", 500)
|
||||
}
|
||||
|
||||
// manualConvert is /!convert/?url=...&dest=gif&type=image/gif (or src= a
|
||||
// local file).
|
||||
func (t *transit) manualConvert(query string) {
|
||||
if !t.cfg.EnableManualConverting {
|
||||
t.sendInfoPage("WebOne: Feature disabled", "Feature disabled",
|
||||
"Manual file converting is disabled for security purposes.<br>Proxy administrator can enable it via <code>[Server]</code> section, <code>EnableManualConverting</code> option.", 500)
|
||||
return
|
||||
}
|
||||
q := "?" + query
|
||||
get := func(name, def string) (string, bool) {
|
||||
g := rx.FindGroups(`(`+name+`)=([^&]+)`, q)
|
||||
if g == nil {
|
||||
return def, false
|
||||
}
|
||||
v, err := url.PathUnescape(g[2])
|
||||
if err != nil {
|
||||
v = g[2]
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
src, hasSrc := get("src", "")
|
||||
srcURL, hasURL := get("url", "")
|
||||
dest, _ := get("dest", "xbm")
|
||||
destMime, _ := get("type", "image/x-xbitmap")
|
||||
name, _ := get("util", "convert")
|
||||
arg1, _ := get("arg", "")
|
||||
arg2, _ := get("arg2", "")
|
||||
|
||||
if !hasURL && !hasSrc {
|
||||
t.sendError(200, "<big>Here you can summon ImageMagick to convert a picture file</big>.<br>"+
|
||||
"<p>Usage: /!convert/?url=https://example.com/filename.ext&dest=gif&type=image/gif<br>"+
|
||||
"or: /!convert/?src=filename.ext&dest=gif&type=image/gif</p>"+
|
||||
`<p>See <a href="http://github.com/atauenis/webone/wiki">WebOne wiki</a> for help on this.</p>`)
|
||||
return
|
||||
}
|
||||
cv, ok := t.s.converter(name)
|
||||
if !ok {
|
||||
t.sendError(503, "<big>Converter "<b>"+name+"</b>" is unknown</big>.<br>"+
|
||||
"<p>This converter is not listed in configuration file.</p>"+
|
||||
`<p>See <a href="http://github.com/atauenis/webone/wiki">WebOne wiki</a> for help on this.</p>`)
|
||||
return
|
||||
}
|
||||
var in io.ReadCloser
|
||||
if hasURL {
|
||||
if !cv.SelfDownload {
|
||||
t.log.Printf(">Downloading source stream...")
|
||||
resp, err := t.s.fetch(srcURL)
|
||||
if err != nil {
|
||||
t.log.Printf(" Converter cannot download source: %v", err)
|
||||
t.sendError(503, "<p><big><b>Converter cannot download the source</b>: "+err.Error()+"</big></p>Source URL: "+srcURL)
|
||||
return
|
||||
}
|
||||
in = resp.Body
|
||||
}
|
||||
} else {
|
||||
srcURL = "http://0.0.0.0/localfile"
|
||||
if !cv.SelfDownload {
|
||||
// only files of the proxy's own folder: no paths
|
||||
p, err := localFile(src)
|
||||
if err == nil && (src == "CON:" || strings.ContainsAny(src, `/\`) || strings.Contains(src, "..")) {
|
||||
err = errors.New("Bad source file name")
|
||||
}
|
||||
var f *os.File
|
||||
if err == nil {
|
||||
f, err = os.Open(p)
|
||||
}
|
||||
if err != nil {
|
||||
t.log.Printf(" Converter cannot open source: %v", err)
|
||||
t.sendError(503, "<p><big><b>Converter cannot open the source</b>: "+err.Error()+"</big></p>Source URL: "+srcURL)
|
||||
return
|
||||
}
|
||||
in = f
|
||||
}
|
||||
}
|
||||
out, n, err := t.s.runConverter(cv, t.log, in, arg1, arg2, dest, srcURL)
|
||||
if err != nil {
|
||||
t.log.Printf(" Converter error: %v", err)
|
||||
t.sendError(502, "<p><big><b>Converter error</b>: "+err.Error()+"</big></p>Source URL: "+srcURL+"<br>Utility: "+cv.Executable)
|
||||
return
|
||||
}
|
||||
t.sendStream(out, destMime, n, 200)
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/rx"
|
||||
)
|
||||
|
||||
// handleFetchError answers a request whose server could not be reached
|
||||
// (the catch blocks around SendRequest in ProcessTransit). It returns true
|
||||
// when the client has its answer.
|
||||
func (t *transit) handleFetchError(err error) bool {
|
||||
u := t.urlString()
|
||||
archived := `<li>Try to use an <a href="http://web.archive.org/web/` + strconv.Itoa(time.Now().Year()) + "/" + u + `">archived copy</a> of the web site.</li>`
|
||||
check := "<li>If you are unable to load any pages, check your proxy server's network connection.</li>" +
|
||||
"<li>If your proxy server or network is protected by a firewall, make sure that WebOne is permitted to access the Web.</li>"
|
||||
|
||||
var bad *badURLError
|
||||
if errors.As(err, &bad) {
|
||||
t.dump("!Invalid URL")
|
||||
t.sendError(400, "The URL <b>"+bad.u+"</b> is not valid.")
|
||||
return true
|
||||
}
|
||||
var dec *decodeError
|
||||
if errors.As(err, &dec) {
|
||||
t.dump("!Decompression failed")
|
||||
if t.sendInternalContent("Err-InvalidDataException.htm", "?ErrorMessage=Cannot+decode+HTTP+data.&URL="+qe(u), 200) {
|
||||
return true
|
||||
}
|
||||
msg := "<p><big>Cannot decode HTTP data.</big></p>" +
|
||||
"<ul>Remote server may use unsupported HTTP compression algorithm." +
|
||||
"<li>Try to set AllowHttpCompression=false option in configuration file to skip HTTP decompression.</li>" +
|
||||
"<li>If you are unable to load any pages, check your proxy server's network connection.</li></ul>"
|
||||
t.sendInfoPage("WebOne: Decompression failed", "Invalid data has been recieved", msg+"<br>URL: "+u, 500)
|
||||
return true
|
||||
}
|
||||
|
||||
if isTimeout(err) {
|
||||
t.dump("!Connection timeout")
|
||||
const m = "The request was canceled due to Timeout of 100 seconds elapsing."
|
||||
if t.sendInternalContent("Err-TaskCanceledException.htm", "?ErrorMessage="+qe(m)+"&URL="+qe(u), 200) {
|
||||
return true
|
||||
}
|
||||
msg := "<p><big>" + m + "</big></p>" +
|
||||
"<ul><li>The site could be temporarily unavailable or too busy. Try again in a few moments.</li>" + archived +
|
||||
"<li>Internet Archive sometimes became busy. Be patient, wait a some time.</li>" + check + "</ul>"
|
||||
t.sendInfoPage("WebOne: Operation timeout", "The connection has timed out", msg+"<br>URL: "+u, 200)
|
||||
return true
|
||||
}
|
||||
|
||||
t.log.Printf(" Cannot load this page: %v.", err)
|
||||
t.dump("!Network error: " + err.Error())
|
||||
if t.lookInWebArchive() {
|
||||
return true
|
||||
}
|
||||
|
||||
title, header, message := "connection error", "Cannot load this page", ""
|
||||
if code, text := socketError(err); code != "" {
|
||||
if t.sendInternalContent("Err-"+code+".htm", "?ErrorMessage="+qe(text)+"&URL="+qe(u), 200) {
|
||||
return true
|
||||
}
|
||||
switch code {
|
||||
case "HostNotFound":
|
||||
header = "Cannot find the server"
|
||||
message = "<p><big>" + text + "</big></p>" +
|
||||
"<ul><li>Check the address for typing errors such as <strong>ww</strong>.example.com instead of <strong>www</strong>.example.com.</li>" +
|
||||
archived + check + "</ul>"
|
||||
case "ConnectionRefused", "ConnectionReset", "TimedOut":
|
||||
header = map[string]string{
|
||||
"ConnectionRefused": "The connection was refused",
|
||||
"ConnectionReset": "The connection has been reset",
|
||||
"TimedOut": "The connection has timed out",
|
||||
}[code]
|
||||
message = "<p><big>" + text + "</big></p>" +
|
||||
"<ul><li>The site could be temporarily unavailable or too busy. Try again in a few moments.</li>" + archived + check + "</ul>"
|
||||
default:
|
||||
header = "The connection can't be stablished"
|
||||
message = "<p><big>" + text + "</big></p>" +
|
||||
"<ul><li>The site could be temporarily unavailable or too busy. Try again in a few moments.</li>" + archived + check +
|
||||
"</ul><br>Error code: " + code
|
||||
}
|
||||
} else if polerr := tlsPolicyError(err); polerr != "" {
|
||||
if t.sendInternalContent("Err-TlsPolicyErrorException.htm", "?ErrorMessage="+qe(polerr)+"&URL="+qe(u), 200) {
|
||||
return true
|
||||
}
|
||||
header = "Secure connection could not be established"
|
||||
message = "<p><big>" + polerr + "</big></p>" +
|
||||
"<ul><li>The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.</li>" +
|
||||
"<li>Make sure that the OS on the proxy server have all updates installed.</li>" +
|
||||
"<li>Check date and time on the proxy server.</li>" +
|
||||
"<li>Verify that the proxy server operating system have proper support for TLS/SSL version and chiphers used on the site.</li>" +
|
||||
archived +
|
||||
"<li>To disable this security check, set <q><b>ValidateCertificates=no</b></q> in proxy configuration file. But this will make the proxy less secure, do this at your own risk.</li></ul>"
|
||||
} else {
|
||||
title = fmt.Sprintf("%T", errors.Unwrap(err))
|
||||
if title == "<nil>" {
|
||||
title = "connection error"
|
||||
}
|
||||
message = "There are problems, that are preventing from displaying the page:<br>" + strings.ReplaceAll(err.Error(), "\n", "<br>")
|
||||
}
|
||||
t.sendInfoPage("WebOne: "+title, header, message+"<br>URL: "+u, 200)
|
||||
return true
|
||||
}
|
||||
|
||||
func isTimeout(err error) bool {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return true
|
||||
}
|
||||
var ne net.Error
|
||||
var oe *net.OpError
|
||||
// a dial timeout is a socket error (TimedOut); a whole-request
|
||||
// timeout is the 100 seconds one
|
||||
return errors.As(err, &ne) && ne.Timeout() && !(errors.As(err, &oe) && oe.Op == "dial")
|
||||
}
|
||||
|
||||
// socketError is the .NET SocketError name of a network error, and its
|
||||
// message.
|
||||
func socketError(err error) (string, string) {
|
||||
var dnsErr *net.DNSError
|
||||
if errors.As(err, &dnsErr) {
|
||||
if dnsErr.IsNotFound {
|
||||
return "HostNotFound", "No such host is known. (" + dnsErr.Name + ")"
|
||||
}
|
||||
if dnsErr.IsTimeout {
|
||||
return "TryAgain", dnsErr.Error()
|
||||
}
|
||||
return "HostNotFound", dnsErr.Error()
|
||||
}
|
||||
var oe *net.OpError
|
||||
if !errors.As(err, &oe) {
|
||||
return "", ""
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, syscall.ECONNREFUSED):
|
||||
return "ConnectionRefused", "Connection refused (" + oe.Addr.String() + ")"
|
||||
case errors.Is(err, syscall.ECONNRESET):
|
||||
return "ConnectionReset", "Connection reset by peer"
|
||||
case errors.Is(err, syscall.EHOSTUNREACH):
|
||||
return "HostUnreachable", "No route to host"
|
||||
case errors.Is(err, syscall.ENETUNREACH):
|
||||
return "NetworkUnreachable", "Network is unreachable"
|
||||
case oe.Timeout():
|
||||
return "TimedOut", "Connection timed out"
|
||||
}
|
||||
return "SocketError", oe.Err.Error()
|
||||
}
|
||||
|
||||
// tlsPolicyError describes a server certificate that is not trusted.
|
||||
func tlsPolicyError(err error) string {
|
||||
var host x509.HostnameError
|
||||
var unk x509.UnknownAuthorityError
|
||||
var inv x509.CertificateInvalidError
|
||||
var verr *tlsVerifyError
|
||||
switch {
|
||||
case errors.As(err, &host):
|
||||
return "The certificate is issued for another site."
|
||||
case errors.As(err, &unk):
|
||||
return "Certificate chain is incorrect."
|
||||
case errors.As(err, &inv):
|
||||
return "Certificate is not valid: " + inv.Error()
|
||||
case errors.As(err, &verr):
|
||||
return verr.Error()
|
||||
case strings.Contains(err.Error(), "tls:"):
|
||||
return err.Error()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type tlsVerifyError struct{ msg string }
|
||||
|
||||
func (e *tlsVerifyError) Error() string { return e.msg }
|
||||
|
||||
// lookInWebArchive looks for the page in the Wayback Machine and answers
|
||||
// with it (HttpTransit.LookInWebArchive). It returns true when the client
|
||||
// has its answer, or the archived page is fetched and ready to send.
|
||||
func (t *transit) lookInWebArchive() bool {
|
||||
if !t.cfg.SearchInArchive || t.url == nil {
|
||||
return false
|
||||
}
|
||||
if h := t.url.Hostname(); h == "web.archive.org" || h == "archive.org" {
|
||||
return false
|
||||
}
|
||||
t.log.Printf(" Look in Archive.org...")
|
||||
t.dump("=Look in Web Archive...")
|
||||
archived, err := t.s.webArchive(t.urlString())
|
||||
if err != nil {
|
||||
if t.resp.HeadersSent {
|
||||
return true
|
||||
}
|
||||
m := strings.ReplaceAll(err.Error(), "\n", "<br>")
|
||||
if t.sendInternalContent("Err-WArchiveException.htm", "?ErrorMessage="+qe(m)+"&URL="+qe(t.urlString()), 200) {
|
||||
return true
|
||||
}
|
||||
t.sendInfoPage("WebOne: Web Archive error.", "Cannot load this page",
|
||||
"<b>The requested server or page is not found and a Web Archive error occured.</b><br>"+m, 200)
|
||||
return true
|
||||
}
|
||||
if archived == "" {
|
||||
t.log.Printf(" No snapshots.")
|
||||
t.dump("=Not in Web Archive")
|
||||
return false
|
||||
}
|
||||
t.log.Printf(" Available.")
|
||||
g := rx.FindGroups(`^http://web.archive.org/web/([0-9]*)/(.*)`, archived)
|
||||
if t.cfg.HideArchiveRedirect && g != nil {
|
||||
target := "http://web.archive.org/web/" + g[1] + "id_/" + g[2]
|
||||
nu, perr := parseURL(target)
|
||||
if perr == nil {
|
||||
t.dump("=Go to Web Archive, internal: " + target)
|
||||
if t.transitStream != nil {
|
||||
t.transitStream.Close()
|
||||
t.transitStream = nil
|
||||
}
|
||||
t.url = nu
|
||||
if t.op == nil {
|
||||
t.op = &operation{Method: "GET", Header: NewHeader(), HTTPVersion: t.requestHTTPVersion, log: t.log}
|
||||
}
|
||||
t.op.Body = nil
|
||||
t.op.Secure = false
|
||||
perr = t.sendRequest()
|
||||
}
|
||||
if perr == nil {
|
||||
return true
|
||||
}
|
||||
m := strings.ReplaceAll(perr.Error(), "\n", "<br>")
|
||||
if t.sendInternalContent("Err-WArchiveRetrieveException.htm", "?ErrorMessage="+qe(m)+"&URL="+qe(t.urlString()), 200) {
|
||||
return true
|
||||
}
|
||||
t.sendInfoPage("WebOne: Web Archive retrieve error.", "Cannot load this page from Web Archive",
|
||||
"<b>The requested page is found only at Web Archive, but cannot be delivered from it.</b><br>"+m, 200)
|
||||
return true
|
||||
}
|
||||
if t.cfg.ArchiveUrlSuffix != "" && g != nil {
|
||||
scheme := "http"
|
||||
if t.req.Secure {
|
||||
scheme = "https"
|
||||
}
|
||||
archived = scheme + "://web.archive.org/web/" + g[1] + t.cfg.ArchiveUrlSuffix + "/" + g[2]
|
||||
}
|
||||
t.sendRedirect(archived, "<b>Good news:</b> an archived copy of now-removed content is available.")
|
||||
return true
|
||||
}
|
||||
|
||||
// webArchive asks the Wayback Machine's CDX API for the latest good
|
||||
// snapshot of u (WebArchiveRequest.cs). "" means none.
|
||||
func (s *Server) webArchive(u string) (string, error) {
|
||||
cdx := "https://web.archive.org/cdx/search/cdx?fl=timestamp,original,statuscode&url=" + url.QueryEscape(u)
|
||||
resp, err := s.fetch(cdx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return "", errors.New("Unsuccessful Web Archive request: " + resp.Status)
|
||||
}
|
||||
var lines []string
|
||||
sc := bufio.NewScanner(resp.Body)
|
||||
sc.Buffer(make([]byte, 64*1024), 4<<20)
|
||||
for sc.Scan() {
|
||||
lines = append(lines, sc.Text())
|
||||
}
|
||||
for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" {
|
||||
lines = lines[:len(lines)-1]
|
||||
}
|
||||
if len(lines) == 0 || lines[0] == "" {
|
||||
return "", nil
|
||||
}
|
||||
last := ""
|
||||
for _, l := range lines {
|
||||
f := strings.Split(l, " ")
|
||||
if len(f) != 3 {
|
||||
continue
|
||||
}
|
||||
if s.cfg.ArchiveDateLimit > 0 {
|
||||
ts, _ := strconv.ParseInt(f[0], 10, 64)
|
||||
if ts > int64(s.cfg.ArchiveDateLimit)*1000000 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if f[2] == "200" {
|
||||
last = l
|
||||
}
|
||||
}
|
||||
if last == "" {
|
||||
last = lines[len(lines)-1]
|
||||
}
|
||||
f := strings.Split(last, " ")
|
||||
if len(f) != 3 {
|
||||
return "", errors.New("Incorrect Web Archive request: " + last)
|
||||
}
|
||||
return "http://web.archive.org/web/" + f[0] + "/" + f[1], nil
|
||||
}
|
||||
|
||||
// isLanIP: ip is on a local network (loopback, private, link-local).
|
||||
// WebOne pings the address with TTL 1 instead; this is the same answer
|
||||
// without sending anything.
|
||||
func isLanIP(ip net.IP) bool {
|
||||
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast()
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"net"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/rx"
|
||||
)
|
||||
|
||||
// ftpClient is one FTP session that the Web-FTP pages drive (FtpClient.cs).
|
||||
type ftpClient struct {
|
||||
mu sync.Mutex
|
||||
log logger
|
||||
lastUsed time.Time
|
||||
ftpLog string
|
||||
Server string
|
||||
User string
|
||||
Pass string
|
||||
Port int
|
||||
Workdir string
|
||||
|
||||
conn net.Conn
|
||||
br *bufio.Reader
|
||||
data net.Conn
|
||||
ok bool
|
||||
}
|
||||
|
||||
type ftpResponse struct {
|
||||
Code int
|
||||
Result string
|
||||
}
|
||||
|
||||
func (r ftpResponse) String() string { return fmt.Sprintf("%03d%s", r.Code, r.Result) }
|
||||
|
||||
func clientErr(msg string) ftpResponse { return ftpResponse{0, " CLIENT ERROR: " + msg} }
|
||||
|
||||
const ftpIdleTimeout = 5 * time.Minute
|
||||
|
||||
// ftpBackends are the open sessions by client number (FtpTransitManager).
|
||||
var ftpBackends = struct {
|
||||
sync.Mutex
|
||||
m map[int]*ftpClient
|
||||
started bool
|
||||
}{m: map[int]*ftpClient{}}
|
||||
|
||||
func addFtpBackend(id int, c *ftpClient) {
|
||||
ftpBackends.Lock()
|
||||
defer ftpBackends.Unlock()
|
||||
ftpBackends.m[id] = c
|
||||
if !ftpBackends.started {
|
||||
ftpBackends.started = true
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(ftpIdleTimeout + time.Second)
|
||||
ftpBackends.Lock()
|
||||
for id, c := range ftpBackends.m {
|
||||
c.mu.Lock()
|
||||
switch {
|
||||
case !c.ok:
|
||||
c.log.Printf(" Remove closed FTP connection to %s.", c.Server)
|
||||
delete(ftpBackends.m, id)
|
||||
case time.Since(c.lastUsed) > ftpIdleTimeout:
|
||||
c.log.Printf(" Close abandoned FTP connection to %s.", c.Server)
|
||||
c.close()
|
||||
delete(ftpBackends.m, id)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
ftpBackends.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func getFtpBackend(id int) *ftpClient {
|
||||
ftpBackends.Lock()
|
||||
defer ftpBackends.Unlock()
|
||||
return ftpBackends.m[id]
|
||||
}
|
||||
|
||||
// dialFtp connects and logs in. server may be "user:pass@host:port".
|
||||
func dialFtp(d *net.Dialer, server, user, pass string, log logger) (*ftpClient, error) {
|
||||
c := &ftpClient{log: log, Server: server, User: user, Pass: pass, Port: 21, lastUsed: time.Now()}
|
||||
if strings.Contains(c.Server, "/") {
|
||||
return nil, errors.New(`Malformed server name. Use only "user@password:ftp.example.com:21" format or shorter.`)
|
||||
}
|
||||
if cred, host, ok := strings.Cut(c.Server, "@"); ok {
|
||||
if u, p, ok := strings.Cut(cred, ":"); ok {
|
||||
c.User, c.Pass = u, p
|
||||
} else {
|
||||
c.User = cred
|
||||
}
|
||||
c.Server = host
|
||||
}
|
||||
if h, p, ok := strings.Cut(c.Server, ":"); ok {
|
||||
n, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
return nil, errors.New("Malformed port number: " + p)
|
||||
}
|
||||
c.Server, c.Port = h, n
|
||||
}
|
||||
log.Printf(">FTP connect to: %s", c.Server)
|
||||
conn, err := d.Dial("tcp", net.JoinHostPort(c.Server, strconv.Itoa(c.Port)))
|
||||
if err != nil {
|
||||
log.Printf(" Connecting error: %v", err)
|
||||
code, text := socketError(err)
|
||||
switch code {
|
||||
case "HostNotFound":
|
||||
c.ftpLog += "\nUnknown host name."
|
||||
case "ConnectionRefused":
|
||||
c.ftpLog += "\nConnection refused."
|
||||
case "TimedOut":
|
||||
c.ftpLog += "\nConnection request was sent, but no reply has received in a reasonable time."
|
||||
case "":
|
||||
c.ftpLog += "\nERROR: " + err.Error()
|
||||
default:
|
||||
c.ftpLog += "\n" + text + " (" + code + ")."
|
||||
}
|
||||
log.Printf(" Connect failed.")
|
||||
return c, nil
|
||||
}
|
||||
c.conn, c.br, c.ok = conn, bufio.NewReader(conn), true
|
||||
c.ftpLog += "\nEstablished a TCP/IP connection."
|
||||
c.ftpLog += "\n" + c.reply().String()
|
||||
r := c.command("USER " + c.User)
|
||||
c.ftpLog += "\nUSER => " + r.String()
|
||||
switch r.Code {
|
||||
case 230:
|
||||
c.ftpLog += "\nSuccessfull."
|
||||
case 331:
|
||||
r = c.command("PASS " + c.Pass)
|
||||
c.ftpLog += "\nPASS => " + r.String()
|
||||
if r.Code == 230 || r.Code == 202 {
|
||||
c.ftpLog += "\nSuccessfull."
|
||||
} else {
|
||||
c.close()
|
||||
c.ftpLog += "\nDisconnected by client."
|
||||
}
|
||||
default:
|
||||
c.close()
|
||||
c.ftpLog += "\nUser name not accepted. Disconnecting."
|
||||
}
|
||||
if c.ok {
|
||||
log.Printf(" Success.")
|
||||
} else {
|
||||
log.Printf(" Connect failed.")
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// reply reads one (possibly multi-line) reply; its first line is the
|
||||
// result.
|
||||
func (c *ftpClient) reply() ftpResponse {
|
||||
c.lastUsed = time.Now()
|
||||
if !c.ok {
|
||||
return clientErr("not connected")
|
||||
}
|
||||
c.conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
|
||||
defer c.conn.SetReadDeadline(time.Time{})
|
||||
line, err := c.br.ReadString('\n')
|
||||
if err != nil {
|
||||
c.log.Printf("!Errror on NetworkStream: %v", err)
|
||||
c.close()
|
||||
return clientErr("unexpected close of NetworkStream")
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n\x00")
|
||||
if len(line) < 3 {
|
||||
return clientErr("incorrect FTP server response")
|
||||
}
|
||||
code, err := strconv.Atoi(line[:3])
|
||||
if err != nil {
|
||||
return clientErr("incorrect FTP server response")
|
||||
}
|
||||
r := ftpResponse{code, line[3:]}
|
||||
if len(line) > 3 && line[3] == '-' {
|
||||
end := line[:3] + " "
|
||||
for {
|
||||
l, err := c.br.ReadString('\n')
|
||||
if err != nil {
|
||||
c.close()
|
||||
break
|
||||
}
|
||||
if strings.HasPrefix(l, end) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (c *ftpClient) command(cmd string) ftpResponse {
|
||||
c.lastUsed = time.Now()
|
||||
if !c.ok {
|
||||
return clientErr("cannot use NetworkStream")
|
||||
}
|
||||
if _, err := io.WriteString(c.conn, cmd+"\r\n"); err != nil {
|
||||
c.close()
|
||||
return clientErr("cannot use NetworkStream")
|
||||
}
|
||||
return c.reply()
|
||||
}
|
||||
|
||||
// pasvData opens the data connection a 227 reply describes.
|
||||
func (c *ftpClient) pasvData(d *net.Dialer, info string) (net.Conn, error) {
|
||||
m := rx.FindGroups(`\(([0-9,]*)\)`, info)
|
||||
if m == nil {
|
||||
return nil, errors.New("PASV 227 reply is not correct")
|
||||
}
|
||||
p := strings.Split(m[1], ",")
|
||||
if len(p) < 6 {
|
||||
return nil, errors.New("PASV 227 reply contains not full IP")
|
||||
}
|
||||
p1, _ := strconv.Atoi(p[4])
|
||||
p2, _ := strconv.Atoi(p[5])
|
||||
port := strconv.Itoa(p1*256 + p2)
|
||||
ip := strings.Join(p[:4], ".")
|
||||
conn, err := d.Dial("tcp", net.JoinHostPort(ip, port))
|
||||
if err != nil {
|
||||
// servers behind NAT often give their private address
|
||||
conn, err = d.Dial("tcp", net.JoinHostPort(c.Server, port))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.data = conn
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (c *ftpClient) closeData() {
|
||||
c.lastUsed = time.Now()
|
||||
if c.data != nil {
|
||||
c.data.Close()
|
||||
c.data = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ftpClient) close() {
|
||||
if c.conn != nil {
|
||||
c.conn.Close()
|
||||
}
|
||||
c.closeData()
|
||||
c.ok = false
|
||||
}
|
||||
|
||||
// ftpEntry is a line of a LIST reply (FtpDirectoryListEntry.cs).
|
||||
type ftpEntry struct {
|
||||
Name, Date string
|
||||
Size int64
|
||||
Directory, Link bool
|
||||
}
|
||||
|
||||
const (
|
||||
ftpUnixPattern = `^([\w-]+)\s+(\d+)\s+(\w+)\s+(\w+)\s+(\d+)\s+(\w+\s+\d+\s+\d+|\w+\s+\d+\s+\d+:\d+)\s+(.+)$`
|
||||
ftpDosPattern = `^(\d+-\d+-\d+\s+\d+:\d+(?:AM|PM))\s+(<DIR>|\d+)\s+(.+)$`
|
||||
)
|
||||
|
||||
func parseFtpLine(line string) (ftpEntry, bool) {
|
||||
if g := rx.FindGroups(ftpDosPattern, line); g != nil {
|
||||
e := ftpEntry{Date: g[1], Directory: g[2] == "<DIR>", Name: g[3], Size: -1}
|
||||
if !e.Directory {
|
||||
e.Size, _ = strconv.ParseInt(g[2], 10, 64)
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
if g := rx.FindGroups(ftpUnixPattern, line); g != nil {
|
||||
e := ftpEntry{Date: g[6], Name: g[7], Directory: strings.HasPrefix(g[1], "d"), Link: strings.HasPrefix(g[1], "l")}
|
||||
e.Size, _ = strconv.ParseInt(g[5], 10, 64)
|
||||
return e, true
|
||||
}
|
||||
return ftpEntry{}, false
|
||||
}
|
||||
|
||||
// ftpPage is the Web-FTP client, /!ftp/ (FtpClientGUI.cs).
|
||||
func (t *transit) ftpPage() *infoPage {
|
||||
return t.ftpPageFor("")
|
||||
}
|
||||
|
||||
func newFtpPage() *infoPage {
|
||||
p := newInfoPage("WebOne: FTP client", "File Transfer Protocol client", "This is a FTP Web-GUI page.", 200)
|
||||
p.ShowFooter = false
|
||||
p.HTMLHeaders = "<link href=\"/webone.css\" rel=\"stylesheet\"/>\n<link rel=\"shortcut icon\" href=\"/ftpfav.ico\" type=\"image/x-icon\">"
|
||||
return p
|
||||
}
|
||||
|
||||
func (t *transit) ftpPageFor(dest string) (page *infoPage) {
|
||||
args := url.Values{}
|
||||
if t.url != nil {
|
||||
args, _ = url.ParseQuery(t.url.RawQuery)
|
||||
}
|
||||
clientID, _ := strconv.Atoi(args.Get("client"))
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.log.Printf(" FTP Client Error: %v", r)
|
||||
page = newFtpPage()
|
||||
page.Header = "File Transfer Error"
|
||||
page.Content = "<big>An error occured in FTP Client.</big><p>" + strings.ReplaceAll(fmt.Sprint(r), "\n", "<br>") + "</p>" +
|
||||
"<p>Navigation: <a href=\"javascript:history.back()\"><b>Go back</b></a>. " +
|
||||
"<a href=\"/!ftp/\"><b>Reconnect</b></a>. Directory listing: " +
|
||||
"<a href=\"/!ftp/?client=" + strconv.Itoa(clientID) + "&task=listdir&cwd=/\"><b>root</b></a>, " +
|
||||
"<a href=\"/!ftp/?client=" + strconv.Itoa(clientID) + "&task=listdir\"><b>current</b>.</a> </p>"
|
||||
}
|
||||
}()
|
||||
if !t.cfg.EnableWebFtp {
|
||||
t.log.Printf("<Web-FTP: disabled.")
|
||||
p := newFtpPage()
|
||||
p.Header = "Sorry"
|
||||
p.Content = "The server administrator has disabled FTP browsing via this proxy."
|
||||
return p
|
||||
}
|
||||
switch clientID {
|
||||
case 0:
|
||||
return t.ftpWelcome()
|
||||
case -1:
|
||||
return t.ftpConnect(args, dest)
|
||||
}
|
||||
return t.ftpResult(args, clientID)
|
||||
}
|
||||
|
||||
func (t *transit) ftpWelcome() *infoPage {
|
||||
t.log.Printf("<Web-FTP: welcome page.")
|
||||
p := newFtpPage()
|
||||
p.Header = "File Transfer Protocol client"
|
||||
p.Content = "<p>Welcome to space of computer files, directories and servers. Here you'll be able to download something to your PC from FTP servers without quitting a web browser.</p>"
|
||||
p.HTMLHeaders += "\n<style>.formlabel { width: 80px; display: inline-block; display:-moz-inline-block; display:-moz-inline-stack; text-align: right; }</style>"
|
||||
p.Content += "<form action=\"/!ftp/\" method=\"GET\" name=\"Connect\">\n" +
|
||||
"<center><input type=\"hidden\" name=\"client\" value=\"-1\">\n" +
|
||||
"<p><label class=\"formlabel\" for=\"server\">Server:</label> <input type=\"text\" size=\"23\" name=\"server\" id=\"server\" value=\"\"><br>\n" +
|
||||
"<label class=\"formlabel\" for=\"uri\">or URI:</label> <input type=\"text\" size=\"23\" name=\"uri\" id=\"uri\" value=\"\"></p>\n" +
|
||||
"<p><label class=\"formlabel\" for=\"user\">Username:</label> <input type=\"text\" size=\"20\" name=\"user\" id=\"user\" value=\"anonymous\"><br>\n" +
|
||||
"<label class=\"formlabel\" for=\"pass\">Password:</label> <input type=\"password\" size=\"20\" name=\"pass\" id=\"pass\" value=\"user@domain.su\"></p>\n" +
|
||||
"<p><input type=\"submit\" value=\"Let's go!\"></p>\n" +
|
||||
"</center></form>"
|
||||
return p
|
||||
}
|
||||
|
||||
func argOr(v url.Values, k, def string) string {
|
||||
if _, ok := v[k]; ok {
|
||||
return v.Get(k)
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func (t *transit) ftpConnect(args url.Values, dest string) *infoPage {
|
||||
p := newFtpPage()
|
||||
server := args.Get("server")
|
||||
user := argOr(args, "user", "anonymous")
|
||||
pass := argOr(args, "pass", "email@example.com")
|
||||
uri := args.Get("uri")
|
||||
if dest != "" {
|
||||
uri = dest
|
||||
}
|
||||
if server == "" && uri == "" {
|
||||
p.Content = "<h2>Empty connection data</h2>\n<p>You need to specify the remote server first.</p><p><a href=\"/!ftp/\"><b>Go back.</b></a></p>"
|
||||
return p
|
||||
}
|
||||
id := int(rand.Int32N(1<<31-2)) + 1
|
||||
web := "http://" + t.serverName() + "/!ftp/?client=" + strconv.Itoa(id)
|
||||
if uri == "" {
|
||||
web += "&task=listdir"
|
||||
} else {
|
||||
if !strings.HasPrefix(uri, "ftp://") {
|
||||
p.Content = "<h2>Malformed Universal Resource Identificator</h2>\n" +
|
||||
"<p>URIs (locations) are accepted only in the following format:\n" +
|
||||
"<pre>ftp://ftp.microsoft.com/MISC1/DESKAPPS/DOSWORD/KB/Q81/4/46.TXT</pre>\n" +
|
||||
"Also the Identificator can contain FTP user name, password and port.</p><p><a href=\"/!ftp/\"><b>Go back.</b></a></p>"
|
||||
return p
|
||||
}
|
||||
path := rx.Replace(`(;type=.*)`, uri, "", rx.None)
|
||||
path = rx.Replace(`ftp://`, path, "", rx.IgnoreCase)
|
||||
path = rx.Replace(`http://`, path, "", rx.IgnoreCase)
|
||||
if !strings.Contains(path, "/") {
|
||||
path += "/"
|
||||
}
|
||||
i := strings.Index(path, "/")
|
||||
server, path = path[:i], path[i:]
|
||||
if strings.HasSuffix(path, "/") {
|
||||
web += "&cwd=" + path + "&task=listdir"
|
||||
} else {
|
||||
web += "&name=" + path + "&task=retr"
|
||||
}
|
||||
}
|
||||
c, err := dialFtp(t.s.up.dialer, server, user, pass, t.log)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
if c.ok {
|
||||
addFtpBackend(id, c)
|
||||
p.Header = "File Transfer: " + c.Server
|
||||
p.Content = "<h2>Connecting to the server</h2>\n<pre>" + c.ftpLog + "</pre>\n<p>Okay, <a href=\"" + web + "\"><b>click here</b></a>.</p>"
|
||||
p.Status = 302
|
||||
p.Headers.Add("Location", web)
|
||||
return p
|
||||
}
|
||||
p.Title = "WebOne cannot open FTP connection"
|
||||
p.Header = "File Transfer: " + c.Server
|
||||
p.Content = "<h2>The client could not connect to the server.</h2>\n<pre>" + c.ftpLog + "</pre>\n" +
|
||||
"<p>Return to <a href=\"/!ftp/\"><b>connection page</b></a> and try again.</p>"
|
||||
return p
|
||||
}
|
||||
|
||||
func (t *transit) ftpIconsOn() bool {
|
||||
if !t.cfg.ShowFileIcons {
|
||||
return false
|
||||
}
|
||||
for _, f := range []string{"_dir.gif", "_dir-up.gif", "_file.gif", "_link.gif"} {
|
||||
if !fileExists(filepath.Join(t.cfg.ContentDirectory, "filetypes", f)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (t *transit) ftpIcon(name string) string {
|
||||
i := strings.LastIndexByte(name, '.')
|
||||
if i < 0 || strings.TrimSpace(name[i+1:]) == "" {
|
||||
return "/filetypes/_file.gif"
|
||||
}
|
||||
ext := name[i+1:]
|
||||
if !strings.ContainsAny(ext, `/\`) && fileExists(filepath.Join(t.cfg.ContentDirectory, "filetypes", ext+".gif")) {
|
||||
return "/filetypes/" + ext + ".gif"
|
||||
}
|
||||
return "/filetypes/_file.gif"
|
||||
}
|
||||
|
||||
func (t *transit) ftpResult(args url.Values, id int) *infoPage {
|
||||
p := newFtpPage()
|
||||
c := getFtpBackend(id)
|
||||
if c == nil {
|
||||
t.log.Printf(" Web-FTP: unknown client ID.")
|
||||
return t.ftpWelcome()
|
||||
}
|
||||
c.mu.Lock()
|
||||
unlock := true
|
||||
defer func() {
|
||||
if unlock {
|
||||
c.mu.Unlock()
|
||||
}
|
||||
}()
|
||||
sid := strconv.Itoa(id)
|
||||
again := "<p>Return to <a href=\"/!ftp/\"><b>start page</b></a> and try to connect again.</p>"
|
||||
p.Title = c.Server + " - FTP"
|
||||
p.Header = "File Transfer: " + c.Server
|
||||
p.Content = ""
|
||||
if !c.ok {
|
||||
p.Content = "<h2>Connection lost</h2><p>The FTP connection to the server is closed.</p><p><a href=\"/!ftp/\"><b>Go to start</b></a> and try again.</p>"
|
||||
return p
|
||||
}
|
||||
icons := t.ftpIconsOn()
|
||||
img := func(src string) string {
|
||||
return "<img border=\"0\" src=\"" + src + "\" width=\"16px\" height=\"16px\" class=\"fileicon\"> "
|
||||
}
|
||||
d := t.s.up.dialer
|
||||
switch args.Get("task") {
|
||||
case "listdir":
|
||||
if cwd := args.Get("cwd"); cwd != "" {
|
||||
if r := c.command("CWD " + cwd); r.Code != 250 {
|
||||
p.Content += "<p><b>Cannot change working directory:</b> " + r.String() + "</p>"
|
||||
}
|
||||
}
|
||||
r := c.command("PWD")
|
||||
if r.Code != 257 {
|
||||
p.Content += "<p><b>"Print Working Directory" command has returned an unexpected result:</b> " + r.String() + "</p>"
|
||||
p.Content += "<p>Reload this page or return to <a href=\"/!ftp/\"><b>start page</b></a> and try to connect again.</p>"
|
||||
return p
|
||||
}
|
||||
if g := rx.FindGroups(`"(.*)"`, r.Result); g != nil {
|
||||
p.Content += "<h2><b><a href=\"/!ftp/?client=" + sid + "&task=listdir&cwd=" + url.QueryEscape("/") + "\">Server root</a></b>"
|
||||
c.Workdir = ""
|
||||
for _, dir := range strings.Split(g[1], "/") {
|
||||
c.Workdir += dir + "/"
|
||||
if dir != "" {
|
||||
p.Content += " » <b><a href=\"/!ftp/?client=" + sid + "&task=listdir&cwd=" + url.QueryEscape(c.Workdir) + "\">" + dir + "</a></b>"
|
||||
}
|
||||
}
|
||||
p.Content += "</h2>\n"
|
||||
} else {
|
||||
p.Content += "<h2>" + r.Result + "</h2>\n"
|
||||
c.Workdir = "./"
|
||||
}
|
||||
c.command("OPTS UTF8 ON")
|
||||
if r = c.command("TYPE A"); r.Code != 200 {
|
||||
p.Content += "<p><b>Cannot set ASCII mode:</b> " + r.String() + "</p>" + again
|
||||
return p
|
||||
}
|
||||
if r = c.command("PASV"); r.Code != 227 {
|
||||
p.Content += "<p><b>Cannot prepare data connection:</b> " + r.String() + "</p>" + again
|
||||
return p
|
||||
}
|
||||
data, err := c.pasvData(d, r.Result)
|
||||
if err != nil {
|
||||
p.Content += "<p><b>Cannot establish data connection:</b> " + r.String() + "</p>" + again
|
||||
return p
|
||||
}
|
||||
if r = c.command("LIST"); r.Code != 150 && r.Code != 125 {
|
||||
c.closeData()
|
||||
p.Content += "<p><b>Directory listing is inaccessible:</b> " + r.String() + "</p>" + again
|
||||
return p
|
||||
}
|
||||
data.SetReadDeadline(time.Now().Add(2 * time.Minute))
|
||||
list, _ := io.ReadAll(data)
|
||||
c.closeData()
|
||||
c.reply()
|
||||
var entries []ftpEntry
|
||||
for _, l := range strings.Split(string(list), "\n") {
|
||||
l = strings.Trim(l, "\r\n")
|
||||
if strings.TrimSpace(l) == "" {
|
||||
continue
|
||||
}
|
||||
e, ok := parseFtpLine(l)
|
||||
if !ok || e.Name == "." || e.Name == ".." {
|
||||
continue
|
||||
}
|
||||
entries = append(entries, e)
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("<table>\n")
|
||||
if c.Workdir != "//" {
|
||||
b.WriteString("<tr><td>")
|
||||
if icons {
|
||||
b.WriteString(img("/filetypes/_dir-up.gif"))
|
||||
}
|
||||
b.WriteString("[<a href=\"/!ftp/?client=" + sid + "&task=listdir&cwd=" + url.QueryEscape(c.Workdir+"..") + "\">..</a>]")
|
||||
b.WriteString("</td><td></td><td></td></tr>\n")
|
||||
}
|
||||
for _, e := range entries {
|
||||
icon := ""
|
||||
if icons {
|
||||
if e.Directory {
|
||||
icon = img("/filetypes/_dir.gif")
|
||||
} else {
|
||||
icon = img(t.ftpIcon(e.Name))
|
||||
}
|
||||
}
|
||||
b.WriteString("<tr><td>")
|
||||
switch {
|
||||
case e.Directory && !e.Link:
|
||||
b.WriteString(icon + "[<a href=\"/!ftp/?client=" + sid + "&task=listdir&cwd=" + url.QueryEscape(c.Workdir+e.Name) + "\">" + e.Name + "</a>]")
|
||||
case e.Link:
|
||||
if icons {
|
||||
b.WriteString(img("/filetypes/_link.gif"))
|
||||
}
|
||||
if e.Directory {
|
||||
b.WriteString("<i>[" + e.Name + "]</i>")
|
||||
} else {
|
||||
b.WriteString("<i>" + e.Name + "</i>")
|
||||
}
|
||||
default:
|
||||
b.WriteString(icon + "<a href=\"/!ftp/?client=" + sid + "&task=retr&name=" + url.QueryEscape(c.Workdir+e.Name) + "\" target='_blank'>" + e.Name + "</a>")
|
||||
}
|
||||
b.WriteString("</td><td>" + strconv.FormatInt(e.Size, 10) + "</td><td>" + e.Date + "</td></tr>\n")
|
||||
}
|
||||
b.WriteString("\n</table><br>\n<table class=\"nostyle\" border=\"0\"><tr class=\"nostyle\"><td class=\"nostyle\" width=\"100%\">")
|
||||
uri := "ftp://"
|
||||
if c.User != "anonymous" {
|
||||
uri += c.User + ":" + c.Pass + "@"
|
||||
}
|
||||
uri += c.Server
|
||||
if c.Port != 21 {
|
||||
uri += ":" + strconv.Itoa(c.Port)
|
||||
}
|
||||
uri += strings.ReplaceAll(c.Workdir, "//", "/")
|
||||
b.WriteString("<a href=\"/!ftp/?client=-1&uri=" + url.QueryEscape(uri) + "\" title=\"Files from " + c.Server + "\">Permanent link</a> ")
|
||||
b.WriteString("(<a href=\"" + uri + "\" title=\"" + uri + "\">direct</a>).</td>\n")
|
||||
b.WriteString("<td class=\"nostyle\"><a href=\"/!ftp/?client=" + sid + "&task=close\" title=\"End this FTP session\">Disconnect</a>.</td>\n</tr></table>")
|
||||
p.Content += b.String()
|
||||
return p
|
||||
|
||||
case "retr":
|
||||
name := args.Get("name")
|
||||
if name == "" {
|
||||
p.Content += "<h2>Nothing to download</h2><p><a href=\"/!ftp/?client=" + sid + "&task=listdir\">Click here</a> to see directory listing.</p>"
|
||||
return p
|
||||
}
|
||||
r := c.command("TYPE I")
|
||||
if r.Code != 200 {
|
||||
p.Content += "<p><b>Cannot set BINARY mode:</b> " + r.String() + "</p>" + again
|
||||
return p
|
||||
}
|
||||
if r = c.command("PASV"); r.Code != 227 {
|
||||
p.Content += "<p><b>Cannot prepare data connection:</b> " + r.String() + "</p>" + again
|
||||
return p
|
||||
}
|
||||
data, err := c.pasvData(d, r.Result)
|
||||
if err != nil {
|
||||
p.Content += "<p><b>Cannot establish data connection:</b> " + r.String() + "</p>" + again
|
||||
return p
|
||||
}
|
||||
if r = c.command("RETR " + name); r.Code != 150 && r.Code != 125 {
|
||||
c.closeData()
|
||||
p.Content += "<p><b>Cannot download the file:</b> " + r.String() + "</p>"
|
||||
return p
|
||||
}
|
||||
ct := "application/octet-stream"
|
||||
lower := strings.ToLower(name)
|
||||
for ext, mt := range t.cfg.MimeTypes {
|
||||
if strings.HasSuffix(lower, "."+ext) {
|
||||
ct = mt
|
||||
break
|
||||
}
|
||||
}
|
||||
base := name[strings.LastIndexByte(name, '/')+1:]
|
||||
if ct == "application/octet-stream" {
|
||||
p.Headers.Add("Content-Disposition", `attachment; filename="`+base+`"`)
|
||||
} else {
|
||||
p.Headers.Add("Content-Disposition", `inline; filename="`+base+`"`)
|
||||
}
|
||||
p.AttachmentType = ct
|
||||
// the session stays locked until the file is sent
|
||||
unlock = false
|
||||
p.Attachment = &ftpDownload{Conn: data, c: c, log: t.log}
|
||||
return p
|
||||
|
||||
case "close":
|
||||
c.close()
|
||||
p.Content = "<h2>Disconnected from the server</h2>\n<p>The file transfer session has been ended.</p>\n<p>Return to <a href=\"/!ftp/\"><b>connection page</b></a>.</p>"
|
||||
return p
|
||||
}
|
||||
p.Content = "<h2>No or unknown task</h2><p>The specified <i>task</i> argument is not recognized by WebOne.</p>" +
|
||||
"<p><a href=\"/!ftp/?client=" + sid + "&task=listdir\">Click here</a> to see directory listing.</p>"
|
||||
return p
|
||||
}
|
||||
|
||||
// ftpDownload is a file being downloaded; closing it reads the server's
|
||||
// "transfer complete" and frees the session.
|
||||
type ftpDownload struct {
|
||||
net.Conn
|
||||
c *ftpClient
|
||||
log logger
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (f *ftpDownload) Close() error {
|
||||
f.once.Do(func() {
|
||||
f.c.closeData()
|
||||
f.c.reply()
|
||||
f.log.Printf(" Close data stream.")
|
||||
f.c.mu.Unlock()
|
||||
})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Header is an ordered list of HTTP headers, looked up ignoring case, as
|
||||
// WebOne's WebHeaderCollection is used.
|
||||
type Header struct {
|
||||
kv []hkv
|
||||
}
|
||||
|
||||
type hkv struct{ k, v string }
|
||||
|
||||
// NewHeader is an empty header list.
|
||||
func NewHeader() *Header { return &Header{} }
|
||||
|
||||
// Get is a header's value; several of one name are joined with ", ".
|
||||
// "" when absent.
|
||||
func (h *Header) Get(k string) string {
|
||||
var vals []string
|
||||
for _, e := range h.kv {
|
||||
if strings.EqualFold(e.k, k) {
|
||||
vals = append(vals, e.v)
|
||||
}
|
||||
}
|
||||
return strings.Join(vals, ", ")
|
||||
}
|
||||
|
||||
// Values is every value of a header.
|
||||
func (h *Header) Values(k string) []string {
|
||||
var vals []string
|
||||
for _, e := range h.kv {
|
||||
if strings.EqualFold(e.k, k) {
|
||||
vals = append(vals, e.v)
|
||||
}
|
||||
}
|
||||
return vals
|
||||
}
|
||||
|
||||
// Has: the header is present.
|
||||
func (h *Header) Has(k string) bool {
|
||||
for _, e := range h.kv {
|
||||
if strings.EqualFold(e.k, k) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Add appends a header line.
|
||||
func (h *Header) Add(k, v string) { h.kv = append(h.kv, hkv{k, v}) }
|
||||
|
||||
// AddLine appends a "Name: value" line.
|
||||
func (h *Header) AddLine(line string) {
|
||||
k, v, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.Add(strings.TrimSpace(k), strings.TrimLeft(v, " "))
|
||||
}
|
||||
|
||||
// Set replaces a header's values with one (keeping its place).
|
||||
func (h *Header) Set(k, v string) {
|
||||
for i, e := range h.kv {
|
||||
if strings.EqualFold(e.k, k) {
|
||||
h.kv[i].v = v
|
||||
h.delFrom(k, i+1)
|
||||
return
|
||||
}
|
||||
}
|
||||
h.Add(k, v)
|
||||
}
|
||||
|
||||
func (h *Header) delFrom(k string, from int) {
|
||||
out := h.kv[:from]
|
||||
for _, e := range h.kv[from:] {
|
||||
if !strings.EqualFold(e.k, k) {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
h.kv = out
|
||||
}
|
||||
|
||||
// Del removes a header.
|
||||
func (h *Header) Del(k string) { h.delFrom(k, 0) }
|
||||
|
||||
// Keys is each header name once, in order.
|
||||
func (h *Header) Keys() []string {
|
||||
var keys []string
|
||||
seen := map[string]bool{}
|
||||
for _, e := range h.kv {
|
||||
lk := strings.ToLower(e.k)
|
||||
if !seen[lk] {
|
||||
seen[lk] = true
|
||||
keys = append(keys, e.k)
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// Each calls fn for each header line.
|
||||
func (h *Header) Each(fn func(k, v string)) {
|
||||
for _, e := range h.kv {
|
||||
fn(e.k, e.v)
|
||||
}
|
||||
}
|
||||
|
||||
// Map replaces each value with fn's.
|
||||
func (h *Header) Map(fn func(k, v string) string) {
|
||||
for i, e := range h.kv {
|
||||
h.kv[i].v = fn(e.k, e.v)
|
||||
}
|
||||
}
|
||||
|
||||
// Clone copies the list.
|
||||
func (h *Header) Clone() *Header { return &Header{kv: append([]hkv(nil), h.kv...)} }
|
||||
|
||||
// Len is the number of lines.
|
||||
func (h *Header) Len() int { return len(h.kv) }
|
||||
|
||||
// String renders the lines as on the wire, each ending in CRLF.
|
||||
func (h *Header) String() string {
|
||||
var b strings.Builder
|
||||
for _, e := range h.kv {
|
||||
b.WriteString(e.k)
|
||||
b.WriteString(": ")
|
||||
b.WriteString(e.v)
|
||||
b.WriteString("\r\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// FromHTTP is a header list of an http.Header (names sorted).
|
||||
func FromHTTP(hh http.Header) *Header {
|
||||
h := NewHeader()
|
||||
keys := make([]string, 0, len(hh))
|
||||
for k := range hh {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
for _, v := range hh[k] {
|
||||
h.Add(k, v)
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/config"
|
||||
)
|
||||
|
||||
// Kind is how a request names its target (HttpUtil.RequestKind).
|
||||
//
|
||||
// GET /123, Host: example.com -> http://example.com/123 StandardRemote
|
||||
// GET /123, Host: (the proxy) -> the proxy's own page StandardHttp
|
||||
// GET /http://example.com/123 -> http://example.com/123 AlternateProxy
|
||||
// GET http://example.com/123 -> http://example.com/123 StandardProxy
|
||||
// GET ftp://example.com/pub -> ftp://example.com/pub StandardProxy
|
||||
// CONNECT example.com:443 -> (a tunnel) StandardSslProxy
|
||||
type Kind int
|
||||
|
||||
const (
|
||||
StandardRemote Kind = iota
|
||||
StandardHttp
|
||||
AlternateProxy
|
||||
DirtyAlternateProxy
|
||||
StandardProxy
|
||||
StandardSslProxy
|
||||
)
|
||||
|
||||
func (k Kind) String() string {
|
||||
return [...]string{"StandardRemote", "StandardHttp", "AlternateProxy", "DirtyAlternateProxy", "StandardProxy", "StandardSslProxy"}[k]
|
||||
}
|
||||
|
||||
// kindOf works out a request's Kind (HttpUtil.GetKindOfRequest).
|
||||
func (s *Server) kindOf(rawURL, hostHeader string, isConnect bool) (Kind, error) {
|
||||
host := hostHeader
|
||||
if host == "" {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
port := 80
|
||||
if !strings.HasPrefix(host, "/") && strings.Contains(host, ":") && !strings.HasSuffix(host, "]") {
|
||||
i := strings.LastIndexByte(host, ':')
|
||||
if p, err := strconv.Atoi(host[i+1:]); err == nil {
|
||||
port = p
|
||||
}
|
||||
host = host[:i]
|
||||
}
|
||||
lower := strings.ToLower(rawURL)
|
||||
if strings.HasPrefix(rawURL, "/") {
|
||||
if s.isLocalhost(host, port) {
|
||||
if strings.HasPrefix(lower, "/http:") || strings.HasPrefix(lower, "/https:") || strings.HasPrefix(lower, "/ftp:") {
|
||||
return AlternateProxy, nil
|
||||
}
|
||||
// (WebOne's DirtyAlternateProxy test never succeeds; it is not ported.)
|
||||
return StandardHttp, nil
|
||||
}
|
||||
return StandardRemote, nil
|
||||
}
|
||||
self := "http://" + host + ":" + strconv.Itoa(port) + "/"
|
||||
if strings.HasPrefix(rawURL, self) && strings.Contains(rawURL[len(self):], ":") {
|
||||
return AlternateProxy, nil
|
||||
}
|
||||
if s.isLocalhost(host, port) {
|
||||
return StandardHttp, nil
|
||||
}
|
||||
if strings.Contains(rawURL, "://") {
|
||||
return StandardProxy, nil
|
||||
}
|
||||
if isConnect {
|
||||
return StandardSslProxy, nil
|
||||
}
|
||||
return 0, errors.New("cannot guess kind of requested target")
|
||||
}
|
||||
|
||||
// isLocalhost: host:port is this proxy.
|
||||
func (s *Server) isLocalhost(host string, port int) bool {
|
||||
if port != s.cfg.Port {
|
||||
return false
|
||||
}
|
||||
h := strings.ToLower(host)
|
||||
for _, n := range s.localHostNames() {
|
||||
if strings.Contains(h, strings.ToLower(n)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// localHostNames is the names and addresses the proxy answers to.
|
||||
func (s *Server) localHostNames() []string {
|
||||
var names []string
|
||||
for _, ip := range config.LocalIPs() {
|
||||
if ip.To4() == nil {
|
||||
names = append(names, "["+ip.String()+"]")
|
||||
} else {
|
||||
names = append(names, ip.String())
|
||||
}
|
||||
}
|
||||
host, _ := os.Hostname()
|
||||
names = append(names, "wpad", "localhost", host, s.cfg.DefaultHostName)
|
||||
names = append(names, s.cfg.HostNames...)
|
||||
var out []string
|
||||
for _, n := range names {
|
||||
if n != "" {
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/config"
|
||||
"github.com/D-Modem/webone-go/internal/textenc"
|
||||
)
|
||||
|
||||
// infoPage is one of the proxy's own HTML pages (InfoPage.cs).
|
||||
type infoPage struct {
|
||||
Title, Header, Content string
|
||||
Status int
|
||||
Headers *Header
|
||||
HTMLHeaders string
|
||||
ShowFooter bool
|
||||
Attachment io.ReadCloser
|
||||
AttachmentType string
|
||||
}
|
||||
|
||||
func newInfoPage(title, header, content string, status int) *infoPage {
|
||||
if content == "" {
|
||||
content = "No description is available."
|
||||
}
|
||||
return &infoPage{Title: title, Header: header, Content: content, Status: status, Headers: NewHeader(), ShowFooter: true}
|
||||
}
|
||||
|
||||
// outEnc is the code page the proxy's own pages are sent in.
|
||||
func (t *transit) outEnc() *textenc.Encoding {
|
||||
if t.outputEncoding != nil {
|
||||
return t.outputEncoding
|
||||
}
|
||||
return textenc.UTF8
|
||||
}
|
||||
|
||||
// sendBytes sends a complete response.
|
||||
func (t *transit) sendBytes(status int, contentType string, body []byte) {
|
||||
w := t.resp
|
||||
w.Status = status
|
||||
if contentType != "" {
|
||||
w.SetContentType(contentType)
|
||||
}
|
||||
w.SetContentLength(int64(len(body)))
|
||||
if err := w.SendHeaders(Version); err != nil {
|
||||
t.clientError(err)
|
||||
return
|
||||
}
|
||||
if t.req.Method != "HEAD" {
|
||||
if _, err := w.Write(body); err != nil {
|
||||
t.clientError(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sendError sends a short error page (HttpTransit.SendError).
|
||||
func (t *transit) sendError(code int, text string) {
|
||||
if t.resp.HeadersSent {
|
||||
t.log.Printf("<!Not returned code %d. Response is in process of sending.", code)
|
||||
t.resp.KeepAlive = false
|
||||
return
|
||||
}
|
||||
t.log.Printf("<Return code %d.", code)
|
||||
text += t.s.infoString()
|
||||
head := ""
|
||||
if r := t.resp.Header.Get("Refresh"); r != "" {
|
||||
head = `<META HTTP-EQUIV="REFRESH" CONTENT="` + r + `">`
|
||||
}
|
||||
enc := t.outEnc()
|
||||
head += `<META CHARSET="` + enc.Name + `">`
|
||||
html := "<HTML>" + head + "<BODY><H1>" + strconv.Itoa(code) + " " + StatusName(code) + "</H1>" + text + "</BODY></HTML>"
|
||||
t.sendBytes(code, "text/html", enc.Encode(html))
|
||||
t.dump("End is internal page: code " + strconv.Itoa(code) + ", " + text)
|
||||
}
|
||||
|
||||
// sendRedirect sends a 302 to url (HttpTransit.SendRedirect).
|
||||
func (t *transit) sendRedirect(u, message string) {
|
||||
target := u
|
||||
if t.req.Secure && strings.HasPrefix(target, "http://") {
|
||||
target = "https://" + target[len("http://"):]
|
||||
}
|
||||
if strings.HasPrefix(target, "//") {
|
||||
if t.req.Secure {
|
||||
target = "https:" + target
|
||||
} else {
|
||||
target = "http:" + target
|
||||
}
|
||||
}
|
||||
t.log.Printf("<Return redirect.")
|
||||
html := `<HTML><HEAD><META HTTP-EQUIV="REFRESH" CONTENT="` + target + `"><TITLE>WebOne: redirect by proxy</TITLE></HEAD><BODY>`
|
||||
if message != "" {
|
||||
html += "<P>" + message + "</P>"
|
||||
}
|
||||
html += `<P>Please navigate your browser to <A HREF="` + target + `">` + target + "</A>.</P>" + t.s.infoString() + "</BODY></HTML>"
|
||||
t.resp.AddHeader("Location", target)
|
||||
t.sendBytes(302, "text/html", t.outEnc().Encode(html))
|
||||
t.dump("End is 302 to " + target)
|
||||
}
|
||||
|
||||
// sendInfoPage sends an information page.
|
||||
func (t *transit) sendInfoPage(title, header, content string, status int) {
|
||||
t.sendInfo(newInfoPage(title, header, content, status))
|
||||
}
|
||||
|
||||
func (t *transit) sendInfo(p *infoPage) {
|
||||
p.Headers.Each(func(k, v string) {
|
||||
if !strings.EqualFold(k, "Content-Type") {
|
||||
t.resp.AddHeader(k, v)
|
||||
}
|
||||
})
|
||||
if p.Attachment != nil {
|
||||
ct := p.AttachmentType
|
||||
if ct == "" {
|
||||
ct = p.Headers.Get("Content-Type")
|
||||
}
|
||||
t.sendStream(p.Attachment, ct, -1, p.Status)
|
||||
return
|
||||
}
|
||||
t.log.Printf("<Return information page: %s.", p.Title)
|
||||
if p.ShowFooter && fileExists(filepath.Join(t.cfg.ContentDirectory, "InfoPage.htm")) {
|
||||
args := "?Title=" + url.QueryEscape(p.Title) + "&Header=" + url.QueryEscape(p.Header) + "&Content=" + url.QueryEscape(p.Content)
|
||||
if ct := p.Headers.Get("Content-Type"); ct != "" {
|
||||
t.resp.SetContentType(ct)
|
||||
}
|
||||
if t.sendInternalContent("InfoPage.htm", args, p.Status) {
|
||||
return
|
||||
}
|
||||
}
|
||||
enc := t.outEnc()
|
||||
title := "<title>WebOne: untitled</title>"
|
||||
if p.Title != "" {
|
||||
title = "<title>" + p.Title + "</title>\n"
|
||||
}
|
||||
h1 := ""
|
||||
if p.Header != "" {
|
||||
h1 = "<h1>" + p.Header + "</h1>\n"
|
||||
}
|
||||
footer := ""
|
||||
if p.ShowFooter {
|
||||
footer = t.s.infoString() + "\n"
|
||||
}
|
||||
html := "<html>\n" + title + `<meta charset="` + enc.Name + `"/>` + "\n" + p.HTMLHeaders + "<body>\n" + h1 + "\n" + p.Content + "\n" + footer + "</body>\n</html>"
|
||||
ct := p.Headers.Get("Content-Type")
|
||||
if ct == "" {
|
||||
ct = "text/html"
|
||||
}
|
||||
t.sendBytes(p.Status, ct, enc.Encode(html))
|
||||
t.dump("End is information page: " + p.Header)
|
||||
}
|
||||
|
||||
// sendStream sends a stream (length -1 if unknown).
|
||||
func (t *transit) sendStream(r io.ReadCloser, contentType string, length int64, status int) {
|
||||
defer r.Close()
|
||||
if length >= 0 {
|
||||
t.log.Printf("<Send stream with %dK of %s.", length/1024, contentType)
|
||||
} else {
|
||||
t.log.Printf("<Send %s stream.", contentType)
|
||||
}
|
||||
w := t.resp
|
||||
if status == 0 {
|
||||
status = 200
|
||||
}
|
||||
w.Status = status
|
||||
w.SetContentType(contentType)
|
||||
w.SetContentLength(length)
|
||||
if err := w.SendHeaders(Version); err != nil {
|
||||
t.clientError(err)
|
||||
return
|
||||
}
|
||||
if _, err := io.Copy(w, r); err != nil {
|
||||
t.log.Printf("<Stream closed: %v", err)
|
||||
w.KeepAlive = false
|
||||
}
|
||||
t.dump("End is stream of " + contentType)
|
||||
}
|
||||
|
||||
// sendFile sends a file.
|
||||
func (t *transit) sendFile(name, contentType, downloadName string) {
|
||||
t.log.Printf("<Send file %s.", name)
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
code := 500
|
||||
if os.IsNotExist(err) {
|
||||
code = 404
|
||||
}
|
||||
t.sendError(code, "Cannot open the file <i>"+name+"</i>.<br>"+err.Error())
|
||||
return
|
||||
}
|
||||
st, _ := f.Stat()
|
||||
if downloadName != "" {
|
||||
t.resp.AddHeader("Content-Disposition", `attachment; filename="`+downloadName+`"`)
|
||||
}
|
||||
t.sendStream(f, contentType, st.Size(), 200)
|
||||
}
|
||||
|
||||
func fileExists(p string) bool {
|
||||
st, err := os.Stat(p)
|
||||
return err == nil && !st.IsDir()
|
||||
}
|
||||
|
||||
// contentPath is a file in the content directory, or "" when the id
|
||||
// tries to climb out of it.
|
||||
func (t *transit) contentPath(id string) string {
|
||||
if strings.Contains(id, "..") {
|
||||
return ""
|
||||
}
|
||||
id = strings.TrimLeft(strings.ReplaceAll(id, `\`, "/"), "/")
|
||||
return filepath.Join(t.cfg.ContentDirectory, filepath.FromSlash(id))
|
||||
}
|
||||
|
||||
// parseQueryString reads "?a=b&c=d" as WebOne does: names trimmed of "?"
|
||||
// and spaces, values URL-decoded.
|
||||
// qe escapes a value for an internal page's query string.
|
||||
func qe(s string) string { return url.QueryEscape(s) }
|
||||
|
||||
func parseQueryString(q string) *config.Vars {
|
||||
v := config.NewVars()
|
||||
if strings.TrimSpace(q) == "" {
|
||||
return v
|
||||
}
|
||||
for _, seg := range strings.Split(q, "&") {
|
||||
k, val, ok := strings.Cut(seg, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
k = strings.Trim(k, "? ")
|
||||
if d, err := url.QueryUnescape(val); err == nil {
|
||||
val = d
|
||||
}
|
||||
v.TryAdd(k, strings.TrimSpace(val))
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// sendInternalContent sends a file of the content directory (html/),
|
||||
// expanding %variables% in text files with args and the server's figures.
|
||||
// false: there is no such file.
|
||||
func (t *transit) sendInternalContent(id, args string, status int) bool {
|
||||
if strings.Contains(id, "../") {
|
||||
t.sendError(403, "Please specify an absoulte path.")
|
||||
return true
|
||||
}
|
||||
path := t.contentPath(id)
|
||||
if path == "" || !fileExists(path) {
|
||||
t.log.Printf("Cannot find the file: %s.", filepath.Join(t.cfg.ContentDirectory, id))
|
||||
return false
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(path))
|
||||
ext = strings.TrimPrefix(ext, ".")
|
||||
mime := "application/octet-stream"
|
||||
if m, ok := t.cfg.MimeTypes[ext]; ok {
|
||||
mime = m
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
t.resp.SetVersion(1, 1)
|
||||
if strings.TrimSpace(args) == "" {
|
||||
t.resp.AddHeader("Expires", time.Now().AddDate(0, 0, 30).UTC().Format(http.TimeFormat))
|
||||
}
|
||||
if containsAny(mime, t.cfg.TextTypes) {
|
||||
sub := parseQueryString(args)
|
||||
sub.Set("ServerName", t.serverName())
|
||||
sub.Set("OpenedConnections", strconv.FormatInt(t.s.opened.Load(), 10))
|
||||
sub.Set("BusyConnections", strconv.FormatInt(t.s.busy.Load(), 10))
|
||||
sub.Set("UsedMemory", strconv.Itoa(usedMemoryMB()))
|
||||
sub.Set("ClientIP", t.req.Remote.String())
|
||||
text := string(data)
|
||||
text = strings.TrimPrefix(text, "\uFEFF")
|
||||
text = t.cfg.Expand(text, sub)
|
||||
t.sendBytes(status, mime, t.outEnc().Encode(text))
|
||||
return true
|
||||
}
|
||||
t.sendBytes(status, mime, data)
|
||||
return true
|
||||
}
|
||||
|
||||
// notModified: the client's copy of a content file is current.
|
||||
func (t *transit) notModified(id, ims string) bool {
|
||||
if strings.TrimSpace(ims) == "" {
|
||||
return false
|
||||
}
|
||||
path := t.contentPath(id)
|
||||
st, err := os.Stat(path)
|
||||
if path == "" || err != nil {
|
||||
return false
|
||||
}
|
||||
when, err := http.ParseTime(ims)
|
||||
if err != nil {
|
||||
if w2, err2 := config.ParseDate(ims); err2 == nil {
|
||||
when = w2
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return !when.Before(st.ModTime().Truncate(time.Second))
|
||||
}
|
||||
|
||||
// sendInternalPage serves the proxy's own URLs (HttpTransit.SendInternalPage).
|
||||
func (t *transit) sendInternalPage(page, query string) {
|
||||
t.log.Printf(" Internal page: %s ", page)
|
||||
q := ""
|
||||
if query != "" {
|
||||
q = "?" + query
|
||||
}
|
||||
switch page {
|
||||
case "", "/", "/!", "/!/":
|
||||
t.sendStatusPage()
|
||||
case "/!codepages":
|
||||
t.sendCodepages()
|
||||
case "/!img-test":
|
||||
if t.cfg.EnableManualConverting {
|
||||
t.sendError(200, `ImageMagick test.<br><img src="/!convert/?src=logo.webp&dest=gif&type=image/gif" alt="ImageMagick logo" width=640 height=480><br>A wizard should appear nearby.`)
|
||||
} else {
|
||||
t.sendError(200, `ImageMagick test.<br><img src="/!imagemagicktest.gif" alt="ImageMagick logo" width=640 height=480><br>A wizard should appear nearby.`)
|
||||
}
|
||||
case "/!imagemagicktest.gif":
|
||||
t.imageMagickTest()
|
||||
case "/!convert":
|
||||
t.manualConvert(query)
|
||||
case "/!webvideo":
|
||||
t.webVideo(query)
|
||||
case "/!player":
|
||||
t.sendInfo(t.videoPlayerPage(query))
|
||||
case "/!clear":
|
||||
n := 0
|
||||
files, _ := filepath.Glob(filepath.Join(t.cfg.TemporaryDirectory, "convert-*.*"))
|
||||
for _, f := range files {
|
||||
if os.Remove(f) == nil {
|
||||
n++
|
||||
}
|
||||
}
|
||||
t.sendError(200, "<b>"+strconv.Itoa(n)+"</b> temporary files have been deleted in <i>"+t.cfg.TemporaryDirectory+"</i>.")
|
||||
case "/!ftp":
|
||||
t.sendInfo(t.ftpPage())
|
||||
case "/!redirect":
|
||||
t.sendInfo(t.redirectorPage(query))
|
||||
case "/!ca", "/weboneca.crt", "/weboneca.cer", "/weboneca.der":
|
||||
t.log.Printf("<Return WebOne CA (root) certificate.")
|
||||
if !t.cfg.SslEnable || t.s.RootCA == nil {
|
||||
t.sendError(404, "SSL and TLS are disabled. Use <i>http://</i> URL protocol to access any <i>https://</i> websites.")
|
||||
return
|
||||
}
|
||||
t.resp.AddHeader("Content-Disposition", `attachment; filename="WebOneCA.crt"`)
|
||||
t.sendBytes(200, "application/x-x509-ca-cert", t.s.RootCA.DER())
|
||||
case "/weboneca.pem", "/weboneca.txt":
|
||||
t.log.Printf("<Return WebOne CA (root) certificate in PEM format.")
|
||||
if !t.cfg.SslEnable || t.s.RootCA == nil {
|
||||
t.sendError(404, "SSL and TLS are disabled. Use <i>http://</i> URL protocol to access any <i>https://</i> websites.")
|
||||
return
|
||||
}
|
||||
p := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: t.s.RootCA.DER()})
|
||||
t.resp.AddHeader("Content-Disposition", `attachment; filename="WebOneCA.crt"`)
|
||||
t.sendBytes(200, "application/x-x509-ca-cert", p)
|
||||
case "/!pac", "/auto", "/auto.pac", "/wpad.dat", "/wpad.da":
|
||||
t.log.Printf("<Return PAC/WPAD script.")
|
||||
host := t.serverName()
|
||||
if strings.HasPrefix(host, "[") {
|
||||
host = t.cfg.DefaultHostName + ":" + strconv.Itoa(t.cfg.Port)
|
||||
}
|
||||
t.sendBytes(200, "application/x-ns-proxy-autoconfig", []byte(t.s.pac(host)))
|
||||
case "/robots.txt":
|
||||
t.log.Printf("<Return robot kicker.")
|
||||
if t.sendInternalContent("robots.txt", "", 200) {
|
||||
return
|
||||
}
|
||||
t.sendBytes(200, "text/plain", []byte("User-agent: *\nDisallow: / "))
|
||||
default:
|
||||
if page == "/rovp.htm" && !t.videoEnabled() {
|
||||
t.sendRedirect("/norovp.htm", "ROVP is disabled on this server.")
|
||||
return
|
||||
}
|
||||
if t.notModified(page, t.req.Header.Get("If-Modified-Since")) {
|
||||
t.resp.Status = 304
|
||||
t.resp.SetContentLength(0)
|
||||
t.resp.SendHeaders(Version)
|
||||
return
|
||||
}
|
||||
if t.sendInternalContent(page, q, 200) {
|
||||
return
|
||||
}
|
||||
msg := "<p>The page you are viewing does not exist.</p>" +
|
||||
"<p>If you think we brought you here on purpose by posting a wrong link, send us that link via GitHub.</p>" +
|
||||
"<p>And if you really want to find something on the Internet, specify IP of the WebOne server in your browser's proxy server settings.</p>" +
|
||||
"<pre>" + page + "</pre>"
|
||||
t.sendInfoPage("WebOne: 404", "404 - there's no page.", msg, 404)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *transit) sendCodepages() {
|
||||
var b strings.Builder
|
||||
b.WriteString("<p>The following code pages are available: <br>\n<table><tr><td><b>Name</b></td><td><b>#</b></td><td><b>Description</b></td></tr>\n")
|
||||
b.WriteString("<tr><td><b>AsIs</b></td><td>0</td><td>Keep original encoding (code page)</td></tr>\n")
|
||||
listed := false
|
||||
for _, e := range textenc.All() {
|
||||
fmt.Fprintf(&b, "<tr><td><b>%s</b></td><td>%d</td><td>%s", e.Name, e.CodePage, e.Display)
|
||||
if t.cfg.OutputEncoding != nil && e.CodePage == t.cfg.OutputEncoding.CodePage {
|
||||
b.WriteString(" <b>(Current)</b>")
|
||||
listed = true
|
||||
}
|
||||
b.WriteString("</td></tr>\n")
|
||||
}
|
||||
b.WriteString("</table><br>Use any of these names or numbers.</p>\n")
|
||||
name := func(cp string) string {
|
||||
if e := t.cfg.CodePage(cp); e != nil {
|
||||
return e.Name
|
||||
}
|
||||
return "?"
|
||||
}
|
||||
b.WriteString("<p>Code pages for current server's locale:\n<table>" +
|
||||
"<tr><td>Windows "ANSI"</td><td>" + name("Win") + "</td></tr>\n" +
|
||||
"<tr><td>DOS "OEM"</td><td>" + name("DOS") + "</td></tr>\n" +
|
||||
"<tr><td>MacOS classic</td><td>" + name("Mac") + "</td></tr>\n" +
|
||||
"<tr><td>ISO</td><td>" + name("ISO") + "</td></tr>\n" +
|
||||
"<tr><td>EBCDIC</td><td>" + name("EBCDIC") + "</td></tr>\n" +
|
||||
"</table>Clients without UTF-8 support will got content in these code pages.</p>\n")
|
||||
if t.cfg.OutputEncoding == nil {
|
||||
b.WriteString("<br>Current output encoding: <b>same as source</b>.\n")
|
||||
} else if !listed {
|
||||
fmt.Fprintf(&b, "<br>Current output encoding: <b>%s</b> "%s" (# %d).\n", t.cfg.OutputEncoding.Name, t.cfg.OutputEncoding.Display, t.cfg.OutputEncoding.CodePage)
|
||||
}
|
||||
t.sendInfoPage("WebOne: List of supported code pages", "Content encodings", b.String(), 200)
|
||||
}
|
||||
|
||||
// sendStatusPage is the proxy's home page (HttpTransit.SendInternalStatusPage).
|
||||
func (t *transit) sendStatusPage() {
|
||||
var h strings.Builder
|
||||
opened, busy := t.s.opened.Load(), t.s.busy.Load()
|
||||
switch t.cfg.DisplayStatusPage {
|
||||
case "no":
|
||||
t.sendInfoPage("WebOne status page", "Sorry", "<p>The status page is disabled by server administrator.</p>", 200)
|
||||
return
|
||||
case "short":
|
||||
fmt.Fprintf(&h, "<p>This is <b>%s</b>.<br>", t.serverName())
|
||||
fmt.Fprintf(&h, "Connections open: <b>%d</b> (<b>%d</b> active).<br>", opened, busy)
|
||||
fmt.Fprintf(&h, "Used memory: <b>%d</b> MB.<br>", usedMemoryMB())
|
||||
h.WriteString(`About: <a href="https://github.com/atauenis/webone/">https://github.com/atauenis/webone/</a> (Go port: <a href="https://github.com/D-Modem/webone-go">https://github.com/D-Modem/webone-go</a>)</p>`)
|
||||
fmt.Fprintf(&h, "<p>Client IP: <b>%s</b>.</p>", t.req.Remote)
|
||||
h.WriteString("<h2>May be useful:</h2><ul>")
|
||||
h.WriteString(`<li><a href="/auto.pac">Proxy auto-configuration file</a>: /!pac/, /auto/, /auto, /auto.pac, /wpad.dat.</li>`)
|
||||
h.WriteString(`<li><a href="/!ca">WebOne CA root certificate</a>.</li>`)
|
||||
h.WriteString(`<li><a href="/!ftp/">Web-based FTP client</a>.</li>`)
|
||||
h.WriteString(`<li><a href="/!player/">Online video player</a>.</li>`)
|
||||
h.WriteString("</ul>")
|
||||
case "full":
|
||||
host, _ := os.Hostname()
|
||||
fmt.Fprintf(&h, "This is <b>%s:%d</b>.<br>", host, t.cfg.Port)
|
||||
fmt.Fprintf(&h, "Used memory: <b>%d</b> MB.<br>", usedMemoryMB())
|
||||
fmt.Fprintf(&h, "Connections open: <b>%d</b> (<b>%d</b> active).<br>", opened, busy)
|
||||
h.WriteString("<h2>Aliases:</h2><ul>")
|
||||
evident := false
|
||||
for _, ip := range config.LocalIPs() {
|
||||
a := ip.String()
|
||||
if a == t.cfg.DefaultHostName {
|
||||
evident = true
|
||||
a = "<b>" + a + "</b>"
|
||||
}
|
||||
fmt.Fprintf(&h, "<li>%s:%d</li>", a, t.cfg.Port)
|
||||
}
|
||||
if !evident {
|
||||
fmt.Fprintf(&h, "<li><b>%s</b>:%d</li>", t.cfg.DefaultHostName, t.cfg.Port)
|
||||
}
|
||||
h.WriteString("</ul>")
|
||||
fmt.Fprintf(&h, "<p>Client IP: <b>%s</b>.</p>", t.req.Remote)
|
||||
h.WriteString("<h2>Internal URLs:</h2><ul>" +
|
||||
`<li><a href="/!codepages/">/!codepages/</a> - list of available encodings for OutputEncoding setting</li>` +
|
||||
`<li><a href="/!img-test/">/!img-test/</a> - test if ImageMagick is working</li>` +
|
||||
`<li><a href="/!convert/">/!convert/</a> - run a file format converter (<a href="/!convert/?src=logo.webp&dest=gif&type=image/gif">demo</a>)</li>` +
|
||||
`<li><a href="/!clear/">/!clear/</a> - remove temporary files in WebOne working directory</li>` +
|
||||
`<li><a href="/auto.pac">Proxy auto-configuration file</a>: /!pac/, /auto/, /auto, /auto.pac, /wpad.dat.</li>` +
|
||||
`<li><a href="/!ca">/!ca/</a> - WebOne CA root certificate.</li>` +
|
||||
`<li><a href="/!ftp/">/!ftp/</a> - Web-based FTP client.</li>` +
|
||||
`<li><a href="/!player/">/!player/</a> - online video player.</li>` +
|
||||
`<li><a href="/!webvideo/">/!webvideo/</a> - online video downloader.</li>` +
|
||||
"</ul>")
|
||||
default:
|
||||
if t.sendInternalContent(t.cfg.DisplayStatusPage, "", 200) {
|
||||
return
|
||||
}
|
||||
h.WriteString("<h2>It works!</h2>")
|
||||
}
|
||||
h.WriteString("<h2>Headers sent by browser</h2><ul>")
|
||||
fmt.Fprintf(&h, "<li><b>%s %s HTTP/%s</b></li>", t.req.Method, t.req.RawURL, t.req.ProtoVersion())
|
||||
t.req.Header.Each(func(k, v string) { fmt.Fprintf(&h, "<li>%s: %s</li>", k, v) })
|
||||
h.WriteString("</ul>")
|
||||
t.sendInfoPage("WebOne status page", "", h.String(), 200)
|
||||
}
|
||||
|
||||
// osDescription is %WOSystem%.
|
||||
func osDescription() string {
|
||||
return runtime.GOOS + " " + runtime.GOARCH + " (" + runtime.Version() + ")"
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/certs"
|
||||
"github.com/D-Modem/webone-go/internal/config"
|
||||
"github.com/D-Modem/webone-go/internal/logx"
|
||||
)
|
||||
|
||||
// startProxy runs a proxy with the given configuration text; it returns
|
||||
// the proxy's address and the CA.
|
||||
func startProxy(t *testing.T, conf string) (string, *certs.CA) {
|
||||
t.Helper()
|
||||
logx.SetConsole(io.Discard)
|
||||
dir := t.TempDir()
|
||||
cfg := config.New()
|
||||
cfg.Vars.Set("WOVer", Version)
|
||||
cfg.Vars.Set("WOSystem", "test")
|
||||
cfg.LoadContent([]byte("[Server]\nUpperProxy=no\nSearchInArchive=no\nContentDirectory="+dir+"\n"+conf), "test.conf")
|
||||
if err := cfg.Process(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.ContentDirectory = dir
|
||||
crt, key := filepath.Join(dir, "ca.crt"), filepath.Join(dir, "ca.key")
|
||||
if err := certs.CreateCA(crt, key, "", "SHA256", time.Now().Add(-time.Hour), time.Now().AddDate(1, 0, 0)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ca, err := certs.LoadCA(crt, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Port = ln.Addr().(*net.TCPAddr).Port
|
||||
cfg.DefaultHostName = "127.0.0.1"
|
||||
cfg.SetProxyVars()
|
||||
cfg.PAC = config.DefaultPACHeader + config.DefaultPACHttp + config.DefaultPACFooter
|
||||
s, err := New(cfg, ca, ca)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go s.Serve(ln)
|
||||
t.Cleanup(s.Stop)
|
||||
return ln.Addr().String(), ca
|
||||
}
|
||||
|
||||
// rawGet sends a request by hand (as an old browser would) and returns the
|
||||
// whole reply.
|
||||
func rawGet(t *testing.T, addr, req string) string {
|
||||
t.Helper()
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
io.WriteString(c, req)
|
||||
b, _ := io.ReadAll(c)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestHTTP10ProxyEditsAndCodePage(t *testing.T) {
|
||||
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=1")
|
||||
fmt.Fprint(w, "<html><body>Hello, modern web! Привет</body></html>")
|
||||
}))
|
||||
defer site.Close()
|
||||
addr, _ := startProxy(t, "[Server]\nOutputEncoding=windows-1251\n[Edit:127.0.0.1]\nAddFind=modern\nAddReplace=old\n")
|
||||
reply := rawGet(t, addr, "GET "+site.URL+"/ HTTP/1.0\r\nUser-Agent: Mozilla/2.0\r\n\r\n")
|
||||
head, body, _ := strings.Cut(reply, "\r\n\r\n")
|
||||
if !strings.HasPrefix(head, "HTTP/1.0 200") {
|
||||
t.Fatalf("status: %q", head)
|
||||
}
|
||||
if strings.Contains(head, "Strict-Transport-Security") {
|
||||
t.Error("HSTS header passed to the client")
|
||||
}
|
||||
if strings.Contains(head, "Transfer-Encoding") {
|
||||
t.Error("chunked reply to an HTTP/1.0 client")
|
||||
}
|
||||
if !strings.Contains(body, "Hello, old web!") {
|
||||
t.Errorf("find/replace not done: %q", body)
|
||||
}
|
||||
if !strings.Contains(body, "\xcf\xf0\xe8\xe2\xe5\xf2") { // "Привет" in windows-1251
|
||||
t.Errorf("not in windows-1251: %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPSUpstreamAndAlternateMode(t *testing.T) {
|
||||
site := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
fmt.Fprintf(w, `<a href="https://%s/next">secure link</a>`, r.Host)
|
||||
}))
|
||||
defer site.Close()
|
||||
u, _ := url.Parse(site.URL)
|
||||
addr, _ := startProxy(t, "[Server]\nValidateCertificates=no\n[ForceHttps]\n127.0.0.1\n")
|
||||
|
||||
// the old browser asks for http://; the proxy fetches https:// and
|
||||
// gives the links back as http://
|
||||
reply := rawGet(t, addr, "GET http://"+u.Host+"/ HTTP/1.0\r\n\r\n")
|
||||
if !strings.Contains(reply, "200 OK") || !strings.Contains(reply, `href="http://`+u.Host+`/next"`) {
|
||||
t.Fatalf("reply: %q", reply)
|
||||
}
|
||||
// alternate mode: http://proxy/https://site/
|
||||
reply = rawGet(t, addr, "GET /"+site.URL+"/ HTTP/1.0\r\nHost: "+addr+"\r\n\r\n")
|
||||
if !strings.Contains(reply, "200 OK") || !strings.Contains(reply, "secure link") {
|
||||
t.Fatalf("alternate reply: %q", reply)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeepAliveAndChunked(t *testing.T) {
|
||||
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.(http.Flusher).Flush() // no length: chunked to the proxy
|
||||
w.Write([]byte(strings.Repeat("x", 5000)))
|
||||
}))
|
||||
defer site.Close()
|
||||
addr, _ := startProxy(t, "")
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
br := bufio.NewReader(c)
|
||||
for i := 0; i < 2; i++ {
|
||||
fmt.Fprintf(c, "GET %s/%d HTTP/1.1\r\nHost: %s\r\nConnection: keep-alive\r\n\r\n", site.URL, i, strings.TrimPrefix(site.URL, "http://"))
|
||||
resp, err := http.ReadResponse(br, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("request %d: %v", i, err)
|
||||
}
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if err != nil || len(b) != 5000 {
|
||||
t.Fatalf("request %d: %d bytes, %v", i, len(b), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInternalPages(t *testing.T) {
|
||||
addr, ca := startProxy(t, "")
|
||||
for _, p := range []string{"/", "/!codepages", "/auto.pac", "/!ca"} {
|
||||
reply := rawGet(t, addr, "GET "+p+" HTTP/1.0\r\nHost: "+addr+"\r\n\r\n")
|
||||
if !strings.HasPrefix(reply, "HTTP/1.0 200") {
|
||||
t.Errorf("%s: %q", p, reply[:min(len(reply), 200)])
|
||||
}
|
||||
}
|
||||
reply := rawGet(t, addr, "GET /!ca HTTP/1.0\r\nHost: "+addr+"\r\n\r\n")
|
||||
_, body, _ := strings.Cut(reply, "\r\n\r\n")
|
||||
if body != string(ca.DER()) {
|
||||
t.Error("/!ca is not the CA certificate")
|
||||
}
|
||||
reply = rawGet(t, addr, "HEAD /auto.pac HTTP/1.1\r\nHost: "+addr+"\r\nConnection: close\r\n\r\n")
|
||||
if _, body, _ := strings.Cut(reply, "\r\n\r\n"); body != "" {
|
||||
t.Errorf("HEAD reply has a body: %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectMITM(t *testing.T) {
|
||||
addr, ca := startProxy(t, "[SecureProxy]\nSslHashAlgorithm=SHA256\n")
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(20 * time.Second))
|
||||
fmt.Fprint(c, "CONNECT site.invalid:443 HTTP/1.0\r\n\r\n")
|
||||
br := bufio.NewReader(c)
|
||||
line, _ := br.ReadString('\n')
|
||||
if !strings.HasPrefix(line, "HTTP/1.1 200") {
|
||||
t.Fatalf("CONNECT reply: %q", line)
|
||||
}
|
||||
for {
|
||||
l, err := br.ReadString('\n')
|
||||
if err != nil || l == "\r\n" {
|
||||
break
|
||||
}
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(ca.Cert)
|
||||
tc := tls.Client(&bufConn{Conn: c, r: br}, &tls.Config{ServerName: "site.invalid", RootCAs: pool, MaxVersion: tls.VersionTLS12})
|
||||
if err := tc.Handshake(); err != nil {
|
||||
t.Fatalf("handshake: %v", err)
|
||||
}
|
||||
if got := tc.ConnectionState().PeerCertificates[0].DNSNames; len(got) != 1 || got[0] != "site.invalid" {
|
||||
t.Errorf("certificate names: %v", got)
|
||||
}
|
||||
// a request inside the tunnel is handled as any other: this site does
|
||||
// not exist, so the reply is the proxy's error page
|
||||
fmt.Fprint(tc, "GET / HTTP/1.0\r\nHost: site.invalid\r\n\r\n")
|
||||
resp, err := http.ReadResponse(bufio.NewReader(tc), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
if !strings.Contains(string(b), "site.invalid") {
|
||||
t.Errorf("error page: %d %q", resp.StatusCode, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPassThrough(t *testing.T) {
|
||||
echo, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer echo.Close()
|
||||
go func() {
|
||||
c, err := echo.Accept()
|
||||
if err == nil {
|
||||
io.Copy(c, c)
|
||||
c.Close()
|
||||
}
|
||||
}()
|
||||
addr, _ := startProxy(t, "[ConnectPassThrough]\n127\\.0\\.0\\.1\n")
|
||||
c, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\n\r\n", echo.Addr())
|
||||
br := bufio.NewReader(c)
|
||||
for {
|
||||
l, err := br.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if l == "\r\n" {
|
||||
break
|
||||
}
|
||||
}
|
||||
io.WriteString(c, "ping")
|
||||
buf := make([]byte, 4)
|
||||
if _, err := io.ReadFull(br, buf); err != nil || string(buf) != "ping" {
|
||||
t.Fatalf("tunnel: %q %v", buf, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKindOf(t *testing.T) {
|
||||
cfg := config.New()
|
||||
cfg.Port = 8080
|
||||
cfg.DefaultHostName = "proxy.example"
|
||||
s := &Server{cfg: cfg}
|
||||
cases := []struct {
|
||||
raw, host string
|
||||
connect bool
|
||||
want Kind
|
||||
}{
|
||||
{"/123", "example.com", false, StandardRemote},
|
||||
{"/", "proxy.example:8080", false, StandardHttp},
|
||||
{"/http://example.com/", "proxy.example:8080", false, AlternateProxy},
|
||||
{"http://example.com/", "example.com", false, StandardProxy},
|
||||
{"ftp://example.com/pub", "", false, StandardProxy},
|
||||
{"example.com:443", "", true, StandardSslProxy},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got, err := s.kindOf(c.raw, c.host, c.connect)
|
||||
if err != nil || got != c.want {
|
||||
t.Errorf("kindOf(%q, %q) = %v, %v; want %v", c.raw, c.host, got, err, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFtpListParsing(t *testing.T) {
|
||||
e, ok := parseFtpLine("drwxr-xr-x 2 0 0 4096 Jan 01 2020 pub")
|
||||
if !ok || !e.Directory || e.Name != "pub" {
|
||||
t.Errorf("unix: %+v %v", e, ok)
|
||||
}
|
||||
e, ok = parseFtpLine("01-02-03 10:00AM <DIR> windows")
|
||||
if !ok || !e.Directory || e.Name != "windows" {
|
||||
t.Errorf("dos: %+v %v", e, ok)
|
||||
}
|
||||
e, ok = parseFtpLine("01-02-03 10:00AM 1234 readme.txt")
|
||||
if !ok || e.Directory || e.Size != 1234 {
|
||||
t.Errorf("dos file: %+v %v", e, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivexVersions(t *testing.T) {
|
||||
a, _ := parseDotVersion("6.4.7.1112")
|
||||
b, _ := parseDotVersion("6.4")
|
||||
if cmpVersion(a, b) <= 0 || cmpVersion(b, b) != 0 {
|
||||
t.Error("version compare")
|
||||
}
|
||||
if _, ok := parseDotVersion("6"); ok {
|
||||
t.Error("one-part version accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Request is a client's HTTP request, as WebOne's HttpRequest.
|
||||
type Request struct {
|
||||
Method string
|
||||
RawURL string
|
||||
Proto string // "HTTP/1.1"
|
||||
Major int
|
||||
Minor int
|
||||
Header *Header
|
||||
URL *url.URL // nil for CONNECT
|
||||
Kind Kind
|
||||
Secure bool // came through the proxy's own TLS (a CONNECT tunnel)
|
||||
Remote *net.TCPAddr
|
||||
Local *net.TCPAddr
|
||||
Body io.Reader // the payload (empty reader if none)
|
||||
KeepAlive bool
|
||||
|
||||
conn net.Conn // the connection (or TLS tunnel)
|
||||
br *bufio.Reader // its reader; CONNECT tunnels continue from it
|
||||
}
|
||||
|
||||
// errDropped: the connection did not carry an HTTP request (logged already).
|
||||
var errDropped = errors.New("dropped")
|
||||
|
||||
// errNonHTTPInTLS: a non-HTTP protocol inside a TLS tunnel.
|
||||
var errNonHTTPInTLS = errors.New("write your domain:port to webone.conf/[NonHttpSslServers], please")
|
||||
|
||||
// readRequestHead reads the request line and headers, up to the blank line.
|
||||
// Both CRLF and bare LF line ends are taken.
|
||||
func readRequestHead(br *bufio.Reader) ([]string, error) {
|
||||
var lines []string
|
||||
for {
|
||||
line, err := br.ReadString('\n')
|
||||
if err != nil {
|
||||
if err == io.EOF && line == "" && len(lines) == 0 {
|
||||
return nil, io.EOF
|
||||
}
|
||||
if err == io.EOF && line != "" {
|
||||
lines = append(lines, strings.TrimRight(line, "\r\n"))
|
||||
return lines, nil
|
||||
}
|
||||
return lines, err
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" {
|
||||
if len(lines) == 0 {
|
||||
continue // stray blank lines before a request
|
||||
}
|
||||
return lines, nil
|
||||
}
|
||||
lines = append(lines, line)
|
||||
if len(lines) > 1000 {
|
||||
return nil, errors.New("too many header lines")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parseRequest reads one request from the connection.
|
||||
func (s *Server) parseRequest(br *bufio.Reader, conn net.Conn, secure bool, log logger) (*Request, error) {
|
||||
lines, err := readRequestHead(br)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
first := lines[0]
|
||||
parts := strings.Split(first, " ")
|
||||
if len(parts) != 3 || len(parts[2]) != 8 || !strings.HasPrefix(parts[2], "HTTP/") {
|
||||
if secure {
|
||||
log.Printf("<Dropped: Non-HTTPS connection: %s", first)
|
||||
return nil, errNonHTTPInTLS
|
||||
}
|
||||
log.Printf("<Dropped: Non-HTTP connection: %s", first)
|
||||
return nil, errDropped
|
||||
}
|
||||
r := &Request{
|
||||
Method: parts[0],
|
||||
RawURL: parts[1],
|
||||
Proto: parts[2],
|
||||
Header: NewHeader(),
|
||||
Secure: secure,
|
||||
conn: conn,
|
||||
br: br,
|
||||
}
|
||||
r.Major, _ = strconv.Atoi(r.Proto[5:6])
|
||||
r.Minor, _ = strconv.Atoi(r.Proto[7:8])
|
||||
if ta, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
|
||||
r.Remote = ta
|
||||
} else {
|
||||
r.Remote = &net.TCPAddr{IP: net.IPv4zero}
|
||||
}
|
||||
if ta, ok := conn.LocalAddr().(*net.TCPAddr); ok {
|
||||
r.Local = ta
|
||||
} else {
|
||||
r.Local = &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}
|
||||
}
|
||||
for _, l := range lines[1:] {
|
||||
i := strings.IndexByte(l, ':')
|
||||
if i <= 0 {
|
||||
continue
|
||||
}
|
||||
name := strings.TrimSpace(l[:i])
|
||||
value := strings.TrimSpace(l[i+1:])
|
||||
r.Header.Add(name, value)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(r.RawURL, "ftp:/") && !strings.HasPrefix(r.RawURL, "ftp://") {
|
||||
log.Printf("<Dropped (bad FTP protocol address).") // IBM WebExplorer bug
|
||||
return nil, errDropped
|
||||
}
|
||||
|
||||
// define the URL from the request line and the Host header
|
||||
r.Kind, err = s.kindOf(r.RawURL, r.Header.Get("Host"), r.Method == "CONNECT")
|
||||
if err != nil {
|
||||
log.Printf("<Dropped: %v", err)
|
||||
return nil, errDropped
|
||||
}
|
||||
host := r.Header.Get("Host")
|
||||
if host == "" {
|
||||
host = s.cfg.Vars.Value("Proxy")
|
||||
}
|
||||
switch r.Kind {
|
||||
case StandardProxy:
|
||||
r.URL, err = parseURL(r.RawURL)
|
||||
case StandardHttp, StandardRemote:
|
||||
r.URL, err = parseURL("http://" + host + r.RawURL)
|
||||
if err != nil {
|
||||
r.URL, err = parseURL(r.RawURL)
|
||||
}
|
||||
case AlternateProxy:
|
||||
u := r.RawURL[1:]
|
||||
if strings.Contains(u, ":/") && !strings.Contains(u, "://") {
|
||||
u = strings.Replace(u, ":/", "://", 1)
|
||||
}
|
||||
if strings.HasPrefix(u, "ttp://") {
|
||||
// alternate mode used through the proxy: "http://proxy:port/http://site/"
|
||||
if i := strings.Index(u[7:], "/"); i >= 0 {
|
||||
u = u[7+i+1:]
|
||||
}
|
||||
if i := strings.Index(r.RawURL[8:], "/"); i >= 0 {
|
||||
r.RawURL = r.RawURL[8+i:]
|
||||
}
|
||||
}
|
||||
r.URL, err = parseURL(u)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("<Dropped: bad URL %s", r.RawURL)
|
||||
return nil, errDropped
|
||||
}
|
||||
|
||||
// the payload
|
||||
if cl := r.Header.Get("Content-Length"); cl != "" && cl != "0" {
|
||||
n, err := strconv.ParseInt(strings.TrimSpace(cl), 10, 64)
|
||||
if err != nil || n < 0 {
|
||||
return nil, fmt.Errorf("bad Content-Length %q", cl)
|
||||
}
|
||||
r.Body = io.LimitReader(br, n)
|
||||
} else if strings.Contains(strings.ToLower(r.Header.Get("Transfer-Encoding")), "chunked") && r.Method != "CONNECT" {
|
||||
r.Body = httputil.NewChunkedReader(br)
|
||||
} else {
|
||||
r.Body = strings.NewReader("")
|
||||
}
|
||||
|
||||
// persistent connections (Keep-Alive)
|
||||
// (WebOne keeps only connections that ask for it; HTTP/1.1 ones are
|
||||
// kept unless they say "close", as HTTP/1.1 has it)
|
||||
ch := strings.ToLower(r.Header.Get("Connection") + "," + r.Header.Get("Proxy-Connection"))
|
||||
switch {
|
||||
case strings.Contains(ch, "keep-alive"):
|
||||
r.KeepAlive = true
|
||||
case r.Major == 1 && r.Minor >= 1 && !strings.Contains(ch, "close"):
|
||||
r.KeepAlive = true
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// drainBody reads what is left of the payload, so the next request on the
|
||||
// connection starts where it should.
|
||||
func (r *Request) drainBody() {
|
||||
if r.Body != nil {
|
||||
io.Copy(io.Discard, io.LimitReader(r.Body, 64<<20))
|
||||
}
|
||||
}
|
||||
|
||||
// ProtoVersion is "1.1".
|
||||
func (r *Request) ProtoVersion() string { return fmt.Sprintf("%d.%d", r.Major, r.Minor) }
|
||||
|
||||
// parseURL parses an absolute URL as .NET's Uri would take it: spaces are
|
||||
// escaped first.
|
||||
func parseURL(s string) (*url.URL, error) {
|
||||
s = strings.ReplaceAll(s, " ", "%20")
|
||||
u, err := url.Parse(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if u.Scheme == "" {
|
||||
return nil, fmt.Errorf("not an absolute URL: %s", s)
|
||||
}
|
||||
u.Scheme = strings.ToLower(u.Scheme)
|
||||
u.Host = strings.ToLower(u.Host)
|
||||
if (u.Scheme == "http" || u.Scheme == "https" || u.Scheme == "ftp") && u.Path == "" && u.Opaque == "" {
|
||||
u.Path = "/"
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// absURL is a URL as .NET's Uri.AbsoluteUri gives it: default ports left
|
||||
// out, a path always present.
|
||||
func absURL(u *url.URL) string {
|
||||
if u == nil {
|
||||
return ""
|
||||
}
|
||||
c := *u
|
||||
if p := c.Port(); (c.Scheme == "http" && p == "80") || (c.Scheme == "https" && p == "443") || (c.Scheme == "ftp" && p == "21") {
|
||||
c.Host = c.Hostname()
|
||||
if strings.Contains(c.Host, ":") {
|
||||
c.Host = "[" + c.Host + "]"
|
||||
}
|
||||
}
|
||||
if c.Path == "" && c.Opaque == "" && c.Host != "" {
|
||||
c.Path = "/"
|
||||
}
|
||||
return c.String()
|
||||
}
|
||||
|
||||
// pathAndQuery is the path with "?query" when there is one.
|
||||
func pathAndQuery(u *url.URL) string {
|
||||
p := u.EscapedPath()
|
||||
if p == "" {
|
||||
p = "/"
|
||||
}
|
||||
if u.RawQuery != "" || u.ForceQuery {
|
||||
p += "?" + u.RawQuery
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// segments is .NET's Uri.Segments: "/a/b/c" -> ["/", "a/", "b/", "c"].
|
||||
func segments(u *url.URL) []string {
|
||||
p := u.EscapedPath()
|
||||
if p == "" {
|
||||
return []string{"/"}
|
||||
}
|
||||
var out []string
|
||||
start := 0
|
||||
for i := 0; i < len(p); i++ {
|
||||
if p[i] == '/' {
|
||||
out = append(out, p[start:i+1])
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
if start < len(p) {
|
||||
out = append(out, p[start:])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// statusText is WebOne's list of reason phrases (HttpResponse.cs).
|
||||
var statusText = map[int]string{
|
||||
100: "Continue", 101: "Switching Protocols",
|
||||
200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content",
|
||||
205: "Reset Content", 206: "Partial Content",
|
||||
300: "Multiple Choices", 301: "Moved Permanently", 302: "Moved Temporarily", 303: "See Other",
|
||||
304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", 308: "Permanent Redirect",
|
||||
400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found",
|
||||
405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required",
|
||||
408: "Request Timeout", 409: "Conflict", 410: "Gone", 411: "Length Required", 412: "Precondition Failed",
|
||||
413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type",
|
||||
418: "I'm a teapot", 429: "Too Many Requests",
|
||||
500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable",
|
||||
504: "Gateway Timeout", 505: "HTTP Version Not Supported",
|
||||
}
|
||||
|
||||
// statusName is .NET's HttpStatusCode name of a code ("NotFound"), as
|
||||
// WebOne shows in its error pages.
|
||||
var statusName = map[int]string{
|
||||
200: "OK", 204: "NoContent", 206: "PartialContent", 301: "MovedPermanently", 302: "Redirect", 303: "RedirectMethod",
|
||||
304: "NotModified", 307: "TemporaryRedirect", 308: "PermanentRedirect",
|
||||
400: "BadRequest", 401: "Unauthorized", 403: "Forbidden", 404: "NotFound", 405: "MethodNotAllowed",
|
||||
406: "NotAcceptable", 407: "ProxyAuthenticationRequired", 408: "RequestTimeout", 409: "Conflict", 410: "Gone",
|
||||
429: "TooManyRequests", 451: "UnavailableForLegalReasons",
|
||||
500: "InternalServerError", 501: "NotImplemented", 502: "BadGateway", 503: "ServiceUnavailable",
|
||||
504: "GatewayTimeout",
|
||||
}
|
||||
|
||||
// StatusName is the .NET enum name of a status code, or the number.
|
||||
func StatusName(code int) string {
|
||||
if n, ok := statusName[code]; ok {
|
||||
return n
|
||||
}
|
||||
return strconv.Itoa(code)
|
||||
}
|
||||
|
||||
// Response is the reply to the client, sent by hand on the connection as
|
||||
// WebOne's HttpResponse does (so it can speak HTTP/1.0 to HTTP/1.0 clients).
|
||||
type Response struct {
|
||||
Status int
|
||||
StatusMessage string // "" for the usual one
|
||||
Major, Minor int
|
||||
Header *Header
|
||||
// SimpleContentType strips parameters from Content-Type (RFC 1945
|
||||
// clients: [Http10Only]).
|
||||
SimpleContentType bool
|
||||
// KeepAlive: the connection stays open after this response.
|
||||
KeepAlive bool
|
||||
HeadersSent bool
|
||||
// NoBody: the response has no body (a reply to HEAD; 204, 304, 1xx):
|
||||
// what is written is dropped.
|
||||
NoBody bool
|
||||
|
||||
contentLength int64 // -1 unknown, -2 not set
|
||||
chunked bool
|
||||
bw *bufio.Writer
|
||||
conn net.Conn
|
||||
clientWantsKA bool
|
||||
closed bool
|
||||
wroteBody int64
|
||||
}
|
||||
|
||||
func newResponse(conn net.Conn, keepAlive bool) *Response {
|
||||
return &Response{
|
||||
Status: 200, Major: 1, Minor: 1, Header: NewHeader(),
|
||||
contentLength: -2, bw: bufio.NewWriterSize(conn, 32*1024), conn: conn, clientWantsKA: keepAlive,
|
||||
}
|
||||
}
|
||||
|
||||
// SetVersion sets the HTTP version of the reply ("1.0", "1.1").
|
||||
func (w *Response) SetVersion(major, minor int) {
|
||||
if major < 1 {
|
||||
major, minor = 1, 0
|
||||
}
|
||||
if major > 1 {
|
||||
major, minor = 1, 1
|
||||
}
|
||||
w.Major, w.Minor = major, minor
|
||||
}
|
||||
|
||||
// SetContentType sets Content-Type.
|
||||
func (w *Response) SetContentType(ct string) {
|
||||
if w.SimpleContentType {
|
||||
if i := strings.IndexByte(ct, ';'); i >= 0 {
|
||||
ct = ct[:i]
|
||||
}
|
||||
}
|
||||
w.Header.Set("Content-Type", ct)
|
||||
}
|
||||
|
||||
// AddHeader adds a header (Content-Type replaces).
|
||||
func (w *Response) AddHeader(k, v string) {
|
||||
if strings.EqualFold(k, "Content-Type") {
|
||||
w.SetContentType(v)
|
||||
return
|
||||
}
|
||||
w.Header.Add(k, v)
|
||||
}
|
||||
|
||||
// SetContentLength sets Content-Length; below 0 means unknown: chunked
|
||||
// transfer on HTTP/1.1, and the end of the connection on HTTP/1.0.
|
||||
func (w *Response) SetContentLength(n int64) {
|
||||
w.contentLength = n
|
||||
if n < 0 {
|
||||
w.Header.Del("Content-Length")
|
||||
if w.Major == 1 && w.Minor >= 1 {
|
||||
w.Header.Set("Transfer-Encoding", "chunked")
|
||||
w.chunked = true
|
||||
return
|
||||
}
|
||||
w.KeepAlive = false
|
||||
w.Header.Set("Connection", "Close")
|
||||
return
|
||||
}
|
||||
w.Header.Del("Transfer-Encoding")
|
||||
w.chunked = false
|
||||
w.Header.Set("Content-Length", strconv.FormatInt(n, 10))
|
||||
}
|
||||
|
||||
// ContentLength is what was set (-1 unknown, -2 not set).
|
||||
func (w *Response) ContentLength() int64 { return w.contentLength }
|
||||
|
||||
// SendHeaders writes the status line and headers.
|
||||
func (w *Response) SendHeaders(version string) error {
|
||||
if w.HeadersSent {
|
||||
return errors.New("HTTP response headers are already sent")
|
||||
}
|
||||
if !w.Header.Has("Server") && !w.Header.Has("Via") {
|
||||
w.Header.Add("Server", "WebOne/"+version)
|
||||
}
|
||||
if w.Status == 204 || w.Status == 304 || w.Status/100 == 1 {
|
||||
w.NoBody = true
|
||||
w.Header.Del("Transfer-Encoding")
|
||||
}
|
||||
if w.NoBody {
|
||||
w.chunked = false
|
||||
}
|
||||
if w.Header.Get("Content-Type") == noContentType {
|
||||
w.Header.Del("Content-Type")
|
||||
}
|
||||
if !w.Header.Has("Connection") {
|
||||
// WebOne always answers Keep-Alive; this port only does when the
|
||||
// client asked for it (an HTTP/1.0 client that did not would wait
|
||||
// for the end of the connection)
|
||||
if w.clientWantsKA || (w.Major == 1 && w.Minor >= 1 && w.contentLength >= 0) {
|
||||
w.Header.Add("Connection", "Keep-Alive")
|
||||
w.KeepAlive = true
|
||||
} else {
|
||||
w.Header.Add("Connection", "Close")
|
||||
w.KeepAlive = false
|
||||
}
|
||||
} else if strings.EqualFold(w.Header.Get("Connection"), "close") {
|
||||
w.KeepAlive = false
|
||||
} else if w.contentLength == -2 {
|
||||
w.KeepAlive = false
|
||||
}
|
||||
if w.contentLength == -2 && w.Status != 304 && w.Status != 204 && w.Status/100 != 1 {
|
||||
// no length and no chunks: the end of the body is the end of the connection
|
||||
w.KeepAlive = false
|
||||
}
|
||||
msg := w.StatusMessage
|
||||
if msg == "" {
|
||||
msg = statusText[w.Status]
|
||||
}
|
||||
line := fmt.Sprintf("HTTP/%d.%d %d", w.Major, w.Minor, w.Status)
|
||||
if msg != "" {
|
||||
line += " " + msg
|
||||
}
|
||||
if _, err := io.WriteString(w.bw, line+"\r\n"+w.Header.String()+"\r\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
w.HeadersSent = true
|
||||
return w.bw.Flush()
|
||||
}
|
||||
|
||||
// Write writes body bytes (as a chunk when chunked).
|
||||
func (w *Response) Write(p []byte) (int, error) {
|
||||
if !w.HeadersSent {
|
||||
return 0, errors.New("call SendHeaders() first before sending body")
|
||||
}
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if w.NoBody {
|
||||
return len(p), nil
|
||||
}
|
||||
if w.chunked {
|
||||
if _, err := fmt.Fprintf(w.bw, "%X\r\n", len(p)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := w.bw.Write(p); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err := w.bw.WriteString("\r\n"); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
} else if _, err := w.bw.Write(p); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
w.wroteBody += int64(len(p))
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// Flush sends what is buffered.
|
||||
func (w *Response) Flush() error { return w.bw.Flush() }
|
||||
|
||||
// Close ends the response (and the connection, unless kept alive).
|
||||
func (w *Response) Close(version string) error {
|
||||
if w.closed {
|
||||
return nil
|
||||
}
|
||||
if !w.HeadersSent {
|
||||
if err := w.SendHeaders(version); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
w.closed = true
|
||||
if w.chunked {
|
||||
w.bw.WriteString("0\r\n\r\n")
|
||||
}
|
||||
err := w.bw.Flush()
|
||||
if !w.KeepAlive {
|
||||
w.conn.Close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Connected: the connection is still usable.
|
||||
func (w *Response) Connected() bool { return !w.closed || w.KeepAlive }
|
||||
@@ -0,0 +1,412 @@
|
||||
// Package proxy is WebOne's HTTP proxy server: it takes requests from old
|
||||
// browsers (HTTP/1.0 or 1.1, as a proxy, as a web server, or in
|
||||
// "alternate" /http://site/ form), fetches the pages over today's HTTPS,
|
||||
// edits them as the configuration's edit sets say, and sends them back in
|
||||
// a form and code page the browser can read.
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/certs"
|
||||
"github.com/D-Modem/webone-go/internal/config"
|
||||
"github.com/D-Modem/webone-go/internal/logx"
|
||||
)
|
||||
|
||||
// Version is WebOne's version this port follows, marked as the Go port.
|
||||
const Version = "0.19.0-go"
|
||||
|
||||
// logger is what request handling logs through.
|
||||
type logger interface {
|
||||
Printf(format string, args ...any)
|
||||
}
|
||||
|
||||
// Server is a running WebOne proxy.
|
||||
type Server struct {
|
||||
cfg *config.Config
|
||||
CA *certs.CA // signs site certificates; nil when HTTPS is off
|
||||
RootCA *certs.CA // what clients install (the CA itself, or the root above it)
|
||||
issuer *certs.Issuer
|
||||
|
||||
up *upstream
|
||||
|
||||
ln net.Listener
|
||||
working atomic.Bool
|
||||
|
||||
opened atomic.Int64 // open connections
|
||||
busy atomic.Int64 // connections with a request in progress
|
||||
|
||||
forceMu sync.RWMutex
|
||||
forceHttps []string
|
||||
|
||||
lastMu sync.Mutex
|
||||
lastURL string
|
||||
lastCode int
|
||||
lastContentType string
|
||||
|
||||
clientTLS *tls.Config
|
||||
started time.Time
|
||||
}
|
||||
|
||||
// New makes a server for a loaded configuration. ca may be nil (HTTPS off).
|
||||
func New(cfg *config.Config, ca, root *certs.CA) (*Server, error) {
|
||||
s := &Server{
|
||||
cfg: cfg,
|
||||
CA: ca,
|
||||
RootCA: root,
|
||||
forceHttps: append([]string(nil), cfg.ForceHttps...),
|
||||
lastURL: "http://999.999.999.999/CON",
|
||||
lastCode: 200,
|
||||
lastContentType: "not-a-carousel",
|
||||
started: time.Now(),
|
||||
}
|
||||
if s.RootCA == nil {
|
||||
s.RootCA = ca
|
||||
}
|
||||
if ca != nil {
|
||||
s.issuer = &certs.Issuer{
|
||||
CA: ca,
|
||||
Hash: cfg.SslHashAlgorithm,
|
||||
ValidBeforeNow: cfg.SslCertValidBeforeNow,
|
||||
ValidAfterNow: cfg.SslCertValidAfterNow,
|
||||
SiteCerts: cfg.SslSiteCerts,
|
||||
Generator: cfg.SslSiteCertGenerator,
|
||||
Expand: func(str, subject string) string {
|
||||
v := config.NewVars()
|
||||
v.Set("Subject", subject)
|
||||
return cfg.Expand(str, v)
|
||||
},
|
||||
Log: func(f string, a ...any) { logx.Std.Printf(f, a...) },
|
||||
}
|
||||
s.clientTLS = s.makeClientTLS()
|
||||
}
|
||||
var extraRoots []*x509.Certificate
|
||||
if cfg.SslTrustOwnCA && s.RootCA != nil {
|
||||
extraRoots = append(extraRoots, s.RootCA.Cert)
|
||||
if ca != nil && ca != s.RootCA {
|
||||
extraRoots = append(extraRoots, ca.Cert)
|
||||
}
|
||||
}
|
||||
up, err := newUpstream(cfg, extraRoots)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.up = up
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Config is the server's configuration.
|
||||
func (s *Server) Config() *config.Config { return s.cfg }
|
||||
|
||||
// makeClientTLS is the TLS configuration for clients that CONNECT: old
|
||||
// versions and ciphers on, as old browsers need.
|
||||
func (s *Server) makeClientTLS() *tls.Config {
|
||||
c := &tls.Config{
|
||||
MinVersion: tls.VersionTLS10,
|
||||
MaxVersion: tls.VersionTLS13,
|
||||
GetCertificate: func(h *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
return nil, errors.New("no certificate")
|
||||
},
|
||||
}
|
||||
if s.cfg.SslProtocolsSet && len(s.cfg.SslProtocols) > 0 {
|
||||
lo, hi := uint16(0xffff), uint16(0)
|
||||
for _, v := range s.cfg.SslProtocols {
|
||||
lo, hi = min(lo, v), max(hi, v)
|
||||
}
|
||||
c.MinVersion, c.MaxVersion = lo, hi
|
||||
}
|
||||
if len(s.cfg.SslCipherSuites) > 0 {
|
||||
c.CipherSuites = s.cfg.SslCipherSuites
|
||||
} else {
|
||||
// everything Go has, the old and weak last: an old browser picks
|
||||
// what it knows
|
||||
for _, cs := range tls.CipherSuites() {
|
||||
c.CipherSuites = append(c.CipherSuites, cs.ID)
|
||||
}
|
||||
for _, cs := range tls.InsecureCipherSuites() {
|
||||
c.CipherSuites = append(c.CipherSuites, cs.ID)
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// tlsFor is the TLS configuration that presents host's certificate.
|
||||
func (s *Server) tlsFor(host string) (*tls.Config, error) {
|
||||
cert, err := s.issuer.Get(host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := s.clientTLS.Clone()
|
||||
c.GetCertificate = nil
|
||||
c.Certificates = []tls.Certificate{*cert}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// ListenAndServe listens on the configured address and serves until Stop.
|
||||
func (s *Server) ListenAndServe() error {
|
||||
addr := net.JoinHostPort("", strconv.Itoa(s.cfg.Port))
|
||||
if s.cfg.IP != nil {
|
||||
addr = net.JoinHostPort(s.cfg.IP.String(), strconv.Itoa(s.cfg.Port))
|
||||
}
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.Serve(ln)
|
||||
}
|
||||
|
||||
// Serve serves connections from ln until Stop.
|
||||
func (s *Server) Serve(ln net.Listener) error {
|
||||
s.ln = ln
|
||||
s.working.Store(true)
|
||||
proto := " (plain)"
|
||||
if s.cfg.SslEnable && s.CA != nil {
|
||||
proto = ", HTTPS"
|
||||
}
|
||||
logx.Server(true, "Supported protocols: HTTP%s, FTP via Web browser.", proto)
|
||||
for {
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
if !s.working.Load() {
|
||||
return nil
|
||||
}
|
||||
var ne net.Error
|
||||
if errors.As(err, &ne) && ne.Timeout() {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
go s.serveConn(c)
|
||||
}
|
||||
}
|
||||
|
||||
// Addr is the listening address.
|
||||
func (s *Server) Addr() net.Addr {
|
||||
if s.ln == nil {
|
||||
return nil
|
||||
}
|
||||
return s.ln.Addr()
|
||||
}
|
||||
|
||||
// Working: the server is serving.
|
||||
func (s *Server) Working() bool { return s.working.Load() }
|
||||
|
||||
// Stop stops listening.
|
||||
func (s *Server) Stop() {
|
||||
if s.working.Swap(false) && s.ln != nil {
|
||||
s.ln.Close()
|
||||
logx.Server(true, "HTTP/HTTPS/CERN Server stopped.")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) serveConn(c net.Conn) {
|
||||
s.opened.Add(1)
|
||||
defer s.opened.Add(-1)
|
||||
defer c.Close()
|
||||
log := logx.New()
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("Oops: %v.", r)
|
||||
}
|
||||
}()
|
||||
s.handleConn(c, bufio.NewReaderSize(c, 16*1024), false, "", log)
|
||||
}
|
||||
|
||||
// handleConn serves the requests of one connection (or of one TLS tunnel),
|
||||
// one after another while the connection is kept alive.
|
||||
func (s *Server) handleConn(c net.Conn, br *bufio.Reader, secure bool, prefix string, log *logx.Writer) {
|
||||
for {
|
||||
c.SetReadDeadline(time.Now().Add(5 * time.Minute))
|
||||
req, err := s.parseRequest(br, c, secure, log)
|
||||
if err != nil {
|
||||
if errors.Is(err, errNonHTTPInTLS) {
|
||||
log.Printf("SslOops: %v.", err)
|
||||
} else if !errors.Is(err, io.EOF) && !errors.Is(err, errDropped) && !isClosedErr(err) {
|
||||
if !s.cfg.HideClientErrors {
|
||||
log.Printf("Oops: %v.", err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
c.SetReadDeadline(time.Time{})
|
||||
resp := newResponse(c, req.KeepAlive)
|
||||
resp.NoBody = req.Method == "HEAD"
|
||||
s.busy.Add(1)
|
||||
t := newTransit(s, req, resp, log)
|
||||
if secure {
|
||||
log.Printf(">[%s] %s %s (%s)", prefix, req.Method, req.RawURL, t.clientID())
|
||||
} else {
|
||||
log.Printf(">%s %s (%s)", req.Method, req.RawURL, t.clientID())
|
||||
}
|
||||
t.process()
|
||||
s.busy.Add(-1)
|
||||
if t.hijacked {
|
||||
return
|
||||
}
|
||||
resp.Close(Version)
|
||||
req.drainBody()
|
||||
if req.KeepAlive && resp.KeepAlive {
|
||||
log.Printf("<Done.")
|
||||
log = logx.New()
|
||||
prefix = req.Header.Get("Host")
|
||||
if prefix == "" {
|
||||
prefix = "Keep-Alive, no Host"
|
||||
}
|
||||
continue
|
||||
}
|
||||
log.Printf("<Done (connection close).")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func isClosedErr(err error) bool {
|
||||
if errors.Is(err, net.ErrClosed) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return true
|
||||
}
|
||||
var ne net.Error
|
||||
if errors.As(err, &ne) && ne.Timeout() {
|
||||
return true
|
||||
}
|
||||
msg := err.Error()
|
||||
return strings.Contains(msg, "connection reset") || strings.Contains(msg, "broken pipe")
|
||||
}
|
||||
|
||||
// serverName is "host:port" (or "host" on port 80) as clients reach the
|
||||
// proxy: DefaultHostName, or the address the request came in on when
|
||||
// DefaultHostName is just the machine's name.
|
||||
func (s *Server) serverName(localIP string) string {
|
||||
host, _ := os.Hostname()
|
||||
name := s.cfg.DefaultHostName
|
||||
if strings.EqualFold(name, host) && localIP != "" {
|
||||
name = localIP
|
||||
}
|
||||
if s.cfg.Port == 80 {
|
||||
return name
|
||||
}
|
||||
return name + ":" + strconv.Itoa(s.cfg.Port)
|
||||
}
|
||||
|
||||
// infoString is the footer of WebOne's own pages.
|
||||
func (s *Server) infoString() string {
|
||||
return "<hr>WebOne Proxy Server " + s.cfg.Vars.Value("WOVer") + "<br>on " + s.cfg.Vars.Value("WOSystem")
|
||||
}
|
||||
|
||||
// isForceHttps: s contains one of the [ForceHttps] entries (or the hosts
|
||||
// learned to be HTTPS-only).
|
||||
func (s *Server) isForceHttps(str string) bool {
|
||||
s.forceMu.RLock()
|
||||
defer s.forceMu.RUnlock()
|
||||
for _, f := range s.forceHttps {
|
||||
if strings.Contains(str, f) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) hostForcesHttps(host string) bool {
|
||||
s.forceMu.RLock()
|
||||
defer s.forceMu.RUnlock()
|
||||
for _, f := range s.forceHttps {
|
||||
if strings.HasPrefix(host, f) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) addForceHttps(host string) {
|
||||
s.forceMu.Lock()
|
||||
defer s.forceMu.Unlock()
|
||||
for _, f := range s.forceHttps {
|
||||
if f == host {
|
||||
return
|
||||
}
|
||||
}
|
||||
s.forceHttps = append(s.forceHttps, host)
|
||||
}
|
||||
|
||||
// processURIMasks expands variables in a value about a URL
|
||||
// (Program.ProcessUriMasks): %URL%, %Url% (escaped), %UrlDomain%,
|
||||
// %UrlNoDomain%, %UrlNoQuery%, %UrlNoPort%, %UrlHttps%, %UrlHttp%, then
|
||||
// extra variables and the global ones.
|
||||
func (s *Server) processURIMasks(masked, possibleURL string, dontTouch bool, extra *config.Vars) string {
|
||||
if possibleURL == "" {
|
||||
possibleURL = "http://webone.github.io:80/index.htm"
|
||||
}
|
||||
u, err := url.Parse(possibleURL)
|
||||
if err != nil || u.Host == "" {
|
||||
u, _ = url.Parse("http://webone.github.io/index.htm")
|
||||
}
|
||||
if s.isForceHttps(possibleURL) && !dontTouch {
|
||||
c := *u
|
||||
c.Scheme = "https"
|
||||
if c.Port() == "80" {
|
||||
c.Host = c.Hostname()
|
||||
}
|
||||
u = &c
|
||||
}
|
||||
full := absURL(u)
|
||||
host := u.Hostname()
|
||||
noDomain := pathAndQuery(u)
|
||||
vars := config.NewVars()
|
||||
vars.Set("URL", full)
|
||||
vars.Set("Url", url.QueryEscape(full))
|
||||
vars.Set("UrlDomain", host)
|
||||
vars.Set("UrlNoDomain", noDomain)
|
||||
vars.Set("UrlNoQuery", u.Scheme+"://"+host+u.EscapedPath())
|
||||
vars.Set("UrlNoPort", u.Scheme+"://"+host+noDomain)
|
||||
vars.Set("UrlHttps", "https://"+host+noDomain)
|
||||
vars.Set("UrlHttp", "http://"+host+noDomain)
|
||||
if extra != nil {
|
||||
for _, k := range extra.Keys() {
|
||||
vars.TryAdd(k, extra.Value(k))
|
||||
}
|
||||
}
|
||||
return s.cfg.Expand(masked, vars)
|
||||
}
|
||||
|
||||
// userAgent is the User-Agent sent upstream ([Server] UserAgent with
|
||||
// %Original% the client's).
|
||||
func (s *Server) userAgent(client string) string {
|
||||
v := config.NewVars()
|
||||
if client == "" {
|
||||
client = "Mozilla/5.0 (Kundryuchy-Leshoz)"
|
||||
}
|
||||
v.Set("Original", client)
|
||||
return s.cfg.Expand(s.cfg.UserAgent, v)
|
||||
}
|
||||
|
||||
// usedMemoryMB is the memory the process holds, for the status page.
|
||||
func usedMemoryMB() int {
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
return int(m.Sys / 1024 / 1024)
|
||||
}
|
||||
|
||||
// pac is the proxy auto-configuration script.
|
||||
func (s *Server) pac(localHost string) string {
|
||||
v := config.NewVars()
|
||||
v.Set("PACProxy", localHost)
|
||||
return s.processURIMasks(s.cfg.PAC, localHost, false, v)
|
||||
}
|
||||
|
||||
// String describes the server for the log.
|
||||
func (s *Server) String() string {
|
||||
return fmt.Sprintf("WebOne @ %s:%d [%d/%d]", s.cfg.DefaultHostName, s.cfg.Port, s.opened.Load(), s.busy.Load())
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,252 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"compress/flate"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/config"
|
||||
"github.com/D-Modem/webone-go/internal/logx"
|
||||
)
|
||||
|
||||
// upstream is how the proxy reaches servers (Program.HTTPClient): no
|
||||
// redirects followed, no cookies kept, decompression of what it asked for.
|
||||
type upstream struct {
|
||||
cfg *config.Config
|
||||
h1 *http.Client // HTTP/1.1 only
|
||||
auto *http.Client // HTTP/2 when the server offers it
|
||||
dialer *net.Dialer
|
||||
tlsCfg *tls.Config
|
||||
}
|
||||
|
||||
func newUpstream(cfg *config.Config, extraRoots []*x509.Certificate) (*upstream, error) {
|
||||
u := &upstream{cfg: cfg}
|
||||
timeout := time.Duration(cfg.ConnectionTimeout) * time.Second
|
||||
if timeout <= 0 {
|
||||
timeout = 100 * time.Second
|
||||
}
|
||||
u.dialer = &net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second}
|
||||
if cfg.DnsServer != "" {
|
||||
dns := cfg.DnsServer
|
||||
u.dialer.Resolver = &net.Resolver{
|
||||
PreferGo: true,
|
||||
Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
|
||||
d := net.Dialer{Timeout: 5 * time.Second}
|
||||
return d.DialContext(ctx, network, dns)
|
||||
},
|
||||
}
|
||||
}
|
||||
u.tlsCfg = &tls.Config{MinVersion: tls.VersionTLS10}
|
||||
if len(cfg.SecurityProtocols) > 0 {
|
||||
lo, hi := uint16(0xffff), uint16(0)
|
||||
for _, v := range cfg.SecurityProtocols {
|
||||
lo, hi = min(lo, v), max(hi, v)
|
||||
}
|
||||
u.tlsCfg.MinVersion, u.tlsCfg.MaxVersion = lo, hi
|
||||
}
|
||||
if len(extraRoots) > 0 {
|
||||
pool, err := x509.SystemCertPool()
|
||||
if err != nil || pool == nil {
|
||||
pool = x509.NewCertPool()
|
||||
}
|
||||
for _, c := range extraRoots {
|
||||
pool.AddCert(c)
|
||||
}
|
||||
u.tlsCfg.RootCAs = pool
|
||||
}
|
||||
if !cfg.ValidateCertificates {
|
||||
u.tlsCfg.InsecureSkipVerify = true
|
||||
}
|
||||
|
||||
var proxy func(*http.Request) (*url.URL, error)
|
||||
switch strings.ToLower(strings.TrimSpace(cfg.UpperProxy)) {
|
||||
case "":
|
||||
proxy = http.ProxyFromEnvironment
|
||||
case "no", "off", "disable", "false", "direct":
|
||||
proxy = nil
|
||||
default:
|
||||
pu, err := url.Parse(cfg.UpperProxy)
|
||||
if err != nil || pu.Host == "" {
|
||||
pu, err = url.Parse("http://" + cfg.UpperProxy)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bad UpperProxy %q: %v", cfg.UpperProxy, err)
|
||||
}
|
||||
proxy = http.ProxyURL(pu)
|
||||
}
|
||||
|
||||
mk := func(h2 bool) *http.Client {
|
||||
tr := &http.Transport{
|
||||
Proxy: proxy,
|
||||
DialContext: u.dialer.DialContext,
|
||||
TLSClientConfig: u.tlsCfg.Clone(),
|
||||
TLSHandshakeTimeout: timeout,
|
||||
DisableCompression: true, // decompressed here, as asked
|
||||
MaxIdleConnsPerHost: 8,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
ExpectContinueTimeout: time.Second,
|
||||
ForceAttemptHTTP2: h2,
|
||||
}
|
||||
if !h2 {
|
||||
tr.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: tr,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
}
|
||||
u.h1 = mk(false)
|
||||
u.auto = mk(true)
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// operation is one request to a server and its response (HttpOperation.cs).
|
||||
type operation struct {
|
||||
Method string
|
||||
URL *url.URL
|
||||
Header *Header
|
||||
HTTPVersion string // RemoteHttpVersion rule: "auto", "=1.1", ">2.0" ...
|
||||
Secure bool // the client came in over TLS: fetch over HTTPS
|
||||
Body io.Reader
|
||||
log logger
|
||||
|
||||
Resp *http.Response
|
||||
RespHeader *Header
|
||||
RespBody io.ReadCloser
|
||||
}
|
||||
|
||||
// hopHeader: not sent on to the server.
|
||||
func hopHeader(name string) bool {
|
||||
n := strings.ToLower(name)
|
||||
return strings.HasPrefix(n, "proxy-") || strings.HasSuffix(n, "-encoding") || n == "host" ||
|
||||
n == "connection" || n == "keep-alive" || n == "upgrade" || n == "te" || n == "trailer"
|
||||
}
|
||||
|
||||
// send makes the request.
|
||||
func (s *Server) send(op *operation) error {
|
||||
if op.HTTPVersion == "" {
|
||||
op.HTTPVersion = s.cfg.RemoteHttpVersion
|
||||
}
|
||||
target := *op.URL
|
||||
if op.Secure || s.hostForcesHttps(target.Hostname()) {
|
||||
target.Scheme = "https"
|
||||
if target.Port() == "80" {
|
||||
target.Host = target.Hostname()
|
||||
}
|
||||
op.URL = &target
|
||||
}
|
||||
var body io.Reader
|
||||
if op.Body != nil {
|
||||
body = op.Body
|
||||
}
|
||||
req, err := http.NewRequest(op.Method, target.String(), body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if target.RawQuery == "" && strings.HasSuffix(op.URL.String(), "?") {
|
||||
req.URL.ForceQuery = true
|
||||
}
|
||||
op.Header.Each(func(k, v string) {
|
||||
if strings.HasSuffix(strings.ToLower(k), "-encoding") && strings.Contains(v, "xpress") && s.cfg.AllowHttpCompression {
|
||||
op.log.Printf(" Warning: This connection to server may use unsupported 'xpress' compression algorithm. Consider set AllowHttpCompression=false to get out some possible errors.")
|
||||
}
|
||||
if hopHeader(k) {
|
||||
return
|
||||
}
|
||||
if strings.EqualFold(k, "Content-Length") {
|
||||
return
|
||||
}
|
||||
req.Header.Add(k, v)
|
||||
})
|
||||
if cl := op.Header.Get("Content-Length"); cl != "" && body != nil {
|
||||
var n int64
|
||||
fmt.Sscan(cl, &n)
|
||||
req.ContentLength = n
|
||||
} else if body == nil {
|
||||
req.ContentLength = 0
|
||||
}
|
||||
if s.cfg.AllowHttpCompression {
|
||||
req.Header.Set("Accept-Encoding", "gzip, deflate")
|
||||
}
|
||||
if req.Header.Get("User-Agent") == "" {
|
||||
req.Header["User-Agent"] = []string{""} // Go would send its own
|
||||
}
|
||||
|
||||
client := s.up.auto
|
||||
switch v := op.HTTPVersion; {
|
||||
case v == "auto":
|
||||
case strings.HasSuffix(v, "1.1"), strings.HasSuffix(v, "1.0"):
|
||||
if v[0] != '>' {
|
||||
client = s.up.h1
|
||||
}
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
op.Resp = resp
|
||||
op.RespBody = resp.Body
|
||||
switch strings.ToLower(resp.Header.Get("Content-Encoding")) {
|
||||
case "gzip", "x-gzip":
|
||||
zr, err := gzip.NewReader(resp.Body)
|
||||
if err == nil {
|
||||
op.RespBody = struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{zr, resp.Body}
|
||||
resp.Header.Del("Content-Encoding")
|
||||
resp.Header.Del("Content-Length")
|
||||
resp.ContentLength = -1
|
||||
} else if !errors.Is(err, io.EOF) {
|
||||
resp.Body.Close()
|
||||
return &decodeError{err}
|
||||
}
|
||||
case "deflate":
|
||||
op.RespBody = struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{flate.NewReader(resp.Body), resp.Body}
|
||||
resp.Header.Del("Content-Encoding")
|
||||
resp.Header.Del("Content-Length")
|
||||
resp.ContentLength = -1
|
||||
}
|
||||
op.RespHeader = FromHTTP(resp.Header)
|
||||
for k, vs := range resp.Trailer {
|
||||
for _, v := range vs {
|
||||
op.RespHeader.Add(k, v)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeError: the server's compressed content cannot be read
|
||||
// (InvalidDataException).
|
||||
type decodeError struct{ err error }
|
||||
|
||||
func (e *decodeError) Error() string { return "cannot decode HTTP data: " + e.err.Error() }
|
||||
|
||||
// fetch is a plain GET (for the Web Archive and converters).
|
||||
func (s *Server) fetch(rawURL string) (*http.Response, error) {
|
||||
req, err := http.NewRequest("GET", rawURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", "WebOne/"+s.cfg.Vars.Value("WOVer"))
|
||||
resp, err := s.up.auto.Do(req)
|
||||
if err != nil {
|
||||
logx.Std.Printf(" Fetch %s failed: %v", rawURL, err)
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"io"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/config"
|
||||
"github.com/D-Modem/webone-go/internal/rx"
|
||||
)
|
||||
|
||||
func setOf(keys ...string) map[string]bool {
|
||||
m := make(map[string]bool, len(keys))
|
||||
for _, k := range keys {
|
||||
m[k] = true
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// ytdlpOptions are the yt-dlp options /!webvideo/ passes on
|
||||
// (WebVideoConverter.cs).
|
||||
var ytdlpOptions = setOf(
|
||||
"abort-on-error", "abort-on-unavailable-fragments", "add-chapters", "add-headers", "add-metadata",
|
||||
"age-limit", "alias", "allow-dynamic-mpd", "ap-list-mso", "ap-mso", "ap-password", "ap-username",
|
||||
"audio-format", "audio-multistreams", "audio-quality", "batch-file", "bidi-workaround",
|
||||
"break-match-filters", "break-on-existing", "break-per-input", "buffer-size", "cache-dir",
|
||||
"check-all-formats", "check-formats", "clean-info-json", "client-certificate",
|
||||
"client-certificate-key", "client-certificate-password", "color", "compat-options",
|
||||
"concat-playlist", "concurrent-fragments", "config-locations", "console-title", "continue",
|
||||
"convert-", "convert-subs", "convert-thumbnails", "cookies", "cookies-from-browser", "date",
|
||||
"dateafter", "datebefore", "default-search", "download-archive", "download-sections",
|
||||
"downloader", "downloader-args", "dump-pages", "embed-chapters", "embed-info-json",
|
||||
"embed-metadata", "embed-subs", "embed-thumbnail", "enable-file-urls", "encoding", "exec",
|
||||
"external-downloader", "external-downloader-args", "extract-audio", "extractor-args",
|
||||
"extractor-descriptions", "extractor-retries", "ffmpeg-location", "file-access-retries", "fixup",
|
||||
"flat-playlist", "force-download-archive", "force-ipv", "force-keyframes-at-cuts", "format",
|
||||
"format-sort", "format-sort-force", "fragment-retries", "geo-verification-proxy", "get-audio",
|
||||
"get-comments", "help", "hls-split-discontinuity", "hls-use-mpegts", "http-chunk-size", "ies",
|
||||
"ignore-config", "ignore-dynamic-mpd", "ignore-errors", "ignore-no-formats-error", "impersonate",
|
||||
"js-runtimes", "keep-fragments", "keep-video", "lazy-playlist", "legacy-server-connect",
|
||||
"limit-rate", "list-extractors", "list-formats", "list-impersonate-targets", "list-subs",
|
||||
"list-thumbnails", "live-from-start", "load-info-json", "mark-watched", "match-filters",
|
||||
"max-downloads", "max-filesize", "max-sleep-interval", "merge-output-format", "min-filesize",
|
||||
"min-sleep-interval", "mtime", "netrc", "netrc-cmd", "netrc-location", "newline",
|
||||
"no-abort-on-error", "no-abort-on-unavailable-fragments", "no-add-chapters", "no-add-metadata",
|
||||
"no-allow-dynamic-mpd", "no-audio-multistreams", "no-batch-file", "no-break-match-filters",
|
||||
"no-break-on-existing", "no-break-per-input", "no-cache-dir", "no-check-certificates",
|
||||
"no-check-formats", "no-clean-info-json", "no-config", "no-config-locations", "no-continue",
|
||||
"no-cookies", "no-cookies-from-browser", "no-download", "no-download-archive",
|
||||
"no-embed-chapters", "no-embed-info-json", "no-embed-metadata", "no-embed-subs",
|
||||
"no-embed-thumbnail", "no-exec", "no-flat-playlist", "no-force-keyframes-at-cuts",
|
||||
"no-force-overwrites", "no-format-sort-force", "no-get-comments", "no-hls-split-discontinuity",
|
||||
"no-hls-use-mpegts", "no-ignore-dynamic-mpd", "no-ignore-errors", "no-ignore-no-formats-error",
|
||||
"no-js-", "no-js-runtimes", "no-keep-fragments", "no-keep-video", "no-lazy-playlist",
|
||||
"no-live-from-start", "no-mark-watched", "no-match-filters", "no-mtime", "no-overwrites",
|
||||
"no-part", "no-playlist", "no-plugin-dirs", "no-post-overwrites", "no-prefer-free-formats",
|
||||
"no-progress", "no-quiet", "no-remote-components", "no-remove-chapters", "no-resize-buffer",
|
||||
"no-restrict-filenames", "no-simulate", "no-skip-unavailable-fragments", "no-split-chapters",
|
||||
"no-sponsorblock", "no-update", "no-video-multistreams", "no-wait-for-video", "no-warnings",
|
||||
"no-windows-filenames", "no-write-auto-subs", "no-write-automatic-subs", "no-write-comments",
|
||||
"no-write-description", "no-write-info-json", "no-write-playlist-metafiles", "no-write-subs",
|
||||
"no-write-thumbnail", "output", "output-na-placeholder", "parse-metadata", "part", "password",
|
||||
"paths", "playlist-items", "playlist-random", "playlist-reverse", "plugin-dirs",
|
||||
"postprocessor-args", "ppa", "prefer-free-formats", "prefer-insecure", "preset-alias", "print",
|
||||
"print-to-file", "print-traffic", "progress", "progress-delta", "progress-template", "proxy",
|
||||
"quiet", "recode-video", "remote-components", "remove-chapters", "remux-video",
|
||||
"replace-in-metadata", "resize-buffer", "restrict-filenames", "retries", "retry-sleep",
|
||||
"rm-cache-dir", "simulate", "skip-download", "skip-playlist-after-errors",
|
||||
"skip-unavailable-fragments", "sleep-interval", "sleep-requests", "sleep-subtitles",
|
||||
"socket-timeout", "source-address", "split-chapters", "sponsorblock-api",
|
||||
"sponsorblock-chapter-title", "sponsorblock-mark", "sponsorblock-remove", "sub-", "sub-format",
|
||||
"sub-langs", "throttled-rate", "trim-filenames", "twofactor", "use-extractors",
|
||||
"use-postprocessor", "username", "verbose", "version", "video-multistreams", "video-password",
|
||||
"wait-for-video", "windows-filenames", "xattrs", "xff", "yes-playlist", "a", "audio", "based",
|
||||
"c", "compatible", "dl", "dlc", "dlp-ejs", "encode", "extracted", "factor", "filler", "free",
|
||||
"generated", "generic", "h", "i", "inf", "k", "language", "letter", "live", "modified", "n", "o",
|
||||
"only", "preview", "processed", "q", "range", "restricted", "restriction", "sensitive",
|
||||
"separated", "side", "specific", "system", "title", "tty", "v", "w", "x",
|
||||
)
|
||||
|
||||
// ytdlpUnsafe are yt-dlp options that read or write files on the proxy or
|
||||
// run programs. WebOne passes them from the URL; this port takes them only
|
||||
// from [WebVideoOptions] in the configuration.
|
||||
var ytdlpUnsafe = setOf(
|
||||
"a", "batch-file", "cache-dir", "client-certificate", "client-certificate-key", "client-certificate-password",
|
||||
"config-locations", "cookies", "cookies-from-browser", "download-archive", "downloader", "downloader-args",
|
||||
"enable-file-urls", "exec", "external-downloader", "external-downloader-args", "ffmpeg-location",
|
||||
"load-info-json", "netrc", "netrc-cmd", "netrc-location", "o", "output", "p", "paths", "plugin-dirs",
|
||||
"postprocessor-args", "ppa", "print-to-file", "rm-cache-dir", "use-postprocessor",
|
||||
)
|
||||
|
||||
// ffmpegOptions are the ffmpeg options /!webvideo/ passes on.
|
||||
var ffmpegOptions = setOf(
|
||||
"loglevel", "max_alloc", "filter_threads", "filter_complex_threads", "stats", "max_error_rate",
|
||||
"bits_per_raw_sample", "vol", "codec", "pre", "t", "to", "fs", "ss", "sseof", "seek_timestamp",
|
||||
"timestamp", "metadata", "program", "target", "apad", "frames", "filter_script", "reinit_filter",
|
||||
"discard", "disposition", "vframes", "r", "s", "aspect", "vn", "vcodec", "timecode", "pass", "ab", "b",
|
||||
"dn", "aframes", "aq", "ar", "ac", "an", "acodec", "sn", "scodec", "stag", "fix_sub_duration",
|
||||
"canvas_size", "spre", "f",
|
||||
)
|
||||
|
||||
var videoFormats = map[string][2]string{
|
||||
"avi": {"video/msvideo", "onlinevideo.avi"},
|
||||
"mpeg1video": {"video/mpeg", "onlinevideo.mpg"},
|
||||
"mpeg2video": {"video/mpeg", "onlinevideo.mpg"},
|
||||
"mpeg4": {"video/mp4", "onlinevideo.mp4"},
|
||||
"mpegts": {"video/mp2t", "onlinevideo.mts"},
|
||||
"asf": {"video/x-ms-asf", "onlinevideo.asf"},
|
||||
"asf_stream": {"video/x-ms-asf", "onlinevideo.asf"},
|
||||
"wmv": {"video/x-ms-asf", "onlinevideo.asf"},
|
||||
"mov": {"video/qucktime", "onlinevideo.mov"},
|
||||
"ogg": {"video/ogg", "onlinevideo.ogg"},
|
||||
"webm": {"video/webm", "onlinevideo.webm"},
|
||||
"swf": {"application/x-shockwave-flash", "onlinevideo.swf"},
|
||||
"rm": {"application/vnd.rn-realmedia", "onlinevideo.rm"},
|
||||
"3gp": {"video/3gpp", "onlinevideo.3gp"},
|
||||
}
|
||||
|
||||
// videoEnabled: [WebVideoOptions] Enable is on.
|
||||
func (t *transit) videoEnabled() bool {
|
||||
v, ok := t.cfg.WebVideoOptions["Enable"]
|
||||
return ok && config.ToBool(v)
|
||||
}
|
||||
|
||||
func (t *transit) videoOption(name, def string) string {
|
||||
if v, ok := t.cfg.WebVideoOptions[name]; ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// queryArgs is the query string as ordered pairs (later duplicates win).
|
||||
func queryArgs(q string) *config.Vars {
|
||||
v := config.NewVars()
|
||||
vals, _ := url.ParseQuery(q)
|
||||
keys := make([]string, 0, len(vals))
|
||||
for k := range vals {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
// keep the order of the query string
|
||||
sort.SliceStable(keys, func(i, j int) bool { return strings.Index(q, keys[i]+"=") < strings.Index(q, keys[j]+"=") })
|
||||
for _, k := range keys {
|
||||
v.Set(k, vals.Get(k))
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// webVideo is /!webvideo/: an online video through yt-dlp (and ffmpeg),
|
||||
// in a format the old computer can play (WebVideoConverter.cs).
|
||||
func (t *transit) webVideo(query string) {
|
||||
if !t.videoEnabled() {
|
||||
t.sendRedirect("/norovp.htm", "Video Converting and ROVP are disabled on this server.")
|
||||
return
|
||||
}
|
||||
args := queryArgs(query)
|
||||
if _, ok := args.Get("url"); !ok {
|
||||
help := "<p>WebOne can help download videos from popular sites in preferred format.</p>" +
|
||||
"<p>To download a video, go to <b><a href=\"/!player/\">Online Video Player</a></b>, enter URL of the video, " +
|
||||
"choose container and codecs valid for your system, and then select <b>file</b> or <b>link</b> option.</p>" +
|
||||
"<p>If you choose <b>file</b> option, the video file will start download automatically. " +
|
||||
"If you choose <b>link</b> option, you will get a link, which can be copied to multimedia player program.</p>" +
|
||||
"<p>Manual use parameters:<ul>" +
|
||||
"<li><b>url</b> - Address of the video (e.g. https://www.youtube.com/watch?v=fPnO26CwqYU or similar)</li>" +
|
||||
"<li><b>f</b> - Target format of the file (e.g. avi)</li>" +
|
||||
"<li><b>vcodec</b> - Codec for video (e.g. mpeg4)</li>" +
|
||||
"<li><b>acodec</b> - Codec for audio (e.g. mp3)</li>" +
|
||||
"<li><b>content-type</b> - override MIME content type for the file (optional).</li>" +
|
||||
"<li>Also you can use many <i>" + t.videoOption("YouTubeDlApp", "yt-dlp") +
|
||||
"</i> and <i>" + t.videoOption("FFmpegApp", "ffmpeg") +
|
||||
"</i> options like <b>aspect</b>, <b>b</b>, <b>no-mark-watched</b> and other.</li>" +
|
||||
"<li>Default parameter values are stored in configuration file.</li></ul></p>"
|
||||
t.sendInfoPage("Online video converter", "Web video converting", help, 200)
|
||||
return
|
||||
}
|
||||
v, err := t.convertVideo(args)
|
||||
if err != nil {
|
||||
t.log.Printf("Cannot convert video: %v", err)
|
||||
msg := "<p>" + err.Error() + "</p>" +
|
||||
"<p>Make sure that parameters are correct, and both <i>yt-dlp</i> and <i>ffmpeg</i> are properly installed on the server.</p>"
|
||||
t.sendInfoPage("Online video converter", "Web video converting", msg, 200)
|
||||
return
|
||||
}
|
||||
t.resp.AddHeader("Content-Disposition", `attachment; filename="`+v.fileName+`"`)
|
||||
t.sendStream(v.stream, v.contentType, -1, 200)
|
||||
}
|
||||
|
||||
type webVideo struct {
|
||||
stream io.ReadCloser
|
||||
contentType string
|
||||
fileName string
|
||||
}
|
||||
|
||||
func (t *transit) convertVideo(args *config.Vars) (*webVideo, error) {
|
||||
fromURL := map[string]bool{}
|
||||
for _, k := range args.Keys() {
|
||||
fromURL[k] = true
|
||||
}
|
||||
opts := make([]string, 0, len(t.cfg.WebVideoOptions))
|
||||
for k := range t.cfg.WebVideoOptions {
|
||||
opts = append(opts, k)
|
||||
}
|
||||
sort.Strings(opts)
|
||||
for _, k := range opts {
|
||||
args.TryAdd(k, t.cfg.WebVideoOptions[k])
|
||||
}
|
||||
mime, name := "application/octet-stream", "video.avi"
|
||||
if f, ok := args.Get("f"); ok {
|
||||
if p, ok := videoFormats[f]; ok {
|
||||
mime, name = p[0], p[1]
|
||||
} else {
|
||||
name = "onlinevideo." + f
|
||||
}
|
||||
}
|
||||
for _, k := range []string{"j", "J", "dump-json", "dump-single-json", "print-json"} {
|
||||
if _, ok := args.Get(k); ok {
|
||||
mime, name = "application/json", "metadata.json"
|
||||
}
|
||||
}
|
||||
args.TryAdd("content-type", mime)
|
||||
args.TryAdd("filename", name)
|
||||
|
||||
var ytArgs, ffArgs []string
|
||||
add := func(list *[]string, prefix, k, v string) {
|
||||
*list = append(*list, prefix+k)
|
||||
if v != "" {
|
||||
*list = append(*list, v)
|
||||
}
|
||||
}
|
||||
useFFmpeg, json := true, false
|
||||
vcodec, _ := args.Get("vcodec")
|
||||
acodec, _ := args.Get("acodec")
|
||||
for _, k := range args.Keys() {
|
||||
v := args.Value(k)
|
||||
if (strings.HasPrefix(k, "vf") && vcodec != "copy") || (strings.HasPrefix(k, "af") && acodec != "copy") || strings.HasPrefix(k, "filter") {
|
||||
add(&ffArgs, "-", k, v)
|
||||
continue
|
||||
}
|
||||
lk := strings.ToLower(k)
|
||||
switch {
|
||||
case lk == "enable":
|
||||
if !config.ToBool(v) {
|
||||
return nil, errors.New("This feature is disabled by administrator.")
|
||||
}
|
||||
case lk == "url" || lk == "content-type" || lk == "filename" || lk == "prefer" || lk == "gui" || lk == "youtubedlapp" || lk == "ffmpegapp":
|
||||
case lk == "noffmpeg":
|
||||
useFFmpeg = !config.ToBool(v)
|
||||
case lk == "j" || lk == "dump-json" || lk == "dump-single-json" || lk == "print-json":
|
||||
add(&ytArgs, "--", k, v)
|
||||
useFFmpeg, json = false, true
|
||||
case ytdlpOptions[lk]:
|
||||
if ytdlpUnsafe[lk] && fromURL[k] {
|
||||
t.log.Printf(" Refused argument from URL: %s", k)
|
||||
continue
|
||||
}
|
||||
add(&ytArgs, "--", k, v)
|
||||
case ffmpegOptions[lk]:
|
||||
add(&ffArgs, "-", k, v)
|
||||
default:
|
||||
t.log.Printf(" Unsupported argument: %s", k)
|
||||
}
|
||||
}
|
||||
video := args.Value("url")
|
||||
if strings.HasPrefix(video, "-") {
|
||||
return nil, errors.New("Internet video address is not correct.")
|
||||
}
|
||||
yt := exec.Command(t.videoOption("YouTubeDlApp", "yt-dlp"), append(append([]string{video}, ytArgs...), "-o", "-")...)
|
||||
ytOut, err := yt.StdoutPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ytErr, err := yt.StderrPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ff *exec.Cmd
|
||||
var out io.ReadCloser = ytOut
|
||||
if useFFmpeg {
|
||||
ff = exec.Command(t.videoOption("FFmpegApp", "ffmpeg"), append(append([]string{"-i", "pipe:"}, ffArgs...), "pipe:")...)
|
||||
ff.Stdin = ytOut
|
||||
if out, err = ff.StdoutPipe(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.log.Printf(" Video convert: %s %s | %s %s", yt.Path, strings.Join(yt.Args[1:], " "), ff.Path, strings.Join(ff.Args[1:], " "))
|
||||
} else {
|
||||
t.log.Printf(" Video convert: %s %s", yt.Path, strings.Join(yt.Args[1:], " "))
|
||||
}
|
||||
if err := yt.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ff != nil {
|
||||
if err := ff.Start(); err != nil {
|
||||
yt.Process.Kill()
|
||||
yt.Wait()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// yt-dlp's messages: an ERROR line means there is no video
|
||||
var mu sync.Mutex
|
||||
failure := ""
|
||||
failed := make(chan struct{}, 1)
|
||||
go func() {
|
||||
sc := bufio.NewScanner(ytErr)
|
||||
for sc.Scan() {
|
||||
l := sc.Text()
|
||||
switch {
|
||||
case strings.HasPrefix(l, "ERROR:"):
|
||||
mu.Lock()
|
||||
failure = "Online video failed to download: " + strings.TrimSpace(l[6:])
|
||||
mu.Unlock()
|
||||
t.log.Printf(" yt-dlp: %s", l)
|
||||
select {
|
||||
case failed <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
case strings.HasPrefix(l, "WARNING:"):
|
||||
t.log.Printf(" yt-dlp: %s", l)
|
||||
}
|
||||
}
|
||||
}()
|
||||
pr := &videoReader{br: bufio.NewReaderSize(out, 64*1024), procs: []*exec.Cmd{yt, ff}}
|
||||
ready := make(chan error, 1)
|
||||
go func() { _, err := pr.br.Peek(1); ready <- err }()
|
||||
select {
|
||||
case err = <-ready:
|
||||
case <-failed:
|
||||
err = errors.New("failed")
|
||||
case <-time.After(10 * time.Minute):
|
||||
err = errors.New("Online video download has timed out.")
|
||||
}
|
||||
if err != nil {
|
||||
mu.Lock()
|
||||
msg := failure
|
||||
mu.Unlock()
|
||||
if msg == "" {
|
||||
msg = "Online video is not available: " + err.Error()
|
||||
}
|
||||
pr.Close()
|
||||
return nil, errors.New(msg)
|
||||
}
|
||||
ct := args.Value("content-type")
|
||||
if json {
|
||||
ct = "application/json"
|
||||
}
|
||||
return &webVideo{stream: pr, contentType: ct, fileName: args.Value("filename")}, nil
|
||||
}
|
||||
|
||||
// videoReader is the converted video; closing it stops the programs.
|
||||
type videoReader struct {
|
||||
br *bufio.Reader
|
||||
procs []*exec.Cmd
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (v *videoReader) Read(p []byte) (int, error) { return v.br.Read(p) }
|
||||
|
||||
func (v *videoReader) Close() error {
|
||||
v.once.Do(func() {
|
||||
for _, c := range v.procs {
|
||||
if c != nil && c.Process != nil {
|
||||
c.Process.Kill()
|
||||
}
|
||||
}
|
||||
for _, c := range v.procs {
|
||||
if c != nil && c.Process != nil {
|
||||
c.Wait()
|
||||
}
|
||||
}
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// videoPlayerPage is the Retro Online Video Player, /!player/
|
||||
// (WebVideoPlayer.cs).
|
||||
func (t *transit) videoPlayerPage(query string) *infoPage {
|
||||
p := newInfoPage("Retro online video player", "", "", 200)
|
||||
p.ShowFooter = false
|
||||
p.HTMLHeaders = "<style type='text/css'>html, body { border-style: none; } </style>"
|
||||
args := queryArgs(query)
|
||||
pass := func(base string) string {
|
||||
for _, k := range args.Keys() {
|
||||
if k != "type" {
|
||||
base += k + "=" + url.QueryEscape(args.Value(k)) + "&"
|
||||
}
|
||||
}
|
||||
return base
|
||||
}
|
||||
videoURL := pass("/!webvideo/?")
|
||||
typ := args.Value("type")
|
||||
profile := args.Value("profile")
|
||||
if strings.TrimSpace(typ) == "" && strings.TrimSpace(profile) != "" {
|
||||
if prof, ok := t.cfg.WebVideoProfiles[profile]; ok && len(prof) > 1 {
|
||||
p.Content = "Loading the profile..."
|
||||
p.Status = 302
|
||||
p.Headers.Add("Location", pass("/!player/?")+prof[1])
|
||||
return p
|
||||
}
|
||||
}
|
||||
if !t.videoEnabled() {
|
||||
p.Content = "It's disabled."
|
||||
p.Status = 302
|
||||
p.Headers.Add("Location", "/norovp.htm")
|
||||
return p
|
||||
}
|
||||
if strings.TrimSpace(typ) == "" {
|
||||
typ = "splash"
|
||||
}
|
||||
switch typ {
|
||||
case "link":
|
||||
p.Content = "<center><big><a href='" + videoURL + "'>Download the video</a></big></center>"
|
||||
if _, ok := args.Get("f"); !ok {
|
||||
p.Content += "<center><p>Or select format, codecs and convert the video online.</p></center>"
|
||||
}
|
||||
p.Title = "Video player - link only"
|
||||
case "file":
|
||||
p.Content = "<center>Please wait up to 30 sec.<br>If nothing appear, <a href='" + videoURL + "'>click here</a> to download manually.</center>"
|
||||
p.Headers.Add("Refresh", "0; url="+videoURL)
|
||||
p.Title = "Video player - FILE REDIRECT"
|
||||
default:
|
||||
p.Status = 302
|
||||
loc := "/rovp-" + typ + ".htm"
|
||||
if videoURL != "/!webvideo/?" {
|
||||
loc += "?VideoUrl=" + url.QueryEscape(videoURL)
|
||||
}
|
||||
if typ == "html5" {
|
||||
loc += "&JsonUrl=" + url.QueryEscape("/!webvideo/?&dump-json=&url="+args.Value("url")+"&no-warnings=&quiet=")
|
||||
}
|
||||
p.Headers.Add("Location", loc)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// redirectorPage is /!redirect/?RegExMask=...&RegExGroup=n&OriginalString=...
|
||||
// (RedirectorInfoPage.cs).
|
||||
func (t *transit) redirectorPage(query string) *infoPage {
|
||||
p := newInfoPage("WebOne: Redirection", "Redirection", "", 200)
|
||||
p.Content = ""
|
||||
args, _ := url.ParseQuery(query)
|
||||
mask := args.Get("RegExMask")
|
||||
orig := args.Get("OriginalString")
|
||||
group := 0
|
||||
if g := args.Get("RegExGroup"); g != "" {
|
||||
for _, r := range g {
|
||||
if r < '0' || r > '9' {
|
||||
group = 0
|
||||
break
|
||||
}
|
||||
group = group*10 + int(r-'0')
|
||||
}
|
||||
}
|
||||
fail := func(msg string) *infoPage {
|
||||
p.Content += "<p><b>Error: " + msg + "</b></p>"
|
||||
return p
|
||||
}
|
||||
if strings.TrimSpace(mask) == "" {
|
||||
return fail("RegExMask is empty.")
|
||||
}
|
||||
if strings.TrimSpace(orig) == "" {
|
||||
return fail("OriginalString is empty.")
|
||||
}
|
||||
m, ok := rx.FindGroupsOK(mask, orig)
|
||||
if m == nil {
|
||||
return p
|
||||
}
|
||||
if group >= len(m) {
|
||||
return fail("RegExGroup is more than " + strconv.Itoa(len(m)) + ".")
|
||||
}
|
||||
u := ""
|
||||
if ok[group] {
|
||||
u = m[group]
|
||||
}
|
||||
p.Content = "<p>It will be better to open <a href='" + u + "'>" + u + "</a> instead of this stub.</p>"
|
||||
p.Status = 302
|
||||
p.Headers.Add("Location", u)
|
||||
return p
|
||||
}
|
||||
Reference in new issue
Block a user