mirror of
https://github.com/D-Modem/WebOne-go.git
synced 2026-11-28 12:38:05 -08:00
Port WebOne 0.19.0 to Go
A Go translation of WebOne (github.com/atauenis/webone, commit e940b43), the HTTP 1.x proxy that lets old browsers use today's web: config loader with sets of edits and .NET regular expressions, the HTTP/1.0-1.1 server with keep-alive, HTTPS fetching and patching, code pages, the CONNECT proxy (MITM, pass-through, non-HTTP tunnels), the CA and site certificates (MD5/SHA-1 signing included), internal and error pages, Web Archive fallback, converters, web FTP client and online video. WebOne's licence, configuration files and html pages are kept. Go-only options: SslCaDirectory signs with the D-Modem BBS's proxy sub-CA (or its root), SslTrustOwnCA, and DnsServer. README lists the differences: no SSL 2.0/3.0 in Go's TLS, and the upstream bugs fixed on purpose. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B82eRRH4kntyPfrY1bFWC3
This commit is contained in:
271 files changed
+11967
-1
No files matched your search
@@ -0,0 +1,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: "<p>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.</p>",
|
||||
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(`([=><a])[u0-3][t\.][o0-9]`, s) {
|
||||
return s, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// ParseDate reads a date as .NET's DateTimeOffset.Parse would for the forms
|
||||
// in webone.conf ("2019-05-20 00:00:00+0"), or "now".
|
||||
func ParseDate(s string) (time.Time, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if strings.EqualFold(s, "now") {
|
||||
return time.Now(), nil
|
||||
}
|
||||
// "+0" and "+3" offsets: make them "+00:00"
|
||||
if m := rx.FindGroups(`^(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2})([+-])(\d{1,2})$`, s); m != nil {
|
||||
h, _ := strconv.Atoi(m[3])
|
||||
s = fmt.Sprintf("%s%s%02d:00", m[1], m[2], h)
|
||||
}
|
||||
layouts := []string{
|
||||
"2006-01-02 15:04:05-07:00", "2006-01-02T15:04:05-07:00", "2006-01-02 15:04:05Z07:00",
|
||||
time.RFC3339, "2006-01-02 15:04:05", "2006-01-02T15:04:05", "2006-01-02",
|
||||
time.RFC1123, time.RFC1123Z, time.RFC850, time.ANSIC, "01/02/2006 15:04:05", "01/02/2006",
|
||||
}
|
||||
for _, l := range layouts {
|
||||
if t, err := time.Parse(l, s); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("cannot read date %q", s)
|
||||
}
|
||||
|
||||
// CodePage resolves an OutputEncoding value: AsIs (nil), Windows/ANSI,
|
||||
// DOS/OEM, Mac/Apple, EBCDIC/IBM, ISO, or a code page name or number.
|
||||
func (c *Config) CodePage(cp string) *textenc.Encoding {
|
||||
switch strings.ToLower(strings.TrimSpace(cp)) {
|
||||
case "windows", "win", "ansi":
|
||||
if c.CodepageANSI != nil {
|
||||
return c.CodepageANSI
|
||||
}
|
||||
return textenc.FromCodePageOr(c.CodepageCulture.ANSI, textenc.ByCodePage(1252))
|
||||
case "dos", "oem", "ascii":
|
||||
if c.CodepageASCII != nil {
|
||||
return c.CodepageASCII
|
||||
}
|
||||
return textenc.FromCodePageOr(c.CodepageCulture.OEM, textenc.ByCodePage(437))
|
||||
case "mac", "apple":
|
||||
if c.CodepageMac != nil {
|
||||
return c.CodepageMac
|
||||
}
|
||||
return textenc.FromCodePageOr(c.CodepageCulture.Mac, textenc.ByCodePage(10000))
|
||||
case "ebcdic", "ibm":
|
||||
if c.CodepageEBCDIC != nil {
|
||||
return c.CodepageEBCDIC
|
||||
}
|
||||
return textenc.FromCodePageOr(c.CodepageCulture.EBCDIC, textenc.ByCodePage(37))
|
||||
case "iso", "iso-8859", "iso8859":
|
||||
return textenc.ISO(c.CodepageCulture.Lang)
|
||||
case "0", "asis", "":
|
||||
return nil
|
||||
}
|
||||
if e := textenc.Lookup(cp); e != nil {
|
||||
return e
|
||||
}
|
||||
logx.Server(true, "Warning: Unknown codepage %s, using AsIs.", cp)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Expand expands variables in s (global ones, then extra).
|
||||
func (c *Config) Expand(s string, extra *Vars) string { return Expand(s, c.Vars, extra) }
|
||||
|
||||
// configDirs is where WebOne looks for webone.conf and webone.conf.d.
|
||||
func defaultConfigDir() string {
|
||||
dir := "."
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
if d := os.Getenv("ProgramData"); d != "" && isDir(filepath.Join(d, "WebOne")) {
|
||||
dir = filepath.Join(d, "WebOne")
|
||||
}
|
||||
if d, err := os.UserConfigDir(); err == nil && isDir(filepath.Join(d, "WebOne")) {
|
||||
dir = filepath.Join(d, "WebOne")
|
||||
}
|
||||
default:
|
||||
home, _ := os.UserHomeDir()
|
||||
for _, d := range []string{"/etc/webone.conf.d/", filepath.Join(home, ".config/webone/"),
|
||||
"/Library/Application Support/WebOne/", filepath.Join(home, "Library/Application Support/WebOne/")} {
|
||||
if isDir(d) {
|
||||
dir = d
|
||||
}
|
||||
}
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func isDir(p string) bool {
|
||||
st, err := os.Stat(p)
|
||||
return err == nil && st.IsDir()
|
||||
}
|
||||
|
||||
func isFile(p string) bool {
|
||||
st, err := os.Stat(p)
|
||||
return err == nil && !st.IsDir()
|
||||
}
|
||||
|
||||
// FindConfigFile is the configuration file to use: custom if given, else
|
||||
// webone.conf in the current directory, the program's directory, the
|
||||
// user's configuration directory, or the system's.
|
||||
func FindConfigFile(custom string) (string, error) {
|
||||
if custom != "" {
|
||||
if isFile(custom) {
|
||||
abs, _ := filepath.Abs(custom)
|
||||
return abs, nil
|
||||
}
|
||||
return "", fmt.Errorf("custom configuration file is not found: %s", custom)
|
||||
}
|
||||
exeDir := "."
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
exeDir = filepath.Dir(exe)
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
var cands []string
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
cands = []string{`.\webone.conf`, filepath.Join(exeDir, "webone.conf")}
|
||||
if d, err := os.UserConfigDir(); err == nil {
|
||||
cands = append(cands, filepath.Join(d, "WebOne", "webone.conf"))
|
||||
}
|
||||
if d := os.Getenv("ProgramData"); d != "" {
|
||||
cands = append(cands, filepath.Join(d, "WebOne", "webone.conf"))
|
||||
}
|
||||
default:
|
||||
user := filepath.Join(home, ".config/webone/webone.conf")
|
||||
common := "/etc/webone.conf"
|
||||
if p := filepath.Join(home, "Library/Application Support/WebOne/webone.conf"); isFile(p) {
|
||||
user = p
|
||||
}
|
||||
if p := "/Library/Application Support/WebOne/webone.conf"; isFile(p) {
|
||||
common = p
|
||||
}
|
||||
cands = []string{"./webone.conf", filepath.Join(exeDir, "webone.conf"), user, common}
|
||||
}
|
||||
for _, p := range cands {
|
||||
if isFile(p) {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("cannot guess configuration file name; run webone with /full/path/to/webone.conf or create webone.conf in program directory")
|
||||
}
|
||||
|
||||
// TLSVersionName names a TLS version for the log.
|
||||
func TLSVersionName(v uint16) string {
|
||||
switch v {
|
||||
case tls.VersionTLS10:
|
||||
return "Tls"
|
||||
case tls.VersionTLS11:
|
||||
return "Tls11"
|
||||
case tls.VersionTLS12:
|
||||
return "Tls12"
|
||||
case tls.VersionTLS13:
|
||||
return "Tls13"
|
||||
}
|
||||
return fmt.Sprintf("0x%04x", v)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/logx"
|
||||
)
|
||||
|
||||
func TestParseOptionEscapes(t *testing.T) {
|
||||
o, err := ParseOption(`AddVariable="Name", "a \"quoted\"\tvalue"`, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if o.Key != "AddVariable" || len(o.Values) != 2 || o.Values[0] != "Name" || o.Values[1] != "a \"quoted\"\tvalue" {
|
||||
t.Errorf("got %q %q", o.Key, o.Values)
|
||||
}
|
||||
o, _ = ParseOption("Port=8080", "test")
|
||||
if o.Key != "Port" || o.Value != "8080" || o.Values != nil {
|
||||
t.Errorf("plain option: %+v", o)
|
||||
}
|
||||
}
|
||||
|
||||
func load(t *testing.T, text string) *Config {
|
||||
t.Helper()
|
||||
logx.SetConsole(io.Discard)
|
||||
c := New()
|
||||
c.LoadContent([]byte(text), "test.conf")
|
||||
if err := c.Process(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func TestLoadServerAndEdits(t *testing.T) {
|
||||
c := load(t, `
|
||||
[Server]
|
||||
Port=8088
|
||||
DefaultHostName=bbs.local
|
||||
OutputEncoding=Windows
|
||||
UserAgent=%Original% WebOne/%WOVer%
|
||||
|
||||
[ForceHttps]
|
||||
example.com
|
||||
|
||||
[Edit:^http://example\.com/]
|
||||
OnContentType=text/html
|
||||
AddFind=foo
|
||||
AddReplace=bar
|
||||
AddResponseHeader=X-Test: 1
|
||||
|
||||
[Edit:\.js$]
|
||||
AddRedirect=http://cdn.example/x.js
|
||||
`)
|
||||
if c.Port != 8088 || c.DefaultHostName != "bbs.local" {
|
||||
t.Errorf("server: %d %s", c.Port, c.DefaultHostName)
|
||||
}
|
||||
if c.OutputEncoding == nil || c.OutputEncoding.CodePage != c.CodepageCulture.ANSI {
|
||||
t.Errorf("OutputEncoding=Windows gave %v", c.OutputEncoding)
|
||||
}
|
||||
if len(c.ForceHttps) != 1 || c.ForceHttps[0] != "example.com" {
|
||||
t.Errorf("ForceHttps: %q", c.ForceHttps)
|
||||
}
|
||||
if v := c.Vars.Value("Proxy"); v != "bbs.local:8088" {
|
||||
t.Errorf("%%Proxy%% = %q", v)
|
||||
}
|
||||
if len(c.EditRules) != 2 {
|
||||
t.Fatalf("%d edit sets", len(c.EditRules))
|
||||
}
|
||||
set := c.EditRules[0]
|
||||
if len(set.ContentTypeMasks) != 1 || set.IsForRequest {
|
||||
t.Errorf("first set: %+v", set)
|
||||
}
|
||||
found := false
|
||||
for _, e := range set.Edits {
|
||||
if e.Action == AddFindReplace && e.Find == "foo" && e.Replace == "bar" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("AddFind+AddReplace not joined: %+v", set.Edits)
|
||||
}
|
||||
if !c.EditRules[1].IsForRequest {
|
||||
t.Error("a redirect set is for requests")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpand(t *testing.T) {
|
||||
g := NewVars()
|
||||
g.Set("Proxy", "bbs:80")
|
||||
g.Set("ProxyHost", "bbs")
|
||||
extra := NewVars()
|
||||
extra.Set("URL", "http://x/")
|
||||
got := Expand("%Proxy% %ProxyHost% %URL% $ProxyHost", g, extra)
|
||||
if !strings.HasPrefix(got, "bbs:80 bbs http://x/ bbs") {
|
||||
t.Errorf("Expand: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDate(t *testing.T) {
|
||||
for _, s := range []string{"2001-02-03", "2001-02-03T04:05:06", "2001-02-03T04:05:06+0", "2001-02-03T04:05:06Z"} {
|
||||
d, err := ParseDate(s)
|
||||
if err != nil || d.Year() != 2001 || d.Month() != 2 || d.Day() != 3 {
|
||||
t.Errorf("ParseDate(%q) = %v, %v", s, d, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/D-Modem/webone-go/internal/logx"
|
||||
"github.com/D-Modem/webone-go/internal/rx"
|
||||
)
|
||||
|
||||
// Condition rules of edit sets
|
||||
// (https://github.com/atauenis/webone/wiki/Sets-of-edits).
|
||||
const (
|
||||
OnUrl = "OnUrl"
|
||||
OnCode = "OnCode"
|
||||
IgnoreUrl = "IgnoreUrl"
|
||||
OnContentType = "OnContentType"
|
||||
OnHeader = "OnHeader"
|
||||
OnHostOS = "OnHostOS"
|
||||
OnHttpOnly = "OnHttpOnly"
|
||||
OnHttpsOnly = "OnHttpsOnly"
|
||||
OnUser = "OnUser"
|
||||
)
|
||||
|
||||
// Action rules of edit sets.
|
||||
const (
|
||||
AddRedirect = "AddRedirect"
|
||||
AddInternalRedirect = "AddInternalRedirect"
|
||||
AddFind = "AddFind"
|
||||
AddReplace = "AddReplace"
|
||||
AddFindReplace = "AddFindReplace"
|
||||
AddConvert = "AddConvert"
|
||||
AddConvertDest = "AddConvertDest"
|
||||
AddConvertArg1 = "AddConvertArg1"
|
||||
AddConvertArg2 = "AddConvertArg2"
|
||||
AddConverting = "AddConverting"
|
||||
AddRequestHeaderFind = "AddRequestHeaderFind"
|
||||
AddRequestHeaderReplace = "AddRequestHeaderReplace"
|
||||
AddRequestHeaderFindReplace = "AddRequestHeaderFindReplace"
|
||||
AddResponseHeaderFind = "AddResponseHeaderFind"
|
||||
AddResponseHeaderReplace = "AddResponseHeaderReplace"
|
||||
AddResponseHeaderFindReplace = "AddResponseHeaderFindReplace"
|
||||
AddHeaderDumping = "AddHeaderDumping"
|
||||
AddRequestDumping = "AddRequestDumping"
|
||||
AddDumping = "AddDumping"
|
||||
AddOutputEncoding = "AddOutputEncoding"
|
||||
AddTranslit = "AddTranslit"
|
||||
AddDebugPrint = "AddDebugPrint"
|
||||
AddHeader = "AddHeader"
|
||||
AddRequestHeader = "AddRequestHeader"
|
||||
AddResponseHeader = "AddResponseHeader"
|
||||
AddRequestHttpVersion = "AddRequestHttpVersion"
|
||||
AddResponseHttpVersion = "AddResponseHttpVersion"
|
||||
AddVariable = "AddVariable"
|
||||
)
|
||||
|
||||
// EditRule is one action of an edit set.
|
||||
type EditRule struct {
|
||||
Action string
|
||||
Value string // the value (parameters joined)
|
||||
Params []string // the quoted parameters, if any
|
||||
|
||||
// AddFindReplace, AddRequestHeaderFindReplace, AddResponseHeaderFindReplace
|
||||
Find, Replace string
|
||||
// AddConverting
|
||||
Converter, ConvertDest, ConvertArg1, ConvertArg2 string
|
||||
}
|
||||
|
||||
// EditSet is an [Edit] section: conditions, then the edits to make.
|
||||
type EditSet struct {
|
||||
Location string
|
||||
UrlMasks []string
|
||||
UrlIgnoreMasks []string
|
||||
ContentTypeMasks []string
|
||||
OnCode *int
|
||||
HttpOnly bool
|
||||
HttpsOnly bool
|
||||
HeaderMasks []string
|
||||
Users []string
|
||||
CorrectHostOS bool
|
||||
// IsForRequest: the set can be applied when the request is made, as
|
||||
// it needs nothing from the response
|
||||
IsForRequest bool
|
||||
Edits []EditRule
|
||||
}
|
||||
|
||||
// NewEditSet builds an edit set from an [Edit] or [Edit:mask] section.
|
||||
// authenticate and converters are what is configured so far, for warnings.
|
||||
func NewEditSet(s *Section, c *Config) (*EditSet, error) {
|
||||
e := &EditSet{Location: s.Location, CorrectHostOS: true}
|
||||
mayBeForResponse := false
|
||||
if s.HasMask {
|
||||
if err := checkRegExp(s.Mask, s.Location); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.UrlMasks = append(e.UrlMasks, s.Mask)
|
||||
}
|
||||
for _, line := range s.Options {
|
||||
if !line.HasKeyValue() {
|
||||
continue
|
||||
}
|
||||
switch line.Key {
|
||||
case OnUrl:
|
||||
if err := checkRegExp(line.Value, line.Location); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.UrlMasks = append(e.UrlMasks, line.Value)
|
||||
continue
|
||||
case OnCode:
|
||||
n, err := strconv.Atoi(strings.TrimSpace(line.Value))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bad OnCode at %s", line.Location)
|
||||
}
|
||||
e.OnCode = &n
|
||||
continue
|
||||
case IgnoreUrl:
|
||||
if err := checkRegExp(line.Value, line.Location); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.UrlIgnoreMasks = append(e.UrlIgnoreMasks, line.Value)
|
||||
continue
|
||||
case OnContentType:
|
||||
if err := checkRegExp(line.Value, line.Location); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.ContentTypeMasks = append(e.ContentTypeMasks, line.Value)
|
||||
continue
|
||||
case OnHeader:
|
||||
if err := checkRegExp(line.Value, line.Location); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.HeaderMasks = append(e.HeaderMasks, line.Value)
|
||||
continue
|
||||
case OnHostOS:
|
||||
switch strings.ToLower(line.Value) {
|
||||
case "windows":
|
||||
e.CorrectHostOS = runtime.GOOS == "windows"
|
||||
case "linux":
|
||||
e.CorrectHostOS = runtime.GOOS == "linux"
|
||||
case "macos":
|
||||
e.CorrectHostOS = runtime.GOOS == "darwin"
|
||||
default:
|
||||
logx.Server(true, "Warning: unknown host OS \"%s\", edit set disabled.", line.Value)
|
||||
e.CorrectHostOS = false
|
||||
}
|
||||
continue
|
||||
case OnHttpOnly:
|
||||
e.HttpOnly = ToBool(line.Value)
|
||||
continue
|
||||
case OnHttpsOnly:
|
||||
e.HttpsOnly = ToBool(line.Value)
|
||||
continue
|
||||
case OnUser:
|
||||
for _, user := range line.ValuesOrValue() {
|
||||
e.Users = append(e.Users, user)
|
||||
found := false
|
||||
for _, reg := range c.Authenticate {
|
||||
if strings.HasPrefix(reg, user+":") {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
logx.Server(true, "Warning: unknown user \"%s\" at %s.", user, line.Location)
|
||||
}
|
||||
}
|
||||
continue
|
||||
|
||||
case AddRedirect, AddInternalRedirect, AddFind, AddReplace:
|
||||
if err := checkRegExp(line.Value, line.Location); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.Edits = append(e.Edits, EditRule{Action: line.Key, Value: line.Value})
|
||||
case AddConvert, AddConvertDest, AddConvertArg1, AddConvertArg2,
|
||||
AddRequestHeaderFind, AddRequestHeaderReplace, AddResponseHeaderFind, AddResponseHeaderReplace,
|
||||
AddHeaderDumping, AddRequestDumping, AddDumping, AddOutputEncoding, AddTranslit, AddDebugPrint:
|
||||
e.Edits = append(e.Edits, EditRule{Action: line.Key, Value: line.Value, Params: line.ValuesOrValue()})
|
||||
case AddHeader, AddRequestHeader, AddResponseHeader:
|
||||
if strings.Contains(line.Value, ": ") {
|
||||
e.Edits = append(e.Edits, EditRule{Action: line.Key, Value: line.Value, Params: line.ValuesOrValue()})
|
||||
} else {
|
||||
logx.Server(true, "Warning: Incorrect HTTP header at %s. Line ignored.", line.Location)
|
||||
}
|
||||
case AddRequestHttpVersion:
|
||||
if v, ok := ParseHTTPVersionRule(line.Value); ok {
|
||||
e.Edits = append(e.Edits, EditRule{Action: AddRequestHttpVersion, Value: v})
|
||||
} else {
|
||||
logx.Server(true, "Warning: Incorrect HTTP version at %s. Line ignored.", line.Location)
|
||||
}
|
||||
case AddResponseHttpVersion:
|
||||
if _, _, ok := ParseVersion(line.Value); ok {
|
||||
e.Edits = append(e.Edits, EditRule{Action: line.Key, Value: line.Value})
|
||||
} else {
|
||||
logx.Server(true, "Warning: Incorrect HTTP version at %s. Line ignored.", line.Location)
|
||||
}
|
||||
case AddVariable:
|
||||
p := line.ValuesOrValue()
|
||||
switch len(p) {
|
||||
case 2, 3:
|
||||
e.Edits = append(e.Edits, EditRule{Action: line.Key, Value: line.Value, Params: p})
|
||||
case 4:
|
||||
if n, err := strconv.Atoi(p[3]); err == nil && n >= 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
|
||||
}
|
||||
@@ -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 + "]" }
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user