diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml new file mode 100644 index 0000000..0ae43a8 --- /dev/null +++ b/.github/workflows/go.yml @@ -0,0 +1,18 @@ +name: Go + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + - run: go vet ./... + - run: go test -race ./... + - run: go build -o webone ./cmd/webone diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d5f0071 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/webone +/webone.exe +ssl.crt +ssl.key +*.log diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..baf9e73 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,29 @@ +License agreement for WebOne Proxy Server +========================================= + +Copyright (C) 2019+, WebOne Development Team. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +* Neither the name of the WebOne nor the names of its contributors may be used + to endorse or promote products derived from this software without specific + prior written permission. +* All users (clients) of service(s) based on this software must be notified + about traffic changes and possible security problems. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/README.md b/README.md index 6028a00..c5db361 100644 --- a/README.md +++ b/README.md @@ -1 +1,223 @@ -# WebOne-go \ No newline at end of file +# WebOne-go + +A Go port of [WebOne](https://github.com/atauenis/webone), the HTTP 1.x proxy +that makes old web browsers, media players and messengers usable again on +today's web. Old browsers ask the proxy for `http://` pages. The proxy fetches +them over modern HTTPS, patches what old browsers choke on, converts the text +to a code page they can read, and sends it back as HTTP/1.0 or 1.1. + +D-Modem uses it so that callers dialling into the BBS can browse the web from +period machines. The proxy can sign its HTTPS certificates with the BBS's own +CA, so callers only have to install one certificate. + +## Where this comes from + +WebOne is written in C# by Alexander Tauenis and the WebOne Development Team, +under the BSD-style licence in [LICENSE.txt](LICENSE.txt). This repository is +a derivative work. It follows WebOne **0.19.0** at upstream commit +[`e940b43`](https://github.com/atauenis/webone/commit/e940b4304779f1f1a58d1e9df9500bdb6461e41e) +(22 October 2026). The Go code is a new translation of that C#, file by file: +`HttpTransit.cs` became `internal/proxy/transit.go`, `ConfigFileLoader.cs` +became `internal/config/loader.go`, and so on. The files below are WebOne's +own and are kept as upstream has them, except where noted: + +* `LICENSE.txt`, unchanged. Its last clause applies to this port too: **all + users of a service based on this software must be told that their traffic + is changed, and about the security problems that brings.** +* `webone.conf`, `codepage.conf`, `escargot.conf`: WebOne's configuration + and sets of edits. `webone.conf` has the Go port's options added as + comments, and `SslProtocols` no longer lists SSL 2.0 and 3.0 (see below). +* `html/` (internal and error pages, icons) and `logo.webp`. +* `webone.service`, `webone.logrotate`. The service file drops the .NET-only + `OPENSSL_CONF` line and gains a note about running as the BBS's user. + +The [WebOne wiki](https://github.com/atauenis/webone/wiki) documents the +configuration, and that documentation holds for this port. The differences +are listed below. + +## Build and run + +Go 1.26 or later: + +```sh +go build -o webone ./cmd/webone +./webone # finds webone.conf (here, next to the program, ~/.config/webone, /etc) +./webone 8080 # on another port +./webone -cfg /etc/webone.conf -l /var/log/webone.log +./webone --help +``` + +The `html/` directory goes next to the program, or wherever `ContentDirectory=` +points. Then set the old browser's HTTP proxy to `host:8080`, or its automatic +configuration URL to `http://host:8080/auto.pac`. Browsers with no proxy +setting can use `http://host:8080/http://example.com/`. Open +`http://host:8080/` to see the proxy's status page. + +What works: + +* All three ways of asking: as a proxy, as a web server for its own pages, + and the `http://proxy/http://site/` alternate mode. CERN-style FTP is + supported too. +* HTTP/1.0 and HTTP/1.1 clients, with keep-alive. The reply uses chunked + transfer only for HTTP/1.1 clients. +* Fetching over HTTPS (and HTTP/2), with HTTP→HTTPS upgrades, + `[ForceHttps]`, and redirect loop ("carousel") handling. +* Sets of edits (`[Edit:...]`): every condition and action WebOne has, .NET + regular expressions included (through + [regexp2](https://github.com/dlclark/regexp2)). +* Code pages: `OutputEncoding`, `[Translit]`, and `codepage.conf`. Windows, + DOS, Mac, ISO and KOI8 code pages are included, as are UTF-16 and the CJK + ones. +* The HTTPS proxy (CONNECT): man-in-the-middle with a per-site + certificate, pass-through (`[ConnectPassThrough]`), non-HTTP tunnels + (`[NonHttpSslServers]`, `[NonHttpConnectRedirect]`) and `[NonHttpSslDecrypt]`. +* The CA: made on first start, or `--rebuild-ca`. MD5, SHA-1 or SHA-2 + signatures. External generators (`SslSiteCerts`, `SslSiteCertGenerator`). + `/!ca` and `/weboneca.pem` serve the CA certificate. +* Internal pages: status, `/!codepages`, PAC/WPAD, `/!ftp/` (the web FTP + client), `/!convert/` and on-the-fly converters (ImageMagick and others), + `/!webvideo/` and `/!player/` (yt-dlp and ffmpeg), `/!redirect/`, + `/!clear/`, and the `html/` pages and error pages. +* The Web Archive fallback, proxy logins, IP and URL lists, traffic dumps + (`--dump`), ActiveX codebase emulation, and log files. + +## Using the D-Modem BBS's CA + +The BBS keeps a CA (see the BBS's *Certificates* wiki page). Callers install +its root, `ca/ca.crt`, from `ca/install-ca.zip`. Give the proxy a sub-CA of +its own: + +```sh +bbs ca subca proxy # makes ca/proxy-ca.crt and ca/proxy-ca.key +``` + +and point the proxy at the directory: + +```ini +[SecureProxy] +SslEnable=yes +SslCaDirectory=/var/lib/bbs/ca ; the BBS's ca/ directory, beside its database +;SslHashAlgorithm=SHA1 ; leave out to sign as the sub-CA is signed + +[Server] +DnsServer=127.0.0.1:53 ; optional: look sites up through the BBS's DNS +``` + +With `SslCaDirectory` set: + +* The proxy signs each site's certificate with `proxy-ca.key`, and sends + `proxy-ca.crt` after it. Callers who installed the BBS root trust both. +* `/!ca` hands out the root `ca.crt`, which is the one callers install. +* Unless `SslHashAlgorithm` is set, certificates are signed with the + sub-CA's own algorithm. A CA made with `bbs ca init -sha1` therefore gives + SHA-1 certificates, which Windows 95 to XP SP2 need. +* Site certificates last at most 397 days. They are cached, and each subject + keeps one serial number. +* The BBS's files are never changed, and `--rebuild-ca` refuses to touch them. + A directory with no `proxy-ca` falls back to signing with the root's + `ca.key`, and logs a warning. Making the sub-CA is the better way. + +**Permissions.** The BBS keeps `ca/` at mode 0700 and the keys at 0600, owned +by the user in its `[general]` section. Either run the proxy as that user +(see `webone.service`), or give the proxy's user read access to +`ca/proxy-ca.key`, `ca/proxy-ca.crt` and `ca/ca.crt` (for example, through a +shared group), plus search access to `ca/`. The proxy says plainly when it +cannot read them. + +`SslTrustOwnCA=yes` makes the proxy also trust that CA when it fetches pages +itself. Use it for sites the BBS serves under its own CA. + +## Differences from WebOne + +### Not available in Go + +* **No SSL 2.0 or 3.0, and no SSLv2-format hello.** Go's TLS starts at + TLS 1.0. Browsers that only speak SSL (Netscape 1 to 4, IE 2 to 5 with its + defaults) cannot use the CONNECT/MITM mode. They work fine through the + plain HTTP proxy, which is WebOne's main mode anyway: the browser asks for + `http://`, and the proxy does the HTTPS. `Ssl2` and `Ssl3` in + `SslProtocols` are ignored with a warning. Clients that need TLS 1.0 with + old ciphers (IE 6 to 8 on XP) do work: all of Go's suites, the weak ones + included, are offered unless `SslCipherSuites` says otherwise. Supporting + SSL 3.0 is a possible follow-up. +* `UseMsHttpApi` (Windows' HTTP.sys server) does not exist here. It is + ignored with a warning, and the proxy always uses its own server, as + WebOne does by default. +* `MultipleHttp2Connections` is accepted, but Go decides this itself. + +### Fixed on purpose + +These are bugs or rough edges in WebOne 0.19.0 that the port does not copy: + +* Edit sets' `OnContentType` masks are tested against the response's content + type in the right order. +* `%UrlNoDomain%`, `%UrlNoQuery%`, `%UrlNoPort%`, `%UrlHttp%` and + `%UrlHttps%` no longer produce `//` or `??`. +* Several `Set-Cookie` headers reach the client as separate lines, instead + of joined with commas. +* `Connection: Keep-Alive` is sent only to clients that keep connections: + ones that ask for it, and HTTP/1.1 ones unless they say `close`. Other + clients get `Connection: Close`. WebOne promises keep-alive to everyone and + then closes. +* Replies to `HEAD`, and `204`/`304` replies, have no body or chunk + terminator. +* Request bodies sent chunked are accepted (WebOne has this stubbed out). +* `$Variable` names are replaced longest first, so `$UA-Firefox` is not cut + short by `$UA`. +* `OpenForLocalIPs` decides what is "local" from the address (loopback, + private, link-local) instead of pinging the client with a TTL of 1. +* Error pages escape what they pass to `html/Err-*.htm`, so a URL with `&` in + it is shown whole. +* The web FTP client reads multi-line FTP replies properly instead of timing + them. It accepts `125` as well as `150`, and falls back to the control + connection's host when a server behind NAT gives a private address for + passive mode. +* Code pages round-trip: bytes a code page leaves undefined come back as the + same bytes, as .NET does. +* `/!webvideo/` with `dump-json` returns yt-dlp's output, where WebOne + returned its error stream. + +### Tightened + +* `/!convert/?src=` opens only files in the proxy's own directory (no paths). + WebOne opens any path it is given. +* `/!webvideo/` does not take yt-dlp options that read or write files or run + programs (`exec`, `output`, `batch-file`, `config-locations`, `cookies`, + `netrc-cmd` and similar) from the URL. They still work from + `[WebVideoOptions]` in the configuration. +* Converters that hang are stopped when the client goes away. WebOne instead + measures CPU use with Windows performance counters. + +### Added (Go port only) + +| Option | Section | What it does | +|---|---|---| +| `SslCaDirectory` | `[SecureProxy]` | sign with the D-Modem BBS's CA (above) | +| `SslTrustOwnCA` | `[SecureProxy]` | trust the proxy's CA for fetched sites too | +| `DnsServer` | `[Server]` | look sites up through this DNS server (`host` or `host:port`) | + +The version is reported as `0.19.0-go`. + +## Layout + +``` +cmd/webone the program: command line, CA loading, start-up +internal/config webone.conf: loading, [Include:], variables, sets of edits +internal/proxy the server, request handling, CONNECT, internal pages, FTP, video +internal/certs the CA, site certificates (MD5/SHA-1 signing), the BBS's CA +internal/textenc code pages +internal/rx .NET-style regular expressions, cached +internal/logx the log, in WebOne's format +``` + +`go test ./...` covers configuration parsing, edit sets, code pages, the +certificates (including a BBS-style sub-CA chain), and the proxy end to end: +HTTP/1.0 with edits and a code page, HTTPS fetching, alternate mode, +keep-alive with chunked replies, internal pages, CONNECT with MITM, and +pass-through. + +## Licence + +This port is under the same terms as WebOne: see [LICENSE.txt](LICENSE.txt). +Copyright (C) 2019+, WebOne Development Team. The Go port is copyright the +D-Modem project contributors. diff --git a/cmd/webone/main.go b/cmd/webone/main.go new file mode 100644 index 0000000..6d6e292 --- /dev/null +++ b/cmd/webone/main.go @@ -0,0 +1,326 @@ +// Command webone is WebOne, the HTTP proxy that lets old web browsers +// reach today's web, ported to Go. +// +// webone [config file] [port] [-cfg file] [-l logfile|no] [-p port] +// [-h hostname] [-t tempdir] [-a user:pass] [--dump [file]] +// [--rebuild-ca] [--daemon] [--help] +package main + +import ( + "errors" + "fmt" + "net" + "os" + "os/signal" + "runtime" + "strconv" + "strings" + "syscall" + "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" + "github.com/D-Modem/webone-go/internal/proxy" +) + +type arg struct{ name, value string } + +const unnamed = "--wo-short" + +// parseArgs splits the command line as WebOne does: "-name value" pairs, +// and values without a name (a port or a configuration file). +func parseArgs(args []string) []arg { + var out []arg + name, value, lastWasValue := unnamed, "", false + for _, a := range args { + if strings.HasPrefix(a, "-") || (runtime.GOOS == "windows" && strings.HasPrefix(a, "/")) { + out = append(out, arg{name, value}) + name, value, lastWasValue = a, "", false + continue + } + if lastWasValue { + out = append(out, arg{name, value}) + } + value, lastWasValue = a, true + } + return append(out, arg{name, value}) +} + +func main() { + os.Exit(run(os.Args[1:])) +} + +func run(argv []string) int { + version := proxy.Version + system := runtime.GOOS + " " + runtime.GOARCH + " (Go " + runtime.Version() + ")" + fmt.Printf("WebOne HTTP Proxy Server %s\nhttps://github.com/D-Modem/webone-go (a Go port of https://github.com/atauenis/webone)\n\n\n", version) + + args := parseArgs(argv) + var customConfig, logFile string + logSet, logOff, rebuildCA, daemon := false, false, false, false + port := -1 + for _, a := range args { + switch a.name { + case "/cfg", "-cfg", "-config", "--config": + customConfig = a.value + case "/l", "-l", "--log": + logSet = true + if a.value == "" || a.value == "no" { + logOff = true + } else { + logFile = a.value + } + case "/t", "-t", "--tmp", "--temp", "/p", "-p", "--port", "--http-port", "--https-port", "--ftp-port", + "/h", "-h", "--host", "--hostname", "/a", "-a", "--proxy-authenticate", + "--dump", "--dump-headers", "--dump-requests": + // after the configuration is loaded + case "--rebuild-ca": + rebuildCA = true + case "--daemon": + daemon = true + case "--help", "-?", "/?": + fmt.Println("Usage: webone [config file] [port] [options]") + fmt.Println() + fmt.Println(" -cfg FILE configuration file (default: webone.conf, searched for)") + fmt.Println(" -l FILE | -l no log file, or no log file") + fmt.Println(" -p PORT port to listen on") + fmt.Println(" -h NAME host name of the proxy as clients reach it") + fmt.Println(" -t DIR directory for temporary files") + fmt.Println(" -a USER:PASS require this proxy login (replaces the configured ones)") + fmt.Printf(" --dump [FILE] save all HTTP traffic (default dump-%%Url%%.log)\n") + fmt.Println(" --rebuild-ca make a new CA certificate, then exit") + fmt.Println(" --daemon print nothing; log to the log file only") + fmt.Println() + fmt.Println("All of WebOne's options are described in its wiki: https://github.com/atauenis/webone/wiki") + fmt.Println() + fmt.Println("Initially made by Alexander Tauenis. Moscow, Russian Federation.") + return 0 + case unnamed: + if strings.TrimSpace(a.value) == "" { + break + } + if n, err := strconv.Atoi(a.value); err == nil { + port = n + fmt.Printf("Using custom port %d.\n", port) + break + } + customConfig = a.value + default: + fmt.Printf("Unknown command line argument: %s.\n", a.name) + } + } + + cfg := config.New() + cfg.Vars.Set("WOVer", version) + cfg.Vars.Set("WOSystem", system) + if customConfig != "" { + customConfig = cfg.Expand(customConfig, nil) + } + if logFile != "" { + logx.OpenLogFile(cfg.Expand(logFile, nil), false, version, argv) + } + + cfgFile, err := config.FindConfigFile(customConfig) + if err == nil { + if err = cfg.LoadFile(cfgFile); err == nil { + err = cfg.Process() + } + } + if err != nil { + fmt.Printf("Error while loading configuration: %v\n", err) + logx.Server(false, "WebOne has been exited due to lack of configuration.") + return 1 + } + if port > 0 { + cfg.Port = port + } + if !logSet && cfg.LogFile != "" { + logx.OpenLogFile(cfg.Expand(cfg.LogFile, nil), cfg.LogFileAppend, version, argv) + } + + // options that override the configuration + for _, a := range args { + switch a.name { + case "/t", "-t", "--tmp", "--temp": + cfg.TemporaryDirectory = cfg.Expand(a.value, nil) + case "/p", "-p", "--port", "--http-port", "--https-port", "--ftp-port": + n, err := strconv.Atoi(a.value) + if err != nil { + fmt.Printf("Warning: Wrong argument '%s %s': %v.\n", a.name, a.value, err) + continue + } + cfg.Port = n + case "/h", "-h", "--host", "--hostname": + cfg.DefaultHostName = a.value + case "/a", "-a", "--proxy-authenticate": + cfg.Authenticate = []string{a.value} + case "--dump", "--dump-headers", "--dump-requests": + file := "dump-%Url%.log" + if a.value != "" { + file = a.value + } + logx.Server(true, "Will save all HTTP traffic to: %s.", file) + sec, _ := config.ParseSection("[Edit]", "[command line]") + opt, _ := config.ParseOption("AddDumping="+file, "[command line]") + sec.Options = append(sec.Options, opt) + if set, err := config.NewEditSet(sec, cfg); err == nil { + cfg.EditRules = append(cfg.EditRules, set) + } + } + } + cfg.SetProxyVars() + + if logOff || (!logSet && cfg.LogFile == "") { + logx.OpenLogFile("", false, version, argv) + } + if daemon { + if !logx.Enabled() { + fmt.Println("Error: log file is not available, please fix the problem. Exiting.") + return 1 + } + fmt.Println("The proxy runs in daemon mode. See all messages in the log file.") + logx.Daemon = true + } + + pacDefault := cfg.PAC == "" + pac := config.DefaultPACHeader + config.DefaultPACHttp + protocols := "HTTP 1.1" + + var ca, root *certs.CA + if cfg.SslEnable { + ca, root, err = loadCA(cfg, rebuildCA) + if rebuildCA { + if err != nil { + logx.Server(true, "Unable to create CA Certificate: %v.", err) + return 1 + } + return 0 + } + if err != nil { + logx.Server(true, "%v.", err) + cfg.SslEnable = false + } else { + protocols += ", HTTPS 1.1" + pac += config.DefaultPACHttps + } + if cfg.SslSiteCertGenerator != "" && cfg.SslSiteCerts == "" { + logx.Server(true, "Warning: `SslSiteCertGenerator` is set but `SslSiteCerts` is not. Will use internal certificate generator.") + cfg.SslSiteCertGenerator = "" + } + } + protocols += ", CERN-compatible" + pac += config.DefaultPACFtp + config.DefaultPACFooter + if pacDefault { + cfg.PAC = pac + } + logx.Server(false, "Configured to http://%s:%d/, %s", cfg.DefaultHostName, cfg.Port, protocols) + + srv, err := proxy.New(cfg, ca, root) + if err != nil { + logx.Server(true, "Server initialize failed: %v", err) + return 1 + } + + sig := make(chan os.Signal, 1) + signal.Notify(sig, os.Interrupt, syscall.SIGTERM) + go func() { + <-sig + srv.Stop() + }() + + addr := net.JoinHostPort("", strconv.Itoa(cfg.Port)) + if cfg.IP != nil { + addr = net.JoinHostPort(cfg.IP.String(), strconv.Itoa(cfg.Port)) + } + ln, err := net.Listen("tcp", addr) + if err != nil { + logx.Server(true, "Cannot start server: %v", err) + if errors.Is(err, syscall.EACCES) && runtime.GOOS != "windows" { + fmt.Println() + fmt.Println(`You need to use "sudo webone" or use Port greater than 1024.`) + } + logx.Close() + return 1 + } + logx.Server(true, "Listening for HTTP 1.x on port %d.", cfg.Port) + if err := srv.Serve(ln); err != nil { + logx.Server(true, "Server stopped: %v", err) + logx.Close() + return 1 + } + logx.Server(false, "WebOne has been exited.") + logx.Close() + return 0 +} + +// loadCA is the CA that signs site certificates and the root clients +// install: the D-Modem BBS's (SslCaDirectory), or WebOne's own, made when +// missing (or always with --rebuild-ca). +func loadCA(cfg *config.Config, rebuild bool) (*certs.CA, *certs.CA, error) { + if cfg.SslCaDirectory != "" { + if rebuild { + return nil, nil, fmt.Errorf("the CA in %s belongs to the BBS (bbs ca); it is not rebuilt here", cfg.SslCaDirectory) + } + ca, root, err := certs.BBSCA(cfg.SslCaDirectory) + if err != nil { + return nil, nil, fmt.Errorf("Unable to load CA Certificate: %v", err) + } + if !cfg.SslHashAlgorithmSet { + // sign as the CA above does: a SHA-1 root is for clients that + // know no better + cfg.SslHashAlgorithm = certs.HashOf(ca.Cert) + } + if ca == root { + logx.Server(true, "Using as SSL Certificate Authority: %s (the BBS root CA itself; better give the proxy a sub-CA of its own with \"bbs ca subca proxy\").", cfg.SslCaDirectory) + } else { + logx.Server(false, "Using as SSL Certificate Authority: %s, sub-CA \"%s\" of \"%s\".", + cfg.SslCaDirectory, ca.Cert.Subject.CommonName, root.Cert.Subject.CommonName) + } + checkValidity(cfg, ca) + return ca, root, nil + } + + const minPEM = 52 // header and footer only + have := false + if st, err := os.Stat(cfg.SslCertificate); err == nil && st.Size() > minPEM { + if st, err := os.Stat(cfg.SslPrivateKey); err == nil && st.Size() > minPEM { + have = true + } + } + if have && !rebuild { + logx.Server(false, "Using as SSL Certificate Authority: %s, %s.", cfg.SslCertificate, cfg.SslPrivateKey) + } else { + if rebuild { + fmt.Println() + logx.Server(true, "CA Certificate will be new, so import it to browser(s) after build succeeds.") + } + logx.Server(true, "Creating root SSL Certificate & Private Key for CA...") + if err := certs.CreateCA(cfg.SslCertificate, cfg.SslPrivateKey, cfg.SslRootSubject, cfg.SslHashAlgorithm, + cfg.SslRootValidAfter, cfg.SslRootValidBefore); err != nil { + return nil, nil, fmt.Errorf("Unable to create CA Certificate: %v", err) + } + logx.Server(true, "CA Certificate: %s; Key: %s.", cfg.SslCertificate, cfg.SslPrivateKey) + } + ca, err := certs.LoadCA(cfg.SslCertificate, cfg.SslPrivateKey) + if err != nil { + return nil, nil, fmt.Errorf("Unable to load CA Certificate: %v", err) + } + if rebuild { + logx.Server(true, "The new certificate is called \"%s\".", ca.Cert.Subject.CommonName) + logx.Server(true, "WebOne will now exit.") + return ca, ca, nil + } + checkValidity(cfg, ca) + return ca, ca, nil +} + +func checkValidity(cfg *config.Config, ca *certs.CA) { + now := time.Now() + if ca.Cert.NotAfter.Before(now) || ca.Cert.NotBefore.After(now) { + logx.Server(true, "Warning! CA Certificate is out of date: %s-%s, now %s.", ca.Cert.NotBefore, ca.Cert.NotAfter, now) + } + if ca.Cert.NotAfter.Before(now.AddDate(0, 0, cfg.SslCertValidAfterNow)) || ca.Cert.NotBefore.After(now.AddDate(0, 0, cfg.SslCertValidBeforeNow)) { + logx.Server(true, "Warning! CA Certificate is too fresh or expires too soon. Check configuration.") + } +} diff --git a/codepage.conf b/codepage.conf new file mode 100644 index 0000000..120c38e --- /dev/null +++ b/codepage.conf @@ -0,0 +1,114 @@ +; Automatic output encoding select +; You may edit this file if experience problems with non-English content: +; https://github.com/atauenis/webone/wiki/Troubleshooting-language-support + +; Mosaic, Netscape 0-3, IE 1-3, Arachne - Windows ANSI +[Edit] +OnHeader=User-Agent: NCSA_Mosaic +OnHeader=User-Agent: Mozilla/[0123].*Win +OnHeader=User-Agent: xChaos_Arachne/ +AddOutputEncoding=Windows + +; Netscape 0-3 - OS/2 (prefers DOS code pages) +[Edit] +OnHeader=User-Agent: Mozilla/[0123].*OS/2 +AddOutputEncoding=DOS + +; IBM WebExplorer - OS/2 (prefers ISO code pages) +[Edit] +OnHeader=User-Agent: IBM WebExplorer +AddOutputEncoding=ISO-8859 + +; Netscape 0-3, IE 1-3 - classic Apple MacOS +[Edit] +OnHeader=User-Agent: Mozilla/[0123].*Mac +AddOutputEncoding=Apple + +; DosLynx - DOS OEM +[Edit] +OnHeader=User-Agent: .*DOS +OnHeader=User-Agent: .*Dos +AddOutputEncoding=DOS +; uncomment line below to enable alphabet transliteration +;AddTranslit=yes + + +; Alphabet transliteration table +; The following example is from Russian to Latin (English letters). +; Any other alphabet can be used here too. Just write it in same syntax. +; Works only if there is an "AddTranslit=yes" in any active edit set. +[Translit] +а=a +б=b +в=v +г=g +ґ=gg +д=d +е=e +ё=yo +є=ye +ж=zh +з=z +и=i +й=j +ї=yi +к=k +л=l +м=m +н=n +о=o +п=p +р=r +с=s +т=t +у=u +ў=w +ф=f +х=h +ц=c +ч=ch +ш=sh +щ=sch +ъ=_ +ь=' +ы=y +э=e +ю=yu +я=ya +А=A +Б=B +В=V +Г=G +Ґ=GG +Д=D +Е=E +Ё=YO +Є=YE +Ж=ZH +З=Z +И=I +Й=J +Ї=YI +К=K +Л=L +М=M +Н=N +О=O +П=P +Р=R +С=S +Т=T +У=U +Ў=W +Ф=F +Х=H +Ц=C +Ч=CH +Ш=SH +Щ=SCH +Ъ=~ +Ь=' +Ы=Y +Э=E +Ю=YU +Я=YA diff --git a/escargot.conf b/escargot.conf new file mode 100644 index 0000000..a126fdf --- /dev/null +++ b/escargot.conf @@ -0,0 +1,153 @@ +; Windows Live Messenger - Escargot gateway configuration. +; Don't forget to import WebOne Root Certificate in Windows registry. + +; Login +[Edit:^http://messenger.hotmail.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; Gateway +[Edit:^http://gateway.messenger.hotmail.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; MSN 4.7-7.0 Login +[Edit:^http://nexus.passport.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 +AddResponseHeader=PassportURLs: DALogin=https://ds.escargot.nina.chat/login,DAReg=http://%Proxy%/msnreg.htm,Properties=https://account.escargot.chat/,Privacy=https://escargot.chat/legal/privacy/ + +; MSN 4.7 Login, step 2 +[Edit:http://login.live.com/login2.srf] +AddInternalRedirect=https://msnmsgr.escargot.chat/login + +; MSN 7.5 Login +[Edit:^http://loginnet.passport.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; MSN 8 Login +[Edit:^http://login.live.com/(.*)] +IgnoreUrl=login2.srf +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; MSN login fix +[Edit:^http://ds.escargot.nina.chat/loginDALogin=https://ds.escargot.nina.chat/login] +AddInternalRedirect=https://ds.escargot.nina.chat/login + +; PocketMSN 5 Login +[Edit:^http://[a-zA-Z0-9\.]*.mobile.msn.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; PocketWLM 10 Login +[Edit:^http://[a-zA-Z0-9\.]*.mobile.live.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; MSN 6+ configuration +[Edit:^http://config.messenger.msn.com/(.*)] +AddInternalRedirect=https://conf.escargot.chat/$1 + +; MSN 8+ contacts +[Edit:^http://byrdr.omega.contacts.msn.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; Offline messaging +[Edit:^http://ows.messenger.msn.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 +[Edit:^http://rsi.hotmail.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; MSN 8+ Windows Live Space +[Edit:^http://tkrdr.storage.msn.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; MSN 9+ What's New service +[Edit:^http://sup.live.com/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 + +; MSN 7 (old Escargot patch) +[Edit:http://m1.escargot.chat/login] +AddInternalRedirect=https://msnmsgr.escargot.chat/login + +; Login (application bug) +[Edit:^http://255.255.255.255/(.*)] +AddInternalRedirect=https://msnmsgr.escargot.chat/$1 +; used if HKCU\Software\Microsoft\MessengerService\Server = "messenger.hotmail.com;255.255.255.255" + +; HTML content: +; .NET Service Status +[Edit:^http://status.messenger.msn.com/(.*)] +AddInternalRedirect=http://web.archive.org/web/20090212104204id_/http://status.messenger.msn.com/$1 + +; Connection troubleshooter +[Edit:^http://g.msn.com/5meen_us/140] +AddRedirect=http://web.archive.org/web/20070704092740if_/http://messenger.msn.com/ct/ + +; What's new in Messenger +[Edit:^http://g.msn.com/5meen_us/153] +AddRedirect=https://web.archive.org/web/20060411191031if_/http://www.imagine-msn.com/messenger/runonce/mosaic.aspx?locale=en + +; Avatar gallery +[Edit:^http://g.msn.com/5meen_us/117] +AddRedirect=https://web.archive.org/web/20040130070134if_/http://messenger.msn.com/resource/cTiles.aspx?mkt=- + +; Help +[Edit:^http://g.msn.com/5meen_us/107] +AddRedirect=https://web.archive.org/web/20110601234816/http://help.live.com/help.aspx?project=a&market=en-us + +; Privacy +[Edit:^http://g.msn.com/5meen_us/112] +AddRedirect=https://web.archive.org/web/20060423153451if_/http://privacy.microsoft.com/en-us/default.aspx + +; Send Feedback +[Edit:^http://g.msn.com/5meen_us/150] +AddRedirect=https://web.archive.org/web/20061022190527if_/http://feedback.live.com/eform.aspx?productkey=wlmessenger + +; MSN Home Page +[Edit:^http://g.msn.com/5meen_us/103] +AddRedirect=https://escargot.chat/ + +; Service Status +[Edit:^http://g.msn.com/5meen_us/109] +AddRedirect=https://escargot.chat/stats/ + +; MSN Users Directory +[Edit:^http://g.msn.com/5meen_us/125] +AddRedirect=https://escargot.chat/contacts/ + +; Windows XP .NET Passport Sign up wizard +[Edit:^http://register.passport.com/defaultwiz.asp] +AddRedirect=http://%Proxy%/msnreg.htm + +; Windows XP .NET Passport Sign up wizard (WL) +[Edit:^https://login.live.com/err.srf] +AddRedirect=http://%Proxy%/msnreg.htm + +; Windows XP .NET Passport Edit profile +[Edit:^http://memberservices.passport.com/ppsecure/MSRV_EditProfile.asp] +AddRedirect=https://escargot.chat/account/ + +; Windows XP .NET Passport Edit profile (WL) +[Edit:^http://account.live.com/EditProf.aspx] +AddRedirect=https://escargot.chat/account/ + +; Windows XP .NET Passport Privacy policy +[Edit:^http://www.passport.com/consumer/privacypolicy.asp] +AddRedirect=https://escargot.chat/legal/privacy/ + +; Windows XP .NET Passport Privacy policy (WL) +[Edit:^http://login.live.com/gls.srf\?urlID=MSNPrivacyStatement] +AddRedirect=https://escargot.chat/legal/privacy/ + +; Windows XP .NET Passport Help +[Edit:^http://memberservices.passport.com/UI/MSRV_UI_Help.asp] +AddRedirect=https://escargot.chat/legal/rules/ + +; Windows XP .NET Passport Help (WL) +[Edit:^http://account.live.com/.*dc=PPRDR_Help] +AddRedirect=https://escargot.chat/legal/rules/ + +; Sign Up for a new .NET Passport +[Edit:^http://g.msn.com/5meen_us/105] +AddRedirect=https://escargot.chat/register/ + + +; Docs: +; https://wiki.nina.chat/wiki/Protocols/MSNP/URLs_used_by_MSN +; https://gitlab.com/escargot-chat/server/-/wikis/urls-used-by-msn \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f83c563 --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module github.com/D-Modem/webone-go + +go 1.26.0 + +require ( + github.com/dlclark/regexp2 v1.12.0 + golang.org/x/text v0.44.0 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..452339f --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8= +github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= diff --git a/html/Err-ConnectionRefused.htm b/html/Err-ConnectionRefused.htm new file mode 100644 index 0000000..5985160 --- /dev/null +++ b/html/Err-ConnectionRefused.htm @@ -0,0 +1,16 @@ + +WebOne: connection error + + + +

The connection was refused

+

%ErrorMessage%.

+ +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-ConnectionReset.htm b/html/Err-ConnectionReset.htm new file mode 100644 index 0000000..a20aa5d --- /dev/null +++ b/html/Err-ConnectionReset.htm @@ -0,0 +1,16 @@ + +WebOne: connection error + + + +

The connection has been reset

+

%ErrorMessage%.

+ +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-HostNotFound.htm b/html/Err-HostNotFound.htm new file mode 100644 index 0000000..f3550ad --- /dev/null +++ b/html/Err-HostNotFound.htm @@ -0,0 +1,16 @@ + +WebOne: connection error + + + +

Cannot find the server

+

%ErrorMessage%.

+ +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-InvalidDataException.htm b/html/Err-InvalidDataException.htm new file mode 100644 index 0000000..8ffecad --- /dev/null +++ b/html/Err-InvalidDataException.htm @@ -0,0 +1,16 @@ + +WebOne: Decompression failed + + + +

Invalid data has been recieved

+

Cannot decode HTTP data.

+ + +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-IpNotWhitelisted.htm b/html/Err-IpNotWhitelisted.htm new file mode 100644 index 0000000..8fb557e --- /dev/null +++ b/html/Err-IpNotWhitelisted.htm @@ -0,0 +1,33 @@ + +Non-whitelisted client + + + +

Goodbye, %IP%

+

You are not in the list of allowed clients. Contact proxy server's administrator to add your IP address in it.

+
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-LoopRequest.htm b/html/Err-LoopRequest.htm new file mode 100644 index 0000000..828edf4 --- /dev/null +++ b/html/Err-LoopRequest.htm @@ -0,0 +1,12 @@ + +Loop requests are probhited + + + +

Seems that you have looped connection.

+

This may be caused by incorrect WebOne or operating system configuration.

+

Set UpperProxy to no in configuration file to enable WebOne direct connection to the Internet.

+

Make sure that only the client browser is accessing Internet via proxy, and the proxy server have a true direct connection. Note that WebOne is using system settings to access Internet. Some browsers (Internet Explorer, Safari, all Chromium-based) are using same settings as the OS where they are started.

+
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-SslDisabled.htm b/html/Err-SslDisabled.htm new file mode 100644 index 0000000..65731f0 --- /dev/null +++ b/html/Err-SslDisabled.htm @@ -0,0 +1,11 @@ + +HTTPS Is Not Supported + + + +

Sorry, Secure traffic transfer is disabled on proxy server.

+

Set SslEnable to yes in configuration file to allow work with HTTPS & SSL. Also make sure that CA files are accessible.

+

Or set the proxy usage only for HTTP protocol in your Web-browser settings. Any HTTPS websites can be accessed via plain HTTP protocol via the proxy.

+
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-TaskCanceledException.htm b/html/Err-TaskCanceledException.htm new file mode 100644 index 0000000..40b4140 --- /dev/null +++ b/html/Err-TaskCanceledException.htm @@ -0,0 +1,17 @@ + +WebOne: Operation timeout + + + +

The connection has timed out

+

The request was canceled due to Timeout of 100 seconds elapsing.

+ +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-TimedOut.htm b/html/Err-TimedOut.htm new file mode 100644 index 0000000..cb209e3 --- /dev/null +++ b/html/Err-TimedOut.htm @@ -0,0 +1,16 @@ + +WebOne: connection error + + + +

The connection has timed out

+

%ErrorMessage%.

+ +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-TlsPolicyErrorException.htm b/html/Err-TlsPolicyErrorException.htm new file mode 100644 index 0000000..7ed71c7 --- /dev/null +++ b/html/Err-TlsPolicyErrorException.htm @@ -0,0 +1,18 @@ + +WebOne: connection error + + + +

Secure connection could not be established

+

%ErrorMessage%.

+ +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-UnknownProtocol.htm b/html/Err-UnknownProtocol.htm new file mode 100644 index 0000000..67a0231 --- /dev/null +++ b/html/Err-UnknownProtocol.htm @@ -0,0 +1,12 @@ + +%Scheme% Is Not Supported + + + +

Unsupported protocol

+

You're attempted to request content from %URL%. The protocol specified in the URL is not supported by this proxy server.

+

Consider connect directly to the server, bypassing the proxy. This error message may appear if your Web browser settings have enabled "Use proxy for all protocols" option. Uncheck it and set only for protocols supported by WebOne. List of them can be found in project's Wiki.

+

This message also may appear if you have not installed an appication that designed to handle %Scheme% addresses.

+
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-UrlBlacklisted.htm b/html/Err-UrlBlacklisted.htm new file mode 100644 index 0000000..bd48b3d --- /dev/null +++ b/html/Err-UrlBlacklisted.htm @@ -0,0 +1,9 @@ + +Blacklisted URL + + + +

Access to this web page is disallowed by proxy settings.

+
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-UrlNotWhitelisted.htm b/html/Err-UrlNotWhitelisted.htm new file mode 100644 index 0000000..3b905b1 --- /dev/null +++ b/html/Err-UrlNotWhitelisted.htm @@ -0,0 +1,10 @@ + +URL out of white list + + + +

Proxy server administrator has been limited this proxy server to work with several web sites only.

+ +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-WA403.htm b/html/Err-WA403.htm new file mode 100644 index 0000000..8dce07e --- /dev/null +++ b/html/Err-WA403.htm @@ -0,0 +1,12 @@ + +Web Archive Error: 403 + + + +

This URL has been excluded from the Wayback Machine.

+

This page is not present in Web Archive.

+You see this message because ShortenArchiveErrors option is enabled. +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-WA404.htm b/html/Err-WA404.htm new file mode 100644 index 0000000..6424951 --- /dev/null +++ b/html/Err-WA404.htm @@ -0,0 +1,12 @@ + +Web Archive Error: 404 + + + +

The Wayback Machine has not archived that URL.

+

Try to slightly change the URL.

+You see this message because ShortenArchiveErrors option is enabled. +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-WA500.htm b/html/Err-WA500.htm new file mode 100644 index 0000000..147bec2 --- /dev/null +++ b/html/Err-WA500.htm @@ -0,0 +1,12 @@ + +Web Archive Error + + + +

The Wayback Machine cannot give this page.

+

This is reason: %ErrorMessage%.

+You see this message because ShortenArchiveErrors option is enabled. +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-WA502.htm b/html/Err-WA502.htm new file mode 100644 index 0000000..75cbe5e --- /dev/null +++ b/html/Err-WA502.htm @@ -0,0 +1,12 @@ + +Web Archive - bad gateway + + + +

"Bad gateway"

+

There are problems in Internet Archive Wayback Machine (it returned a HTTP 502 status code) or the link is broken.

+You see this message because ShortenArchiveErrors option is enabled. +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-WA503.htm b/html/Err-WA503.htm new file mode 100644 index 0000000..94b3e3b --- /dev/null +++ b/html/Err-WA503.htm @@ -0,0 +1,13 @@ + +Web Archive is unavailable + + + +

Internet Archive services are temporarily offline.

+

The Wayback Machine is not currently available. Please check Twitter feed for the latest information.

+

We apologize for the inconvenience.

+You see this message because ShortenArchiveErrors option is enabled. +
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/Err-WArchiveException.htm b/html/Err-WArchiveException.htm new file mode 100644 index 0000000..5eee496 --- /dev/null +++ b/html/Err-WArchiveException.htm @@ -0,0 +1,12 @@ + +WebOne: Web Archive error + + + +

Cannot load this page

+

The requested server or page is not found and a Web Archive error occured.

+

%ErrorMessage%.

+
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + diff --git a/html/Err-WArchiveRetrieveException.htm b/html/Err-WArchiveRetrieveException.htm new file mode 100644 index 0000000..d7b1d2c --- /dev/null +++ b/html/Err-WArchiveRetrieveException.htm @@ -0,0 +1,12 @@ + +WebOne: Web Archive retrieve error + + + +

Cannot load this page from Web Archive

+

The requested page is found only at Web Archive, but cannot be delivered from it.

+

%ErrorMessage%.

+
URL: %URL% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + diff --git a/html/InfoPage.htm b/html/InfoPage.htm new file mode 100644 index 0000000..fb072ba --- /dev/null +++ b/html/InfoPage.htm @@ -0,0 +1,10 @@ + +%Title% + + + +

%Header%

+%Content% +
WebOne Proxy Server %WOVer%
on %WOSystem% + + \ No newline at end of file diff --git a/html/filetypes/386.gif b/html/filetypes/386.gif new file mode 100644 index 0000000..e211d31 Binary files /dev/null and b/html/filetypes/386.gif differ diff --git a/html/filetypes/3gp.gif b/html/filetypes/3gp.gif new file mode 100644 index 0000000..66337f1 Binary files /dev/null and b/html/filetypes/3gp.gif differ diff --git a/html/filetypes/7z.gif b/html/filetypes/7z.gif new file mode 100644 index 0000000..c9b31ea Binary files /dev/null and b/html/filetypes/7z.gif differ diff --git a/html/filetypes/_dir-up.gif b/html/filetypes/_dir-up.gif new file mode 100644 index 0000000..cd75eda Binary files /dev/null and b/html/filetypes/_dir-up.gif differ diff --git a/html/filetypes/_dir.gif b/html/filetypes/_dir.gif new file mode 100644 index 0000000..ab0514d Binary files /dev/null and b/html/filetypes/_dir.gif differ diff --git a/html/filetypes/_file.gif b/html/filetypes/_file.gif new file mode 100644 index 0000000..04b5d82 Binary files /dev/null and b/html/filetypes/_file.gif differ diff --git a/html/filetypes/_link.gif b/html/filetypes/_link.gif new file mode 100644 index 0000000..a9a96d8 Binary files /dev/null and b/html/filetypes/_link.gif differ diff --git a/html/filetypes/ace.gif b/html/filetypes/ace.gif new file mode 100644 index 0000000..a857331 Binary files /dev/null and b/html/filetypes/ace.gif differ diff --git a/html/filetypes/ade.gif b/html/filetypes/ade.gif new file mode 100644 index 0000000..df94d98 Binary files /dev/null and b/html/filetypes/ade.gif differ diff --git a/html/filetypes/adp.gif b/html/filetypes/adp.gif new file mode 100644 index 0000000..cacb1a2 Binary files /dev/null and b/html/filetypes/adp.gif differ diff --git a/html/filetypes/apk.gif b/html/filetypes/apk.gif new file mode 100644 index 0000000..fac2fb3 Binary files /dev/null and b/html/filetypes/apk.gif differ diff --git a/html/filetypes/app.gif b/html/filetypes/app.gif new file mode 100644 index 0000000..05b886c Binary files /dev/null and b/html/filetypes/app.gif differ diff --git a/html/filetypes/arj.gif b/html/filetypes/arj.gif new file mode 100644 index 0000000..a857331 Binary files /dev/null and b/html/filetypes/arj.gif differ diff --git a/html/filetypes/asf.gif b/html/filetypes/asf.gif new file mode 100644 index 0000000..bf46c77 Binary files /dev/null and b/html/filetypes/asf.gif differ diff --git a/html/filetypes/asm.gif b/html/filetypes/asm.gif new file mode 100644 index 0000000..310b29d Binary files /dev/null and b/html/filetypes/asm.gif differ diff --git a/html/filetypes/asx.gif b/html/filetypes/asx.gif new file mode 100644 index 0000000..2efa749 Binary files /dev/null and b/html/filetypes/asx.gif differ diff --git a/html/filetypes/avi.gif b/html/filetypes/avi.gif new file mode 100644 index 0000000..66337f1 Binary files /dev/null and b/html/filetypes/avi.gif differ diff --git a/html/filetypes/bas.gif b/html/filetypes/bas.gif new file mode 100644 index 0000000..b452106 Binary files /dev/null and b/html/filetypes/bas.gif differ diff --git a/html/filetypes/bat.gif b/html/filetypes/bat.gif new file mode 100644 index 0000000..8ec32cf Binary files /dev/null and b/html/filetypes/bat.gif differ diff --git a/html/filetypes/bmp.gif b/html/filetypes/bmp.gif new file mode 100644 index 0000000..f718668 Binary files /dev/null and b/html/filetypes/bmp.gif differ diff --git a/html/filetypes/bz2.gif b/html/filetypes/bz2.gif new file mode 100644 index 0000000..a857331 Binary files /dev/null and b/html/filetypes/bz2.gif differ diff --git a/html/filetypes/c.gif b/html/filetypes/c.gif new file mode 100644 index 0000000..a099ce7 Binary files /dev/null and b/html/filetypes/c.gif differ diff --git a/html/filetypes/cab.gif b/html/filetypes/cab.gif new file mode 100644 index 0000000..7f69f01 Binary files /dev/null and b/html/filetypes/cab.gif differ diff --git a/html/filetypes/cat.gif b/html/filetypes/cat.gif new file mode 100644 index 0000000..d366faf Binary files /dev/null and b/html/filetypes/cat.gif differ diff --git a/html/filetypes/cda.gif b/html/filetypes/cda.gif new file mode 100644 index 0000000..550ad08 Binary files /dev/null and b/html/filetypes/cda.gif differ diff --git a/html/filetypes/cdf.gif b/html/filetypes/cdf.gif new file mode 100644 index 0000000..ebe4412 Binary files /dev/null and b/html/filetypes/cdf.gif differ diff --git a/html/filetypes/cer.gif b/html/filetypes/cer.gif new file mode 100644 index 0000000..4b2249a Binary files /dev/null and b/html/filetypes/cer.gif differ diff --git a/html/filetypes/chm.gif b/html/filetypes/chm.gif new file mode 100644 index 0000000..f9b0c6f Binary files /dev/null and b/html/filetypes/chm.gif differ diff --git a/html/filetypes/cmd.gif b/html/filetypes/cmd.gif new file mode 100644 index 0000000..8ec32cf Binary files /dev/null and b/html/filetypes/cmd.gif differ diff --git a/html/filetypes/com.gif b/html/filetypes/com.gif new file mode 100644 index 0000000..c5a91f5 Binary files /dev/null and b/html/filetypes/com.gif differ diff --git a/html/filetypes/conf.gif b/html/filetypes/conf.gif new file mode 100644 index 0000000..3f42682 Binary files /dev/null and b/html/filetypes/conf.gif differ diff --git a/html/filetypes/config.gif b/html/filetypes/config.gif new file mode 100644 index 0000000..3f42682 Binary files /dev/null and b/html/filetypes/config.gif differ diff --git a/html/filetypes/cpp.gif b/html/filetypes/cpp.gif new file mode 100644 index 0000000..17e2b3d Binary files /dev/null and b/html/filetypes/cpp.gif differ diff --git a/html/filetypes/crl.gif b/html/filetypes/crl.gif new file mode 100644 index 0000000..508060c Binary files /dev/null and b/html/filetypes/crl.gif differ diff --git a/html/filetypes/crt.gif b/html/filetypes/crt.gif new file mode 100644 index 0000000..4b2249a Binary files /dev/null and b/html/filetypes/crt.gif differ diff --git a/html/filetypes/cs.gif b/html/filetypes/cs.gif new file mode 100644 index 0000000..2b5f7a6 Binary files /dev/null and b/html/filetypes/cs.gif differ diff --git a/html/filetypes/csproj.gif b/html/filetypes/csproj.gif new file mode 100644 index 0000000..1bc0711 Binary files /dev/null and b/html/filetypes/csproj.gif differ diff --git a/html/filetypes/css.gif b/html/filetypes/css.gif new file mode 100644 index 0000000..423225b Binary files /dev/null and b/html/filetypes/css.gif differ diff --git a/html/filetypes/csv.gif b/html/filetypes/csv.gif new file mode 100644 index 0000000..33ec87c Binary files /dev/null and b/html/filetypes/csv.gif differ diff --git a/html/filetypes/ctt.gif b/html/filetypes/ctt.gif new file mode 100644 index 0000000..1149467 Binary files /dev/null and b/html/filetypes/ctt.gif differ diff --git a/html/filetypes/deb.gif b/html/filetypes/deb.gif new file mode 100644 index 0000000..da0ddde Binary files /dev/null and b/html/filetypes/deb.gif differ diff --git a/html/filetypes/dib.gif b/html/filetypes/dib.gif new file mode 100644 index 0000000..f718668 Binary files /dev/null and b/html/filetypes/dib.gif differ diff --git a/html/filetypes/diz.gif b/html/filetypes/diz.gif new file mode 100644 index 0000000..6936a18 Binary files /dev/null and b/html/filetypes/diz.gif differ diff --git a/html/filetypes/dll.gif b/html/filetypes/dll.gif new file mode 100644 index 0000000..e211d31 Binary files /dev/null and b/html/filetypes/dll.gif differ diff --git a/html/filetypes/dmg.gif b/html/filetypes/dmg.gif new file mode 100644 index 0000000..e008b3c Binary files /dev/null and b/html/filetypes/dmg.gif differ diff --git a/html/filetypes/doc.gif b/html/filetypes/doc.gif new file mode 100644 index 0000000..5954db7 Binary files /dev/null and b/html/filetypes/doc.gif differ diff --git a/html/filetypes/dot.gif b/html/filetypes/dot.gif new file mode 100644 index 0000000..de71caa Binary files /dev/null and b/html/filetypes/dot.gif differ diff --git a/html/filetypes/drv.gif b/html/filetypes/drv.gif new file mode 100644 index 0000000..e211d31 Binary files /dev/null and b/html/filetypes/drv.gif differ diff --git a/html/filetypes/dsk.gif b/html/filetypes/dsk.gif new file mode 100644 index 0000000..d0131f4 Binary files /dev/null and b/html/filetypes/dsk.gif differ diff --git a/html/filetypes/dun.gif b/html/filetypes/dun.gif new file mode 100644 index 0000000..4519ae3 Binary files /dev/null and b/html/filetypes/dun.gif differ diff --git a/html/filetypes/elf.gif b/html/filetypes/elf.gif new file mode 100644 index 0000000..9d597ed Binary files /dev/null and b/html/filetypes/elf.gif differ diff --git a/html/filetypes/emf.gif b/html/filetypes/emf.gif new file mode 100644 index 0000000..c0f4687 Binary files /dev/null and b/html/filetypes/emf.gif differ diff --git a/html/filetypes/eml.gif b/html/filetypes/eml.gif new file mode 100644 index 0000000..cde8de1 Binary files /dev/null and b/html/filetypes/eml.gif differ diff --git a/html/filetypes/evt.gif b/html/filetypes/evt.gif new file mode 100644 index 0000000..dd6fa2d Binary files /dev/null and b/html/filetypes/evt.gif differ diff --git a/html/filetypes/evtx.gif b/html/filetypes/evtx.gif new file mode 100644 index 0000000..dd6fa2d Binary files /dev/null and b/html/filetypes/evtx.gif differ diff --git a/html/filetypes/exe.gif b/html/filetypes/exe.gif new file mode 100644 index 0000000..b104a5d Binary files /dev/null and b/html/filetypes/exe.gif differ diff --git a/html/filetypes/fon.gif b/html/filetypes/fon.gif new file mode 100644 index 0000000..71cd084 Binary files /dev/null and b/html/filetypes/fon.gif differ diff --git a/html/filetypes/gadget.gif b/html/filetypes/gadget.gif new file mode 100644 index 0000000..0d5440a Binary files /dev/null and b/html/filetypes/gadget.gif differ diff --git a/html/filetypes/gif.gif b/html/filetypes/gif.gif new file mode 100644 index 0000000..c0f4687 Binary files /dev/null and b/html/filetypes/gif.gif differ diff --git a/html/filetypes/gz.gif b/html/filetypes/gz.gif new file mode 100644 index 0000000..a857331 Binary files /dev/null and b/html/filetypes/gz.gif differ diff --git a/html/filetypes/h.gif b/html/filetypes/h.gif new file mode 100644 index 0000000..983772d Binary files /dev/null and b/html/filetypes/h.gif differ diff --git a/html/filetypes/hlp.gif b/html/filetypes/hlp.gif new file mode 100644 index 0000000..5f2bb88 Binary files /dev/null and b/html/filetypes/hlp.gif differ diff --git a/html/filetypes/hqx.gif b/html/filetypes/hqx.gif new file mode 100644 index 0000000..23dbfad Binary files /dev/null and b/html/filetypes/hqx.gif differ diff --git a/html/filetypes/hta.gif b/html/filetypes/hta.gif new file mode 100644 index 0000000..7f69f01 Binary files /dev/null and b/html/filetypes/hta.gif differ diff --git a/html/filetypes/htm.gif b/html/filetypes/htm.gif new file mode 100644 index 0000000..0718b6d Binary files /dev/null and b/html/filetypes/htm.gif differ diff --git a/html/filetypes/html.gif b/html/filetypes/html.gif new file mode 100644 index 0000000..0718b6d Binary files /dev/null and b/html/filetypes/html.gif differ diff --git a/html/filetypes/ico.gif b/html/filetypes/ico.gif new file mode 100644 index 0000000..7f69f01 Binary files /dev/null and b/html/filetypes/ico.gif differ diff --git a/html/filetypes/ima.gif b/html/filetypes/ima.gif new file mode 100644 index 0000000..a8c0913 Binary files /dev/null and b/html/filetypes/ima.gif differ diff --git a/html/filetypes/img.gif b/html/filetypes/img.gif new file mode 100644 index 0000000..a8c0913 Binary files /dev/null and b/html/filetypes/img.gif differ diff --git a/html/filetypes/imz.gif b/html/filetypes/imz.gif new file mode 100644 index 0000000..a8c0913 Binary files /dev/null and b/html/filetypes/imz.gif differ diff --git a/html/filetypes/inf.gif b/html/filetypes/inf.gif new file mode 100644 index 0000000..3f42682 Binary files /dev/null and b/html/filetypes/inf.gif differ diff --git a/html/filetypes/ini.gif b/html/filetypes/ini.gif new file mode 100644 index 0000000..3f42682 Binary files /dev/null and b/html/filetypes/ini.gif differ diff --git a/html/filetypes/ion.gif b/html/filetypes/ion.gif new file mode 100644 index 0000000..6936a18 Binary files /dev/null and b/html/filetypes/ion.gif differ diff --git a/html/filetypes/ipa.gif b/html/filetypes/ipa.gif new file mode 100644 index 0000000..dc0b04d Binary files /dev/null and b/html/filetypes/ipa.gif differ diff --git a/html/filetypes/iso.gif b/html/filetypes/iso.gif new file mode 100644 index 0000000..e0d69a6 Binary files /dev/null and b/html/filetypes/iso.gif differ diff --git a/html/filetypes/jar.gif b/html/filetypes/jar.gif new file mode 100644 index 0000000..d95ac93 Binary files /dev/null and b/html/filetypes/jar.gif differ diff --git a/html/filetypes/jpg.gif b/html/filetypes/jpg.gif new file mode 100644 index 0000000..6611390 Binary files /dev/null and b/html/filetypes/jpg.gif differ diff --git a/html/filetypes/js.gif b/html/filetypes/js.gif new file mode 100644 index 0000000..203732c Binary files /dev/null and b/html/filetypes/js.gif differ diff --git a/html/filetypes/key.gif b/html/filetypes/key.gif new file mode 100644 index 0000000..93392db Binary files /dev/null and b/html/filetypes/key.gif differ diff --git a/html/filetypes/lex.gif b/html/filetypes/lex.gif new file mode 100644 index 0000000..fd0d4ea Binary files /dev/null and b/html/filetypes/lex.gif differ diff --git a/html/filetypes/lha.gif b/html/filetypes/lha.gif new file mode 100644 index 0000000..eb1fb1c Binary files /dev/null and b/html/filetypes/lha.gif differ diff --git a/html/filetypes/lnk.gif b/html/filetypes/lnk.gif new file mode 100644 index 0000000..e8d392e Binary files /dev/null and b/html/filetypes/lnk.gif differ diff --git a/html/filetypes/log.gif b/html/filetypes/log.gif new file mode 100644 index 0000000..e6b11fb Binary files /dev/null and b/html/filetypes/log.gif differ diff --git a/html/filetypes/lst.gif b/html/filetypes/lst.gif new file mode 100644 index 0000000..6dbf37c Binary files /dev/null and b/html/filetypes/lst.gif differ diff --git a/html/filetypes/lzh.gif b/html/filetypes/lzh.gif new file mode 100644 index 0000000..a857331 Binary files /dev/null and b/html/filetypes/lzh.gif differ diff --git a/html/filetypes/lzma.gif b/html/filetypes/lzma.gif new file mode 100644 index 0000000..858328d Binary files /dev/null and b/html/filetypes/lzma.gif differ diff --git a/html/filetypes/m2ts.gif b/html/filetypes/m2ts.gif new file mode 100644 index 0000000..2aa7d68 Binary files /dev/null and b/html/filetypes/m2ts.gif differ diff --git a/html/filetypes/mak.gif b/html/filetypes/mak.gif new file mode 100644 index 0000000..4c703e2 Binary files /dev/null and b/html/filetypes/mak.gif differ diff --git a/html/filetypes/mda.gif b/html/filetypes/mda.gif new file mode 100644 index 0000000..0bc857d Binary files /dev/null and b/html/filetypes/mda.gif differ diff --git a/html/filetypes/mdb.gif b/html/filetypes/mdb.gif new file mode 100644 index 0000000..7324d51 Binary files /dev/null and b/html/filetypes/mdb.gif differ diff --git a/html/filetypes/mdt.gif b/html/filetypes/mdt.gif new file mode 100644 index 0000000..ee231fa Binary files /dev/null and b/html/filetypes/mdt.gif differ diff --git a/html/filetypes/mdw.gif b/html/filetypes/mdw.gif new file mode 100644 index 0000000..99300b9 Binary files /dev/null and b/html/filetypes/mdw.gif differ diff --git a/html/filetypes/mdz.gif b/html/filetypes/mdz.gif new file mode 100644 index 0000000..9ea7612 Binary files /dev/null and b/html/filetypes/mdz.gif differ diff --git a/html/filetypes/mht.gif b/html/filetypes/mht.gif new file mode 100644 index 0000000..0b15a97 Binary files /dev/null and b/html/filetypes/mht.gif differ diff --git a/html/filetypes/mid.gif b/html/filetypes/mid.gif new file mode 100644 index 0000000..9552c8a Binary files /dev/null and b/html/filetypes/mid.gif differ diff --git a/html/filetypes/mov.gif b/html/filetypes/mov.gif new file mode 100644 index 0000000..edd0323 Binary files /dev/null and b/html/filetypes/mov.gif differ diff --git a/html/filetypes/mp3.gif b/html/filetypes/mp3.gif new file mode 100644 index 0000000..0885995 Binary files /dev/null and b/html/filetypes/mp3.gif differ diff --git a/html/filetypes/mp4.gif b/html/filetypes/mp4.gif new file mode 100644 index 0000000..2aa7d68 Binary files /dev/null and b/html/filetypes/mp4.gif differ diff --git a/html/filetypes/mpeg.gif b/html/filetypes/mpeg.gif new file mode 100644 index 0000000..2aa7d68 Binary files /dev/null and b/html/filetypes/mpeg.gif differ diff --git a/html/filetypes/mpg.gif b/html/filetypes/mpg.gif new file mode 100644 index 0000000..2aa7d68 Binary files /dev/null and b/html/filetypes/mpg.gif differ diff --git a/html/filetypes/mpv.gif b/html/filetypes/mpv.gif new file mode 100644 index 0000000..2aa7d68 Binary files /dev/null and b/html/filetypes/mpv.gif differ diff --git a/html/filetypes/msc.gif b/html/filetypes/msc.gif new file mode 100644 index 0000000..a16c7c6 Binary files /dev/null and b/html/filetypes/msc.gif differ diff --git a/html/filetypes/msi.gif b/html/filetypes/msi.gif new file mode 100644 index 0000000..b88d972 Binary files /dev/null and b/html/filetypes/msi.gif differ diff --git a/html/filetypes/msp.gif b/html/filetypes/msp.gif new file mode 100644 index 0000000..b88d972 Binary files /dev/null and b/html/filetypes/msp.gif differ diff --git a/html/filetypes/msstyles.gif b/html/filetypes/msstyles.gif new file mode 100644 index 0000000..14ad916 Binary files /dev/null and b/html/filetypes/msstyles.gif differ diff --git a/html/filetypes/msu.gif b/html/filetypes/msu.gif new file mode 100644 index 0000000..d26fba1 Binary files /dev/null and b/html/filetypes/msu.gif differ diff --git a/html/filetypes/mts.gif b/html/filetypes/mts.gif new file mode 100644 index 0000000..2aa7d68 Binary files /dev/null and b/html/filetypes/mts.gif differ diff --git a/html/filetypes/nfo.gif b/html/filetypes/nfo.gif new file mode 100644 index 0000000..c19b84f Binary files /dev/null and b/html/filetypes/nfo.gif differ diff --git a/html/filetypes/ocx.gif b/html/filetypes/ocx.gif new file mode 100644 index 0000000..e211d31 Binary files /dev/null and b/html/filetypes/ocx.gif differ diff --git a/html/filetypes/odp.gif b/html/filetypes/odp.gif new file mode 100644 index 0000000..32a30a4 Binary files /dev/null and b/html/filetypes/odp.gif differ diff --git a/html/filetypes/ods.gif b/html/filetypes/ods.gif new file mode 100644 index 0000000..604613d Binary files /dev/null and b/html/filetypes/ods.gif differ diff --git a/html/filetypes/odt.gif b/html/filetypes/odt.gif new file mode 100644 index 0000000..121c9c9 Binary files /dev/null and b/html/filetypes/odt.gif differ diff --git a/html/filetypes/otf.gif b/html/filetypes/otf.gif new file mode 100644 index 0000000..4b27513 Binary files /dev/null and b/html/filetypes/otf.gif differ diff --git a/html/filetypes/pdf.gif b/html/filetypes/pdf.gif new file mode 100644 index 0000000..7826edd Binary files /dev/null and b/html/filetypes/pdf.gif differ diff --git a/html/filetypes/pfx.gif b/html/filetypes/pfx.gif new file mode 100644 index 0000000..4a1cad8 Binary files /dev/null and b/html/filetypes/pfx.gif differ diff --git a/html/filetypes/png.gif b/html/filetypes/png.gif new file mode 100644 index 0000000..c0f4687 Binary files /dev/null and b/html/filetypes/png.gif differ diff --git a/html/filetypes/pot.gif b/html/filetypes/pot.gif new file mode 100644 index 0000000..0553426 Binary files /dev/null and b/html/filetypes/pot.gif differ diff --git a/html/filetypes/ppa.gif b/html/filetypes/ppa.gif new file mode 100644 index 0000000..0a3d961 Binary files /dev/null and b/html/filetypes/ppa.gif differ diff --git a/html/filetypes/pps.gif b/html/filetypes/pps.gif new file mode 100644 index 0000000..4cc9e27 Binary files /dev/null and b/html/filetypes/pps.gif differ diff --git a/html/filetypes/ppt.gif b/html/filetypes/ppt.gif new file mode 100644 index 0000000..269b793 Binary files /dev/null and b/html/filetypes/ppt.gif differ diff --git a/html/filetypes/r00.gif b/html/filetypes/r00.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r00.gif differ diff --git a/html/filetypes/r01.gif b/html/filetypes/r01.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r01.gif differ diff --git a/html/filetypes/r02.gif b/html/filetypes/r02.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r02.gif differ diff --git a/html/filetypes/r03.gif b/html/filetypes/r03.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r03.gif differ diff --git a/html/filetypes/r04.gif b/html/filetypes/r04.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r04.gif differ diff --git a/html/filetypes/r05.gif b/html/filetypes/r05.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r05.gif differ diff --git a/html/filetypes/r06.gif b/html/filetypes/r06.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r06.gif differ diff --git a/html/filetypes/r07.gif b/html/filetypes/r07.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r07.gif differ diff --git a/html/filetypes/r08.gif b/html/filetypes/r08.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r08.gif differ diff --git a/html/filetypes/r09.gif b/html/filetypes/r09.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/r09.gif differ diff --git a/html/filetypes/rar.gif b/html/filetypes/rar.gif new file mode 100644 index 0000000..5cc8509 Binary files /dev/null and b/html/filetypes/rar.gif differ diff --git a/html/filetypes/rar5.gif b/html/filetypes/rar5.gif new file mode 100644 index 0000000..70b0acf Binary files /dev/null and b/html/filetypes/rar5.gif differ diff --git a/html/filetypes/rdp.gif b/html/filetypes/rdp.gif new file mode 100644 index 0000000..7f8a808 Binary files /dev/null and b/html/filetypes/rdp.gif differ diff --git a/html/filetypes/reg.gif b/html/filetypes/reg.gif new file mode 100644 index 0000000..82a35ff Binary files /dev/null and b/html/filetypes/reg.gif differ diff --git a/html/filetypes/rom.gif b/html/filetypes/rom.gif new file mode 100644 index 0000000..97db302 Binary files /dev/null and b/html/filetypes/rom.gif differ diff --git a/html/filetypes/rpm.gif b/html/filetypes/rpm.gif new file mode 100644 index 0000000..5ff0116 Binary files /dev/null and b/html/filetypes/rpm.gif differ diff --git a/html/filetypes/rtf.gif b/html/filetypes/rtf.gif new file mode 100644 index 0000000..ef9e15a Binary files /dev/null and b/html/filetypes/rtf.gif differ diff --git a/html/filetypes/sav.gif b/html/filetypes/sav.gif new file mode 100644 index 0000000..f34ef9e Binary files /dev/null and b/html/filetypes/sav.gif differ diff --git a/html/filetypes/scr.gif b/html/filetypes/scr.gif new file mode 100644 index 0000000..b104a5d Binary files /dev/null and b/html/filetypes/scr.gif differ diff --git a/html/filetypes/slk.gif b/html/filetypes/slk.gif new file mode 100644 index 0000000..e02155e Binary files /dev/null and b/html/filetypes/slk.gif differ diff --git a/html/filetypes/sln.gif b/html/filetypes/sln.gif new file mode 100644 index 0000000..8a7e8cb Binary files /dev/null and b/html/filetypes/sln.gif differ diff --git a/html/filetypes/so.gif b/html/filetypes/so.gif new file mode 100644 index 0000000..9d597ed Binary files /dev/null and b/html/filetypes/so.gif differ diff --git a/html/filetypes/squashfs.gif b/html/filetypes/squashfs.gif new file mode 100644 index 0000000..965ee2d Binary files /dev/null and b/html/filetypes/squashfs.gif differ diff --git a/html/filetypes/sys.gif b/html/filetypes/sys.gif new file mode 100644 index 0000000..e211d31 Binary files /dev/null and b/html/filetypes/sys.gif differ diff --git a/html/filetypes/tar.gif b/html/filetypes/tar.gif new file mode 100644 index 0000000..a857331 Binary files /dev/null and b/html/filetypes/tar.gif differ diff --git a/html/filetypes/theme.gif b/html/filetypes/theme.gif new file mode 100644 index 0000000..14ad916 Binary files /dev/null and b/html/filetypes/theme.gif differ diff --git a/html/filetypes/tif.gif b/html/filetypes/tif.gif new file mode 100644 index 0000000..dbee7b7 Binary files /dev/null and b/html/filetypes/tif.gif differ diff --git a/html/filetypes/tiff.gif b/html/filetypes/tiff.gif new file mode 100644 index 0000000..dbee7b7 Binary files /dev/null and b/html/filetypes/tiff.gif differ diff --git a/html/filetypes/ts.gif b/html/filetypes/ts.gif new file mode 100644 index 0000000..2aa7d68 Binary files /dev/null and b/html/filetypes/ts.gif differ diff --git a/html/filetypes/ttf.gif b/html/filetypes/ttf.gif new file mode 100644 index 0000000..110266f Binary files /dev/null and b/html/filetypes/ttf.gif differ diff --git a/html/filetypes/txt.gif b/html/filetypes/txt.gif new file mode 100644 index 0000000..664b791 Binary files /dev/null and b/html/filetypes/txt.gif differ diff --git a/html/filetypes/url.gif b/html/filetypes/url.gif new file mode 100644 index 0000000..9193fdf Binary files /dev/null and b/html/filetypes/url.gif differ diff --git a/html/filetypes/uue.gif b/html/filetypes/uue.gif new file mode 100644 index 0000000..a857331 Binary files /dev/null and b/html/filetypes/uue.gif differ diff --git a/html/filetypes/vb.gif b/html/filetypes/vb.gif new file mode 100644 index 0000000..3848eae Binary files /dev/null and b/html/filetypes/vb.gif differ diff --git a/html/filetypes/vbp.gif b/html/filetypes/vbp.gif new file mode 100644 index 0000000..dd20485 Binary files /dev/null and b/html/filetypes/vbp.gif differ diff --git a/html/filetypes/vbproj.gif b/html/filetypes/vbproj.gif new file mode 100644 index 0000000..092ec51 Binary files /dev/null and b/html/filetypes/vbproj.gif differ diff --git a/html/filetypes/vbs.gif b/html/filetypes/vbs.gif new file mode 100644 index 0000000..a6a66d1 Binary files /dev/null and b/html/filetypes/vbs.gif differ diff --git a/html/filetypes/vcproj.gif b/html/filetypes/vcproj.gif new file mode 100644 index 0000000..fbadc18 Binary files /dev/null and b/html/filetypes/vcproj.gif differ diff --git a/html/filetypes/vxd.gif b/html/filetypes/vxd.gif new file mode 100644 index 0000000..e211d31 Binary files /dev/null and b/html/filetypes/vxd.gif differ diff --git a/html/filetypes/wab.gif b/html/filetypes/wab.gif new file mode 100644 index 0000000..70cf6b3 Binary files /dev/null and b/html/filetypes/wab.gif differ diff --git a/html/filetypes/wav.gif b/html/filetypes/wav.gif new file mode 100644 index 0000000..931fec7 Binary files /dev/null and b/html/filetypes/wav.gif differ diff --git a/html/filetypes/wbk.gif b/html/filetypes/wbk.gif new file mode 100644 index 0000000..abf1000 Binary files /dev/null and b/html/filetypes/wbk.gif differ diff --git a/html/filetypes/wgt.gif b/html/filetypes/wgt.gif new file mode 100644 index 0000000..08ce5e6 Binary files /dev/null and b/html/filetypes/wgt.gif differ diff --git a/html/filetypes/wiz.gif b/html/filetypes/wiz.gif new file mode 100644 index 0000000..d11ba07 Binary files /dev/null and b/html/filetypes/wiz.gif differ diff --git a/html/filetypes/wll.gif b/html/filetypes/wll.gif new file mode 100644 index 0000000..ae9da19 Binary files /dev/null and b/html/filetypes/wll.gif differ diff --git a/html/filetypes/wm.gif b/html/filetypes/wm.gif new file mode 100644 index 0000000..a4014ca Binary files /dev/null and b/html/filetypes/wm.gif differ diff --git a/html/filetypes/wma.gif b/html/filetypes/wma.gif new file mode 100644 index 0000000..59d7efe Binary files /dev/null and b/html/filetypes/wma.gif differ diff --git a/html/filetypes/wmf.gif b/html/filetypes/wmf.gif new file mode 100644 index 0000000..c0f4687 Binary files /dev/null and b/html/filetypes/wmf.gif differ diff --git a/html/filetypes/wms.gif b/html/filetypes/wms.gif new file mode 100644 index 0000000..a1ba280 Binary files /dev/null and b/html/filetypes/wms.gif differ diff --git a/html/filetypes/wmv.gif b/html/filetypes/wmv.gif new file mode 100644 index 0000000..59d7efe Binary files /dev/null and b/html/filetypes/wmv.gif differ diff --git a/html/filetypes/wmz.gif b/html/filetypes/wmz.gif new file mode 100644 index 0000000..a1ba280 Binary files /dev/null and b/html/filetypes/wmz.gif differ diff --git a/html/filetypes/wri.gif b/html/filetypes/wri.gif new file mode 100644 index 0000000..87fe2bf Binary files /dev/null and b/html/filetypes/wri.gif differ diff --git a/html/filetypes/xla.gif b/html/filetypes/xla.gif new file mode 100644 index 0000000..a84e207 Binary files /dev/null and b/html/filetypes/xla.gif differ diff --git a/html/filetypes/xlc.gif b/html/filetypes/xlc.gif new file mode 100644 index 0000000..522a003 Binary files /dev/null and b/html/filetypes/xlc.gif differ diff --git a/html/filetypes/xlk.gif b/html/filetypes/xlk.gif new file mode 100644 index 0000000..3fb4ac5 Binary files /dev/null and b/html/filetypes/xlk.gif differ diff --git a/html/filetypes/xll.gif b/html/filetypes/xll.gif new file mode 100644 index 0000000..5827b7d Binary files /dev/null and b/html/filetypes/xll.gif differ diff --git a/html/filetypes/xls.gif b/html/filetypes/xls.gif new file mode 100644 index 0000000..4e0f573 Binary files /dev/null and b/html/filetypes/xls.gif differ diff --git a/html/filetypes/xlt.gif b/html/filetypes/xlt.gif new file mode 100644 index 0000000..f9ec4f7 Binary files /dev/null and b/html/filetypes/xlt.gif differ diff --git a/html/filetypes/xlv.gif b/html/filetypes/xlv.gif new file mode 100644 index 0000000..b5251f9 Binary files /dev/null and b/html/filetypes/xlv.gif differ diff --git a/html/filetypes/xlw.gif b/html/filetypes/xlw.gif new file mode 100644 index 0000000..a7cd88b Binary files /dev/null and b/html/filetypes/xlw.gif differ diff --git a/html/filetypes/xml.gif b/html/filetypes/xml.gif new file mode 100644 index 0000000..d2bee21 Binary files /dev/null and b/html/filetypes/xml.gif differ diff --git a/html/filetypes/xpi.gif b/html/filetypes/xpi.gif new file mode 100644 index 0000000..4c5a6e4 Binary files /dev/null and b/html/filetypes/xpi.gif differ diff --git a/html/filetypes/xps.gif b/html/filetypes/xps.gif new file mode 100644 index 0000000..3369db2 Binary files /dev/null and b/html/filetypes/xps.gif differ diff --git a/html/filetypes/xsl.gif b/html/filetypes/xsl.gif new file mode 100644 index 0000000..34d1d86 Binary files /dev/null and b/html/filetypes/xsl.gif differ diff --git a/html/filetypes/z.gif b/html/filetypes/z.gif new file mode 100644 index 0000000..a857331 Binary files /dev/null and b/html/filetypes/z.gif differ diff --git a/html/filetypes/zip.gif b/html/filetypes/zip.gif new file mode 100644 index 0000000..ae3f51d Binary files /dev/null and b/html/filetypes/zip.gif differ diff --git a/html/ftpfav.ico b/html/ftpfav.ico new file mode 100644 index 0000000..4150275 Binary files /dev/null and b/html/ftpfav.ico differ diff --git a/html/msnreg.htm b/html/msnreg.htm new file mode 100644 index 0000000..c22531b --- /dev/null +++ b/html/msnreg.htm @@ -0,0 +1,42 @@ + + + + +Passport is live again! + + + + +

Escargot +Account +

+ +

Escargot is a new service +that makes old versions of MSN Messenger and Windows Live +Messenger work again.

+ +

You can use your Escargot +account as .NET Passport in Windows Messenger.

+ +

Learn how to get started

+
+ diff --git a/html/nodynsrc.gif b/html/nodynsrc.gif new file mode 100644 index 0000000..ed2c339 Binary files /dev/null and b/html/nodynsrc.gif differ diff --git a/html/norovp.htm b/html/norovp.htm new file mode 100644 index 0000000..447ed35 --- /dev/null +++ b/html/norovp.htm @@ -0,0 +1,17 @@ + + + + + +Retro online video player + + + + + +

Sorry, proxy server administrator has disabled the online video download feature.

+ + diff --git a/html/robots.txt b/html/robots.txt new file mode 100644 index 0000000..77470cb --- /dev/null +++ b/html/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Disallow: / \ No newline at end of file diff --git a/html/rovp-background.png b/html/rovp-background.png new file mode 100644 index 0000000..95fd24b Binary files /dev/null and b/html/rovp-background.png differ diff --git a/html/rovp-dynimg.htm b/html/rovp-dynimg.htm new file mode 100644 index 0000000..a72edc3 --- /dev/null +++ b/html/rovp-dynimg.htm @@ -0,0 +1,8 @@ + +Video player - Dynamic Image + + + +
+ + \ No newline at end of file diff --git a/html/rovp-embed.htm b/html/rovp-embed.htm new file mode 100644 index 0000000..3951fdc --- /dev/null +++ b/html/rovp-embed.htm @@ -0,0 +1,10 @@ + + +Video player - Universal + + + + + + + \ No newline at end of file diff --git a/html/rovp-embedvlc.htm b/html/rovp-embedvlc.htm new file mode 100644 index 0000000..dc524a8 --- /dev/null +++ b/html/rovp-embedvlc.htm @@ -0,0 +1,8 @@ + +Video player - VLC + + + + + + \ No newline at end of file diff --git a/html/rovp-embedwm.htm b/html/rovp-embedwm.htm new file mode 100644 index 0000000..8578652 --- /dev/null +++ b/html/rovp-embedwm.htm @@ -0,0 +1,8 @@ + +Video player - WMP + + + + + + \ No newline at end of file diff --git a/html/rovp-html5.htm b/html/rovp-html5.htm new file mode 100644 index 0000000..c32246c --- /dev/null +++ b/html/rovp-html5.htm @@ -0,0 +1,47 @@ + + +Video player - HTML5 + + + + + + + + + + +
+
+
+
+ + + \ No newline at end of file diff --git a/html/rovp-intro-mini.htm b/html/rovp-intro-mini.htm new file mode 100644 index 0000000..279b21d --- /dev/null +++ b/html/rovp-intro-mini.htm @@ -0,0 +1,15 @@ + +Video player - mini intro + + + + + + + +
+

Please choose playback profile.

+ +
+ + \ No newline at end of file diff --git a/html/rovp-intro.htm b/html/rovp-intro.htm new file mode 100644 index 0000000..a4039ae --- /dev/null +++ b/html/rovp-intro.htm @@ -0,0 +1,9 @@ + +Video player - INTRO + + + +

Use the toolbar above to watch a video.

+ + + \ No newline at end of file diff --git a/html/rovp-mini.htm b/html/rovp-mini.htm new file mode 100644 index 0000000..df02822 --- /dev/null +++ b/html/rovp-mini.htm @@ -0,0 +1,37 @@ + + + + + +Retro online video player (mini) + + + + + + +
+Retro Online Video Player  + + + +
+ + diff --git a/html/rovp-objectns.htm b/html/rovp-objectns.htm new file mode 100644 index 0000000..9b7f422 --- /dev/null +++ b/html/rovp-objectns.htm @@ -0,0 +1,8 @@ + +Video player - NetShow ActiveX + + + +
This mode is working only with Microsoft Internet Explorer 3 (or newer) and NetShow Player 2.0.
+ + \ No newline at end of file diff --git a/html/rovp-objectwm.htm b/html/rovp-objectwm.htm new file mode 100644 index 0000000..c661a4e --- /dev/null +++ b/html/rovp-objectwm.htm @@ -0,0 +1,8 @@ + +Video player - WMP ActiveX + + + +
Try another player type, as Windows Media Player Control 7.0 (or newer) is unavailable.
+ + \ No newline at end of file diff --git a/html/rovp-splash.htm b/html/rovp-splash.htm new file mode 100644 index 0000000..42511fc --- /dev/null +++ b/html/rovp-splash.htm @@ -0,0 +1,33 @@ + + +Retro online video player + + + +

Click here to open Retro Online Video Player.

Retro Online Video Player

+ + \ No newline at end of file diff --git a/html/rovp.css b/html/rovp.css new file mode 100644 index 0000000..fb7965f --- /dev/null +++ b/html/rovp.css @@ -0,0 +1,89 @@ +/* WebOne ROVP style sheet */ + +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; +} + +body.dark { + border-style: none; + background-image: url('rovp-background.png'); + background-size: cover; + color: #CCCCCC; +} + +body.light { + border-style: none; + color: #3B3B3B; + background-color: #FFFFFF; +} + +body.container { + padding: 1em; +} + +#MediaPlayer { + width: 70%; + min-height: 70%; +} + +a { + text-decoration: none; +} + +a:hover, a:focus { + text-decoration: underline; +} + +.light a { + color: #4daafc; +} + +.dark a { + color: #4daafc; +} + +.title { + font-size: 28px; + font-weight: 300; + margin: 0 0 12px 0; +} + +.subtitle { + font-size: 18px; + font-weight: 300; + margin: 0 0 36px 0; +} + +.light .subtitle { + color: #4d4d4d ; +} + +.dark .subtitle { + color: #929194; +} + +.detail { + font-size: 14px; + opacity: 0.7; + margin: 0; +} + +.error { + color: #F85149; +} + +h1, h2, h3, h4 { + font-family: sans-serif; +} + +li { + margin: 0px; +} + +ul { + list-style: square; +} + +iframe { + border-style: none; +} \ No newline at end of file diff --git a/html/rovp.gif b/html/rovp.gif new file mode 100644 index 0000000..f9700d4 Binary files /dev/null and b/html/rovp.gif differ diff --git a/html/rovp.htm b/html/rovp.htm new file mode 100644 index 0000000..9e3079d --- /dev/null +++ b/html/rovp.htm @@ -0,0 +1,127 @@ + + + + + +Retro online video player + + + + + + + +
+ + + + + + + + + + + + + + + + + +
Video
FormatCodecs   (?)
 Embed, WMP, VLC, WinMedia, NetShow, DynImg, HTML5, link, file
+
+ + + diff --git a/html/rovp.js b/html/rovp.js new file mode 100644 index 0000000..5e53c57 --- /dev/null +++ b/html/rovp.js @@ -0,0 +1,121 @@ +/* Scripts for Retro Online Video Player web form. */ + +function validate(form) { + var good = true; + + //check Container + switch(form.f.value) + { + case "mpeg1video": + if (form.vcodec.value != 'mpeg1video') { + alert('MPEG1 muxer supports only codec MPEG1 for video.'); + return false; + } + break; + case "mpeg2video": + if (form.vcodec.value != 'mpeg2video') { + alert('MPEG2 muxer supports only codec MPEG2 for video.'); + return false; + } + break; + case 'ogg': + if (form.vcodec.value != 'theora') { good = false; } + if (form.acodec.value != 'vorbis -strict -2') { good = false; } + if (!good) { + alert('Ogg is supporting only Theora video and Vorbis audio codecs.'); + return false; + } + break; + case 'webm': + switch (form.vcodec.value) { + case 'vp8': case 'vp9': case 'av1': + good = true; break; + default: + good = false; + } + if (good) switch (form.acodec.value) { + case 'vorbis -strict -2': case 'opus -strict -2': + good = true; break; + default: + good = false; + } + if (!good) { + alert('Only VP8 or VP9 or AV1 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.'); + return false; + } + break; + case 'swf': + if (form.type[0].checked || form.type[7].checked || form.type[8].checked) { good = true; } + else { + good = false; + alert('Flash videos can be played only via Macromedia/Adobe plug-in or player.'); + return false + } + switch (form.vcodec.value) + { + case "mjpeg": + case "flv": + case "vp6": + good = true; + break; + default: + good = false + break; + } + if(form.acodec.value != 'mp3') { good = false; } + if (!good) + { + alert('SWF muxer only supports FLV/MJPEG video and MP3 audio.'); + return false; + } + } + if (!good) return false; + + //check Video Codec + switch(form.vcodec.value) + { + case 'h263': + switch (form.vf.value) { + case 'scale="128x96"': + case 'scale="176x144"': + case 'scale="352x288"': + case 'scale="704x576"': + case 'scale="1408x1152"': + good = true; + break; + default: + good = false; + alert('H.263 - Valid resolutions are 128x96, 176x144, 352x288, 704x576, and 1408x1152.'); + return false; + } + break; + case 'msvideo1': + switch (form.vf.value) { + case 'scale="1024x768"': + case 'scale="800x600"': + case 'scale="640x480"': + case 'scale="320x240"': + good = true; + break; + default: + good = false; + alert('MS Video 1 - width and height must be multiples of 4. Choose 4:3 video format.'); + return false; + } + break; + } + if (!good) return false; + + //check Audio Codec + switch(form.acodec.value) + { + case 'vorbis -strict -2': + if (form.ac.value != '2') { good = false; } + if (!good) { + alert('Current FFmpeg Vorbis encoder only supports 2 channels.'); + return false; + } + } + + return good; +} diff --git a/html/rovpfav.ico b/html/rovpfav.ico new file mode 100644 index 0000000..f411b17 Binary files /dev/null and b/html/rovpfav.ico differ diff --git a/html/simple.htm b/html/simple.htm new file mode 100644 index 0000000..97d8228 --- /dev/null +++ b/html/simple.htm @@ -0,0 +1,49 @@ + + + + + +WebOne status page + + + + + +

Welcome to %ServerName%!

+ +

This is a HTTP 1.x proxy server that makes old Internet +browsers, media players and messengers usable again in the Web +2.0 world.

+ +

You need to set up your Web browser to use %ServerName% +as HTTP Proxy Server. Also you may enter it in HTTPS +and FTP Proxy Server lines. Or enter Proxy +Automatic Configuration Script URL in your Web browser +options:

+ +
http://%ServerName%/auto.pac
+ +

The current server is running WebOne %WOVer% on %WOSystem%.

+ +

Useful stuff

+ +

If you're seeing errors about "unknown certificate +issuer" when opening sites over HTTPS, try to import proxy's +Root Certificate. Note that +to made HTTPS working you need at least Mozilla Firefox 1.0 or +Opera 9 or Microsoft Internet Explorer 8.0 (also IE 6/7 is +supported on systems like WinXP SP3, Vista). Also certificate +import is required to use this proxy with MSN Messenger 4.7 and +newer.

+ +

WebOne can be used to open FTP servers +or to download videos +from YouTube.

+ +

Read more

+ +

About software used on this Proxy Server: https://github.com/atauenis/webone/

+ + diff --git a/html/webone.css b/html/webone.css new file mode 100644 index 0000000..0884f98 --- /dev/null +++ b/html/webone.css @@ -0,0 +1,69 @@ +/* WebOne default stylesheet */ +h1, h2, h3, h4 +{ + font-family: sans-serif; +} +html +{ + font-family: Cambria, sans-serif; +} +body +{ + margin:4em auto; + max-width: 52em; + min-width: 13em; + padding: 3em; +} +li +{ + margin: 0px; +} +ul +{ + list-style: square; +} +table +{ + margin-bottom:1.4em; + width:100%; + border-collapse:collapse; +} +th +{ + font-weight:bold; + background-color:#f0f0f0; +} +th,td +{ + border:1px solid #ddd; + padding:.33em .67em; + vertical-align:middle; +} +tr:nth-of-type(even) +{ + background-color:#f8f8f8; +} +tr:hover +{ + background-color:#FFFCDB; +} +table.nostyle, th.nostyle, tr.nostyle, td.nostyle, tr.nostyle:hover +{ + border-style: none !important; + background-color: transparent !important; + padding: unset !important; +} +tr.nostyle:nth-of-type(even) +{ + /* Separate for Firefox 2 */ + border-style: none !important; + background-color: transparent !important; + padding: unset !important; +} +img.fileicon +{ + vertical-align: bottom; + border-style: none; + width: 16px; + height: 16px; +} \ No newline at end of file diff --git a/internal/certs/certs.go b/internal/certs/certs.go new file mode 100644 index 0000000..3ad9133 --- /dev/null +++ b/internal/certs/certs.go @@ -0,0 +1,526 @@ +// Package certs is WebOne's certificate authority: the CA certificate the +// proxy makes (or is given), and the per-site certificates it signs with it +// on the fly for HTTPS clients, in the old hash algorithms (MD5, SHA-1) +// that old browsers need. +// +// Ported from WebOne's CertificateUtil.cs. Go's crypto/x509 will not sign +// with MD5, so MD5 signatures are made here by hand. +package certs + +import ( + "bytes" + "crypto" + "crypto/ecdsa" + "crypto/md5" + "crypto/rand" + "crypto/rsa" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" + "encoding/pem" + "errors" + "fmt" + "math/big" + mrand "math/rand/v2" + "net" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "time" +) + +// CA is a certificate authority: its certificate and key. +type CA struct { + Cert *x509.Certificate + Key crypto.Signer + PEM []byte // the certificate, PEM +} + +// DER is the CA certificate as DER. +func (ca *CA) DER() []byte { return ca.Cert.Raw } + +// ParseSubject reads a distinguished name as "CN=x,OU=y,O=z,C=w". +func ParseSubject(dn string) pkix.Name { + var n pkix.Name + for _, part := range splitDN(dn) { + k, v, ok := strings.Cut(part, "=") + if !ok { + continue + } + k, v = strings.ToUpper(strings.TrimSpace(k)), strings.TrimSpace(v) + switch k { + case "CN": + n.CommonName = v + case "OU": + n.OrganizationalUnit = append(n.OrganizationalUnit, v) + case "O": + n.Organization = append(n.Organization, v) + case "C": + n.Country = append(n.Country, v) + case "L": + n.Locality = append(n.Locality, v) + case "S", "ST": + n.Province = append(n.Province, v) + case "STREET": + n.StreetAddress = append(n.StreetAddress, v) + } + } + return n +} + +func splitDN(dn string) []string { + var parts []string + var b strings.Builder + quoted, esc := false, false + for _, r := range dn { + switch { + case esc: + b.WriteRune(r) + esc = false + case r == '\\': + esc = true + case r == '"': + quoted = !quoted + case (r == ',' || r == ';') && !quoted: + parts = append(parts, b.String()) + b.Reset() + default: + b.WriteRune(r) + } + } + return append(parts, b.String()) +} + +// sigAlg is the x509 algorithm for a hash name and key. +func sigAlg(hash string, key crypto.Signer) x509.SignatureAlgorithm { + _, isEC := key.Public().(*ecdsa.PublicKey) + switch strings.ToUpper(hash) { + case "MD5": + if isEC { + return x509.ECDSAWithSHA1 + } + return x509.MD5WithRSA + case "SHA1", "SHA": + if isEC { + return x509.ECDSAWithSHA1 + } + return x509.SHA1WithRSA + case "SHA384": + if isEC { + return x509.ECDSAWithSHA384 + } + return x509.SHA384WithRSA + case "SHA512": + if isEC { + return x509.ECDSAWithSHA512 + } + return x509.SHA512WithRSA + } + if isEC { + return x509.ECDSAWithSHA256 + } + return x509.SHA256WithRSA +} + +var ( + oidSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5} + oidMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4} +) + +// createCertificate is x509.CreateCertificate, but also signs with MD5: +// it makes a SHA-1 certificate, then puts MD5's OID in its place (the +// same length) and signs the result again. +func createCertificate(tmpl, parent *x509.Certificate, pub any, priv crypto.Signer) ([]byte, error) { + if tmpl.SignatureAlgorithm != x509.MD5WithRSA { + return x509.CreateCertificate(rand.Reader, tmpl, parent, pub, priv) + } + rsaKey, ok := priv.(*rsa.PrivateKey) + if !ok { + return nil, errors.New("MD5 signatures need an RSA key") + } + t := *tmpl + t.SignatureAlgorithm = x509.SHA1WithRSA + der, err := x509.CreateCertificate(rand.Reader, &t, parent, pub, priv) + if err != nil { + return nil, err + } + var cert struct { + TBS asn1.RawValue + Alg pkix.AlgorithmIdentifier + Sig asn1.BitString + } + if _, err := asn1.Unmarshal(der, &cert); err != nil { + return nil, err + } + sha1OID, _ := asn1.Marshal(oidSHA1WithRSA) + md5OID, _ := asn1.Marshal(oidMD5WithRSA) + tbs := bytes.Replace(cert.TBS.FullBytes, sha1OID, md5OID, 1) + if bytes.Equal(tbs, cert.TBS.FullBytes) { + return nil, errors.New("cannot find the signature algorithm in the certificate") + } + sum := md5.Sum(tbs) + sig, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, crypto.MD5, sum[:]) + if err != nil { + return nil, err + } + cert.TBS = asn1.RawValue{FullBytes: tbs} + cert.Alg = pkix.AlgorithmIdentifier{Algorithm: oidMD5WithRSA, Parameters: asn1.NullRawValue} + cert.Sig = asn1.BitString{Bytes: sig, BitLength: len(sig) * 8} + return asn1.Marshal(cert) +} + +// CreateCA makes a self-signed CA certificate and its RSA 2048 key, and +// writes them as PEM to certFile and keyFile. +func CreateCA(certFile, keyFile, subject, hash string, notBefore, notAfter time.Time) error { + n := mrand.Int64N(900) + 100 + if subject == "" || strings.Contains(subject, "%number%") { + if subject == "" { + subject = "CN=WebOne Certificate Authority %number%,OU=This is not really secure connection,O=MITM Proxy,C=SU" + } + subject = strings.ReplaceAll(subject, "%number%", strconv.FormatInt(n, 10)) + } + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + return err + } + name := ParseSubject(subject) + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(n), + Subject: name, + NotBefore: notBefore, + NotAfter: notAfter, + KeyUsage: x509.KeyUsageCertSign, + BasicConstraintsValid: true, + IsCA: true, + MaxPathLen: 12, + SignatureAlgorithm: sigAlg(hash, key), + } + der, err := createCertificate(tmpl, tmpl, &key.PublicKey, key) + if err != nil { + return err + } + if dir := filepath.Dir(keyFile); dir != "" { + os.MkdirAll(dir, 0o755) + } + kp := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) + if err := os.WriteFile(keyFile, kp, 0o600); err != nil { + return err + } + cp := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + return os.WriteFile(certFile, cp, 0o644) +} + +// LoadCert reads a certificate (PEM or DER) without its key: a root that +// only has to be shown to clients. +func LoadCert(certFile string) (*CA, error) { + cp, err := os.ReadFile(certFile) + if err != nil { + return nil, err + } + der := cp + for rest := cp; ; { + var b *pem.Block + b, rest = pem.Decode(rest) + if b == nil { + break + } + if b.Type == "CERTIFICATE" { + der = b.Bytes + break + } + } + cert, err := x509.ParseCertificate(der) + if err != nil { + return nil, fmt.Errorf("%s: %v", certFile, err) + } + return &CA{Cert: cert, PEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})}, nil +} + +// HashOf is the hash name (as SslHashAlgorithm takes it) of a +// certificate's signature. +func HashOf(c *x509.Certificate) string { + switch c.SignatureAlgorithm { + case x509.MD5WithRSA: + return "MD5" + case x509.SHA1WithRSA, x509.ECDSAWithSHA1, x509.DSAWithSHA1: + return "SHA1" + case x509.SHA384WithRSA, x509.ECDSAWithSHA384, x509.SHA384WithRSAPSS: + return "SHA384" + case x509.SHA512WithRSA, x509.ECDSAWithSHA512, x509.SHA512WithRSAPSS: + return "SHA512" + } + return "SHA256" +} + +// BBSCA is the CA of a D-Modem BBS directory (bbs ca): the proxy signs +// with the sub-CA proxy-ca.crt/.key (made by "bbs ca subca proxy"), and +// clients install the root ca.crt. A directory with no sub-CA but a +// readable ca.key is used directly. +func BBSCA(dir string) (signer, root *CA, err error) { + rootCert := filepath.Join(dir, "ca.crt") + sub, subErr := LoadCA(filepath.Join(dir, "proxy-ca.crt"), filepath.Join(dir, "proxy-ca.key")) + if subErr == nil { + r, err := LoadCert(rootCert) + if err != nil { + return nil, nil, err + } + if err := sub.Cert.CheckSignatureFrom(r.Cert); err != nil { + return nil, nil, fmt.Errorf("proxy-ca.crt is not signed by ca.crt in %s: %v", dir, err) + } + return sub, r, nil + } + if !os.IsNotExist(subErr) { + return nil, nil, fmt.Errorf("cannot read the BBS proxy sub-CA in %s: %v (run the proxy as the BBS user, or give it read access)", dir, subErr) + } + ca, err := LoadCA(rootCert, filepath.Join(dir, "ca.key")) + if err != nil { + return nil, nil, fmt.Errorf("no BBS proxy sub-CA in %s (make it with \"bbs ca subca proxy\"): %v", dir, err) + } + return ca, ca, nil +} + +// LoadCA reads a CA certificate and key (PEM; the key PKCS#1, PKCS#8 or EC). +func LoadCA(certFile, keyFile string) (*CA, error) { + cp, err := os.ReadFile(certFile) + if err != nil { + return nil, err + } + kp, err := os.ReadFile(keyFile) + if err != nil { + return nil, err + } + var cb *pem.Block + for rest := cp; ; { + cb, rest = pem.Decode(rest) + if cb == nil || cb.Type == "CERTIFICATE" { + break + } + } + if cb == nil { + return nil, fmt.Errorf("%s: not a PEM certificate", certFile) + } + cert, err := x509.ParseCertificate(cb.Bytes) + if err != nil { + return nil, err + } + key, err := parseKey(kp) + if err != nil { + return nil, fmt.Errorf("%s: %v", keyFile, err) + } + return &CA{Cert: cert, Key: key, PEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})}, nil +} + +func parseKey(kp []byte) (crypto.Signer, error) { + for { + b, rest := pem.Decode(kp) + if b == nil { + return nil, errors.New("no PEM private key") + } + kp = rest + switch b.Type { + case "RSA PRIVATE KEY": + return x509.ParsePKCS1PrivateKey(b.Bytes) + case "EC PRIVATE KEY": + return x509.ParseECPrivateKey(b.Bytes) + case "PRIVATE KEY": + k, err := x509.ParsePKCS8PrivateKey(b.Bytes) + if err != nil { + return nil, err + } + s, ok := k.(crypto.Signer) + if !ok { + return nil, errors.New("unsupported private key type") + } + return s, nil + } + } +} + +// Issuer makes and caches the certificates of the sites clients connect to. +type Issuer struct { + CA *CA + // Hash: MD5, SHA1, SHA256, SHA384 or SHA512 + Hash string + // days around now a site certificate is good for + ValidBeforeNow, ValidAfterNow int + // SiteCerts is a path (with %Subject%) where site certificates may be + // found as .crt and .key files; Generator is a command that makes them. + SiteCerts, Generator string + // Expand expands variables (and %Subject%) in SiteCerts and Generator. + Expand func(s, subject string) string + // Log reports external generator problems. + Log func(format string, args ...any) + + mu sync.Mutex + cache map[string]*tls.Certificate + key *rsa.PrivateKey +} + +// Get is the certificate for host (cached until it runs out). +func (is *Issuer) Get(host string) (*tls.Certificate, error) { + subject := "CN=" + host + is.mu.Lock() + if is.cache == nil { + is.cache = map[string]*tls.Certificate{} + } + if c, ok := is.cache[subject]; ok { + if now := time.Now(); now.After(c.Leaf.NotBefore) && now.Before(c.Leaf.NotAfter) { + is.mu.Unlock() + return c, nil + } + delete(is.cache, subject) + } + is.mu.Unlock() + + if c, err := is.external(subject); err != nil { + return nil, err + } else if c != nil { + return c, nil + } + + c, err := is.issue(host) + if err != nil { + return nil, err + } + is.mu.Lock() + if old, ok := is.cache[subject]; ok { + c = old // keep one serial per subject (Firefox objects to two) + } else { + is.cache[subject] = c + } + is.mu.Unlock() + return c, nil +} + +// external looks for the site's certificate on disk, or has the external +// generator make it. +func (is *Issuer) external(subject string) (*tls.Certificate, error) { + if strings.TrimSpace(is.SiteCerts) == "" && strings.TrimSpace(is.Generator) == "" { + return nil, nil + } + expand := is.Expand + if expand == nil { + expand = func(s, sub string) string { return strings.ReplaceAll(s, "%Subject%", sub) } + } + base := expand(is.SiteCerts, subject) + crt, key := base+".crt", base+".key" + load := func() *tls.Certificate { + if fileExists(crt) && fileExists(key) { + if c, err := tls.LoadX509KeyPair(crt, key); err == nil { + if c.Leaf == nil { + c.Leaf, _ = x509.ParseCertificate(c.Certificate[0]) + } + return &c + } + } + return nil + } + if strings.TrimSpace(is.SiteCerts) != "" { + if c := load(); c != nil { + return c, nil + } + } + if g := strings.TrimSpace(is.Generator); g != "" { + prog, args, _ := strings.Cut(g, " ") + args = expand(args, subject) + if prog != "" && strings.TrimSpace(args) != "" { + cmd := exec.Command(prog, SplitArgs(args)...) + if err := cmd.Run(); err != nil && is.Log != nil { + is.Log(" Certificate generator failed: %v", err) + } + if c := load(); c != nil { + return c, nil + } + if is.Log != nil { + is.Log(" No certificate and/or private key file were produced: %s (.key)!", crt) + } + } + } + return nil, nil +} + +func (is *Issuer) issue(host string) (*tls.Certificate, error) { + is.mu.Lock() + if is.key == nil { + k, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + is.mu.Unlock() + return nil, err + } + is.key = k + } + key := is.key + is.mu.Unlock() + + serial := make([]byte, 16) + rand.Read(serial) + serial[0] &= 0x7f + now := time.Now() + tmpl := &x509.Certificate{ + SerialNumber: new(big.Int).SetBytes(serial), + Subject: pkix.Name{CommonName: host}, + NotBefore: now.AddDate(0, 0, is.ValidBeforeNow), + NotAfter: now.AddDate(0, 0, is.ValidAfterNow), + SignatureAlgorithm: sigAlg(is.Hash, is.CA.Key), + } + if is.ValidAfterNow == 0 { + tmpl.NotAfter = now.AddDate(0, 0, 7) + } + // today's browsers take no site certificate longer than 397 days + if limit := tmpl.NotBefore.AddDate(0, 0, 397); tmpl.NotAfter.After(limit) { + tmpl.NotAfter = limit + } + if tmpl.NotAfter.After(is.CA.Cert.NotAfter) { + tmpl.NotAfter = is.CA.Cert.NotAfter + } + if ip := net.ParseIP(strings.Trim(host, "[]")); ip != nil { + tmpl.IPAddresses = []net.IP{ip} + } else { + tmpl.DNSNames = []string{host} + } + der, err := createCertificate(tmpl, is.CA.Cert, &key.PublicKey, is.CA.Key) + if err != nil { + return nil, err + } + leaf, err := x509.ParseCertificate(der) + if err != nil { + return nil, err + } + return &tls.Certificate{Certificate: [][]byte{der, is.CA.Cert.Raw}, PrivateKey: key, Leaf: leaf}, nil +} + +func fileExists(p string) bool { + st, err := os.Stat(p) + return err == nil && !st.IsDir() +} + +// SplitArgs splits a command line on spaces, keeping "quoted parts" whole. +func SplitArgs(s string) []string { + var out []string + var b strings.Builder + quoted, any := false, false + for _, r := range s { + switch { + case r == '"': + quoted = !quoted + any = true + case (r == ' ' || r == '\t') && !quoted: + if any { + out = append(out, b.String()) + b.Reset() + any = false + } + default: + b.WriteRune(r) + any = true + } + } + if any { + out = append(out, b.String()) + } + return out +} diff --git a/internal/certs/certs_test.go b/internal/certs/certs_test.go new file mode 100644 index 0000000..c8676c4 --- /dev/null +++ b/internal/certs/certs_test.go @@ -0,0 +1,153 @@ +package certs + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "os" + "path/filepath" + "testing" + "time" +) + +func TestCreateCAHashes(t *testing.T) { + dir := t.TempDir() + for _, h := range []string{"MD5", "SHA1", "SHA256"} { + crt, key := filepath.Join(dir, h+".crt"), filepath.Join(dir, h+".key") + if err := CreateCA(crt, key, "", h, time.Now().Add(-time.Hour), time.Now().AddDate(10, 0, 0)); err != nil { + t.Fatalf("%s: %v", h, err) + } + ca, err := LoadCA(crt, key) + if err != nil { + t.Fatalf("%s: %v", h, err) + } + if got := HashOf(ca.Cert); got != h { + t.Errorf("CA made with %s is signed with %s", h, got) + } + if !ca.Cert.IsCA { + t.Errorf("%s: not a CA", h) + } + is := &Issuer{CA: ca, Hash: h, ValidBeforeNow: -7, ValidAfterNow: 7} + c, err := is.Get("www.example.com") + if err != nil { + t.Fatalf("%s leaf: %v", h, err) + } + if HashOf(c.Leaf) != h { + t.Errorf("leaf made with %s is signed with %s", h, HashOf(c.Leaf)) + } + if len(c.Certificate) != 2 { + t.Errorf("chain has %d certificates", len(c.Certificate)) + } + if h == "SHA256" { + pool := x509.NewCertPool() + pool.AddCert(ca.Cert) + if _, err := c.Leaf.Verify(x509.VerifyOptions{Roots: pool, DNSName: "www.example.com"}); err != nil { + t.Errorf("leaf does not verify: %v", err) + } + } + again, _ := is.Get("www.example.com") + if again != c { + t.Error("certificate not cached") + } + } +} + +func writePEM(t *testing.T, path, typ string, der []byte, mode os.FileMode) { + t.Helper() + if err := os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: typ, Bytes: der}), mode); err != nil { + t.Fatal(err) + } +} + +// bbsCA makes a directory as "bbs ca" and "bbs ca subca proxy" leave it. +func bbsCA(t *testing.T, withSub bool) string { + dir := t.TempDir() + rootKey, _ := rsa.GenerateKey(rand.Reader, 2048) + root := &x509.Certificate{ + SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "D-Modem BBS Root CA"}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().AddDate(20, 0, 0), + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, BasicConstraintsValid: true, IsCA: true, MaxPathLen: 1, + SignatureAlgorithm: x509.SHA256WithRSA, + } + rootDER, err := x509.CreateCertificate(rand.Reader, root, root, &rootKey.PublicKey, rootKey) + if err != nil { + t.Fatal(err) + } + root, _ = x509.ParseCertificate(rootDER) + writePEM(t, filepath.Join(dir, "ca.crt"), "CERTIFICATE", rootDER, 0o644) + writePEM(t, filepath.Join(dir, "ca.key"), "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(rootKey), 0o600) + if !withSub { + return dir + } + subKey, _ := rsa.GenerateKey(rand.Reader, 2048) + sub := &x509.Certificate{ + SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "D-Modem BBS proxy CA"}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().AddDate(10, 0, 0), + KeyUsage: x509.KeyUsageCertSign, BasicConstraintsValid: true, IsCA: true, MaxPathLen: 0, MaxPathLenZero: true, + SignatureAlgorithm: x509.SHA256WithRSA, + } + subDER, err := x509.CreateCertificate(rand.Reader, sub, root, &subKey.PublicKey, rootKey) + if err != nil { + t.Fatal(err) + } + writePEM(t, filepath.Join(dir, "proxy-ca.crt"), "CERTIFICATE", subDER, 0o644) + writePEM(t, filepath.Join(dir, "proxy-ca.key"), "RSA PRIVATE KEY", x509.MarshalPKCS1PrivateKey(subKey), 0o600) + return dir +} + +func TestBBSSubCA(t *testing.T) { + dir := bbsCA(t, true) + signer, root, err := BBSCA(dir) + if err != nil { + t.Fatal(err) + } + if signer == root || signer.Cert.Subject.CommonName != "D-Modem BBS proxy CA" || root.Key != nil { + t.Fatalf("signer %q, root %q", signer.Cert.Subject.CommonName, root.Cert.Subject.CommonName) + } + is := &Issuer{CA: signer, Hash: HashOf(signer.Cert), ValidBeforeNow: -7, ValidAfterNow: 3650} + c, err := is.Get("example.org") + if err != nil { + t.Fatal(err) + } + if d := c.Leaf.NotAfter.Sub(c.Leaf.NotBefore); d > 397*24*time.Hour { + t.Errorf("leaf is valid for %v", d) + } + // a client that has only the root installed trusts the leaf, given + // the sub-CA the proxy sends after it + inter, _ := x509.ParseCertificate(c.Certificate[1]) + roots, inters := x509.NewCertPool(), x509.NewCertPool() + roots.AddCert(root.Cert) + inters.AddCert(inter) + if _, err := c.Leaf.Verify(x509.VerifyOptions{Roots: roots, Intermediates: inters, DNSName: "example.org"}); err != nil { + t.Errorf("chain does not verify: %v", err) + } +} + +func TestBBSRootOnly(t *testing.T) { + signer, root, err := BBSCA(bbsCA(t, false)) + if err != nil { + t.Fatal(err) + } + if signer != root || signer.Key == nil { + t.Error("a directory without a sub-CA uses the root itself") + } + if _, _, err := BBSCA(t.TempDir()); err == nil { + t.Error("an empty directory gave a CA") + } +} + +func TestSplitArgs(t *testing.T) { + got := SplitArgs(`-i "a file.png" -resize 50% out.gif`) + want := []string{"-i", "a file.png", "-resize", "50%", "out.gif"} + if len(got) != len(want) { + t.Fatalf("%q", got) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("%d: %q", i, got[i]) + } + } +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..5626dbf --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,416 @@ +package config + +import ( + "crypto/tls" + "fmt" + "net" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "time" + + "github.com/D-Modem/webone-go/internal/logx" + "github.com/D-Modem/webone-go/internal/rx" + "github.com/D-Modem/webone-go/internal/textenc" +) + +// Converter is a [Converters] line: an external program that converts +// content (ImageMagick's convert, ffmpeg ...), with %SRC%, %DEST%, %ARG1%, +// %ARG2%, %DESTEXT% and %SRCURL% in its command line. +type Converter struct { + Executable string + CommandLine string + UseStdout bool // no %DEST%: the result is on standard output + UseStdin bool // no %SRC%: the source goes to standard input + SelfDownload bool // %SRCURL%: the program fetches the source itself +} + +// ParseConverter parses a [Converters] line. +func ParseConverter(s string) (Converter, error) { + i := strings.IndexByte(s, ' ') + if i < 0 { + return Converter{}, fmt.Errorf("converter line is invalid") + } + c := Converter{Executable: s[:i], CommandLine: s[i+1:]} + c.UseStdout = !strings.Contains(c.CommandLine, "%DEST%") + c.UseStdin = !strings.Contains(c.CommandLine, "%SRC%") + c.SelfDownload = strings.Contains(c.CommandLine, "%SRCURL%") + if c.UseStdin && c.SelfDownload { + c.UseStdin = false + } + return c, nil +} + +// Config is the whole configuration (ConfigFile.cs). +type Config struct { + // [Server] + Port int + IP net.IP + ForceHttps []string + ForceUtf8 []string + TextTypes []string + OutputEncoding *textenc.Encoding // nil: as is + CodepageANSI *textenc.Encoding + CodepageASCII *textenc.Encoding + CodepageMac *textenc.Encoding + CodepageEBCDIC *textenc.Encoding + CodepageCulture textenc.Culture + Authenticate []string + AuthenticateMessage string + AuthenticateRealm string + OpenForLocalIPs bool + HideClientErrors bool + SearchInArchive bool + HideArchiveRedirect bool + ArchiveUrlSuffix string + ShortenArchiveErrors bool + ArchiveDateLimit int + Converters []Converter + UserAgent string + DefaultHostName string + ValidateCertificates bool + EditRules []*EditSet + TranslitTable [][2]string + TemporaryDirectory string + DisplayStatusPage string + IpBanList []string + IpWhiteList []string + UrlBlackList []string + UrlWhiteList []string + HostNames []string + UpperProxy string + PAC string + MultipleHttp2Conns bool + RemoteHttpVersion string + WebVideoOptions map[string]string + WebVideoProfiles map[string][]string + AllowHttpCompression bool + MimeTypes map[string]string + EnableWebFtp bool + ShowFileIcons bool + Http10Only []string + EnableManualConverting bool + ContentDirectory string + DontPreferHTTPS bool + ConnectionTimeout int + ActivexGalleryEmul bool + ActivexGalleryUrls []string + ActivexGalleryCLSIDs map[string]string + // DnsServer (Go port): resolve upstream names through this server + // ("host:port"), such as the BBS's own DNS, rather than the system's. + DnsServer string + + // [SecureProxy] + SslEnable bool + SslCertificate string + SslPrivateKey string + SslProtocols []uint16 // TLS versions for clients + SslProtocolsSet bool + SslCipherSuites []uint16 + SslHashAlgorithm string // MD5, SHA1, SHA256, SHA384, SHA512 + SslHashAlgorithmSet bool // given in the configuration + SecurityProtocols []uint16 // TLS versions for fetching from servers + SslRootSubject string + SslRootValidAfter time.Time + SslRootValidBefore time.Time + SslCertValidBeforeNow int + SslCertValidAfterNow int + SslSiteCerts string + SslSiteCertGenerator string + AllowNonHttpsCONNECT bool + NonHttpSslServers []string + NonHttpConnectRedirect map[string]string + ConnectPassThrough []string + NonHttpSslDecrypt map[string]string + // SslCaDirectory (Go port): use the CA in this directory (ca.crt and + // ca.key, as the D-Modem BBS keeps its own); never made or replaced. + SslCaDirectory string + // SslTrustOwnCA (Go port): also trust the proxy's CA when fetching + // from servers (for sites the BBS serves under its own CA). + SslTrustOwnCA bool + + // Vars is [Variables] plus the built-in ones (WOVer, WOSystem, + // WOConfigDir, Proxy, ProxyHost, ProxyPort). + Vars *Vars + + // where the configuration came from + ConfigFileName string + CustomConfig string + LoadedFiles []string + rawEntries [][2]string // location, line + sections []*Section + + // LogFile/AppendLogFile seen in [Server]; opened by the caller unless + // the command line overrides it + LogFile string + LogFileAppend bool +} + +// DefaultCASubject is the subject of a CA WebOne makes; %number% becomes a +// random number (two CAs of one name confuse Firefox). +const DefaultCASubject = "CN=WebOne Certificate Authority %number%,OU=This is not really secure connection,O=MITM Proxy,C=SU" + +// Default PAC script parts. +const ( + DefaultPACHeader = "function FindProxyForURL(url, host){\n" + DefaultPACHttp = "if (url.substring(0, 5) == 'http:')\n{ return 'PROXY %PACProxy%'; }\n" + DefaultPACHttps = "if (url.substring(0, 6) == 'https:')\n{ return 'PROXY %PACProxy%'; }\n" + DefaultPACFtp = "if (url.substring(0, 4) == 'ftp:')\n{ return 'PROXY %PACProxy%'; }\n" + DefaultPACFooter = "} /*WebOne PAC*/ " +) + +// New is the default configuration (before any file). +func New() *Config { + wd, _ := os.Getwd() + host, _ := os.Hostname() + lang := os.Getenv("LC_ALL") + if lang == "" { + lang = os.Getenv("LANG") + } + return &Config{ + Port: 80, + TextTypes: []string{"text/", "javascript"}, + CodepageCulture: textenc.CultureFor(lang), + AuthenticateMessage: "

Hello! This Web 2.0-to-1.0 proxy server is private. Please reload this page and enter your credentials in browser's pop-up window.

", + AuthenticateRealm: "WebOne", + UserAgent: "%Original% WebOne/%WOVer%", + DefaultHostName: host, + ValidateCertificates: true, + TemporaryDirectory: wd + string(os.PathSeparator), + DisplayStatusPage: "full", + MultipleHttp2Conns: true, + RemoteHttpVersion: "auto", + WebVideoOptions: map[string]string{}, + WebVideoProfiles: map[string][]string{}, + AllowHttpCompression: true, + MimeTypes: map[string]string{}, + EnableWebFtp: true, + ShowFileIcons: true, + EnableManualConverting: true, + ContentDirectory: "./html", + ConnectionTimeout: 100, + ActivexGalleryEmul: true, + ActivexGalleryCLSIDs: map[string]string{}, + SslEnable: true, + SslCertificate: "ssl.crt", + SslPrivateKey: "ssl.key", + SslHashAlgorithm: "SHA1", + SslRootSubject: DefaultCASubject, + SslCertValidBeforeNow: -7, + SslCertValidAfterNow: 7, + AllowNonHttpsCONNECT: true, + NonHttpConnectRedirect: map[string]string{}, + NonHttpSslDecrypt: map[string]string{}, + Vars: NewVars(), + } +} + +// ToBool reads a yes/no value: 1/0, y/n, yes/no, on/off, enable/disable, +// true/false. Anything else is false (WebOne throws; a warning is logged +// by callers that care). +func ToBool(s string) bool { + switch strings.ToLower(strings.TrimSpace(s)) { + case "1", "y", "yes", "on", "enable", "true": + return true + } + return false +} + +// IsBool: s is one of the words ToBool knows. +func IsBool(s string) bool { + switch strings.ToLower(strings.TrimSpace(s)) { + case "1", "y", "yes", "on", "enable", "true", "0", "n", "no", "off", "disable", "false", "": + return true + } + return false +} + +// ParseVersion reads "1.1" or "2". +func ParseVersion(s string) (major, minor int, ok bool) { + s = strings.TrimSpace(s) + parts := strings.Split(s, ".") + if len(parts) == 0 || len(parts) > 4 { + return 0, 0, false + } + var err error + if major, err = strconv.Atoi(parts[0]); err != nil { + return 0, 0, false + } + if len(parts) > 1 { + if minor, err = strconv.Atoi(parts[1]); err != nil { + return 0, 0, false + } + } + return major, minor, true +} + +// ParseHTTPVersionRule reads a RemoteHttpVersion / AddRequestHttpVersion +// value: "1.1" (exactly), "=1.1", ">1.1", "<2.0" or "auto". +func ParseHTTPVersionRule(s string) (string, bool) { + if rx.Match(`[\d][\.][\d]`, s) && !rx.Match(`^[=<>]`, s) { + return "=" + s, true + } + if rx.Match(`([=>= 0 { + e.Edits = append(e.Edits, EditRule{Action: line.Key, Value: line.Value, Params: p}) + } else { + logx.Server(true, "Warning: invalid group number [4th argument] at %s. Line ignored.", line.Location) + } + default: + logx.Server(true, "Warning: bad count of arguments of AddVariable at %s. Line ignored.", line.Location) + } + default: + if strings.HasPrefix(line.Key, "Add") { + logx.Server(true, "Warning: unknown edit action \"%s\" at %s. Line ignored.", line.Key, line.Location) + } else { + logx.Server(true, "Warning: unknown edit set condition \"%s\" at %s. Line ignored.", line.Key, line.Location) + } + } + if strings.HasPrefix(line.Key, AddConvert) || line.Key == AddFind || line.Key == AddReplace { + mayBeForResponse = true + } + if line.Key == AddInternalRedirect { + mayBeForResponse = false + } + } + e.processComplexRules(c) + if len(e.ContentTypeMasks) == 0 && !mayBeForResponse { + e.IsForRequest = true + } + if len(e.UrlMasks) == 0 { + e.UrlMasks = append(e.UrlMasks, ".*") + } + return e, nil +} + +// processComplexRules joins AddFind+AddReplace into AddFindReplace (and the +// header variants), and AddConvert* into AddConverting. +func (e *EditSet) processComplexRules(c *Config) { + var finds, repls, rqFinds, rqRepls, rsFinds, rsRepls []string + var converter, dest, arg1, arg2 string + for _, r := range e.Edits { + switch r.Action { + case AddFind: + finds = append(finds, r.Value) + case AddReplace: + repls = append(repls, r.Value) + case AddRequestHeaderFind: + rqFinds = append(rqFinds, r.Value) + case AddRequestHeaderReplace: + rqRepls = append(rqRepls, r.Value) + case AddResponseHeaderFind: + rsFinds = append(rsFinds, r.Value) + case AddResponseHeaderReplace: + rsRepls = append(rsRepls, r.Value) + case AddConvert: + converter = r.Value + case AddConvertDest: + dest = r.Value + case AddConvertArg1: + arg1 = r.Value + case AddConvertArg2: + arg2 = r.Value + } + } + pair := func(f, r []string, action, what string) { + if len(f) != len(r) { + logx.Server(true, "Warning: Invalid amount of %sfinds/replaces in %s.", what, e.Location) + return + } + for i := range f { + e.Edits = append(e.Edits, EditRule{Action: action, Find: f[i], Replace: r[i]}) + } + } + pair(finds, repls, AddFindReplace, "") + pair(rqFinds, rqRepls, AddRequestHeaderFindReplace, "request header ") + pair(rsFinds, rsRepls, AddResponseHeaderFindReplace, "response header ") + + if converter != "" { + ok := false + for _, cv := range c.Converters { + if cv.Executable == converter { + e.Edits = append(e.Edits, EditRule{Action: AddConverting, Converter: converter, ConvertDest: dest, ConvertArg1: arg1, ConvertArg2: arg2}) + ok = true + break + } + } + if !ok { + logx.Server(true, "Warning: Converter \"%s\" in Edit Set at %s is not present in lists of converters.", converter, e.Location) + } + } else if dest != "" || arg1 != "" || arg2 != "" { + logx.Server(true, "Warning: Please add AddConvert rule to Edit Set starting at %s to use converting.", e.Location) + } +} + +// CheckCode: an OnCode condition (nil: any) admits an HTTP status code. +// 0 is any below 300; 2, 3 and 4 are 2xx, 3xx and 4xx-or-above. +func CheckCode(expected *int, code int) bool { + if expected == nil { + return true + } + switch { + case *expected == code: + return true + case *expected == 0 && code < 300: + return true + case *expected == 2 && code >= 200 && code < 300: + return true + case *expected == 3 && code >= 300 && code < 400: + return true + case *expected == 4 && code > 399: + return true + } + return false +} + +func checkRegExp(pattern, location string) error { + if pattern == "" { + return nil + } + if err := rx.Check(pattern); err != nil { + return fmt.Errorf("problem with regular expression \"%v\" at %s", err, location) + } + return nil +} diff --git a/internal/config/entry.go b/internal/config/entry.go new file mode 100644 index 0000000..b692370 --- /dev/null +++ b/internal/config/entry.go @@ -0,0 +1,159 @@ +// Package config reads WebOne configuration files: an INI-like format whose +// sections may also hold raw lists (ForceHttps, TextTypes ...), may repeat +// (Edit), and may pull in other files ([Include:path]). +// +// Ported from WebOne's ConfigFileEntry.cs, ConfigFileLoader.cs and +// ConfigFile.cs. +package config + +import ( + "fmt" + "strings" +) + +// Option is one line inside a section: "Key=Value" or a raw string. +type Option struct { + Key string // empty for a raw line + Value string // the value, unescaped; the whole line for a raw line + Values []string // the quoted parts of an escaped value ("a", "b"); nil if not escaped + Raw string // the line as written + Location string // "file, line N" +} + +// HasKeyValue: the line is "Key=Value", not a raw list item. +func (o Option) HasKeyValue() bool { return o.Key != "" } + +// ValuesOrValue is Values, or Value alone when the value was not quoted. +func (o Option) ValuesOrValue() []string { + if o.Values != nil { + return o.Values + } + return []string{o.Value} +} + +func (o Option) String() string { return o.Raw } + +// ParseOption parses a section line. Values that start with a double quote +// (or a backslash) use C-like escapes, and may hold several quoted parts +// separated by spaces, tabs or commas, ending at ';'. +func ParseOption(raw, location string) (Option, error) { + o := Option{Raw: raw, Location: location} + i := strings.IndexByte(raw, '=') + if i < 0 { + o.Value = raw + return o, nil + } + o.Key = raw[:i] + o.Value = raw[i+1:] + if o.Key == "" { + // "=x" has no key: WebOne treats an empty key as a raw line + o.Value = raw + return o, nil + } + v := o.Value + if !(strings.HasPrefix(v, `"`) || strings.HasPrefix(v, `\`)) { + return o, nil + } + + var values []string + var sb strings.Builder + escape := false + inString := v[0] == '"' + gap := false + rs := []rune(v) +loop: + for i := 1; i < len(rs); i++ { + c := rs[i] + if !gap { + if !escape && c == '\\' { + escape = true + continue + } + if escape { + escape = false + switch c { + case '\'': + sb.WriteRune('\'') + case '"': + sb.WriteRune('"') + case '\\': + sb.WriteRune('\\') + case '0': + sb.WriteRune(0) + case 'a': + sb.WriteRune('\a') + case 'b': + sb.WriteRune('\b') + case 'f': + sb.WriteRune('\f') + case 'n': + sb.WriteRune('\n') + case 'r': + sb.WriteRune('\r') + case 't': + sb.WriteRune('\t') + case 'v': + sb.WriteRune('\v') + default: + return o, fmt.Errorf("unknown escape sequence: %c", c) + } + continue + } + if c == '"' && inString { + values = append(values, sb.String()) + sb.Reset() + gap = true + inString = false + continue + } + sb.WriteRune(c) + continue + } + // the gap between quoted values + switch c { + case ' ', '\t', ',': + continue + case '"': + gap = false + inString = true + case ';': + break loop + default: + return o, fmt.Errorf("garbage in the middle gap: %c", c) + } + } + if len(values) == 0 { + values = append(values, sb.String()) + } + o.Values = values + o.Value = strings.Join(values, "") + return o, nil +} + +// Section is a "[Kind]" or "[Kind:Mask]" section with its lines. +type Section struct { + Title string + Kind string + Mask string + HasMask bool + Location string + Options []Option +} + +// ParseSection parses a "[Title]" line. +func ParseSection(raw, location string) (*Section, error) { + if !(strings.HasPrefix(raw, "[") && strings.HasSuffix(raw, "]")) || len(raw) < 2 { + return nil, fmt.Errorf("invalid section title") + } + s := &Section{Title: raw[1 : len(raw)-1], Location: location} + if i := strings.IndexByte(s.Title, ':'); i >= 0 { + s.Kind = s.Title[:i] + s.Mask = s.Title[i+1:] + s.HasMask = true + } else { + s.Kind = s.Title + } + return s, nil +} + +func (s *Section) String() string { return "[" + s.Title + "]" } diff --git a/internal/config/loader.go b/internal/config/loader.go new file mode 100644 index 0000000..2f8f368 --- /dev/null +++ b/internal/config/loader.go @@ -0,0 +1,675 @@ +package config + +import ( + "bufio" + "bytes" + "crypto/tls" + "fmt" + "net" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" + + "github.com/D-Modem/webone-go/internal/logx" + "github.com/D-Modem/webone-go/internal/rx" + "github.com/D-Modem/webone-go/internal/textenc" +) + +// configDir is %WOConfigDir%: the directory of a custom configuration +// file, "." for one named ./webone.conf, else the system's. +func (c *Config) configDir() string { + if c.CustomConfig != "" { + return filepath.Dir(c.CustomConfig) + } + if strings.HasPrefix(c.ConfigFileName, "./") || strings.HasPrefix(c.ConfigFileName, `.\`) { + return "." + } + return defaultConfigDir() +} + +// LoadFile reads a configuration file (and what it includes). +func (c *Config) LoadFile(path string) error { + if _, ok := c.Vars.Get("WOConfigDir"); !ok { + c.Vars.Set("WOConfigDir", c.configDir()) + } + path = c.Expand(path, nil) + if !isFile(path) { + return fmt.Errorf("file not found: %s", path) + } + full, _ := filepath.Abs(path) + for _, f := range c.LoadedFiles { + if f == full { + return nil // already loaded: no include loops + } + } + c.LoadedFiles = append(c.LoadedFiles, full) + data, err := os.ReadFile(path) + if err != nil { + return err + } + short := strings.TrimPrefix(strings.TrimPrefix(path, "./"), `.\`) + c.LoadContent(data, short) + return nil +} + +// LoadContent adds a configuration file's lines. +func (c *Config) LoadContent(data []byte, name string) { + logx.Server(true, "Using configuration file %s.", name) + data = bytes.TrimPrefix(data, []byte{0xEF, 0xBB, 0xBF}) + sc := bufio.NewScanner(bytes.NewReader(data)) + sc.Buffer(make([]byte, 64*1024), 4*1024*1024) + n := 0 + for sc.Scan() { + n++ + loc := fmt.Sprintf("%s, line %d", name, n) + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, ";") { + continue + } + if strings.HasPrefix(line, "[Include:") { + if err := c.loadInclude(line); err != nil { + logx.Server(true, "Error in %s: %v Line ignored.", loc, err) + } + continue + } + c.rawEntries = append(c.rawEntries, [2]string{loc, line}) + } +} + +func (c *Config) loadInclude(line string) error { + if !strings.HasSuffix(line, "]") { + return fmt.Errorf("incorrect include section") + } + inc := line[len("[Include:") : len(line)-1] + c.Vars.Set("WOConfigDir", c.configDir()) + inc = c.Expand(inc, nil) + if strings.ContainsAny(inc, "*?") { + dir, mask := filepath.Split(inc) + if dir == "" { + dir = "." + } + return c.loadDirectory(dir, mask) + } + if isDir(inc) { + return c.loadDirectory(inc, "*") + } + return c.LoadFile(inc) +} + +func (c *Config) loadDirectory(dir, mask string) error { + if !isDir(dir) { + return fmt.Errorf("directory not found: %s", dir) + } + files, err := filepath.Glob(filepath.Join(dir, mask)) + if err != nil { + return err + } + sort.Strings(files) + for _, f := range files { + if !isFile(f) { + continue + } + if err := c.LoadFile(f); err != nil { + return fmt.Errorf("can't load included %s: %v", f, err) + } + } + return nil +} + +func (c *Config) warn(format string, args ...any) { logx.Server(true, "Warning: "+format, args...) } + +// Process turns the loaded lines into settings. Unknown options and +// sections are warnings; a bad regular expression or an option outside any +// section is an error. +func (c *Config) Process() error { + for _, e := range c.rawEntries { + loc, line := e[0], e[1] + if strings.HasPrefix(line, "[") { + s, err := ParseSection(line, loc) + if err != nil { + return fmt.Errorf("%s: %v", loc, err) + } + c.sections = append(c.sections, s) + continue + } + if len(c.sections) == 0 { + return fmt.Errorf("found option outside section (%s)", loc) + } + o, err := ParseOption(line, loc) + if err != nil { + c.warn("%v at %s. Line ignored.", err, loc) + continue + } + s := c.sections[len(c.sections)-1] + s.Options = append(s.Options, o) + } + + for _, s := range c.sections { + if err := c.processSection(s); err != nil { + return err + } + } + + if c.SslRootValidAfter.IsZero() || c.SslRootValidAfter.Year() <= 1 { + c.SslRootValidAfter = mustDate("1970-01-01T00:00:00Z") + } + if c.SslRootValidBefore.IsZero() || c.SslRootValidBefore.Year() <= 1 { + c.SslRootValidBefore = mustDate("2070-12-31T23:59:59Z") + } + c.SetProxyVars() + logx.Server(true, "Configuration load complete.") + for _, f := range c.LoadedFiles { + logx.Server(false, "Configuration file %s load complete.", f) + } + return nil +} + +// SetProxyVars sets %Proxy%, %ProxyHost% and %ProxyPort%. +func (c *Config) SetProxyVars() { + c.Vars.Set("Proxy", c.DefaultHostName+":"+strconv.Itoa(c.Port)) + c.Vars.Set("ProxyHost", c.DefaultHostName) + c.Vars.Set("ProxyPort", strconv.Itoa(c.Port)) +} + +func mustDate(s string) (t time.Time) { + t, _ = ParseDate(s) + return t +} + +func (c *Config) processSection(s *Section) error { + switch s.Kind { + case "Server": + if s.Mask != "" { + c.warn("Instead of condition-based setup use Edit Sets. Section ignored. (%s).", s.Location) + return nil + } + for _, o := range s.Options { + if err := c.serverOption(o); err != nil { + return err + } + } + case "ForceHttps": + for _, o := range s.Options { + c.ForceHttps = append(c.ForceHttps, o.Raw) + } + case "TextTypes": + for _, o := range s.Options { + c.TextTypes = append(c.TextTypes, o.Raw) + } + case "ForceUtf8": + for _, o := range s.Options { + c.ForceUtf8 = append(c.ForceUtf8, o.Raw) + } + case "Converters": + for _, o := range s.Options { + cv, err := ParseConverter(o.Raw) + if err != nil { + c.warn("%v at %s.", err, o.Location) + continue + } + c.Converters = append(c.Converters, cv) + } + case "Edit": + e, err := NewEditSet(s, c) + if err != nil { + return err + } + c.EditRules = append(c.EditRules, e) + case "Translit": + for _, o := range s.Options { + if o.HasKeyValue() { + c.TranslitTable = append(c.TranslitTable, [2]string{o.Key, o.Value}) + } + } + case "IpBanList": + for _, o := range s.Options { + c.IpBanList = append(c.IpBanList, o.Raw) + } + case "IpWhiteList": + for _, o := range s.Options { + c.IpWhiteList = append(c.IpWhiteList, o.Raw) + } + case "UrlBlackList": + for _, o := range s.Options { + c.UrlBlackList = append(c.UrlBlackList, o.Raw) + } + case "UrlWhiteList": + for _, o := range s.Options { + c.UrlWhiteList = append(c.UrlWhiteList, o.Raw) + } + case "HostNames": + for _, o := range s.Options { + c.HostNames = append(c.HostNames, c.Expand(o.Raw, nil)) + } + case "Authenticate": + for _, o := range s.Options { + if len(strings.Split(o.Raw, ":")) == 2 && !strings.Contains(o.Raw, " ") { + c.Authenticate = append(c.Authenticate, o.Raw) + continue + } + if !o.HasKeyValue() { + c.warn("Invalid authentication credentials at %s.", o.Location) + continue + } + switch o.Key { + case "AuthenticateMessage": + c.AuthenticateMessage = o.Value + case "AuthenticateRealm": + c.AuthenticateRealm = o.Value + case "OpenForLocalIPs": + c.OpenForLocalIPs = ToBool(o.Value) + default: + c.warn("Invalid authentication option at %s.", o.Location) + } + } + case "MimeTypes": + for _, o := range s.Options { + if o.HasKeyValue() { + c.MimeTypes[strings.ToLower(o.Key)] = strings.ToLower(o.Value) + } else { + c.warn("Invalid content type definition at %s.", o.Location) + } + } + case "PAC": + var b strings.Builder + for _, o := range s.Options { + b.WriteString(o.Raw + "\n") + } + c.PAC = b.String() + case "WebVideoOptions": + for _, o := range s.Options { + if o.HasKeyValue() { + c.WebVideoOptions[o.Key] = o.Value + } else { + c.warn("Incorrect online video convert option at %s.", o.Location) + } + } + case "WebVideoProfiles": + for _, o := range s.Options { + if o.HasKeyValue() && len(o.Values) == 2 { + c.WebVideoProfiles[o.Key] = o.Values + } else { + c.warn("Incorrect online video convert profile at %s.", o.Location) + } + } + case "SecureProxy": + for _, o := range s.Options { + c.secureOption(o) + } + case "NonHttpSslServers": + for _, o := range s.Options { + c.NonHttpSslServers = append(c.NonHttpSslServers, strings.ToLower(o.Raw)) + } + case "NonHttpConnectRedirect", "NonHttpSslDecrypt": + for _, o := range s.Options { + parts := strings.Split(o.Value, ":") + okTarget := o.HasKeyValue() && len(parts) == 2 && strings.TrimSpace(parts[0]) != "" + if okTarget { + _, err := strconv.Atoi(parts[1]) + okTarget = err == nil + } + if !okTarget { + c.warn("Incorrect non-HTTP connection redirect rule at %s.", o.Location) + continue + } + if s.Kind == "NonHttpConnectRedirect" { + c.NonHttpConnectRedirect[o.Key] = o.Value + } else { + c.NonHttpSslDecrypt[o.Key] = o.Value + } + } + case "ConnectPassThrough": + for _, o := range s.Options { + c.ConnectPassThrough = append(c.ConnectPassThrough, strings.ToLower(o.Raw)) + } + case "Http10Only": + for _, o := range s.Options { + if err := checkRegExp(o.Raw, o.Location); err != nil { + return err + } + c.Http10Only = append(c.Http10Only, o.Raw) + } + case "ActivexGallery", "ActiveXGallery": + c.activexSection(s) + case "Variables": + for _, o := range s.Options { + if o.HasKeyValue() { + c.Vars.Set(o.Key, o.Value) + } + } + case "FixableURL", "FixableType", "ContentPatch": + c.warn("%s section at %s is no longer supported.", s.Kind, s.Location) + logx.Server(true, "See https://github.com/atauenis/webone/wiki/Configuration-file about [%s].", s.Kind) + default: + c.warn("Unknown section %s in %s.", s.Kind, s.Location) + } + return nil +} + +func (c *Config) serverOption(o Option) error { + switch o.Key { + case "Port": + p := c.Expand(o.Value, nil) + n, err := strconv.Atoi(strings.TrimSpace(p)) + if err != nil { + return fmt.Errorf("Port: %q is not a TCP/IP port number", p) + } + if n < 0 || n > 65535 { + return fmt.Errorf("Port: %q is out of the range of valid values", p) + } + c.Port = n + case "Port2", "HttpPort", "HttpsPort", "FtpPort": + c.warn("Use of '%s' is deprecated, use 'Port' at %s.", o.Key, o.Location) + case "IP": + ip := net.ParseIP(strings.Trim(strings.TrimSpace(o.Value), "[]")) + if ip == nil { + return fmt.Errorf("IP: %q is not an IP address", o.Value) + } + c.IP = ip + case "OutputEncoding": + c.OutputEncoding = c.CodePage(c.Expand(o.Value, nil)) + case "Authenticate": + c.Authenticate = append(c.Authenticate, o.Value) + case "AuthenticateMessage": + c.AuthenticateMessage = o.Value + case "AuthenticateRealm": + c.AuthenticateRealm = o.Value + case "HideClientErrors": + c.HideClientErrors = ToBool(o.Value) + case "SearchInArchive": + c.SearchInArchive = ToBool(o.Value) + case "HideArchiveRedirect": + c.HideArchiveRedirect = ToBool(o.Value) + case "ShortenArchiveErrors": + c.ShortenArchiveErrors = ToBool(o.Value) + case "ArchiveUrlSuffix": + c.ArchiveUrlSuffix = o.Value + case "UserAgent": + c.UserAgent = o.Value + case "DefaultHostName": + sugg := NewVars() + for i, ip := range LocalIPs() { + sugg.Set("IP"+strconv.Itoa(i), ip.String()) + } + host, _ := os.Hostname() + sugg.Set("HostName", host) + c.DefaultHostName = c.Expand(o.Value, sugg) + valid := strings.EqualFold(host, c.DefaultHostName) + for _, ip := range LocalIPs() { + if ip.String() == c.DefaultHostName { + valid = true + } + } + if !valid { + if addrs, err := net.LookupHost(c.DefaultHostName); err == nil && len(addrs) > 0 { + valid = true + } + } + if !valid { + c.warn("DefaultHostName setting is not applicable to this computer.") + } + case "ValidateCertificates": + c.ValidateCertificates = ToBool(o.Value) + case "TemporaryDirectory": + c.TemporaryDirectory = c.Expand(o.Value, nil) + if !isDir(c.TemporaryDirectory) { + c.warn("Temporary directory %s does not exists.", o.Value) + } + case "LogFile", "AppendLogFile": + c.LogFile = strings.ReplaceAll(strings.ReplaceAll(o.Value, `\\`, `\`), "//", "/") + c.LogFileAppend = o.Key == "AppendLogFile" + case "DisplayStatusPage": + c.DisplayStatusPage = c.Expand(o.Value, nil) + case "ArchiveDateLimit": + n, _ := strconv.Atoi(strings.TrimSpace(o.Value)) + if n > 10000000 && n < 99990000 { + c.ArchiveDateLimit = n + } else { + c.warn("The ArchiveDateLimit must be in YYYYMMDD format.") + } + case "UpperProxy": + c.UpperProxy = c.Expand(o.Value, nil) + case "MultipleHttp2Connections": + c.MultipleHttp2Conns = ToBool(o.Value) + case "SecurityProtocols": + c.SecurityProtocols = nil + for _, n := range strings.Split(o.Value, ",") { + n = strings.ToLower(strings.TrimSpace(n)) + if v, ok := tlsVersionNames[n]; ok { + c.SecurityProtocols = append(c.SecurityProtocols, v) + } else if n != "" { + c.warn("SecurityProtocols: %s is not available, at %s.", n, o.Location) + } + } + case "RemoteHttpVersion": + if v, ok := ParseHTTPVersionRule(o.Value); ok { + c.RemoteHttpVersion = v + } else { + c.warn("Incorrect RemoteHttpVersion '%s'.", o.Value) + } + case "AllowHttpCompression": + c.AllowHttpCompression = ToBool(o.Value) + case "EnableWebFtp": + c.EnableWebFtp = ToBool(o.Value) + case "ShowFileIcons": + c.ShowFileIcons = ToBool(o.Value) + case "UseMsHttpApi": + if ToBool(o.Value) { + c.warn("UseMsHttpApi is a Windows HTTP.SYS option of the .NET WebOne; ignored.") + } + case "EnableManualConverting": + c.EnableManualConverting = ToBool(o.Value) + case "ContentDirectory": + dir := c.Expand(o.Value, nil) + alt := dir + if exe, err := os.Executable(); err == nil { + alt = filepath.Join(filepath.Dir(exe), dir) + } + switch { + case isDir(dir): + c.ContentDirectory = dir + case isDir(alt): + c.ContentDirectory = alt + case isDir("." + dir): + c.ContentDirectory = "." + dir + default: + c.warn("Incorrect ContentDirectory '%s'.", dir) + } + case "DontPreferHTTPS": + c.DontPreferHTTPS = ToBool(o.Value) + case "ConnectionTimeout": + n, err := strconv.Atoi(strings.TrimSpace(o.Value)) + if err != nil { + c.warn("Incorrect ConnectionTimeout '%s'.", o.Value) + } else { + c.ConnectionTimeout = n + } + case "CodepageCulture": + c.CodepageCulture = textenc.CultureFor(o.Value) + case "CodepageANSI": + c.CodepageANSI = textenc.Lookup(o.Value) + case "CodepageASCII": + c.CodepageASCII = textenc.Lookup(o.Value) + case "CodepageMac": + c.CodepageMac = textenc.Lookup(o.Value) + case "CodepageEBCDIC": + c.CodepageEBCDIC = textenc.Lookup(o.Value) + case "DnsServer": + c.DnsServer = c.Expand(strings.TrimSpace(o.Value), nil) + if c.DnsServer != "" { + if _, _, err := net.SplitHostPort(c.DnsServer); err != nil { + c.DnsServer = net.JoinHostPort(strings.Trim(c.DnsServer, "[]"), "53") + } + } + default: + c.warn("Unknown server option %s in %s.", o.Key, o.Location) + } + return nil +} + +var tlsVersionNames = map[string]uint16{ + "tls": tls.VersionTLS10, "tls10": tls.VersionTLS10, "tls11": tls.VersionTLS11, + "tls12": tls.VersionTLS12, "tls13": tls.VersionTLS13, +} + +func cleanPath(s string) string { + return strings.ReplaceAll(strings.ReplaceAll(s, `\\`, `\`), "//", "/") +} + +func (c *Config) secureOption(o Option) { + switch o.Key { + case "SslEnable": + c.SslEnable = ToBool(o.Value) + case "SslCertificate": + c.SslCertificate = cleanPath(c.Expand(o.Value, nil)) + case "SslPrivateKey": + c.SslPrivateKey = cleanPath(c.Expand(o.Value, nil)) + case "SslCaDirectory": + c.SslCaDirectory = cleanPath(c.Expand(o.Value, nil)) + case "SslTrustOwnCA": + c.SslTrustOwnCA = ToBool(o.Value) + case "SslProtocols": + c.SslProtocols = nil + c.SslProtocolsSet = true + for _, p := range strings.Split(o.Value, ",") { + p = strings.ToLower(strings.TrimSpace(p)) + switch p { + case "", "none", "default": + c.SslProtocolsSet = p == "" && c.SslProtocolsSet + case "ssl2", "ssl3": + c.warn("%s is not available in this version (Go's TLS has no SSL 2.0/3.0), at %s.", p, o.Location) + default: + if v, ok := tlsVersionNames[p]; ok { + c.SslProtocols = append(c.SslProtocols, v) + } else { + c.warn("incorrect SSL/TLS protocol set '%s', at %s.", o.Value, o.Location) + } + } + } + if len(c.SslProtocols) == 0 { + c.SslProtocolsSet = false + } + case "SslCipherSuites": + names := map[string]uint16{} + for _, cs := range tls.CipherSuites() { + names[cs.Name] = cs.ID + } + for _, cs := range tls.InsecureCipherSuites() { + names[cs.Name] = cs.ID + } + // .NET's names for the TLS 1.3 suites and others are the IANA ones + for _, n := range strings.Split(o.Value, ",") { + n = strings.TrimSpace(n) + if id, ok := names[n]; ok { + c.SslCipherSuites = append(c.SslCipherSuites, id) + } else { + c.warn("incorrect cipher suite '%s', at %s.", n, o.Location) + } + } + case "SslHashAlgorithm": + c.SslHashAlgorithmSet = true + switch strings.ToUpper(strings.TrimSpace(o.Value)) { + case "MD5", "1.2.840.113549.2.5": + c.SslHashAlgorithm = "MD5" + case "SHA", "SHA1", "1.3.14.3.2.26": + c.SslHashAlgorithm = "SHA1" + case "SHA2", "SHA256", "2.16.840.1.101.3.4.2.1": + c.SslHashAlgorithm = "SHA256" + case "SHA3", "SHA384", "2.16.840.1.101.3.4.2.2": + c.SslHashAlgorithm = "SHA384" + case "SHA5", "SHA512", "2.16.840.1.101.3.4.2.3": + c.SslHashAlgorithm = "SHA512" + default: + c.warn("'%s' is not a valid hash algorithm name, at %s.", o.Value, o.Location) + } + case "SslRootSubject": + if !strings.Contains(o.Value, "CN=") { + c.warn("'%s' is not a valid X.500 distinguished subject name, at %s.", o.Value, o.Location) + } else { + c.SslRootSubject = c.Expand(o.Value, nil) + } + case "SslRootValidAfter", "SslRootValidBefore": + t, err := ParseDate(o.Value) + if err != nil { + c.warn("%v, at %s.", err, o.Location) + return + } + if o.Key == "SslRootValidAfter" { + c.SslRootValidAfter = t + } else { + c.SslRootValidBefore = t + } + case "SslCertVaildBeforeNow", "SslCertValidBeforeNow": + n, err := strconv.Atoi(strings.TrimSpace(o.Value)) + if err == nil && n <= 0 { + c.SslCertValidBeforeNow = n + } else { + c.warn("SslCertVaildBeforeNow must be a negative whole number of days, at %s.", o.Location) + } + case "SslCertVaildAfterNow", "SslCertValidAfterNow": + n, err := strconv.Atoi(strings.TrimSpace(o.Value)) + if err == nil && n >= 1 { + c.SslCertValidAfterNow = n + } else { + c.warn("SslCertVaildAfterNow must be a positive whole number of days, at %s.", o.Location) + } + case "SslSiteCerts": + c.SslSiteCerts = cleanPath(c.Expand(o.Value, nil)) + case "SslSiteCertGenerator": + c.SslSiteCertGenerator = cleanPath(c.Expand(o.Value, nil)) + case "AllowNonHttpsCONNECT": + c.AllowNonHttpsCONNECT = ToBool(o.Value) + } +} + +func (c *Config) activexSection(s *Section) { + for _, o := range s.Options { + if o.HasKeyValue() { + if strings.EqualFold(o.Key, "ActiveXGalleryEmulation") { + c.ActivexGalleryEmul = ToBool(o.Value) + continue + } + clsid := strings.ToUpper(strings.NewReplacer("{", "", "}", "").Replace(o.Key)) + lower := strings.ToLower(clsid) + if !rx.Match("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", lower) && + !rx.Match(`[a-z0-9.\-_]*/[a-z0-9.\-_]`, lower) { + c.warn("Incorrect Internet Component GUID or type at %s.", o.Location) + continue + } + if strings.HasSuffix(o.Key, ",latest") { + ver := strings.ReplaceAll(o.Value, ",", ".") + if !rx.Match(`^\d+(\.\d+){1,3}$`, ver) { + c.warn("Incorrect Internet Component latest version at %s.", o.Location) + continue + } + c.ActivexGalleryCLSIDs[clsid] = ver + continue + } + c.ActivexGalleryCLSIDs[clsid] = o.Value + continue + } + if rx.Match("^http://", o.Raw) { + c.ActivexGalleryUrls = append(c.ActivexGalleryUrls, o.Raw) + } else { + c.warn("Incorrect Microsoft codebase search engine option at %s.", o.Location) + } + } +} + +// LocalIPs is this machine's addresses, and 10.0.2.2 (the host as QEMU, +// SheepShaver and Basilisk II's SLIRP networking sees it). +func LocalIPs() []net.IP { + var ips []net.IP + if addrs, err := net.InterfaceAddrs(); err == nil { + for _, a := range addrs { + if n, ok := a.(*net.IPNet); ok { + ips = append(ips, n.IP) + } + } + } + ips = append(ips, net.ParseIP("10.0.2.2")) + return ips +} diff --git a/internal/config/vars.go b/internal/config/vars.go new file mode 100644 index 0000000..42e7102 --- /dev/null +++ b/internal/config/vars.go @@ -0,0 +1,204 @@ +package config + +import ( + "os" + "path/filepath" + "runtime" + "sort" + "strings" +) + +// Vars is an ordered set of named strings, used as %Name% or $Name in +// configuration values, edit sets and internal pages. +type Vars struct { + keys []string + m map[string]string +} + +// NewVars is an empty set. +func NewVars() *Vars { return &Vars{m: map[string]string{}} } + +// Set sets (or replaces) a variable. +func (v *Vars) Set(k, val string) { + if v.m == nil { + v.m = map[string]string{} + } + if _, ok := v.m[k]; !ok { + v.keys = append(v.keys, k) + } + v.m[k] = val +} + +// TryAdd sets a variable that is not set yet. +func (v *Vars) TryAdd(k, val string) { + if _, ok := v.m[k]; ok { + return + } + v.Set(k, val) +} + +// Get is a variable's value. +func (v *Vars) Get(k string) (string, bool) { + if v == nil { + return "", false + } + s, ok := v.m[k] + return s, ok +} + +// Value is a variable's value, or "". +func (v *Vars) Value(k string) string { s, _ := v.Get(k); return s } + +// Keys in order of first setting. +func (v *Vars) Keys() []string { + if v == nil { + return nil + } + return v.keys +} + +// Clone copies the set. +func (v *Vars) Clone() *Vars { + c := NewVars() + if v != nil { + for _, k := range v.keys { + c.Set(k, v.m[k]) + } + } + return c +} + +// FromMap is a set of the map's entries (sorted by name). +func FromMap(m map[string]string) *Vars { + v := NewVars() + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + v.Set(k, m[k]) + } + return v +} + +// DefaultLogDir is where a log file goes by default (%SYSLOGDIR%). +func DefaultLogDir() string { + switch runtime.GOOS { + case "windows": + if d, err := os.UserConfigDir(); err == nil { + return d + } + case "darwin": + if h, err := os.UserHomeDir(); err == nil { + return filepath.Join(h, "Library", "Logs") + } + default: + return "/var/log" + } + d, _ := os.Getwd() + return d +} + +// tempDir is %TEMP% / $TMPDIR, with a trailing separator as .NET's +// Path.GetTempPath() has. +func tempDir() string { + d := os.TempDir() + if !strings.HasSuffix(d, string(os.PathSeparator)) { + d += string(os.PathSeparator) + } + return d +} + +// replaceFold replaces old with repl, ignoring case. +func replaceFold(s, old, repl string) string { + if old == "" { + return s + } + lo, lold := strings.ToLower(s), strings.ToLower(old) + if !strings.Contains(lo, lold) || len(lo) != len(s) { + if len(lo) != len(s) { + // case folding changed byte lengths; fall back to exact matching + return strings.ReplaceAll(s, old, repl) + } + return s + } + var b strings.Builder + i := 0 + for { + j := strings.Index(lo[i:], lold) + if j < 0 { + b.WriteString(s[i:]) + break + } + b.WriteString(s[i : i+j]) + b.WriteString(repl) + i += j + len(old) + } + return b.String() +} + +// Expand replaces %Name% and $Name with the values of global variables, +// then of extra ones (globals win), then of environment variables. %TEMP%, +// $TMPDIR, %SYSLOGDIR% and $SYSLOGDIR are always known, and "~/" is the +// home directory. +// +// Ported from Program.ExpandMaskedVariables. Unlike the original, $Name is +// replaced longest name first, so $UrlDomain is not taken for $Url. +func Expand(s string, global, extra *Vars) string { + if !strings.ContainsAny(s, "%$~") { + return s + } + tmp, logdir := tempDir(), DefaultLogDir() + s = strings.ReplaceAll(s, "$TMPDIR", tmp) + s = replaceFold(s, "%TEMP%", tmp) + s = strings.ReplaceAll(s, "$SYSLOGDIR", logdir) + s = replaceFold(s, "%SYSLOGDIR%", logdir) + + all := global.Clone() + if extra != nil { + for _, k := range extra.keys { + all.TryAdd(k, extra.m[k]) + } + } + s = replaceVars(s, all, false) + + env := NewVars() + for _, kv := range os.Environ() { + if i := strings.IndexByte(kv, '='); i > 0 { + env.Set(kv[:i], kv[i+1:]) + } + } + s = replaceVars(s, env, true) + if strings.Contains(s, "~/") { + if h, err := os.UserHomeDir(); err == nil { + s = strings.ReplaceAll(s, "~/", h+"/") + } + } + return s +} + +func replaceVars(s string, v *Vars, foldPercent bool) string { + if !strings.ContainsAny(s, "%$") { + return s + } + for _, k := range v.keys { + if foldPercent { + s = replaceFold(s, "%"+k+"%", v.m[k]) + } else { + s = strings.ReplaceAll(s, "%"+k+"%", v.m[k]) + } + } + if !strings.Contains(s, "$") { + return s + } + keys := append([]string(nil), v.keys...) + sort.SliceStable(keys, func(i, j int) bool { return len(keys[i]) > len(keys[j]) }) + for _, k := range keys { + if k == "" { + continue + } + s = strings.ReplaceAll(s, "$"+k, v.m[k]) + } + return s +} diff --git a/internal/logx/log.go b/internal/logx/log.go new file mode 100644 index 0000000..c298b05 --- /dev/null +++ b/internal/logx/log.go @@ -0,0 +1,137 @@ +// Package logx is WebOne's event log: lines go to the console (unless the +// proxy runs as a daemon) and to the log file, each request's lines +// stamped with the time the request began and the time since. +// +// Ported from WebOne's Log.cs. +package logx + +import ( + "fmt" + "io" + "os" + "runtime" + "strings" + "sync" + "time" +) + +const stampLayout = "02.01.2006 15:04:05.000" + +var ( + mu sync.Mutex + file io.WriteCloser + console io.Writer = os.Stdout + // Daemon hides console output (all goes to the log file only). + Daemon bool +) + +// SetConsole sends console output to w (tests). +func SetConsole(w io.Writer) { + mu.Lock() + console = w + mu.Unlock() +} + +// OpenLogFile starts writing the log to path (appending when append is set). +// An empty path stops file logging. +func OpenLogFile(path string, appendTo bool, version string, args []string) { + mu.Lock() + defer mu.Unlock() + if file != nil { + file.Close() + file = nil + } + if path == "" { + fmt.Fprintln(console, "Not using log file.") + return + } + flags := os.O_CREATE | os.O_WRONLY + if appendTo { + flags |= os.O_APPEND + } else { + flags |= os.O_TRUNC + } + f, err := os.OpenFile(path, flags, 0o644) + if err != nil { + fmt.Fprintf(console, "Cannot use log file %s: %v.\n", path, err) + return + } + file = f + fmt.Fprintf(f, "%s\tWebOne %s%s (%s %s, %s) log started.\n", + time.Now().Format("02.01.2006 15:04:05"), version, " "+strings.Join(args, " "), + runtime.GOOS, runtime.GOARCH, runtime.Version()) + fmt.Fprintf(console, "Using event log file %s.\n", path) +} + +// Enabled: a log file is open. +func Enabled() bool { + mu.Lock() + defer mu.Unlock() + return file != nil +} + +// Close closes the log file. +func Close() { + mu.Lock() + defer mu.Unlock() + if file != nil { + file.Close() + file = nil + } +} + +func emit(msg string, display, write bool, displayText string) { + mu.Lock() + defer mu.Unlock() + if display && !Daemon { + if displayText == "" { + fmt.Fprintln(console, msg) + } else { + fmt.Fprintln(console, displayText) + } + } + if write && file != nil { + fmt.Fprintln(file, msg) + } +} + +// Writer logs the lines of one request (or of the server itself). +type Writer struct { + Begin time.Time + first bool +} + +// New is a Writer whose time starts now. +func New() *Writer { return &Writer{Begin: time.Now(), first: true} } + +// Std is the server's own log writer. +var Std = New() + +func (w *Writer) since() string { + ticks := time.Since(w.Begin).Nanoseconds() / 100 + return fmt.Sprintf("%s+%d", w.Begin.Format(stampLayout), ticks/2) +} + +// Printf logs a request line, displayed and timestamped. +func (w *Writer) Printf(format string, args ...any) { w.Log(true, true, format, args...) } + +// Log writes a line. display: also to the console. stamped: a request line +// (">GET http://...") rather than a server message ("Starting ..."). +func (w *Writer) Log(display, stamped bool, format string, args ...any) { + msg := fmt.Sprintf(format, args...) + begin := w.Begin.Format(stampLayout) + if !stamped { + emit(begin+"+0\t"+msg, display, true, msg) + return + } + if w.first { + w.first = false + emit(begin+"+0\t\t"+msg, display, false, "") + emit(begin+"+0\t"+msg, false, true, "") + return + } + emit(w.since()+"\t"+msg, display, true, "") +} + +// Server logs a server message (not a request line). +func Server(display bool, format string, args ...any) { Std.Log(display, false, format, args...) } diff --git a/internal/proxy/activex.go b/internal/proxy/activex.go new file mode 100644 index 0000000..2777ea4 --- /dev/null +++ b/internal/proxy/activex.go @@ -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 +} diff --git a/internal/proxy/connect.go b/internal/proxy/connect.go new file mode 100644 index 0000000..380140a --- /dev/null +++ b/internal/proxy/connect.go @@ -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
CONNECT example.com:443 HTTP/1.1
") + 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("

Incoming HTTPS connections support is disabled on this server.

" + t.s.infoString() + "" + 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("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("= 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 +} diff --git a/internal/proxy/convert.go b/internal/proxy/convert.go new file mode 100644 index 0000000..b145aa3 --- /dev/null +++ b/internal/proxy/convert.go @@ -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, "Converter ""+name+"" is unknown.
"+ + "

This converter is not well listed in configuration file.

"+ + `

See WebOne wiki for help on this.

`) + 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, "

Converter error: "+err.Error()+"

"+ + "Source URL: "+t.urlString()+"
Utility: "+name+"
"+ + "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, "

Converter error: "+err.Error()+"

") + return + } + } + t.sendInfoPage("WebOne: ImageMagick error", "Error", + "

ImageMagick's convert utility is not properly registered in [Converters] section of proxy configuration.

"+ + "

Make sure that the line is present in [Converters] section of configuration: convert %SRC% %ARG1% %DESTEXT%:- %ARG2%

", 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.
Proxy administrator can enable it via [Server] section, EnableManualConverting 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, "Here you can summon ImageMagick to convert a picture file.
"+ + "

Usage: /!convert/?url=https://example.com/filename.ext&dest=gif&type=image/gif
"+ + "or: /!convert/?src=filename.ext&dest=gif&type=image/gif

"+ + `

See WebOne wiki for help on this.

`) + return + } + cv, ok := t.s.converter(name) + if !ok { + t.sendError(503, "Converter ""+name+"" is unknown.
"+ + "

This converter is not listed in configuration file.

"+ + `

See WebOne wiki for help on this.

`) + 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, "

Converter cannot download the source: "+err.Error()+"

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, "

Converter cannot open the source: "+err.Error()+"

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, "

Converter error: "+err.Error()+"

Source URL: "+srcURL+"
Utility: "+cv.Executable) + return + } + t.sendStream(out, destMime, n, 200) +} diff --git a/internal/proxy/errors.go b/internal/proxy/errors.go new file mode 100644 index 0000000..a0e739a --- /dev/null +++ b/internal/proxy/errors.go @@ -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 := `
  • Try to use an archived copy of the web site.
  • ` + check := "
  • If you are unable to load any pages, check your proxy server's network connection.
  • " + + "
  • If your proxy server or network is protected by a firewall, make sure that WebOne is permitted to access the Web.
  • " + + var bad *badURLError + if errors.As(err, &bad) { + t.dump("!Invalid URL") + t.sendError(400, "The URL "+bad.u+" 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 := "

    Cannot decode HTTP data.

    " + + "
      Remote server may use unsupported HTTP compression algorithm." + + "
    • Try to set AllowHttpCompression=false option in configuration file to skip HTTP decompression.
    • " + + "
    • If you are unable to load any pages, check your proxy server's network connection.
    " + t.sendInfoPage("WebOne: Decompression failed", "Invalid data has been recieved", msg+"
    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 := "

    " + m + "

    " + + "
    • The site could be temporarily unavailable or too busy. Try again in a few moments.
    • " + archived + + "
    • Internet Archive sometimes became busy. Be patient, wait a some time.
    • " + check + "
    " + t.sendInfoPage("WebOne: Operation timeout", "The connection has timed out", msg+"
    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 = "

    " + text + "

    " + + "
    • Check the address for typing errors such as ww.example.com instead of www.example.com.
    • " + + archived + check + "
    " + 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 = "

    " + text + "

    " + + "
    • The site could be temporarily unavailable or too busy. Try again in a few moments.
    • " + archived + check + "
    " + default: + header = "The connection can't be stablished" + message = "

    " + text + "

    " + + "
    • The site could be temporarily unavailable or too busy. Try again in a few moments.
    • " + archived + check + + "

    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 = "

    " + polerr + "

    " + + "
    • The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
    • " + + "
    • Make sure that the OS on the proxy server have all updates installed.
    • " + + "
    • Check date and time on the proxy server.
    • " + + "
    • Verify that the proxy server operating system have proper support for TLS/SSL version and chiphers used on the site.
    • " + + archived + + "
    • To disable this security check, set ValidateCertificates=no in proxy configuration file. But this will make the proxy less secure, do this at your own risk.
    " + } else { + title = fmt.Sprintf("%T", errors.Unwrap(err)) + if title == "" { + title = "connection error" + } + message = "There are problems, that are preventing from displaying the page:
    " + strings.ReplaceAll(err.Error(), "\n", "
    ") + } + t.sendInfoPage("WebOne: "+title, header, message+"
    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", "
    ") + 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", + "The requested server or page is not found and a Web Archive error occured.
    "+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", "
    ") + 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", + "The requested page is found only at Web Archive, but cannot be delivered from it.
    "+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, "Good news: 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() +} diff --git a/internal/proxy/ftp.go b/internal/proxy/ftp.go new file mode 100644 index 0000000..f010d80 --- /dev/null +++ b/internal/proxy/ftp.go @@ -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+(|\d+)\s+(.+)$` +) + +func parseFtpLine(line string) (ftpEntry, bool) { + if g := rx.FindGroups(ftpDosPattern, line); g != nil { + e := ftpEntry{Date: g[1], Directory: g[2] == "", 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 = "\n" + 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 = "An error occured in FTP Client.

    " + strings.ReplaceAll(fmt.Sprint(r), "\n", "
    ") + "

    " + + "

    Navigation: Go back. " + + "Reconnect. Directory listing: " + + "root, " + + "current.

    " + } + }() + if !t.cfg.EnableWebFtp { + t.log.Printf("\n" + + "
    \n" + + "


    \n" + + "

    \n" + + "


    \n" + + "

    \n" + + "

    \n" + + "
    " + 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 = "

    Empty connection data

    \n

    You need to specify the remote server first.

    Go back.

    " + 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 = "

    Malformed Universal Resource Identificator

    \n" + + "

    URIs (locations) are accepted only in the following format:\n" + + "

    ftp://ftp.microsoft.com/MISC1/DESKAPPS/DOSWORD/KB/Q81/4/46.TXT
    \n" + + "Also the Identificator can contain FTP user name, password and port.

    Go back.

    " + 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 = "

    Connecting to the server

    \n
    " + c.ftpLog + "
    \n

    Okay, click here.

    " + 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 = "

    The client could not connect to the server.

    \n
    " + c.ftpLog + "
    \n" + + "

    Return to connection page and try again.

    " + 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 := "

    Return to start page and try to connect again.

    " + p.Title = c.Server + " - FTP" + p.Header = "File Transfer: " + c.Server + p.Content = "" + if !c.ok { + p.Content = "

    Connection lost

    The FTP connection to the server is closed.

    Go to start and try again.

    " + return p + } + icons := t.ftpIconsOn() + img := func(src string) string { + return " " + } + 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 += "

    Cannot change working directory: " + r.String() + "

    " + } + } + r := c.command("PWD") + if r.Code != 257 { + p.Content += "

    "Print Working Directory" command has returned an unexpected result: " + r.String() + "

    " + p.Content += "

    Reload this page or return to start page and try to connect again.

    " + return p + } + if g := rx.FindGroups(`"(.*)"`, r.Result); g != nil { + p.Content += "

    Server root" + c.Workdir = "" + for _, dir := range strings.Split(g[1], "/") { + c.Workdir += dir + "/" + if dir != "" { + p.Content += " » " + dir + "" + } + } + p.Content += "

    \n" + } else { + p.Content += "

    " + r.Result + "

    \n" + c.Workdir = "./" + } + c.command("OPTS UTF8 ON") + if r = c.command("TYPE A"); r.Code != 200 { + p.Content += "

    Cannot set ASCII mode: " + r.String() + "

    " + again + return p + } + if r = c.command("PASV"); r.Code != 227 { + p.Content += "

    Cannot prepare data connection: " + r.String() + "

    " + again + return p + } + data, err := c.pasvData(d, r.Result) + if err != nil { + p.Content += "

    Cannot establish data connection: " + r.String() + "

    " + again + return p + } + if r = c.command("LIST"); r.Code != 150 && r.Code != 125 { + c.closeData() + p.Content += "

    Directory listing is inaccessible: " + r.String() + "

    " + 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("\n") + if c.Workdir != "//" { + b.WriteString("\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("\n") + } + b.WriteString("\n
    ") + if icons { + b.WriteString(img("/filetypes/_dir-up.gif")) + } + b.WriteString("[..]") + b.WriteString("
    ") + switch { + case e.Directory && !e.Link: + b.WriteString(icon + "[" + e.Name + "]") + case e.Link: + if icons { + b.WriteString(img("/filetypes/_link.gif")) + } + if e.Directory { + b.WriteString("[" + e.Name + "]") + } else { + b.WriteString("" + e.Name + "") + } + default: + b.WriteString(icon + "" + e.Name + "") + } + b.WriteString("" + strconv.FormatInt(e.Size, 10) + "" + e.Date + "

    \n\n") + b.WriteString("\n
    ") + 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("Permanent link ") + b.WriteString("(direct).Disconnect.
    ") + p.Content += b.String() + return p + + case "retr": + name := args.Get("name") + if name == "" { + p.Content += "

    Nothing to download

    Click here to see directory listing.

    " + return p + } + r := c.command("TYPE I") + if r.Code != 200 { + p.Content += "

    Cannot set BINARY mode: " + r.String() + "

    " + again + return p + } + if r = c.command("PASV"); r.Code != 227 { + p.Content += "

    Cannot prepare data connection: " + r.String() + "

    " + again + return p + } + data, err := c.pasvData(d, r.Result) + if err != nil { + p.Content += "

    Cannot establish data connection: " + r.String() + "

    " + again + return p + } + if r = c.command("RETR " + name); r.Code != 150 && r.Code != 125 { + c.closeData() + p.Content += "

    Cannot download the file: " + r.String() + "

    " + 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 = "

    Disconnected from the server

    \n

    The file transfer session has been ended.

    \n

    Return to connection page.

    " + return p + } + p.Content = "

    No or unknown task

    The specified task argument is not recognized by WebOne.

    " + + "

    Click here to see directory listing.

    " + 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 +} diff --git a/internal/proxy/header.go b/internal/proxy/header.go new file mode 100644 index 0000000..18c8755 --- /dev/null +++ b/internal/proxy/header.go @@ -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 +} diff --git a/internal/proxy/kind.go b/internal/proxy/kind.go new file mode 100644 index 0000000..9735945 --- /dev/null +++ b/internal/proxy/kind.go @@ -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 +} diff --git a/internal/proxy/pages.go b/internal/proxy/pages.go new file mode 100644 index 0000000..448b0ae --- /dev/null +++ b/internal/proxy/pages.go @@ -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("` + } + enc := t.outEnc() + head += `` + html := "" + head + "

    " + strconv.Itoa(code) + " " + StatusName(code) + "

    " + text + "" + 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("WebOne: redirect by proxy` + if message != "" { + html += "

    " + message + "

    " + } + html += `

    Please navigate your browser to ` + target + ".

    " + t.s.infoString() + "" + 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("\n" + } + h1 := "" + if p.Header != "" { + h1 = "

    " + p.Header + "

    \n" + } + footer := "" + if p.ShowFooter { + footer = t.s.infoString() + "\n" + } + html := "\n" + title + `` + "\n" + p.HTMLHeaders + "\n" + h1 + "\n" + p.Content + "\n" + footer + "\n" + 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(""+name+".
    "+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.
    ImageMagick logo
    A wizard should appear nearby.`) + } else { + t.sendError(200, `ImageMagick test.
    ImageMagick logo
    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, ""+strconv.Itoa(n)+" temporary files have been deleted in "+t.cfg.TemporaryDirectory+".") + case "/!ftp": + t.sendInfo(t.ftpPage()) + case "/!redirect": + t.sendInfo(t.redirectorPage(query)) + case "/!ca", "/weboneca.crt", "/weboneca.cer", "/weboneca.der": + t.log.Printf("http:// URL protocol to access any https:// 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("http:// URL protocol to access any https:// 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("If you think we brought you here on purpose by posting a wrong link, send us that link via GitHub.

    " + + "

    And if you really want to find something on the Internet, specify IP of the WebOne server in your browser's proxy server settings.

    " + + "
    " + page + "
    " + t.sendInfoPage("WebOne: 404", "404 - there's no page.", msg, 404) + } +} + +func (t *transit) sendCodepages() { + var b strings.Builder + b.WriteString("

    The following code pages are available:
    \n\n") + b.WriteString("\n") + listed := false + for _, e := range textenc.All() { + fmt.Fprintf(&b, "\n") + } + b.WriteString("
    Name#Description
    AsIs0Keep original encoding (code page)
    %s%d%s", e.Name, e.CodePage, e.Display) + if t.cfg.OutputEncoding != nil && e.CodePage == t.cfg.OutputEncoding.CodePage { + b.WriteString(" (Current)") + listed = true + } + b.WriteString("

    Use any of these names or numbers.

    \n") + name := func(cp string) string { + if e := t.cfg.CodePage(cp); e != nil { + return e.Name + } + return "?" + } + b.WriteString("

    Code pages for current server's locale:\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "
    Windows "ANSI"" + name("Win") + "
    DOS "OEM"" + name("DOS") + "
    MacOS classic" + name("Mac") + "
    ISO" + name("ISO") + "
    EBCDIC" + name("EBCDIC") + "
    Clients without UTF-8 support will got content in these code pages.

    \n") + if t.cfg.OutputEncoding == nil { + b.WriteString("
    Current output encoding: same as source.\n") + } else if !listed { + fmt.Fprintf(&b, "
    Current output encoding: %s "%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", "

    The status page is disabled by server administrator.

    ", 200) + return + case "short": + fmt.Fprintf(&h, "

    This is %s.
    ", t.serverName()) + fmt.Fprintf(&h, "Connections open: %d (%d active).
    ", opened, busy) + fmt.Fprintf(&h, "Used memory: %d MB.
    ", usedMemoryMB()) + h.WriteString(`About: https://github.com/atauenis/webone/ (Go port: https://github.com/D-Modem/webone-go)

    `) + fmt.Fprintf(&h, "

    Client IP: %s.

    ", t.req.Remote) + h.WriteString("

    May be useful:

    ") + case "full": + host, _ := os.Hostname() + fmt.Fprintf(&h, "This is %s:%d.
    ", host, t.cfg.Port) + fmt.Fprintf(&h, "Used memory: %d MB.
    ", usedMemoryMB()) + fmt.Fprintf(&h, "Connections open: %d (%d active).
    ", opened, busy) + h.WriteString("

    Aliases:

      ") + evident := false + for _, ip := range config.LocalIPs() { + a := ip.String() + if a == t.cfg.DefaultHostName { + evident = true + a = "" + a + "" + } + fmt.Fprintf(&h, "
    • %s:%d
    • ", a, t.cfg.Port) + } + if !evident { + fmt.Fprintf(&h, "
    • %s:%d
    • ", t.cfg.DefaultHostName, t.cfg.Port) + } + h.WriteString("
    ") + fmt.Fprintf(&h, "

    Client IP: %s.

    ", t.req.Remote) + h.WriteString("

    Internal URLs:

    ") + default: + if t.sendInternalContent(t.cfg.DisplayStatusPage, "", 200) { + return + } + h.WriteString("

    It works!

    ") + } + h.WriteString("

    Headers sent by browser

      ") + fmt.Fprintf(&h, "
    • %s %s HTTP/%s
    • ", t.req.Method, t.req.RawURL, t.req.ProtoVersion()) + t.req.Header.Each(func(k, v string) { fmt.Fprintf(&h, "
    • %s: %s
    • ", k, v) }) + h.WriteString("
    ") + t.sendInfoPage("WebOne status page", "", h.String(), 200) +} + +// osDescription is %WOSystem%. +func osDescription() string { + return runtime.GOOS + " " + runtime.GOARCH + " (" + runtime.Version() + ")" +} diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go new file mode 100644 index 0000000..9f1acf4 --- /dev/null +++ b/internal/proxy/proxy_test.go @@ -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, "Hello, modern web! Привет") + })) + 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, `secure link`, 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 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") + } +} diff --git a/internal/proxy/request.go b/internal/proxy/request.go new file mode 100644 index 0000000..388c4da --- /dev/null +++ b/internal/proxy/request.go @@ -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("= 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("= 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 +} diff --git a/internal/proxy/response.go b/internal/proxy/response.go new file mode 100644 index 0000000..2ac7337 --- /dev/null +++ b/internal/proxy/response.go @@ -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 } diff --git a/internal/proxy/server.go b/internal/proxy/server.go new file mode 100644 index 0000000..a727cda --- /dev/null +++ b/internal/proxy/server.go @@ -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("WebOne Proxy Server " + s.cfg.Vars.Value("WOVer") + "
    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()) +} diff --git a/internal/proxy/transit.go b/internal/proxy/transit.go new file mode 100644 index 0000000..81da97e --- /dev/null +++ b/internal/proxy/transit.go @@ -0,0 +1,1047 @@ +package proxy + +import ( + "bytes" + "encoding/base64" + "fmt" + "io" + "net/url" + "os" + "strconv" + "strings" + + "github.com/D-Modem/webone-go/internal/config" + "github.com/D-Modem/webone-go/internal/logx" + "github.com/D-Modem/webone-go/internal/rx" + "github.com/D-Modem/webone-go/internal/textenc" +) + +const noContentType = "webone/unknown-content-type" + +// transit is one request's trip through the proxy (HttpTransit.cs). +type transit struct { + s *Server + cfg *config.Config + req *Request + resp *Response + log *logx.Writer + + vars *config.Vars + url *url.URL // RequestURL + editSets []*config.EditSet + stop bool // a converter has answered already + op *operation + + requestHTTPVersion string + respMajor int + respMinor int + responseCode int + responseBody string + transitStream io.ReadCloser + transitLength int64 + contentType string + sourceEncoding *textenc.Encoding + outputEncoding *textenc.Encoding + translit bool + dumpFile string + localIP string + + // hijacked: the connection was taken over (a CONNECT tunnel) and is + // not to be closed or reused by the caller + hijacked bool +} + +func newTransit(s *Server, req *Request, resp *Response, log *logx.Writer) *transit { + return &transit{ + s: s, cfg: s.cfg, req: req, resp: resp, log: log, + vars: config.NewVars(), + requestHTTPVersion: s.cfg.RemoteHttpVersion, + respMajor: 1, respMinor: 1, + responseCode: 502, + responseBody: ":(", + contentType: noContentType, + sourceEncoding: textenc.UTF8, + outputEncoding: s.cfg.OutputEncoding, + transitLength: -1, + } +} + +func (t *transit) urlString() string { return absURL(t.url) } + +// clientID is "user, address" (or the address) for the log. +func (t *transit) clientID() string { + id := t.req.Remote.IP.String() + if pa := t.req.Header.Get("Proxy-Authorization"); strings.HasPrefix(pa, "Basic ") { + if b, err := base64.StdEncoding.DecodeString(pa[6:]); err == nil { + if user, _, ok := strings.Cut(string(b), ":"); ok { + id = user + ", " + id + } + } + } + return id +} + +func (t *transit) serverName() string { return t.s.serverName(t.localIP) } + +func (t *transit) processURIMasks(masked string) string { + return t.s.processURIMasks(masked, t.urlString(), false, t.vars) +} + +// process handles the request (HttpTransit.ProcessTransit). +func (t *transit) process() { + defer func() { + if r := recover(); r != nil { + t.log.Printf(" A error has been catched: %v\n\t Please report to author.", r) + t.sendError(500, fmt.Sprintf("An error occured: %v", r)) + } + }() + t.respMajor, t.respMinor = t.req.Major, t.req.Minor + req := t.req + remote := req.Remote.String() + + // IP black and white lists + if containsAny(remote, t.cfg.IpBanList) { + t.log.Printf(" Banned client.") + t.resp.KeepAlive = false + t.resp.Close(Version) + return + } + if len(t.cfg.IpWhiteList) > 0 && !containsAny(remote, t.cfg.IpWhiteList) { + if t.sendInternalContent("Err-IpNotWhitelisted.htm", "?IP="+req.Remote.IP.String(), 200) { + return + } + t.sendError(403, "You are not in the list of allowed clients. Contact proxy server's administrator to add your IP address in it.") + t.log.Printf(" Non-whitelisted client.") + return + } + + // proxy login + if len(t.cfg.Authenticate) > 0 && !req.Secure { + path := "/" + if req.URL != nil { + path = pathAndQuery(req.URL) + } + switch path { + case "/!pac/", "/auto/", "/auto", "/auto.pac", "/wpad.dat", "/wpad.da": + // the PAC script is always open + default: + if t.cfg.OpenForLocalIPs && isLanIP(req.Remote.IP) { + t.log.Printf(" Bypassed authorization of local client.") + break + } + pa := req.Header.Get("Proxy-Authorization") + if pa == "" { + t.log.Printf(" Unauthorized client.") + t.resp.AddHeader("Proxy-Authenticate", `Basic realm="`+t.cfg.AuthenticateRealm+`"`) + t.sendError(407, t.cfg.AuthenticateMessage) + return + } + auth := "" + if len(pa) > 6 { + if b, err := base64.StdEncoding.DecodeString(strings.TrimSpace(pa[6:])); err == nil { + auth = string(b) + } + } + ok := false + for _, a := range t.cfg.Authenticate { + if a == auth { + ok = true + } + } + if !ok { + t.log.Printf(" Incorrect login: '%s'.", auth) + t.resp.AddHeader("Proxy-Authenticate", `Basic realm="`+t.cfg.AuthenticateRealm+` (retry)"`) + t.sendError(407, t.cfg.AuthenticateMessage+"

    Your login or password is not correct. Please try again.

    ") + return + } + user, _, _ := strings.Cut(auth, ":") + t.vars.Set("ProxyUserName", user) + } + } + + // HTTPS proxy (CONNECT) + if strings.EqualFold(req.Method, "CONNECT") { + t.connect() + return + } + + t.url = req.URL + referer := req.Header.Get("Referer") + + if containsAny(absURL(t.url), t.cfg.UrlBlackList) { + t.log.Printf(" Blacklisted URL.") + if t.sendInternalContent("Err-UrlBlacklisted.htm", "?URL="+qe(t.urlString()), 403) { + return + } + t.sendError(403, "Access to this web page is disallowed by proxy settings.") + return + } + + if ua := req.Header.Get("User-Agent"); strings.TrimSpace(ua) != "" && rx.AnyMatches(ua, t.cfg.Http10Only) { + t.resp.SimpleContentType = true + } + t.resp.SetVersion(t.respMajor, t.respMinor) + + // the proxy's own address, as the client reached it + if ip4 := req.Local.IP.To4(); ip4 != nil { + t.localIP = ip4.String() + } else { + t.localIP = "[" + req.Local.IP.String() + "]" + } + if t.localIP == "127.0.0.1" && req.URL != nil && req.URL.Hostname() == "10.0.2.2" { + t.localIP = "10.0.2.2" // SLIRP + } + + // the proxy's own pages + if req.Kind == StandardHttp && !strings.Contains(t.url.Path, ":") { + page := "/" + segs := segments(t.url) + for _, sg := range segs[1:] { + page += sg + } + page = strings.ToLower(strings.TrimRight(page, "/")) + t.sendInternalPage(page, t.url.RawQuery) + return + } + if req.Kind == AlternateProxy { + t.log.Printf(" Alternate: %s", t.urlString()) + } + + if strings.Contains(req.Header.Get("User-Agent"), "WebOne") { + if t.sendInternalContent("Err-LoopRequest.htm", "", 403) { + return + } + t.sendError(403, "Loop requests are probhited.") + return + } + + // FTP, Gopher, WAIS ... through HTTP (CERN proxy mode) + if strings.Contains(t.url.String(), ":") { + scheme := t.url.Scheme + if scheme != "" && !strings.HasPrefix(scheme, "http") { + t.log.Printf(" CERN Proxy request to %s detected.", strings.ToUpper(scheme)) + } + if req.Kind != StandardProxy && strings.Contains(req.RawURL, "://") { + scheme = req.RawURL[1:strings.Index(req.RawURL, "://")] + } + if !containsAny(scheme, []string{"http", "https", "ftp"}) { + raw := strings.TrimLeft(req.RawURL, "/") + if t.sendInternalContent("Err-UnknownProtocol.htm", "?Scheme="+strings.TrimRight(strings.ToUpper(scheme), ":")+"&URL="+qe(raw), 200) { + return + } + msg := "

    You're attempted to request content from " + req.RawURL + ". " + + "The protocol specified in the URL is not supported by this proxy server.

    " + + "

    Consider connect directly to the server, bypassing the proxy. This error message may also appear if your Web browser settings have enabled " + + ""Use proxy for all protocols" option. Uncheck it and set only for protocols supported by WebOne. List of them can be found in project's Wiki.

    " + t.sendInfoPage(strings.ToUpper(t.url.Scheme)+" Is Not Supported", "Unsupported protocol", msg, 501) + return + } + } + lowerRaw := strings.ToLower(req.RawURL) + ftpRedirect := func(title, target string) { + p := newInfoPage(title, "", "", 302) + p.Headers.Add("Location", "http://"+t.serverName()+"/!ftp/?client=-1&uri="+url.QueryEscape(target)) + t.sendInfo(p) + } + switch { + case strings.HasPrefix(lowerRaw, "ftp://"): + ftpRedirect("CERN Proxy Emulation Redirect", req.RawURL) + return + case strings.HasPrefix(lowerRaw, "http://ftp:"): + ftpRedirect("CERN Proxy Emulation Redirect (NS)", req.RawURL[7:]) + return + case strings.HasPrefix(lowerRaw, "http://ftp//"): + ftpRedirect("CERN Proxy Emulation Redirect (IE)", "ftp://"+req.RawURL[12:]) + return + case strings.HasPrefix(lowerRaw, "/ftp://"): + ftpRedirect("CERN Proxy Emulation Redirect (Alt)", req.RawURL[1:]) + return + } + + // HTTP<->HTTPS redirect loops ("carousels") + cur := t.urlString() + t.s.lastMu.Lock() + lastURL, lastCode, lastCT := t.s.lastURL, t.s.lastCode, t.s.lastContentType + t.s.lastMu.Unlock() + host, _ := os.Hostname() + if (cur == referer || cur == lastURL) && cur != "" && + (strings.HasPrefix(lastCT, "text/htm") || lastCT == "") && + ((lastCode > 299 && lastCode < 400) || lastCode == 200) && + req.Method != "POST" && req.Method != "CONNECT" && + !t.s.isForceHttps(cur) && + !strings.EqualFold(t.url.Hostname(), host) && + !strings.EqualFold(t.url.Hostname(), t.localIP) && + !strings.EqualFold(t.url.Hostname(), t.cfg.DefaultHostName) { + t.log.Printf(" Carousel detected.") + if !strings.HasPrefix(lastURL, "https") && !strings.HasPrefix(cur, "https") { + t.url, _ = parseURL("https" + cur[4:]) + } + if strings.HasPrefix(lastURL, "https") { + if strings.HasPrefix(cur, "https") { + t.url, _ = parseURL("http" + cur[5:]) + } else { + t.url, _ = parseURL("http" + cur[4:]) + } + } + } + + // a secure referer for a secure page of the same site + if referer != "" { + if ru, err := url.Parse(referer); err == nil && ru.Hostname() == t.url.Hostname() { + if t.url.Scheme == "https" && !strings.HasPrefix(referer, "https://") && len(referer) > 4 { + referer = "https" + referer[4:] + } + } + } + + t.s.lastMu.Lock() + t.s.lastURL = t.urlString() + t.s.lastContentType = "unknown/unknown" + t.s.lastCode = 200 + t.s.lastMu.Unlock() + + cur = t.urlString() + if strings.Contains(cur, "??") { + t.sendError(400, "Too many questions.") + return + } + if cur == "" { + t.sendError(400, "Empty URL.") + return + } + + // pick the edit sets for this request + for _, set := range t.cfg.EditRules { + if len(t.cfg.Authenticate) > 0 && len(set.Users) > 0 { + valid := false + for _, u := range set.Users { + if t.vars.Value("ProxyUserName") == u { + valid = true + } + } + if !valid { + continue + } + } + if !set.CorrectHostOS { + continue + } + if !rx.AnyMatches(cur, set.UrlMasks) || rx.AnyMatches(cur, set.UrlIgnoreMasks) { + continue + } + if set.HttpOnly && req.Secure { + continue + } + if set.HttpsOnly && !req.Secure { + continue + } + if len(set.HeaderMasks) > 0 { + good := false + for _, m := range set.HeaderMasks { + req.Header.Each(func(k, v string) { + if !good && rx.Match(m, k+": "+v) { + good = true + } + }) + if good { + break + } + } + if good { + t.editSets = append(t.editSets, set) + } + continue + } + t.editSets = append(t.editSets, set) + } + + if len(t.cfg.UrlWhiteList) > 0 && !containsAny(t.url.String(), t.cfg.UrlWhiteList) { + if t.sendInternalContent("Err-UrlNotWhitelisted.htm", "?URL="+qe(cur), 403) { + return + } + t.sendError(403, "Proxy server administrator has been limited this proxy server to work with several web sites only.") + t.log.Printf(" URL out of white list.") + return + } + + if err := t.forward(referer); err != nil { + if t.handleFetchError(err) { + return + } + } + if t.resp.HeadersSent { + return + } + + // look in the Web Archive on errors + if t.responseCode >= 403 && t.cfg.SearchInArchive && req.Method != "POST" && req.Method != "PUT" && !t.stop { + t.lookInWebArchive() + if t.resp.HeadersSent { + return + } + } + + // shorten the Wayback Machine's error pages + if t.responseCode >= 403 && strings.HasPrefix(t.urlString(), "http://web.archive.org/web/") && t.cfg.ShortenArchiveErrors { + t.log.Printf(" Wayback Machine error page shortened.") + if t.sendInternalContent("Err-WA"+strconv.Itoa(t.responseCode)+".htm", + "?ErrorMessage="+StatusName(t.responseCode)+"&URL="+qe(t.urlString()), t.responseCode) { + return + } + switch t.responseCode { + case 404: + t.sendError(404, "

    The Wayback Machine has not archived that URL.

    Try to slightly change the URL.

    "+ + "You see this message because ShortenArchiveErrors option is enabled.") + case 403: + t.sendError(404, "

    This URL has been excluded from the Wayback Machine.

    This page is not present in Web Archive.

    "+ + "You see this message because ShortenArchiveErrors option is enabled.") + default: + t.sendError(404, "

    The Wayback Machine cannot give this page.

    This is reason: "+StatusName(t.responseCode)+".

    "+ + "You see this message because ShortenArchiveErrors option is enabled.") + } + return + } + + t.sendResult() +} + +// sendResult sends the fetched (and edited) response to the client. +func (t *transit) sendResult() { + defer func() { + if t.transitStream != nil { + t.transitStream.Close() + } + }() + w := t.resp + w.SetVersion(t.respMajor, t.respMinor) + w.Status = t.responseCode + w.AddHeader("Via", "HTTP/1.0 WebOne/"+t.cfg.Vars.Value("WOVer")) + if !w.Header.Has("Content-Type") && t.contentType != "" { + w.AddHeader("Content-Type", t.contentType) + } + if t.req.KeepAlive { + w.AddHeader("Proxy-Connection", "keep-alive") + } + if t.transitStream == nil { + enc := t.outputEncoding + if enc == nil { + enc = t.sourceEncoding + } + buf := enc.Encode(t.responseBody) + w.SetContentLength(int64(len(buf))) + if len(buf) > 300*1024 { + t.log.Printf(" Sending binary.") + } + if err := w.SendHeaders(Version); err != nil { + t.clientError(err) + return + } + if t.req.Method != "HEAD" { + w.Write(buf) + } + if t.dumpFile != "" { + w.Header.Each(func(k, v string) { t.dump(k + ": " + v) }) + t.dump("\n") + if len(buf) < 1024 { + t.dump(t.responseBody) + } else { + t.dump("Over 1 KB response body") + } + } + } else { + if w.ContentLength() == -2 { + w.SetContentLength(t.transitLength) + } + if err := w.SendHeaders(Version); err != nil { + t.clientError(err) + return + } + if _, err := io.Copy(w, t.transitStream); err != nil { + t.clientError(err) + w.KeepAlive = false + return + } + if t.dumpFile != "" { + w.Header.Each(func(k, v string) { t.dump(k + ": " + v) }) + t.dump("\nBody is binary stream") + } + } +} + +func (t *transit) clientError(err error) { + if !t.cfg.HideClientErrors { + t.log.Printf(" 1 + for _, e := range set.Edits { + switch e.Action { + case config.AddVariable: + t.addVariable(e.Params) + case config.AddHeaderDumping, config.AddRequestDumping, config.AddDumping: + f := strings.NewReplacer(":", "-", "<", "(", ">", ")", "?", "-", "|", "!").Replace(t.processURIMasks(e.Value)) + if len(f) > 128 { + f = f[:128] + "-CUT.log" + } + t.dumpFile = f + t.dump(req.Method + " " + req.RawURL + " HTTP/" + req.ProtoVersion()) + case config.AddInternalRedirect: + var target string + if useRegEx { + target = t.processURIMasks(rx.Replace(set.UrlMasks[0], t.urlString(), e.Value, rx.None)) + } else { + target = t.processURIMasks(e.Value) + } + t.log.Printf(" Fix to %s internally", target) + t.dump("~Internal redirect to: " + target) + nu, err := parseURL(target) + if err != nil { + return &badURLError{target} + } + t.url = nu + case config.AddRedirect: + var target string + if useRegEx { + if g := rx.FindGroups(set.UrlMasks[0], t.urlString()); g != nil { + target = t.processURIMasks(rx.Replace(set.UrlMasks[0], g[0], e.Value, rx.None)) + } else { + target = t.processURIMasks(e.Value) + } + } else { + target = t.processURIMasks(e.Value) + } + t.log.Printf(" Fix to %s", target) + t.dump("~Redirect using 302 to: " + target) + t.sendRedirect(target, "Брось каку!") + t.stop = true + return nil + case config.AddRequestHeader, config.AddHeader: + hdr := t.processURIMasks(e.Value) + t.dump("~Add request header: " + hdr) + name := e.Value[:strings.Index(e.Value, ": ")] + h.Del(name) + h.AddLine(hdr) + case config.AddRequestHeaderFindReplace: + h.Map(func(_, v string) string { return strings.ReplaceAll(v, e.Find, e.Replace) }) + t.dump("~Request header find&replace: '" + e.Find + "' / '" + e.Replace + "'") + case config.AddRequestHttpVersion: + t.dump("~Using HTTP(S) " + e.Value + " for remote connection") + t.requestHTTPVersion = e.Value + case config.AddResponseHttpVersion: + t.dump("~Reply as HTTP/" + e.Value) + t.respMajor, t.respMinor, _ = config.ParseVersion(e.Value) + case config.AddOutputEncoding: + t.outputEncoding = t.cfg.CodePage(e.Value) + name := "AsIs" + if t.outputEncoding != nil { + name = t.outputEncoding.Name + } + t.dump("~Output encoding set to: " + name) + case config.AddTranslit: + t.translit = config.ToBool(e.Value) + t.dump("~Enable transliteration") + case config.AddDebugPrint: + t.dump("~" + e.Value + " (at request processing)") + t.log.Printf(" [Request processing] %s", t.processURIMasks(e.Value)) + } + } + } + h.Each(func(k, v string) { + t.vars.TryAdd("Request."+k, v) + t.dump(k + ": " + v) + }) + t.dump("") + + // Microsoft Internet Component Download emulation + if t.cfg.ActivexGalleryEmul && containsAny(t.url.String(), t.cfg.ActivexGalleryUrls) { + if r := t.activexCabURL(); strings.TrimSpace(r) != "" { + if r == "404" { + t.sendError(404, "The specified Internet Component is known and is up to date.") + } else { + t.sendRedirect(r, "Nate entu vashu codebase, zhrite.") + } + t.stop = true + return nil + } + } + + t.op = &operation{ + Method: req.Method, + Header: h, + URL: t.url, + HTTPVersion: t.requestHTTPVersion, + log: t.log, + } + if !t.cfg.DontPreferHTTPS { + t.op.Secure = req.Secure + } + return t.sendRequest() +} + +func (s *Server) forceHttpsList() []string { + s.forceMu.RLock() + defer s.forceMu.RUnlock() + return append([]string(nil), s.forceHttps...) +} + +type badURLError struct{ u string } + +func (e *badURLError) Error() string { return "invalid URL " + e.u } + +// sendRequest sends t.op to the server and makes the output +// (HttpTransit.SendRequest). +func (t *transit) sendRequest() error { + op := t.op + cl := t.req.Header.Get("Content-Length") + op.URL = t.url + if cl == "" || cl == "0" { + t.log.Printf(">Downloading content...") + } else { + n, _ := strconv.Atoi(cl) + t.log.Printf(">Uploading %dK of %s...", n/1024, op.Header.Get("Content-Type")) + if t.dumpFile == "" { + op.Body = t.req.Body + } else { + data, _ := io.ReadAll(t.req.Body) + op.Body = bytes.NewReader(data) + if len(data) > 0 { + if len(data) < 1024 { + t.dump("\nCAUTION: Request body may contain private data!\n" + string(data)) + } else { + t.dump("\nRequest body is longer than 1 KB") + } + } else { + t.dump("\n") + } + } + } + if err := t.s.send(op); err != nil { + return err + } + if op.URL.Scheme != t.url.Scheme { + t.url = op.URL + } + t.makeOutput() + if t.stop { + return nil + } + t.responseCode = op.Resp.StatusCode + + // an HTTP site that moved to HTTPS + if t.responseCode >= 301 && t.responseCode <= 399 { + if loc := op.RespHeader.Get("Location"); loc != "" { + if t.urlString() == strings.Replace(loc, "https://", "http://", 1) { + t.log.Printf(">Reload secure...") + t.dump("Upgrade HTTP to HTTPS") + nu, err := parseURL(strings.Replace(t.urlString(), "http://", "https://", 1)) + if err == nil { + if t.transitStream != nil { + t.transitStream.Close() + t.transitStream = nil + } + h := t.req.Header.Clone() + t.url = nu + t.op = &operation{Method: op.Method, Header: h, URL: nu, HTTPVersion: t.requestHTTPVersion, log: t.log} + err := t.sendRequest() + t.s.addForceHttps(nu.Hostname()) + return err + } + } + if strings.HasPrefix(loc, "https://") { + t.s.addForceHttps(t.url.Hostname()) + } + } + } + + // the server's response headers, made fit for the client + op.RespHeader.Each(func(k, v string) { + cv := v + if !t.req.Secure { + cv = strings.ReplaceAll(cv, "https://", "http://") + cv = rx.Replace("; secure", cv, ";", rx.IgnoreCase) + } + if t.req.Kind == AlternateProxy || t.req.Kind == DirtyAlternateProxy { + sn := t.serverName() + if strings.HasPrefix(cv, "http://") && !strings.HasPrefix(cv, "http://"+sn) { + cv = strings.Replace(cv, "http://", "http://"+sn+"/http://", 1) + } + cv = rx.Replace("domain=[^;]*; ", cv, " ", rx.IgnoreCase) + cv = rx.Replace("path=[^;]*; ", cv, " ", rx.IgnoreCase) + } + if !strings.HasPrefix(k, "Content-") && + !strings.HasPrefix(k, "Connection") && + !strings.HasPrefix(k, "Transfer-Encoding") && + !strings.HasPrefix(k, "Keep-Alive") && + !strings.HasPrefix(k, "Access-Control-Allow-Methods") && + !strings.HasPrefix(k, "Strict-Transport-Security") && + !strings.HasPrefix(k, "Content-Security-Policy") && + !strings.HasPrefix(k, "Upgrade-Insecure-Requests") && + !strings.HasPrefix(k, "Alt-Svc") && + !(strings.HasPrefix(k, "Vary") && strings.Contains(cv, "Upgrade-Insecure-Requests")) { + t.resp.Header.Add(k, cv) + } + if k == "Content-Length" && t.transitStream != nil { + if n, err := strconv.ParseInt(cv, 10, 64); err == nil { + t.resp.SetContentLength(n) + } + } + }) + return nil +} + +// makeOutput looks at the server's response: edits for response headers, +// redirects, converters; text is read and edited, anything else streamed +// (HttpTransit.MakeOutput). +func (t *transit) makeOutput() { + op := t.op + code := op.Resp.StatusCode + ct := op.RespHeader.Get("Content-Type") + if ct == "" { + ct = noContentType + } + lengthKB := "?" + if op.Resp.ContentLength >= 0 { + lengthKB = strconv.FormatInt(op.Resp.ContentLength/1024, 10) + } + t.contentType = ct + srcCT := ct + t.dump(fmt.Sprintf("\n\n%d HTTP/1.0", code)) + t.vars.TryAdd("Response.HttpStatusCode", strconv.Itoa(code)) + t.vars.TryAdd("Response.HttpVersion", fmt.Sprintf("%d.%d", op.Resp.ProtoMajor, op.Resp.ProtoMinor)) + op.RespHeader.Each(func(k, v string) { t.vars.TryAdd("Response."+k, v) }) + + var converter, dest, arg1, arg2, redirect string + for _, set := range t.editSets { + if len(set.ContentTypeMasks) > 0 && !rx.AnyMatches(ct, set.ContentTypeMasks) { + continue + } + if !config.CheckCode(set.OnCode, code) { + continue + } + for _, e := range set.Edits { + switch e.Action { + case config.AddVariable: + t.addVariable(e.Params) + case config.AddConverting: + converter, dest, arg1, arg2 = e.Converter, e.ConvertDest, e.ConvertArg1, e.ConvertArg2 + t.stop = true + t.dump("~~Convert using: " + converter) + case config.AddResponseHeader: + hdr := t.processURIMasks(e.Value) + t.log.Printf(" Add response header: %s", hdr) + op.RespHeader.AddLine(hdr) + if strings.HasPrefix(e.Value, "Content-Type: ") { + ct = e.Value[len("Content-Type: "):] + } + t.dump("~~Add response header: " + hdr) + case config.AddResponseHeaderFindReplace: + op.RespHeader.Map(func(_, v string) string { return strings.ReplaceAll(v, e.Find, e.Replace) }) + t.dump("~~Response header find&replace: " + e.Find + " -> " + e.Replace) + case config.AddRedirect: + redirect = t.processURIMasks(e.Value) + t.log.Printf(" Add redirect: %s", redirect) + t.dump("~~Redirect to: " + redirect) + case config.AddResponseHttpVersion: + t.dump("~Reply as HTTP/" + e.Value) + t.respMajor, t.respMinor, _ = config.ParseVersion(e.Value) + case config.AddDebugPrint: + t.dump("~" + e.Value + " (at response headers processing)") + t.log.Printf("[Response headers processing] %s", t.processURIMasks(e.Value)) + } + } + } + + if redirect != "" { + t.log.Printf(" %d %s. Body %sK of %s [Need to redirect].", code, StatusName(code), lengthKB, srcCT) + op.RespBody.Close() + t.sendRedirect(redirect, "Traffic has been edited.") + t.stop = true + return + } + if converter != "" { + t.log.Printf(" %d %s. Body %sK of %s [Wants %s].", code, StatusName(code), lengthKB, srcCT, converter) + t.convertResponse(converter, dest, arg1, arg2, ct, srcCT) + return + } + + t.s.lastMu.Lock() + t.s.lastCode = code + t.s.lastContentType = ct + t.s.lastMu.Unlock() + + shown := ct + if ct == noContentType { + shown = "something" + } + if containsAny(ct, t.cfg.TextTypes) { + t.log.Printf(" %d %s. Body %sK of %s [Text].", code, StatusName(code), lengthKB, shown) + raw, err := io.ReadAll(op.RespBody) + op.RespBody.Close() + if err != nil && len(raw) == 0 { + t.log.Printf(" Body read error: %v", err) + } + t.sourceEncoding = t.findContentCharset(raw) + if t.outputEncoding == nil { + t.responseBody = t.processBody(t.sourceEncoding.Decode(raw)) + t.contentType = ct + return + } + forceUTF8 := strings.Contains(strings.ToLower(ct), "utf-8") + if !forceUTF8 && len(raw) > 0 { + forceUTF8 = t.sourceEncoding.IsUTF8() + } + for _, f := range t.cfg.ForceUtf8 { + if rx.Match(f, t.urlString()) { + forceUTF8 = true + } + } + if forceUTF8 { + t.responseBody = textenc.UTF8.Decode(raw) + } else { + t.responseBody = t.sourceEncoding.Decode(raw) + } + if rx.MatchOpt(``, t.responseBody, rx.IgnoreCase) { + t.responseBody = textenc.UTF8.Decode(raw) + } + if strings.Contains(strings.ToLower(ct), "utf-8") { + if i := strings.IndexByte(ct, ';'); i >= 0 { + ct = ct[:i] + } + } + t.contentType = ct + t.responseBody = t.processBody(t.responseBody) + return + } + t.log.Printf(" %d %s. Body %sK of %s [Binary].", code, StatusName(code), lengthKB, shown) + t.transitStream = op.RespBody + t.transitLength = op.Resp.ContentLength + t.contentType = ct +} + +// findContentCharset works out the code page of a text body: byte order +// mark, then the Content-Type charset, then a charset, +// else the culture's Windows code page. +func (t *transit) findContentCharset(raw []byte) *textenc.Encoding { + if len(raw) < 1 { + return textenc.UTF8 + } + switch raw[0] { + case 0xEF: + return textenc.UTF8 + case 0xFF: + return textenc.UTF16LE + case 0xFE: + return textenc.UTF16BE + } + if ct := t.op.RespHeader.Get("Content-Type"); ct != "" { + if g := rx.FindGroups(`; ?charset=(.*)`, ct); g != nil { + name := g[1] + if strings.EqualFold(name, "utf8") { + name = "utf-8" + } + name = strings.NewReplacer(`"`, "", "'", "").Replace(name) + if i := strings.IndexByte(name, ';'); i >= 0 { + name = name[:i] + } + if e := textenc.Lookup(name); e != nil { + return e + } + } + } + windows := textenc.FromCodePageOr(t.cfg.CodepageCulture.ANSI, textenc.ByCodePage(1252)) + content := textenc.UTF8.Decode(raw) + meta := rx.FindGroups(``, strings.ToLower(content)) + if meta == nil { + return windows + } + cs := rx.FindGroups(`charset=.*['"]`, meta[0]) + if cs == nil { + return windows + } + name := strings.ReplaceAll(cs[0][len("charset="):], `"`, "") + if e := textenc.Lookup(name); e != nil { + return e + } + return textenc.UTF8 +} + +// processBody edits a text body (HttpTransit.ProcessBody). +func (t *transit) processBody(body string) string { + if !t.req.Secure { + body = strings.ReplaceAll(body, "https", "http") + } + if out := t.outputEncoding; out != nil { + n := out.Name + body = strings.NewReplacer( + `harset="utf-8"`, `harset="`+n+`"`, + `harset="UTF-8"`, `harset="`+n+`"`, + "harset=utf-8", "harset="+n, + "harset=UTF-8", "harset="+n, + "CHARSET=UTF-8", "CHARSET="+n, + `ncoding="utf-8"`, `ncoding="`+n+`"`, + `ncoding="UTF-8"`, `ncoding="`+n+`"`, + "ncoding=utf-8", "ncoding="+n, + "ncoding=UTF-8", "ncoding="+n, + "ENCODING=UTF-8", "ENCODING="+n, + ).Replace(body) + body = strings.ReplaceAll(body, "\uFEFF", "") + body = strings.ReplaceAll(body, out.Decode([]byte{0xEF, 0xBB, 0xBF}), "") + // what the code page has not becomes '?' + body = out.Decode(out.Encode(body)) + } + for _, set := range t.editSets { + // (WebOne tests the masks against the content type the other way + // round here, which misses "text/html; charset=..." for a mask of + // "html"; this port tests as MakeOutput does) + if len(set.ContentTypeMasks) > 0 && !rx.AnyMatches(t.contentType, set.ContentTypeMasks) { + continue + } + if !config.CheckCode(set.OnCode, t.op.Resp.StatusCode) { + continue + } + for _, e := range set.Edits { + switch e.Action { + case config.AddVariable: + t.addVariable(e.Params) + case config.AddFindReplace: + body = rx.Replace(e.Find, body, e.Replace, rx.Singleline) + t.dump("~~Find & replace (RegEx): " + e.Find + " -> " + e.Replace) + case config.AddResponseHttpVersion: + t.dump("~Reply as HTTP/" + e.Value) + t.respMajor, t.respMinor, _ = config.ParseVersion(e.Value) + case config.AddDebugPrint: + t.dump("~" + e.Value + " (at response body processing)") + t.log.Printf("[Response body processing] %s", t.processURIMasks(e.Value)) + } + } + } + if t.translit { + for _, l := range t.cfg.TranslitTable { + body = strings.ReplaceAll(body, l[0], l[1]) + } + } + if t.req.Kind == AlternateProxy || t.req.Kind == DirtyAlternateProxy { + body = t.alternateBody(body) + } + return body +} + +// alternateBody points a page's links back through the proxy, for clients +// that use it as a web server (/http://site/page). +func (t *transit) alternateBody(body string) string { + segs := segments(t.url) + dir := "/" + for i := 0; i < len(segs)-1; i++ { + dir += segs[i] + } + host := t.url.Host + steps := [][2]string{ + {`.replace(/"/g`, `.replace(/"WEBONEGOOGLEFIX1/g`}, + {`.replace(/'/g`, `.replace(/'WEBONEGOOGLEFIX2/g`}, + {`"http://`, `"@@@/http://`}, + {`"https://`, `"@@@/http://`}, + {`"ftp://`, `"@@@/ftp://`}, + {`"//`, `"@@@/http://`}, + {`"/`, `"/http://` + host + `/`}, + {`"./`, `"/http://` + host + dir}, + {`"@@@/http://`, `"/http://`}, + {`"@@@/ftp://`, `"/ftp://`}, + {`'http://`, `'@@@/http://`}, + {`'https://`, `'@@@/http://`}, + {`'ftp://`, `'@@@/ftp://`}, + {`'//`, `'@@@/http://`}, + {`'/`, `'/http://` + host + `/`}, + {`'./`, `'/http://` + host + dir}, + {`'@@@/http://`, `'/http://`}, + {`'@@@/ftp://`, `'/ftp://`}, + {`:url(http://`, `:url(/http://` + host + `/`}, + {`:url(https://`, `:url(/http://` + host + `/`}, + {`:url(//`, `:url(@@@/http://`}, + {`:url(/`, `:url(/http://` + host + `/`}, + {`:url(./`, `:url(/http://` + host + dir}, + {`:url(@@@/http://`, `:url(/http://`}, + {`.replace(/"WEBONEGOOGLEFIX1/g`, `.replace(/"/g`}, + {`.replace(/'WEBONEGOOGLEFIX2/g`, `.replace(/'/g`}, + } + for _, st := range steps { + body = strings.ReplaceAll(body, st[0], st[1]) + } + return body +} + +// addVariable runs AddVariable: "Name","Value"; "Name","Source","Mask"; +// or "Name","Source","Mask","Group". +func (t *transit) addVariable(p []string) { + switch len(p) { + case 2: + t.vars.Set(p[0], p[1]) + case 3, 4: + src := t.processURIMasks(p[1]) + groups, ok := rx.FindGroupsOK(p[2], src) + if groups == nil { + t.log.Printf(" No match for %s in %s found.", p[2], p[1]) + return + } + if len(p) == 3 { + t.vars.Set(p[0], groups[0]) + return + } + n, _ := strconv.Atoi(p[3]) + if n < len(groups) && ok[n] { + t.vars.Set(p[0], groups[n]) + } else { + t.log.Printf(" Group number %s in %s is not success.", p[3], p[1]) + } + } +} + +// dump appends a line to the traffic dump file, if dumping. +func (t *transit) dump(s string) { + if t.dumpFile == "" { + return + } + f, err := os.OpenFile(t.dumpFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + return + } + fmt.Fprintln(f, s) + f.Close() +} + +// containsAny: s contains one of list (Program.CheckString). +func containsAny(s string, list []string) bool { + for _, l := range list { + if strings.Contains(s, l) { + return true + } + } + return false +} diff --git a/internal/proxy/upstream.go b/internal/proxy/upstream.go new file mode 100644 index 0000000..3fa0ed5 --- /dev/null +++ b/internal/proxy/upstream.go @@ -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 +} diff --git a/internal/proxy/video.go b/internal/proxy/video.go new file mode 100644 index 0000000..dc345b5 --- /dev/null +++ b/internal/proxy/video.go @@ -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 := "

    WebOne can help download videos from popular sites in preferred format.

    " + + "

    To download a video, go to Online Video Player, enter URL of the video, " + + "choose container and codecs valid for your system, and then select file or link option.

    " + + "

    If you choose file option, the video file will start download automatically. " + + "If you choose link option, you will get a link, which can be copied to multimedia player program.

    " + + "

    Manual use parameters:

      " + + "
    • url - Address of the video (e.g. https://www.youtube.com/watch?v=fPnO26CwqYU or similar)
    • " + + "
    • f - Target format of the file (e.g. avi)
    • " + + "
    • vcodec - Codec for video (e.g. mpeg4)
    • " + + "
    • acodec - Codec for audio (e.g. mp3)
    • " + + "
    • content-type - override MIME content type for the file (optional).
    • " + + "
    • Also you can use many " + t.videoOption("YouTubeDlApp", "yt-dlp") + + " and " + t.videoOption("FFmpegApp", "ffmpeg") + + " options like aspect, b, no-mark-watched and other.
    • " + + "
    • Default parameter values are stored in configuration file.

    " + 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 := "

    " + err.Error() + "

    " + + "

    Make sure that parameters are correct, and both yt-dlp and ffmpeg are properly installed on the server.

    " + 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 = "" + 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 = "
    Download the video
    " + if _, ok := args.Get("f"); !ok { + p.Content += "

    Or select format, codecs and convert the video online.

    " + } + p.Title = "Video player - link only" + case "file": + p.Content = "
    Please wait up to 30 sec.
    If nothing appear, click here to download manually.
    " + 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 += "

    Error: " + msg + "

    " + 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 = "

    It will be better to open " + u + " instead of this stub.

    " + p.Status = 302 + p.Headers.Add("Location", u) + return p +} diff --git a/internal/rx/rx.go b/internal/rx/rx.go new file mode 100644 index 0000000..b2623ba --- /dev/null +++ b/internal/rx/rx.go @@ -0,0 +1,132 @@ +// Package rx is WebOne's regular expressions: .NET's syntax and +// replacement rules ($1, ${name}, lookarounds, backreferences), which +// configuration files are written in, through regexp2, with compiled +// patterns cached. +package rx + +import ( + "sync" + "time" + + "github.com/dlclark/regexp2" +) + +// Timeout bounds one match, as WebOne's RegexTimeout does. +const Timeout = 5 * time.Second + +type key struct { + pattern string + opts regexp2.RegexOptions +} + +var cache sync.Map // key -> *regexp2.Regexp + +// Options for Get. +const ( + None = regexp2.None + IgnoreCase = regexp2.IgnoreCase + Singleline = regexp2.Singleline +) + +// Get compiles a pattern (cached). +func Get(pattern string, opts regexp2.RegexOptions) (*regexp2.Regexp, error) { + k := key{pattern, opts} + if r, ok := cache.Load(k); ok { + return r.(*regexp2.Regexp), nil + } + r, err := regexp2.Compile(pattern, opts) + if err != nil { + return nil, err + } + r.MatchTimeout = Timeout + cache.Store(k, r) + return r, nil +} + +// Check reports whether a pattern compiles. +func Check(pattern string) error { + _, err := Get(pattern, None) + return err +} + +// Match: pattern matches s. A bad pattern matches nothing. +func Match(pattern, s string) bool { + return MatchOpt(pattern, s, None) +} + +// MatchOpt is Match with options. +func MatchOpt(pattern, s string, opts regexp2.RegexOptions) bool { + r, err := Get(pattern, opts) + if err != nil { + return false + } + ok, err := r.MatchString(s) + return err == nil && ok +} + +// AnyMatches: one of patterns matches s (Program.CheckStringRegExp(What, For[])). +func AnyMatches(s string, patterns []string) bool { + for _, p := range patterns { + if Match(p, s) { + return true + } + } + return false +} + +// Replace replaces every match of pattern in s with repl (.NET substitution +// syntax). On a bad pattern or a timeout s comes back unchanged. +func Replace(pattern, s, repl string, opts regexp2.RegexOptions) string { + r, err := Get(pattern, opts) + if err != nil { + return s + } + out, err := r.Replace(s, repl, -1, -1) + if err != nil { + return s + } + return out +} + +// GroupCount is the number of groups in pattern, the whole match included. +func GroupCount(pattern string) int { + r, err := Get(pattern, None) + if err != nil { + return 0 + } + return len(r.GetGroupNumbers()) +} + +// FindGroups is the first match's groups (index 0 the whole match), or nil. +func FindGroups(pattern, s string) []string { + r, err := Get(pattern, None) + if err != nil { + return nil + } + m, err := r.FindStringMatch(s) + if err != nil || m == nil { + return nil + } + var out []string + for _, g := range m.Groups() { + out = append(out, g.String()) + } + return out +} + +// FindGroupsOK is FindGroups with each group's success. +func FindGroupsOK(pattern, s string) (groups []string, ok []bool) { + r, err := Get(pattern, None) + if err != nil { + return nil, nil + } + m, err := r.FindStringMatch(s) + if err != nil || m == nil { + return nil, nil + } + for _, g := range m.Groups() { + groups = append(groups, g.String()) + ok = append(ok, len(g.Captures) > 0) + } + return groups, ok +} diff --git a/internal/textenc/textenc.go b/internal/textenc/textenc.go new file mode 100644 index 0000000..2053e07 --- /dev/null +++ b/internal/textenc/textenc.go @@ -0,0 +1,357 @@ +// Package textenc is the set of text encodings (code pages) WebOne can +// convert content to and from, named as .NET and Windows name them +// ("windows-1251", "ibm866", "macintosh", 1251, 866 ...), and the default +// code pages of a language (Windows ANSI, DOS OEM, Mac, EBCDIC, ISO). +package textenc + +import ( + "bytes" + "sort" + "strconv" + "strings" + "unicode/utf8" + + "golang.org/x/text/encoding" + "golang.org/x/text/encoding/charmap" + "golang.org/x/text/encoding/htmlindex" + "golang.org/x/text/encoding/ianaindex" + "golang.org/x/text/encoding/japanese" + "golang.org/x/text/encoding/korean" + "golang.org/x/text/encoding/simplifiedchinese" + "golang.org/x/text/encoding/traditionalchinese" + "golang.org/x/text/encoding/unicode" +) + +// Encoding is a code page. +type Encoding struct { + Name string // web name, as in a charset= parameter + CodePage int + Display string + enc encoding.Encoding // nil for UTF-8 + cm *charmap.Charmap +} + +func (e *Encoding) String() string { return e.Name } + +// IsUTF8 is the UTF-8 encoding. +func (e *Encoding) IsUTF8() bool { return e.enc == nil } + +// Decode turns text in this encoding into a Go (UTF-8) string. +func (e *Encoding) Decode(b []byte) string { + if e.enc == nil { + return string(bytes.ToValidUTF8(b, []byte("�"))) + } + if e.cm != nil { + // byte by byte; bytes the code page leaves undefined become the + // control characters of the same number, as .NET does, so that + // decoding and encoding again gives the same bytes + var sb strings.Builder + sb.Grow(len(b)) + for _, c := range b { + r := e.cm.DecodeByte(c) + if r == utf8.RuneError && c >= 0x80 { + r = rune(c) + } + sb.WriteRune(r) + } + return sb.String() + } + out, err := e.enc.NewDecoder().Bytes(b) + if err != nil { + return string(b) + } + return string(out) +} + +// Encode turns a string into this encoding; characters it has not are '?'. +func (e *Encoding) Encode(s string) []byte { + if e.enc == nil { + return []byte(s) + } + if e.cm != nil { + out := make([]byte, 0, len(s)) + for _, r := range s { + if b, ok := e.cm.EncodeRune(r); ok { + out = append(out, b) + } else if r >= 0x80 && r < 0x100 && e.cm.DecodeByte(byte(r)) == utf8.RuneError { + out = append(out, byte(r)) + } else { + out = append(out, '?') + } + } + return out + } + if out, err := e.enc.NewEncoder().Bytes([]byte(s)); err == nil { + return out + } + // slow path: rune by rune, '?' for what does not fit + var out []byte + enc := e.enc.NewEncoder() + buf := make([]byte, utf8.UTFMax) + for _, r := range s { + n := utf8.EncodeRune(buf, r) + b, err := enc.Bytes(buf[:n]) + if err != nil { + out = append(out, '?') + enc.Reset() + continue + } + out = append(out, b...) + } + return out +} + +// Preamble is the byte order mark of the Unicode encodings (nil otherwise). +func (e *Encoding) Preamble() []byte { + switch e.CodePage { + case 65001: + return []byte{0xEF, 0xBB, 0xBF} + case 1200: + return []byte{0xFF, 0xFE} + case 1201: + return []byte{0xFE, 0xFF} + } + return nil +} + +var ( + UTF8 = &Encoding{Name: "utf-8", CodePage: 65001, Display: "Unicode (UTF-8)"} + UTF16LE = &Encoding{Name: "utf-16", CodePage: 1200, Display: "Unicode", enc: unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)} + UTF16BE = &Encoding{Name: "utf-16BE", CodePage: 1201, Display: "Unicode (Big-Endian)", enc: unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM)} +) + +type entry struct { + name string + cp int + display string + enc encoding.Encoding + aliases []string +} + +var table = []entry{ + {"IBM037", 37, "IBM EBCDIC (US-Canada)", charmap.CodePage037, []string{"cp037", "ebcdic-cp-us"}}, + {"IBM437", 437, "OEM United States", charmap.CodePage437, []string{"cp437", "437"}}, + {"IBM850", 850, "Western European (DOS)", charmap.CodePage850, []string{"cp850"}}, + {"IBM852", 852, "Central European (DOS)", charmap.CodePage852, []string{"cp852"}}, + {"IBM855", 855, "OEM Cyrillic", charmap.CodePage855, []string{"cp855"}}, + {"IBM00858", 858, "OEM Multilingual Latin I", charmap.CodePage858, []string{"cp858"}}, + {"IBM860", 860, "Portuguese (DOS)", charmap.CodePage860, []string{"cp860"}}, + {"IBM862", 862, "Hebrew (DOS)", charmap.CodePage862, []string{"cp862", "dos-862"}}, + {"IBM863", 863, "French Canadian (DOS)", charmap.CodePage863, []string{"cp863"}}, + {"IBM865", 865, "Nordic (DOS)", charmap.CodePage865, []string{"cp865"}}, + {"cp866", 866, "Cyrillic (DOS)", charmap.CodePage866, []string{"ibm866", "866"}}, + {"IBM01047", 1047, "IBM Latin-1", charmap.CodePage1047, []string{"cp1047"}}, + {"IBM01140", 1140, "IBM EBCDIC (US-Canada-Euro)", charmap.CodePage1140, []string{"cp1140"}}, + {"windows-874", 874, "Thai (Windows)", charmap.Windows874, []string{"cp874", "tis-620"}}, + {"shift_jis", 932, "Japanese (Shift-JIS)", japanese.ShiftJIS, []string{"sjis", "ms_kanji", "csshiftjis", "x-sjis"}}, + {"gb2312", 936, "Chinese Simplified (GB2312)", simplifiedchinese.GBK, []string{"gbk", "cp936"}}, + {"ks_c_5601-1987", 949, "Korean", korean.EUCKR, []string{"euc-kr", "cp949"}}, + {"big5", 950, "Chinese Traditional (Big5)", traditionalchinese.Big5, []string{"cp950"}}, + {"windows-1250", 1250, "Central European (Windows)", charmap.Windows1250, []string{"cp1250"}}, + {"windows-1251", 1251, "Cyrillic (Windows)", charmap.Windows1251, []string{"cp1251"}}, + {"windows-1252", 1252, "Western European (Windows)", charmap.Windows1252, []string{"cp1252"}}, + {"windows-1253", 1253, "Greek (Windows)", charmap.Windows1253, []string{"cp1253"}}, + {"windows-1254", 1254, "Turkish (Windows)", charmap.Windows1254, []string{"cp1254"}}, + {"windows-1255", 1255, "Hebrew (Windows)", charmap.Windows1255, []string{"cp1255"}}, + {"windows-1256", 1256, "Arabic (Windows)", charmap.Windows1256, []string{"cp1256"}}, + {"windows-1257", 1257, "Baltic (Windows)", charmap.Windows1257, []string{"cp1257"}}, + {"windows-1258", 1258, "Vietnamese (Windows)", charmap.Windows1258, []string{"cp1258"}}, + {"macintosh", 10000, "Western European (Mac)", charmap.Macintosh, []string{"x-mac-roman", "mac"}}, + {"x-mac-cyrillic", 10007, "Cyrillic (Mac)", charmap.MacintoshCyrillic, []string{"x-mac-ukrainian"}}, + {"koi8-r", 20866, "Cyrillic (KOI8-R)", charmap.KOI8R, []string{"koi8"}}, + {"koi8-u", 21866, "Cyrillic (KOI8-U)", charmap.KOI8U, nil}, + {"iso-8859-1", 28591, "Western European (ISO)", charmap.ISO8859_1, []string{"latin1", "l1"}}, + {"iso-8859-2", 28592, "Central European (ISO)", charmap.ISO8859_2, []string{"latin2"}}, + {"iso-8859-3", 28593, "Latin 3 (ISO)", charmap.ISO8859_3, []string{"latin3"}}, + {"iso-8859-4", 28594, "Baltic (ISO)", charmap.ISO8859_4, []string{"latin4"}}, + {"iso-8859-5", 28595, "Cyrillic (ISO)", charmap.ISO8859_5, nil}, + {"iso-8859-6", 28596, "Arabic (ISO)", charmap.ISO8859_6, nil}, + {"iso-8859-7", 28597, "Greek (ISO)", charmap.ISO8859_7, nil}, + {"iso-8859-8", 28598, "Hebrew (ISO-Visual)", charmap.ISO8859_8, nil}, + {"iso-8859-9", 28599, "Turkish (ISO)", charmap.ISO8859_9, []string{"latin5"}}, + {"iso-8859-10", 28600, "Nordic (ISO)", charmap.ISO8859_10, []string{"latin6"}}, + {"iso-8859-13", 28603, "Estonian (ISO)", charmap.ISO8859_13, []string{"latin7"}}, + {"iso-8859-14", 28604, "Celtic (ISO)", charmap.ISO8859_14, []string{"latin8"}}, + {"iso-8859-15", 28605, "Latin 9 (ISO)", charmap.ISO8859_15, []string{"latin9", "latin0"}}, + {"iso-8859-16", 28606, "South-Eastern European (ISO)", charmap.ISO8859_16, []string{"latin10"}}, + {"euc-jp", 51932, "Japanese (EUC)", japanese.EUCJP, nil}, + {"iso-2022-jp", 50220, "Japanese (JIS)", japanese.ISO2022JP, nil}, + {"gb18030", 54936, "Chinese Simplified (GB18030)", simplifiedchinese.GB18030, nil}, + {"hz-gb-2312", 52936, "Chinese Simplified (HZ)", simplifiedchinese.HZGB2312, nil}, +} + +var ( + byName = map[string]*Encoding{} + byCP = map[int]*Encoding{} + all []*Encoding +) + +func init() { + add := func(e *Encoding, aliases ...string) { + byName[strings.ToLower(e.Name)] = e + for _, a := range aliases { + byName[strings.ToLower(a)] = e + } + byCP[e.CodePage] = e + all = append(all, e) + } + add(UTF8, "utf8") + add(UTF16LE, "utf-16le", "unicode") + add(UTF16BE, "unicodefffe") + for _, t := range table { + e := &Encoding{Name: t.name, CodePage: t.cp, Display: t.display, enc: t.enc} + if cm, ok := t.enc.(*charmap.Charmap); ok { + e.cm = cm + } + add(e, t.aliases...) + } + sort.Slice(all, func(i, j int) bool { return strings.ToLower(all[i].Display) < strings.ToLower(all[j].Display) }) +} + +// All is every known encoding, by display name. +func All() []*Encoding { return all } + +// ByCodePage is the encoding of a Windows code page number (nil if unknown). +func ByCodePage(cp int) *Encoding { return byCP[cp] } + +// Lookup finds an encoding by name (charset label) or code page number; +// nil if unknown. +func Lookup(name string) *Encoding { + n := strings.ToLower(strings.TrimSpace(name)) + if n == "" { + return nil + } + if e := byName[n]; e != nil { + return e + } + if cp, err := strconv.Atoi(n); err == nil { + return byCP[cp] + } + // any other label the WHATWG or IANA registries know + if enc, err := htmlindex.Get(n); err == nil { + return fromEncoding(n, enc) + } + if enc, err := ianaindex.IANA.Encoding(n); err == nil && enc != nil { + return fromEncoding(n, enc) + } + return nil +} + +func fromEncoding(label string, enc encoding.Encoding) *Encoding { + if enc == unicode.UTF8 || enc == encoding.Nop { + return UTF8 + } + for _, e := range all { + if e.enc == enc { + return e + } + } + name, _ := htmlindex.Name(enc) + if name == "" { + name = label + } + e := &Encoding{Name: name, Display: name, enc: enc} + if cm, ok := enc.(*charmap.Charmap); ok { + e.cm = cm + } + return e +} + +// Culture is a language's default code pages, as Windows' locale tables +// give them. +type Culture struct { + Lang string // two-letter ISO 639 code + ANSI int + OEM int + Mac int + EBCDIC int +} + +var cultures = map[string]Culture{ + "en": {"en", 1252, 437, 10000, 37}, + "de": {"de", 1252, 850, 10000, 20273}, + "fr": {"fr", 1252, 850, 10000, 20297}, + "es": {"es", 1252, 850, 10000, 20284}, + "it": {"it", 1252, 850, 10000, 20280}, + "pt": {"pt", 1252, 850, 10000, 37}, + "nl": {"nl", 1252, 850, 10000, 500}, + "sv": {"sv", 1252, 850, 10000, 20278}, + "da": {"da", 1252, 850, 10000, 20277}, + "no": {"no", 1252, 850, 10000, 20277}, + "nb": {"nb", 1252, 850, 10000, 20277}, + "fi": {"fi", 1252, 850, 10000, 20278}, + "is": {"is", 1252, 850, 10079, 20871}, + "ru": {"ru", 1251, 866, 10007, 20880}, + "uk": {"uk", 1251, 866, 10017, 500}, + "be": {"be", 1251, 866, 10007, 500}, + "bg": {"bg", 1251, 866, 10007, 500}, + "sr": {"sr", 1251, 855, 10007, 500}, + "mk": {"mk", 1251, 866, 10007, 500}, + "pl": {"pl", 1250, 852, 10029, 20880}, + "cs": {"cs", 1250, 852, 10029, 500}, + "sk": {"sk", 1250, 852, 10029, 500}, + "hu": {"hu", 1250, 852, 10029, 500}, + "sl": {"sl", 1250, 852, 10029, 500}, + "hr": {"hr", 1250, 852, 10082, 500}, + "ro": {"ro", 1250, 852, 10010, 20880}, + "el": {"el", 1253, 737, 10006, 20273}, + "tr": {"tr", 1254, 857, 10081, 20905}, + "he": {"he", 1255, 862, 10005, 500}, + "ar": {"ar", 1256, 720, 10004, 20420}, + "et": {"et", 1257, 775, 10029, 500}, + "lv": {"lv", 1257, 775, 10029, 500}, + "lt": {"lt", 1257, 775, 10029, 500}, + "vi": {"vi", 1258, 1258, 10000, 500}, + "th": {"th", 874, 874, 10021, 20838}, + "ja": {"ja", 932, 932, 10001, 20290}, + "zh": {"zh", 936, 936, 10008, 500}, + "ko": {"ko", 949, 949, 10003, 20833}, +} + +// CultureFor is the culture of a language tag ("ru", "ru-RU", "ru_RU.UTF-8"); +// English when unknown. +func CultureFor(tag string) Culture { + t := strings.ToLower(tag) + if i := strings.IndexAny(t, "-_.@"); i >= 0 { + t = t[:i] + } + if c, ok := cultures[t]; ok { + return c + } + return cultures["en"] +} + +// ISO is the ISO 8859 part WebOne picks for a language (Program.GetCodePage). +func ISO(lang string) *Encoding { + switch strings.ToLower(lang) { + case "bs", "pl", "cr", "cz", "sk", "sl", "hu": + return Lookup("iso-8859-2") + case "mt", "eo": + return Lookup("iso-8859-3") + case "kl", "se": + return Lookup("iso-8859-4") + case "be", "bu", "mk", "ru", "sr", "ua": + return Lookup("iso-8859-5") + case "ar": + return Lookup("iso-8859-6") + case "gr": + return Lookup("iso-8859-7") + case "hw": + return Lookup("iso-8859-8") + case "tr": + return Lookup("iso-8859-9") + case "lv", "lt": + return Lookup("iso-8859-13") + case "fr", "fi", "es": + return Lookup("iso-8859-15") + } + return Lookup("iso-8859-1") +} + +// FromCodePageOr is ByCodePage(cp), or fallback when Go does not know cp. +func FromCodePageOr(cp int, fallback *Encoding) *Encoding { + if e := ByCodePage(cp); e != nil { + return e + } + return fallback +} diff --git a/internal/textenc/textenc_test.go b/internal/textenc/textenc_test.go new file mode 100644 index 0000000..55b7e34 --- /dev/null +++ b/internal/textenc/textenc_test.go @@ -0,0 +1,36 @@ +package textenc + +import ( + "bytes" + "testing" +) + +func TestRoundTrip(t *testing.T) { + all := make([]byte, 256) + for i := range all { + all[i] = byte(i) + } + for _, cp := range []int{1252, 1251, 866, 437, 28591} { + e := ByCodePage(cp) + if e == nil { + t.Errorf("no code page %d", cp) + continue + } + if got := e.Encode(e.Decode(all)); !bytes.Equal(got, all) { + t.Errorf("%s: bytes change on decode and encode", e.Name) + } + } +} + +func TestEncodeUnknown(t *testing.T) { + e := Lookup("windows-1251") + if e == nil { + t.Fatal("no windows-1251") + } + if got := string(e.Encode("Ж€你")); got != "\xc6\x88?" { + t.Errorf("got %q", got) + } + if Lookup("utf-8") != UTF8 || Lookup("koi8-r") == nil || Lookup("x-mac-cyrillic") == nil { + t.Error("lookup by name") + } +} diff --git a/logo.webp b/logo.webp new file mode 100644 index 0000000..0bad112 Binary files /dev/null and b/logo.webp differ diff --git a/webone.conf b/webone.conf new file mode 100644 index 0000000..eb504b8 --- /dev/null +++ b/webone.conf @@ -0,0 +1,1358 @@ +; WebOne Configuration File +; Its format is like INI, but also can contain raw lists inside some sections. +; For binary options use: 1/0, y/n, yes/no, on/off, enable/disable, true/false. +; Help and documentation: https://github.com/atauenis/webone/wiki/Configuration-file + +[Server] +; Server settings +; Port=Port to listen for incoming connections +; IP=Interface used for listening for incoming connections (IP or IPv6 address), optional +; DefaultHostName=Proxy's host name (set to valid IP or domain name for use with/on Linux or macOS) +; Authenticate=Set if the proxy needs to be protected by "login:password" or leave blank +; OutputEncoding=Codepage for patched output content (list of available: http://localhost/!codepages/) +; CodepageCulture=Language for codepages used for specifying OutputEncoding +; UseMsHttpApi=Enable if you have problems with communicating with the proxy (but will disable SSL&FTP) +; HideClientErrors=Hide client connection error messages in log (for Netscape 3 PNG rejections) +; SearchInArchive=Enable searching for unavailable pages (Server Not Found or 404) in archive.org +; HideArchiveRedirect=Display archived pages just as they are still live +; ArchiveUrlSuffix=May be "fw_" to hide archive.org toolbar or "id_" to keep original links +; ShortenArchiveErrors=Enable shortening of 404s on web.archive.org to get off large scipts and images +; ArchiveDateLimit=Upper limit of date for web.archive.org archived pages +; EnableManualConverting=Allow manual run of file converters (will not affect converting in Edit Sets) +; SecurityProtocols=Forcely set SSL/TLS protocols that can be used for retrieving web content +; ValidateCertificates=Break network operations when the remote TLS certificate is bad +; MultipleHttp2Connections=Allow multiple HTTP/2 connections to servers +; RemoteHttpVersion=Version of HTTP(S) protocol, used to communicate with servers (min/max/exact) +; ConnectionTimeout=Timeout to wait before the remote connection establishing times out (secs) +; UpperProxy=Another proxy server, used by WebOne to connect to Internet (optional) +; UserAgent=Override user-agent string to fetch uncut content +; AllowHttpCompression=Uncomment & disable to fix work of WSUS or LegacyUpdate (but proxy will slow) +; TemporaryDirectory=Directory which should be used for temporary files (%TEMP%, $TEMP or any other) +; LogFile=Path to server log file. To use a log file without erasing, use AppendLogFile instead +; DisplayStatusPage=Set status page display style (no, short, full) or file name +; ContentDirectory=Location of internal pages' HTML (CSS, JS, GIF, etc) files +; DnsServer=(Go port) DNS server to look up sites with, e.g. the D-Modem BBS's (host:port) +Port=8080 +;IP=127.0.0.1 +DefaultHostName=%HostName% +;Authenticate=login:password +OutputEncoding=AsIs +;OutputEncoding=Windows +;OutputEncoding=DOS +;OutputEncoding=Apple +;CodepageCulture=ru +UseMsHttpApi=no +HideClientErrors=yes +SearchInArchive=yes +HideArchiveRedirect=yes +ArchiveUrlSuffix=fw_ +ShortenArchiveErrors=yes +;ArchiveDateLimit=20070101 +EnableManualConverting=yes +;SecurityProtocols=Tls, Tls11, Tls12 +ValidateCertificates=yes +MultipleHttp2Connections=yes +;RemoteHttpVersion=1.1 +ConnectionTimeout=30 +;UpperProxy=http://corporateproxyserver:80/ +;UpperProxy=no +UserAgent=%Original% WebOne/%WOVer% +;UserAgent=Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0 +;AllowHttpCompression=no +TemporaryDirectory=%TEMP% +;LogFile=%SYSLOGDIR%/webone.log +AppendLogFile=%SYSLOGDIR%/webone.log +DisplayStatusPage=short +;DisplayStatusPage=simple.htm +ContentDirectory=/html +;DnsServer=127.0.0.1:53 + + +[SecureProxy] +; HTTPS proxy options +; SslEnable=Enable Secure proxy mode +; SslCertificate=Path to CA Certificate file (PEM) +; SslPrivateKey=Path to CA Certificate Private Key file (PEM) +; SslProtocols=Versions of SSL/TLS used to communicate with clients (System.Security.Authentication.SslProtocols) +; SslCipherSuites=Long list of SSL/TLS cipher suites used to communicate with clients (System.Net.Security.TlsCipherSuite) +; SslRootValidAfter, SslRootValidBefore=Begin and end of life period of CA Certificate +; SslCertVaildBeforeNow, SslCertVaildAfterNow=Begin and end of life period of site certificates (relative to today) +; SslHashAlgorithm=Hashing algorithm for certificates (MD5, SHA1 is ok for old browsers; SHA256 for modern) +; SslSiteCerts=Path to site certificate files (if use external generator) +; SslSiteCertGenerator=External utility which will generate site certificates and private keys +; AllowNonHttpsCONNECT=Allow use HTTPS proxy tunnel (CONNECT method) with non-HTTPS protocols +; SslCaDirectory=(Go port) Sign with the D-Modem BBS's CA: its ca/ directory (proxy-ca.crt/.key from "bbs ca subca proxy") +; SslTrustOwnCA=(Go port) Also trust the proxy's CA for sites it fetches (the BBS's own HTTPS servers) +; (The Go port has no SSL 2.0 or 3.0: Go's TLS starts at TLS 1.0.) +SslEnable=yes +SslCertificate=%WOConfigDir%/ssl.crt +SslPrivateKey=%WOConfigDir%/ssl.key +SslProtocols=Tls, Tls11, Tls12 +;SslCipherSuites=TLS_RSA_WITH_NULL_MD5, TLS_RSA_WITH_RC4_128_MD5, TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_3DES_EDE_CBC_SHA +SslRootValidAfter=2019-05-20 00:00:00+0 +SslRootValidBefore=2037-12-31 23:59:59+0 +SslCertVaildBeforeNow=-7 +SslCertVaildAfterNow=7 +SslHashAlgorithm=SHA1 +;SslSiteCerts=/var/webone/ssl/%Subject% +;SslSiteCertGenerator=openssl --do --some-magic /var/webone/ssl/%Subject% --ca %WOConfigDir%/ssl.crt +AllowNonHttpsCONNECT=true +;SslCaDirectory=/var/lib/bbs/ca +;SslTrustOwnCA=yes + + +[Variables] +; assign values to variable strings and constants +UA-Netscape="Mozilla/4.75 [en] (Windows NT 5.0; U)" +UA-Firefox="Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0" +UA-FirefoxAndroid="Mozilla/5.0 (Android 17; Mobile; LG-M255; rv:153.0) Gecko/153.0 Firefox/153.0" +UA-FirefoxWin7="Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0" +UA-Chrome="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36" +UA-MsEdge="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36 Edg/150.0.0.0" + + +[ForceHttps] +; list of domains that should be always accessed via HTTPS +phantom.sannata.org +www.phantom.sannata.org +dl2.old-games.su +login.vk.com +m.vk.com +vk.com +webdav +webdav.yandex.ru +web.archive.org +googlevideo.com +commondatastorage.googleapis.com +u.icq.net +msnmsgr.escargot.chat +rutracker.org +www.vogons.org + + + +[ForceUtf8] +; list of URLs that should be always downloaded as UTF-8 +^http://.*yandex.ru/ + + +[TextTypes] +; list of MIME type mask that means files which should be patched during transfer +text/ +javascript +json +cdf +x-netcdf +x-cdf +xml + + +[Converters] +; Whitelist of known local format converters +convert %SRC% %ARG1% %DESTEXT%:- %ARG2% +magick %SRC% %ARG1% %DEST% %ARG2% +ffmpeg -i pipe: %ARG1% pipe: + + +; Save a dump of HTTP traffic +; Use only for debug purposes! +; uncomment section below to enable traffic sniffing +;[Edit] +;AddDumping=dump-%Url%.log + + +; Sets of traffic edits +[Edit:jquery.min.js] +; Redirect all requests to jQuery of versions other than 1.9.1 to Google's CDN with +; the last version supported by Firefox 3.6. This will not touch WebDAV traffic. +; Title: RegExp mask of URLs that should be touched by this Set of edits. +; IgnoreUrl: RegExp mask(s) of URLs which should NOT be touched by this Set of edits. +; OnUrl: additional URL RegExp masks not listed in section's title. +; AddRedirect: the destination URL of this redirection rule +IgnoreUrl=1.9.1 +IgnoreUrl=webdav +IgnoreUrl=php +OnUrl=jquery2.js +OnUrl=jquery-[0-9]*\.[0-9]*\.[0-9]*\.min\.js +IgnoreUrl=webdav +AddRedirect=http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js + +[Edit:jquery-ui.js] +; similar to jquery main file, but for jquery-ui +IgnoreUrl=1.9.1 +IgnoreUrl=webdav +IgnoreUrl=php +OnUrl=jquery-ui[a-z0-9\.\-]*.js +AddRedirect=http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js + +[Edit:bootstrap.min.js] +IgnoreUrl=2.3.1 +IgnoreUrl=webdav +IgnoreUrl=php +AddRedirect=http://maxcdn.bootstrapcdn.com/bootstrap/2.3.1/js/bootstrap.min.js + + +[Edit:(^http://.*/styles/prosilver/theme/)(.*)] +; downgrade stylesheets of phpBB proSilver skin to version 3.0 on old browsers +OnHeader=User-Agent: .*MSIE [3456] +OnHeader=User-Agent: Mozilla/3 +OnHeader=User-Agent: Mozilla/4 +IgnoreUrl=webdav +AddRedirect=http://atauenis.github.io/webone-webfixes/prosilver/theme/$2 + + +[Edit:^http://super8russia.ning.com] +; another example of redirect, but to Wayback Machine +; IgnoreUrl is not need here (the RegExp used here is quite detailed) +AddRedirect=http://web.archive.org/web/2010/%URL% + + +[Edit::443] +; another example of redirect, but with remove of 443 port (final murder of SSL) +; the redirect is internal (hidden, seamless) so we're using AddInternalRedirect here +AddInternalRedirect=%UrlNoPort% + +[Edit:^http://web.archive.org/web/([0-9]*)/(.*)] +; Disable Web Archive toolbar on archived pages +AddInternalRedirect=http://web.archive.org/web/$1fw_/$2 + +; Dead hosting providers +[Edit:^(http://www\.|http://)geocities.com/] +AddRedirect=http://web.archive.org/web/2008/%URL% + +[Edit:^http://web.ukonline.co.uk/] +AddRedirect=http://web.archive.org/web/2007/%URL% + +[Edit:^(http://www\.|http://)narod.ru/] +AddRedirect=http://web.archive.org/web/2012/http://narod.yandex.ru/%UrlNoDomain% + +[Edit:^http://narod.yandex.ru/] +AddRedirect=http://web.archive.org/web/2012/%URL% + +[Edit:^http://.*.by.ru/] +IgnoreUrl=web.archive.org +AddRedirect=http://web.archive.org/web/2011/%URL% + + +; Microsoft software interactivity +; Microsoft Internet Explorer +[Edit] +OnUrl=^(http://www\.|http://)microsoft.com/IE] +OnUrl=^(http://www\.|http://)microsoft.com/ie] +AddRedirect=http://web.archive.org/web/1997/%URL% + +[Edit:^(http://www\.|http://)iechannelguide.com] +AddRedirect=http://web.archive.org/web/1997/%URL% + +[Edit:^http://ie.search.msn.com/] +AddRedirect=http://web.archive.org/web/2000/%URL% + +[Edit:^(?:http://www\.|http://)microsoft.com/windows/ie/(.*)/download/rtw/x86/ie[0-9]sites.dat] +AddRedirect=http://atauenis.github.io/webone-webfixes/iesetup/SITES-$1.dat + +[Edit:^(?:http://www\.|http://)microsoft.com/ie/ie(.*)/download/rtw/x86/IE[0-9]SITES.DAT] +AddRedirect=http://atauenis.github.io/webone-webfixes/iesetup/SITES-$1.dat + +[Edit:^http://windowsupdate.microsoft.com/ident.cab] +AddInternalRedirect=http://web.archive.org/web/20040801000000/http://windowsupdate.microsoft.com/ident.cab + +[Edit:http://web.archive.org/web/0/http://mssjus.www.conxion.com/download/ie60/install/ie6_pp_refresh/w98nt42kme/en-us//MAILNEWS.CAB] +AddRedirect=http://web.archive.org/web/20010619061300/http://download.microsoft.com:80/download/IE60/Install/IE6/WIN98Me/EN-US/MAILNEWS.CAB + +[Edit:http://www.microsoft.com/ie/ie3setup/win31.asp] +AddRedirect=http://web.archive.org/web/19991012061034/http://microsoft.com/windows/ie/ie3setup/win31/default.htm + +[Edit:http://www.microsoft.com/ie/ie3setup/win95.asp] +AddRedirect=http://web.archive.org/web/19990508114332/http://www.microsoft.com/windows/ie/ie3setup/default.htm + +[Edit:http://www.microsoft.com/isapi/redir.dll?prd=windows98&clcid=&pver=4.10&ar=runonce] +AddRedirect=http://web.archive.org/web/20030801082935fw_/http://runonce.msn.com/en/runonce.asp + +[Edit:http://www.microsoft.com/isapi/redir.dll\?prd=windows98&clcid=0x0419&pver=4.10&ar=runonce] +AddRedirect=http://web.archive.org/web/20040406004224/http://runonce.msn.com/ru/runonce.asp + +[Edit:http://web.archive.org/web/20031204050930fw_/http://www.msn.com/runonce.asp] +AddRedirect=http://web.archive.org/web/20030801082935fw_/http://runonce.msn.com/en/runonce.asp + +[Edit:^http://runonce.msn.com/runonce3.aspx] +AddInternalRedirect=http://web.archive.org/web/20150112210507id_/http://runonce.msn.com/runonce3.aspx + +[Edit:^http://runonce.msn.com/wt_v3.js] +AddInternalRedirect=https://web.archive.org/web/20210507083740id_/http://runonce.msn.com/wt_v3.js + +[Edit:^http://runonce.msn.com/IE7LOC_V3/en/AP.js] +AddInternalRedirect=https://web.archive.org/web/20210507083734id_/http://runonce.msn.com/IE7LOC_V3/en/AP.js + +[Edit:^http://runonce.msn.com/.*\.png] +AddInternalRedirect=http://web.archive.org/web/2009im_/%URL% + +[Edit:^http://runonce.msn.com/.*\.css] +AddInternalRedirect=http://web.archive.org/web/2009id_/%URL% + +; Windows Vista +[Edit:^http://go.microsoft.com/fwlink/\?LinkId=58336] +AddRedirect=http://web.archive.org/web/20091227133434/http://www.microsoft.com:80/business/smb/en-hk/default.mspx + +[Edit:^http://g.msn.com/WMHFUSEN/101997.*] +AddRedirect=http://web.archive.org/web/20071029113251/http://www.windowsmarketplace.com/?WT.mc_id=0806_271 + +[Edit:^http://go.microsoft.com/fwlink/\?LinkId=68199] +AddRedirect=http://web.archive.org/web/20090531195910/http://www.microsoft.com/windows/ + +; Microsoft Data Access Components +[Edit:^http://www.microsoft.com/data/download.htm] +AddRedirect=http://web.archive.org/web/20030207190128/http://www.microsoft.com/data/download.htm + +; Microsoft Windows Media Player +[Edit:^http://windowsmedia.com/redir/mediaguide.asp\?WMPFriendly=true.*version=7.*] +AddRedirect=http://web.archive.org/web/20000815054018/http://windowsmedia.com/mediaguide/defaultalt.asp + +[Edit:^http://windowsmedia.com/redir/mediaguide.asp\?WMPFriendly=true.*version=8.*] +AddRedirect=http://web.archive.org/web/2002/http://windowsmedia.com/MediaGuide/Home + +[Edit:^http://windowsmedia.com/redir/mediaguide.asp\?WMPFriendly=true.*version=9.*] +AddRedirect=http://web.archive.org/web/2004/http://windowsmedia.com/MediaGuide/Home + +[Edit:^http://windowsmedia.com/redir/mediaguide.asp\?WMPFriendly=true.*version=10.*] +AddRedirect=http://web.archive.org/web/2006/http://windowsmedia.com/MediaGuide/Home + +[Edit:^http://windowsmedia.com/redir/radiotuner.asp\?WMPFriendly=true.*version=7.*] +AddRedirect=http://web.archive.org/web/20000511102520/http://windowsmedia.com/radiotuner/default.asp?WMPFriendly=true + +[Edit:^http://windowsmedia.com/redir/radiotuner.asp\?WMPFriendly=true.*version=8.*] +AddRedirect=http://web.archive.org/web/20020127155207/http://windowsmedia.com/mg/Radio.asp + +[Edit:^http://windowsmedia.com/redir/radiotuner.asp\?WMPFriendly=true.*version=9.*] +AddRedirect=http://web.archive.org/web/20070324112702/http://www.windowsmedia.com/mediaguide/Radio + +[Edit:^http://windowsmedia.com/redir/radiotuner.asp\?WMPFriendly=true.*version=10.*] +AddRedirect=http://web.archive.org/web/20070324112702/http://www.windowsmedia.com/mediaguide/Radio + +[Edit:^http://windowsmedia.com/redir/services.asp\?WMPFriendly=true] +AddRedirect=http://web.archive.org/web/20070503030453/http://www.windowsmedia.com/services/Services-Intl.asp?WMPFriendly=true + +[Edit:^http://www.microsoft.com/isapi/redir.dll\?Prd=windows&Sbp=MediaPlayer&Pver=7.0&Ar=Galleryredir.dll.*] +AddRedirect=http://web.archive.org/web/20010417185034/http://windowsmedia.com/mg/skins.asp + +[Edit:^http://go.microsoft.com/fwlink/\?LinkId=32129] +AddRedirect=http://onlinestores.metaservices.microsoft.com/serviceswitching/AllServices.aspx + +[Edit:^http://go.microsoft.com/fwlink/\?LinkId=28433.*version=10.0] +AddRedirect=http://onlinestores.metaservices.microsoft.com/serviceswitching/bas/BrowseAllServicesWMP10-1033.html + +[Edit:^http://go.microsoft.com/fwlink/\?LinkId=28433.*version=11.0.5] +AddRedirect=http://onlinestores.metaservices.microsoft.com/serviceswitching/bas/BrowseAllServicesWMPPL-1033.html + +[Edit:^http://go.microsoft.com/fwlink/\?LinkId=28433.*version=11.0.6] +AddRedirect=http://onlinestores.metaservices.microsoft.com/serviceswitching/bas/BrowseAllServicesWMPLH-1033.html + +[Edit:^http://go.microsoft.com/fwlink/\?LinkId=28433.*version=12.0] +AddRedirect=http://onlinestores.metaservices.microsoft.com/serviceswitching/bas/BrowseAllServicesWMP12-1033.html + +[Edit:^http://www.microsoft.com/windows/windowsmedia/player/faq/stores.mspx] +AddRedirect=http://web.archive.org/web/20090801080119/http://www.microsoft.com/windows/windowsmedia/player/faq/stores.mspx + +[Edit:^http://images.windowsmedia.com/svcswitch/] +AddRedirect=http://web.archive.org/web/0im_/%URL% + +[Edit:^http://windowsmedia.com/redir/GetMDRCD.asp\?(.*)] +AddRedirect=http://musicmatch-ssl.xboxlive.com/cdinfo/GetMDRCD.aspx?$1 + +[Edit:^http://redir.metaservices.microsoft.com/redir/getmdrcd.*\?(.*)] +AddRedirect=http://musicmatch-ssl.xboxlive.com/cdinfo/GetMDRCD.aspx?$1 + +[Edit:^http://[a-z]*.music.metaservices.microsoft.com/cdinfo/GetMDRCD.*\?(.*)] +AddRedirect=http://musicmatch-ssl.xboxlive.com/cdinfo/GetMDRCD.aspx?$1 + +[Edit:^http://.*?/https:/musicimage.xboxlive.com/(.*)] +AddRedirect=http://musicimage.xboxlive.com/$1 + +[Edit:^http://windowsmedia.com/redir/QueryTOC.asp\?.*?cd=(.*)] +IgnoreUrl=WMPFriendly +AddRedirect=http://cddb.retrobridge.org/tunes-cgi2/tunes/disc_info/203/cd=$1 + +[Edit:^(?:http://www\.|http://)www.microsoft.com/windows/windowsmedia/features/compression/] +AddRedirect=http://web.archive.org/web/20010101/%URL% + +[Edit:^http://codecs.microsoft.com/codecs/] +AddInternalRedirect=http://web.archive.org/web/2010/%URL% + +[Edit:^http://download.microsoft.com/download/C/A/0/CA0BE0D2-9C2C-4F52-8181-99A03BE96BB4/mpg4sdmo.CAB] +AddRedirect=http://web.archive.org/web/20070114231650/http://download.microsoft.com/download/0/8/D/08D91A3B-CFF6-45DE-95DF-64415075E344/mpg4sdmo.cab + +[Edit:^http://download.microsoft.com/download/F/C/6/FC636FA3-701B-4BA5-9D55-76CAC20A0C8D/mpg4sax.CAB] +AddRedirect=http://web.archive.org/web/0/http://codecs.microsoft.com/codecs/i386/mpg4sax.cab +;https://wiki.multimedia.cx/index.php/Talk:Microsoft, by http://activex.microsoft.com/objects/ocget.dll + +[Edit:^http://autoupdate.windowsmedia.com/update/update.asp\?LANG=(...)] +AddRedirect=http://web.archive.org/web/2/http://autoupdate.windowsmedia.com:80/update/$1/autoload.asp + +[Edit] +OnUrl=^http://[a-z\.]*windowsmedia.com/ +OnUrl=^http://windowsmedia.com/ +AddRedirect=http://web.archive.org/web/2002/%URL% + +;[Edit] +;OnUrl=^http://[a-z\.]*metaservices.microsoft.com +;AddRedirect=http://web.archive.org/web/2010/%URL% +;13.09.2022 - still works (WMP 10, 11) and not well archived + +; Windows CD Player +[Edit:^http://www.tunes.com/tunes-cgi2/tunes/disc_info/(.*)] +AddRedirect=http://cddb.retrobridge.org/tunes-cgi2/tunes/disc_info/$1 + +; Microsoft Windows Update +[Edit:^http://www.update.microsoft.com/windowsupdate.*] +OnUrl=^http://fe2.update.microsoft.com/windowsupdate.* +OnHeader=User-Agent: .*Windows [9M].* +AddRedirect=http://windowsupdaterestored.com/ + +[Edit:^http://www.update.microsoft.com/windowsupdate.*] +OnUrl=^http://fe2.update.microsoft.com/windowsupdate.* +OnHeader=User-Agent: .*Windows NT\) +AddRedirect=http://windowsupdaterestored.com/ + +[Edit:^http://www.update.microsoft.com/windowsupdate.*] +OnUrl=^http://fe2.update.microsoft.com/windowsupdate.* +OnHeader=User-Agent: .*Windows NT [56]* +AddRedirect=http://legacyupdate.net + +; Microsoft Office Update +[Edit:^http://officeupdate.microsoft.com/office/redirect/10/MSOfficeOnTheWeb.asp] +AddRedirect=http://web.archive.org/web/20021215132011/http://officeupdate.microsoft.com/office/redirect/10/english.htm?&path=msofficeontheweb.asp + +[Edit:^http://office.microsoft.com/officeupdate] +AddRedirect=http://web.archive.org/web/20050531233719fw_/%URL% + +[Edit:^http://office.microsoft.com/([a-z]*)/ProductUpdates/(.*)] +AddRedirect=http://web.archive.org/web/20020804172757/http://office.microsoft.com/$1/ProductUpdates/$2 + +[Edit:^http://officeupdate.microsoft.com/office/redirect/fromOffice9/MSOfficeOnTheWeb.htm.*] +AddRedirect=http://web.archive.org/web/0/http://officeupdate.microsoft.com:80/office/redirect/fromOffice9/english.htm?DPC=%7b00000409-78E1-11D2-B60F-006097C998E7%7d&DCC=%7bCC29E963-7BC2-11D1-A921-00A0C91E2AA2%7d&AppName=Microsoft+Word&HelpLCID=1033&path=msofficeontheweb.htm + +[Edit:^http://officeupdate.microsoft.com/office/redirect/10/] +AddRedirect=http://web.archive.org/web/2003/%URL% + +; Non-localzed pages and XML data +[Edit:^http://web.archive.org/web/.*/http://shell.windows.com/fileassoc/fileassoc1.asp\?LangID=(.*)&ext=(.*)] +OnCode=404 +AddRedirect=http://web.archive.org/web/2005/http://shell.windows.com/fileassoc/0409/xml/redir.asp?Ext=$2 + +[Edit] +OnUrl=^http://go.microsoft.com/fwlink/\?LinkId=57426&Ext=([a-zA-Z0-9\.]*) +AddRedirect=http://web.archive.org/web/2009/http://shell.windows.com/fileassoc/0409/xml/redir.asp?EXT=$1 + +[Edit:^http://web.archive.org/web/.*/http://shell.windows.com/publishwizard/] +OnCode=404 +AddRedirect=http://web.archive.org/web/20050615234639if_/http://shell.windows.com:80/publishwizard/usa.xml + +[Edit:^(http://web.archive.org/web/.*/http://onlinestores.metaservices.microsoft.com/bing/bing.xml)\?locale=] +OnCode=404 +AddRedirect=$1 + +; Microsoft Office +[Edit:^http://office.microsoft.com/office/redirect/10/services.asp] +AddRedirect=http://web.archive.org/web/20030417170535/http://office.microsoft.com/services/default.aspx + +[Edit:^http://office.microsoft.com/office/redirect/] +AddRedirect=http://web.archive.org/web/2003/%URL% + +[Edit:^http://mgn.microsoft.com/mg10/tools/] +AddRedirect=http://web.archive.org/web/20011213221110fw_/http://mgn.microsoft.com/mg10/tools/ + +[Edit:^http://mgn.microsoft.com] +OnUrl=^http://insertmedia.office.microsoft.com/clipart/dglx.aspx +AddInternalRedirect=http://web.archive.org/web/20031016195742id_/http://office.microsoft.com/clipart/dglx.aspx + +[Edit:^http://mgn.microsoft.com] +AddRedirect=http://web.archive.org/web/2001/%URL% + +[Edit:^http://r.office.microsoft.com/r/hlidOfficeHomeFromClient] +AddRedirect=http://web.archive.org/web/20060131190549fw_/http://office.microsoft.com/en-us/default.aspx + +[Edit:^http://r.office.microsoft.com/r/hlidAsstWordFromClient] +AddRedirect=http://web.archive.org/web/20060411234706fw_/http://office.microsoft.com/en-us/assistance/CH790018161033.aspx + +[Edit:^http://r.office.microsoft.com/r/hlidAsstExclFromClient] +AddRedirect=http://web.archive.org/web/20060423213900fw_/http://office.microsoft.com/en-us/assistance/CH790018021033.aspx + +[Edit:^http://r.office.microsoft.com/r/hlidAsstPwrtFromClient] +AddRedirect=http://web.archive.org/web/20060428161000fw_/http://office.microsoft.com/en-us/assistance/CH790018081033.aspx + +[Edit:^http://r.office.microsoft.com/r/hlidAsstAccsFromClient] +AddRedirect=http://web.archive.org/web/20040831035152fw/http://office.microsoft.com/en-us/assistance/CH790018001033.aspx + +[Edit:^http://r.office.microsoft.com/r/hlidAsstOutkFromClient] +AddRedirect=http://web.archive.org/web/20060411161213fw_/http://office.microsoft.com/en-us/assistance/CH790018071033.aspx + +[Edit:^http://r.office.microsoft.com/r/hlidClipArtFromClient] +AddRedirect=http://web.archive.org/web/20040715073143fw_/http://office.microsoft.com/clipart/default.aspx + +[Edit:^http://r.office.microsoft.com/r/hlidTemplatesFromClient] +AddRedirect=http://web.archive.org/web/20060423225118fw_/http://office.microsoft.com/en-us/templates/default.aspx + +[Edit:^http://r.office.microsoft.com/r/rlidRRDirectory] +AddRedirect=http://web.archive.org/web/20090106065003fw_/http://office.microsoft.com/en-us/marketplace/EY010687411033.aspx + +[Edit:^http://r.office.microsoft.com/r/rlidMsoMoreSmartTags] +AddRedirect=http://web.archive.org/web/20100105050947fw_/http://office.microsoft.com/en-us/marketplace/EY010504821033.aspx + +[Edit:^http://r.office.microsoft.com/r/rlidOutlookDigitalID] +AddRedirect=http://web.archive.org/web/20040925031648fw_/http://office.microsoft.com:80/en-us/marketplace/EY010504841033.aspx + +[Edit:^http://r.office.microsoft.com/r/] +AddRedirect=http://web.archive.org/web/2006/%URL% + +; Microsoft Reader 2.0 +[Edit:^http://das.microsoft.com/activate] +AddRedirect=http://web.archive.org/web/20040803152319/http://www.microsoft.com/reader/en/update/default.asp + +; MSN Messenger Service +[Edit:^http://services.msn.com/svcs/mms/([a-zA-Z0-9]*)] +AddRedirect=http://web.archive.org/web/2004/http://services.msn.com/svcs/mms/$1.asp + +; Windows Live Toolbar +[Edit:^http://login.live.com/login.srf\?id=] +AddRedirect=https://web.archive.org/web/20110427073719id_/http://toolbar.live.com/signin.htm + +[Edit:^http://toolbar.live.com/] +AddRedirect=http://web.archive.org/web/2012/%URL% + +[Edit:^http://help.live.com/] +AddRedirect=http://web.archive.org/web/2012/%URL% + +[Edit:^http://home.live.com/] +AddRedirect=http://web.archive.org/web/2012/%URL% + +[Edit:^http://toolbar.msn.com/static/toolbar/ru-ru/manifest.cfg] +AddRedirect=http://web.archive.org/web/20040213021205/http://toolbar.msn.com:80/static/toolbar/en-us/manifest.cfg + +[Edit:^http://toolbar.msn.com/] +AddRedirect=http://web.archive.org/web/2003/%URL% + +; Microsoft - common +[Edit:^http://go.microsoft.com/] +AddRedirect=http://web.archive.org/web/2005/%URL% + +[Edit:^(http://www\.|http://)microsoft.com/isapi/] +AddRedirect=http://web.archive.org/web/2005/%URL% + +[Edit:^http://[a-z\.]*.windows.com/] +AddRedirect=http://web.archive.org/web/2005/%URL% + +[Edit:^http://g.msn.com/] +AddInternalRedirect=http://web.archive.org/web/2010id_/%URL% + +[Edit:^http://prodreg.microsoft.com/register.asp] +AddInternalRedirect=http://web.archive.org/web/2004fw_/%URL% + + + +; Netscape Communicator stuff +[Edit:^http://.*\.netscape.com/] +OnUrl=^http://netscape.com/ +IgnoreUrl=web.archive.org +OnHeader=User-Agent: Mozilla/5 +AddInternalRedirect=http://web.archive.org/web/2009id_/%URL% + +[Edit:^http://.*\.netscape.com/] +OnUrl=^http://netscape.com/ +IgnoreUrl=web.archive.org +OnHeader=User-Agent: Mozilla/4 +AddInternalRedirect=http://web.archive.org/web/2002id_/%URL% + +[Edit:^http://.*\.netscape.com/] +OnUrl=^http://netscape.com/ +IgnoreUrl=web.archive.org +OnHeader=User-Agent: Mozilla/3 +AddInternalRedirect=http://web.archive.org/web/1997id_/%URL% + +[Edit:^http://.*\.netscape.com/] +OnUrl=^http://netscape.com/ +IgnoreUrl=web.archive.org +OnHeader=User-Agent: Mozilla/2 +AddInternalRedirect=http://web.archive.org/web/1996id_/%URL% + +[Edit:^http://.*\.netscape.com/] +OnUrl=^http://netscape.com/ +IgnoreUrl=web.archive.org +OnHeader=User-Agent: Mozilla/1 +OnHeader=User-Agent: Mozilla/0 +AddInternalRedirect=http://web.archive.org/web/1995id_/%URL% + + +; Mozilla & Firefox stuff +[Edit:^http:\/\/[a-z\-]*.start.mozilla.com] +OnHeader=User-Agent: Mozilla\/5.*rv:1\.9\.[1-3] +AddInternalRedirect=http://web.archive.org/web/20101127020412/http://www.google.com/firefox + +[Edit:^http:\/\/[a-z\-]*.start2.mozilla.com] +OnHeader=User-Agent: Mozilla\/5.*rv:1\.9\.[1-3] +AddInternalRedirect=http://web.archive.org/web/20101127020412/http://www.google.com/firefox + +[Edit:^http:\/\/[a-z\-]*.start.mozilla.com] +OnHeader=User-Agent: Mozilla\/5.*rv:1\.9\.0 +AddInternalRedirect=http://web.archive.org/web/20080531193518/http://www.google.com/firefox + +[Edit:^http:\/\/[a-z\-]*.start2.mozilla.com] +OnHeader=User-Agent: Mozilla\/5.*rv:1\.9\.0 +AddInternalRedirect=http://web.archive.org/web/20080531193518/http://www.google.com/firefox + +[Edit:^http:\/\/[a-z\-]*.start.mozilla.com] +OnHeader=User-Agent: Mozilla\/5.*rv:1\.8 +AddInternalRedirect=http://web.archive.org/web/20080227003647/http://www.google.com/firefox + +[Edit:^http:\/\/[a-z\-]*.start2.mozilla.com] +OnHeader=User-Agent: Mozilla\/5.*rv:1\.8 +AddInternalRedirect=http://web.archive.org/web/20080227003647/http://www.google.com/firefox + +[Edit:^http:\/\/[a-z\-]*.start.mozilla.com] +OnHeader=User-Agent: Mozilla\/5.*rv:1.[0-7] +AddInternalRedirect=http://web.archive.org/web/20041130152007/http://www.google.com/firefox + +[Edit:^(http://www\.|http://)mozdev.org/(.*)] +AddInternalRedirect=http://web.archive.org/web/2010if_/http://mozdev.org/$2 + +[Edit:^http://.*\.mozdev.org] +IgnoreUrl=web.archive.org +AddRedirect=http://web.archive.org/web/2007if_/%URL% + +[Edit:^http://update.mozilla.org/] +AddRedirect=http://web.archive.org/web/20041110063619/%URL% + +[Edit:^http://addons.mozilla.org/] +OnHeader=User-Agent: Mozilla\/5.*rv:1.[0-7] +AddRedirect=http://web.archive.org/web/20050101/%URL% + +[Edit:^http://addons.mozilla.org/] +OnHeader=User-Agent: Mozilla\/5.*rv:1.8.0 +AddRedirect=http://web.archive.org/web/20070101/%URL% + +[Edit:^http://addons.mozilla.org/] +OnHeader=User-Agent: Mozilla\/5.*rv:1.8.1 +AddRedirect=http://web.archive.org/web/20080101/%URL% + +[Edit:^http://addons.mozilla.org/] +OnHeader=User-Agent: Mozilla\/5.*rv:1.9.0 +AddRedirect=http://web.archive.org/web/20100101/%URL% + +[Edit:^http://addons.mozilla.org/] +OnHeader=User-Agent: Mozilla\/5.*rv:1.9.[0-9] +AddRedirect=http://web.archive.org/web/2012/%URL% + +[Edit:^http://addons.mozilla.org/] +OnHeader=User-Agent: Mozilla\/5.*rv:[2-9] +AddRedirect=http://web.archive.org/web/2015/%URL% + +[Edit:^(http://www\.|http://)mozilla.ru/(.*)] +AddRedirect=http://mozilla-russia.org/$2 + +[Edit:^http://forum.mozilla.ru/(.*)] +AddRedirect=http://forum.mozilla-russia.org/$1 + + +; Opera stuff +[Edit:^http://www.opera.com/buy/] +AddRedirect=http://web.archive.org/web/20050801075133fw_/%UrlNoPort% + +[Edit:^http://my.opera.com] +OnHeader=User-Agent: .*Opera.7 +AddRedirect=http://web.archive.org/web/2004fw_/%URL% + +[Edit:^http://my.opera.com] +OnHeader=User-Agent: .*Opera.8 +AddRedirect=http://web.archive.org/web/2006fw_/%URL% + +[Edit:^http://my.opera.com] +OnHeader=User-Agent: .*Opera.9 +AddRedirect=http://web.archive.org/web/2009fw_/%URL% + +[Edit:^http://my.opera.com] +OnHeader=User-Agent: .*Opera.9.80 +AddRedirect=http://web.archive.org/web/2012fw_/%URL% + +[Edit:^http://redir.opera.com/community/skins/embedded/] +AddRedirect=http://web.archive.org/web/20110804224038/http://my.opera.com/community/customize/skins/embedded/ + +[Edit:^http://redir.opera.com/community/] +AddRedirect=http://web.archive.org/web/20130226143206/http://www.opera.com/community/ + +[Edit:^http://redir.opera.com/www.opera.com/support/] +AddRedirect=http://web.archive.org/web/20120802190035/http://www.opera.com/support + +[Edit:^http://widgets.opera.com/] +AddRedirect=http://web.archive.org/web/20130402011214/http://widgets.opera.com/ + + +; WinPlay3 links +[Edit:^http://www.iis.fhg.de/audio/] +AddRedirect=http://web.archive.org/web/1997fw_/%URL% + +[Edit:^http://www.iis.fhg.de/departs/amm/] +AddRedirect=http://web.archive.org/web/1997fw_/%URL% + + +; YouTube playback (in external player) +[Edit:^(http://www\.|http://)youtube.com/watch.*&dl] +AddRedirect=http://%Proxy%/!webvideo/?url=%Url% + +; YouTube playback (in browser) +[Edit:^((http://www\.|http://)youtube.com/watch.*)&play=(.*)] +AddRedirect=http://%Proxy%/!player/?url=$1&gui=1&prefer=$3 + +; YouTube playback (via original ViewTube) +[Edit:^(http://www\.|http://).*.googlevideo.com/] +AddConvert=ffmpeg +AddConvertArg1=-vcodec mpeg2video -acodec mp2 -f mpegts +AddResponseHeader=Content-Type: video/MP2T +; Choose right codecs which are correct for client PC and media player. + + +; Content patches +; Apply some edits to page's content. Here are two edits, in example: +; 1. Replace "eval()" with direct calls for IE3/4 +; 2. Fix work with _tmr JS variable in inline scripts (for IE4 too) +; AddFind: the find mask. +; AddReplace: the replacement. +[Edit:^http://old-dos.ru] +AddFind=eval\(('|")(.*?)\1\) +AddReplace=$2 +AddFind=var _tmr = _tmr .* \[\]; +AddReplace=var _tmr = _tmr; + +; Fixes for Microsoft Internet Explorer 4.0/5.x/6.0 Active Channels +; Fix links in all CDFs +[Edit] +OnContentType=application/x-netcdf +AddFind=\"(http:\\/\\/(?!web.archive.org)[^\"]*)\" +AddReplace=\"http://web.archive.org/web/1998/$1\" +[Edit:\.cdf$] +AddFind=\"(http:\\/\\/(?!web.archive.org)[^\"]*)\" +AddReplace=\"http://web.archive.org/web/1998/$1\" + +; Fix Channel Bar buttons (where URL doesn't end with ".cdf") +[Edit] +; Common +OnUrl=^http://www.iechannelguide.com/ +OnUrl=^http://www.microsoft.com/ie/ie40/ +OnUrl=^http://www.microsoft.com/ie_intl/ +; links from MS IE 4.01 SP2 +; Default Channel Setup (CHLEN-US.CAB) +OnUrl=^http://home.snap.com:8005/channel/cdf/0,6,home-0,00.cdf +OnUrl=^http://www.msnbc.com/tools/channel/msnbcsports-cdf.asp +OnUrl=^http://iechannel.quicken.com/iechannel/gencdf.cgi +OnUrl=^http://expedia.com/IEChannel/content/default.asp +OnUrl=^http://www.msnbc.com/tools/channel/msnbc-cdf.asp +OnUrl=^http://ie4cdf.pointcast.net/ie40/cdf/ie40cdf.dll +OnUrl=^http://warnerbros.entertaindom.com/cdf/wb.cgi +; Russian Channel Setup (CHLRU-RU.CAB) +OnUrl=^http://www.online.ru/channel/ +OnUrl=^http://www.cityline.ru/obs/ +OnUrl=^http://www.zdnet.ru/channels/default.asp +OnUrl=^http://www.weekend.ru/Channel/ +OnUrl=^http://channel.park.ru/intro.asp +OnUrl=^http://rbn.newstv.ru/intro.html +OnUrl=^http://www.rocit.ru/cdf/intro.htm +OnUrl=^http://www.izvestia.ru/ +OnUrl=^http://www.vinco.ru/channel/ +OnUrl=^http://www.algo.ru/channels/default.asp +; German Channel Setup (CHLDE-DE.CAB) +OnUrl=^http://www.wirtschaft-online.de/cgi-bin/channel.exe?fn=wocie&sfn=cdf +; Czech Channel Setup (CHLCS-CZ.CAB) +OnUrl=^http://muj.atlas.cz/cdf/ie40/atlas1.asp +OnUrl=^http://modrysvet.codalan.cz/new/asp/cdf-namodro.asp +; UK Channel Setup (CHLEN-UK.CAB) +OnUrl=^http://www.briefing.ft.com/cgi-bin/gen_cdf.pl +OnUrl=^http://www.uk.msn.com/cdf/msnukcdf.asp +; French Channel Setup (CHLFR-FR.CAB) +OnUrl=^http://www.toutenville.com/tev.asp? +; Belgian Channel Setup (CHLFR-BE.CAB) +OnUrl=^http://ch.advalvas.be/scripts/ch.dll +; Malaysian Channel Setup (CHLML-MY.CAB) +OnUrl=^http://active.asiaconnect.com.my/active/subscribe.asp +; Dutch Channel Setup (CHLNL-NL.CAB) - may be Holland? +OnUrl=^http://www.zaak.nl/scripts/channel/cdf.pl +; Taiwan Channel Setup (CHLZH-TW.CAB) +OnUrl=^http://www.icrt.com.tw/CHANNEL/icrt.asp +AddRedirect=http://web.archive.org/web/19990101if_/%URL% + +; Disable inline Web Archive scripts on pre-2012 browsers +[Edit:^http://web.archive.org/web/] +OnHeader=User-Agent: NCSA_Mosaic +OnHeader=User-Agent: Mozilla/[01234] +OnHeader=User-Agent: Mozilla/5.*rv:0 +OnHeader=User-Agent: Mozilla/5.*rv:1\. +OnHeader=User-Agent: Opera/ +OnHeader=User-Agent: .*Opera +OnHeader=User-Agent: IBM WebExplorer +OnHeader=User-Agent: xChaos_Arachne/ +OnHeader=User-Agent: .*DOS +OnHeader=User-Agent: .*Dos +AddFind= +AddReplace= + +; Disable inline Web Archive scripts on InternalRedirect pages +[Edit] +OnHeader=User-Agent: NCSA_Mosaic +OnHeader=User-Agent: Mozilla/[01234] +OnHeader=User-Agent: Mozilla/5.*rv:0 +OnHeader=User-Agent: Mozilla/5.*rv:1\. +OnHeader=User-Agent: Opera/ +OnHeader=User-Agent: .*Opera +OnHeader=User-Agent: xChaos_Arachne/ +OnHeader=User-Agent: .*DOS +OnHeader=User-Agent: .*Dos +AddFind=.* +AddReplace= +AddFind=