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() + ")" }