wrp/wrp.go

331 lines
10 KiB
Go
Raw Normal View History

2019-05-30 01:53:05 +00:00
//
// WRP - Web Rendering Proxy
//
// Copyright (c) 2013-2018 Antoni Sawicki
// Copyright (c) 2019 Google LLC
//
2019-05-29 08:29:01 +00:00
package main
import (
"bytes"
2019-05-29 08:52:28 +00:00
"context"
"flag"
"fmt"
"image/gif"
"image/png"
2019-05-29 08:52:28 +00:00
"log"
2019-05-30 09:03:17 +00:00
"math/rand"
2019-05-29 08:52:28 +00:00
"net/http"
"net/url"
2019-07-17 05:29:35 +00:00
"os"
"os/signal"
2019-05-29 08:52:28 +00:00
"strconv"
"strings"
2019-07-17 05:29:35 +00:00
"syscall"
2019-05-29 08:52:28 +00:00
"time"
2019-05-29 08:29:01 +00:00
2019-08-13 06:35:29 +00:00
"github.com/chromedp/cdproto/css"
2019-05-29 09:39:06 +00:00
"github.com/chromedp/cdproto/emulation"
2019-05-29 08:52:28 +00:00
"github.com/chromedp/chromedp"
"github.com/ericpauley/go-quantize/quantize"
2019-05-29 08:29:01 +00:00
)
var (
2019-08-04 16:21:17 +00:00
version = "4.4"
2019-06-18 06:53:22 +00:00
srv http.Server
2019-06-04 08:23:46 +00:00
ctx context.Context
cancel context.CancelFunc
2019-06-02 23:19:08 +00:00
gifmap = make(map[string]bytes.Buffer)
2019-07-11 06:58:40 +00:00
ismap = make(map[string]wrpReq)
nodel bool
2019-05-29 08:29:01 +00:00
)
2019-07-11 06:58:40 +00:00
type wrpReq struct {
2019-06-26 00:07:43 +00:00
U string // url
W int64 // width
H int64 // height
S float64 // scale
C int64 // #colors
2019-07-10 08:01:40 +00:00
X int64 // mouseX
Y int64 // mouseY
K string // keys to send
F string // Fn buttons
2019-06-26 00:07:43 +00:00
}
2019-06-24 07:40:34 +00:00
2019-07-11 06:58:40 +00:00
func (w *wrpReq) parseForm(req *http.Request) {
2019-06-26 00:07:43 +00:00
req.ParseForm()
2019-07-11 06:58:40 +00:00
w.U = req.FormValue("url")
if len(w.U) > 1 && !strings.HasPrefix(w.U, "http") {
w.U = fmt.Sprintf("http://www.google.com/search?q=%s", url.QueryEscape(w.U))
2019-06-26 00:07:43 +00:00
}
2019-07-11 06:58:40 +00:00
w.W, _ = strconv.ParseInt(req.FormValue("w"), 10, 64)
if w.W < 10 {
w.W = 1152
2019-05-31 01:08:48 +00:00
}
2019-07-11 06:58:40 +00:00
w.H, _ = strconv.ParseInt(req.FormValue("h"), 10, 64)
if w.H < 10 {
w.H = 600
2019-05-29 08:52:28 +00:00
}
2019-07-11 06:58:40 +00:00
w.S, _ = strconv.ParseFloat(req.FormValue("s"), 64)
if w.S < 0.1 {
w.S = 1.0
2019-05-31 01:08:48 +00:00
}
2019-07-11 06:58:40 +00:00
w.C, _ = strconv.ParseInt(req.FormValue("c"), 10, 64)
if w.C < 2 || w.C > 256 {
w.C = 256
2019-06-03 00:06:41 +00:00
}
w.K = req.FormValue("k")
w.F = req.FormValue("Fn")
2019-07-14 08:53:33 +00:00
log.Printf("%s WrpReq from Form: %+v\n", req.RemoteAddr, w)
2019-06-26 00:07:43 +00:00
}
2019-08-13 06:35:29 +00:00
func (w wrpReq) printPage(out http.ResponseWriter, bgcolor string) {
2019-07-17 05:47:23 +00:00
out.Header().Set("Cache-Control", "max-age=0")
out.Header().Set("Expires", "-1")
out.Header().Set("Pragma", "no-cache")
2019-05-29 08:52:28 +00:00
out.Header().Set("Content-Type", "text/html")
2019-06-02 23:24:46 +00:00
fmt.Fprintf(out, "<!-- Web Rendering Proxy Version %s -->\n", version)
2019-08-13 06:35:29 +00:00
fmt.Fprintf(out, "<HTML>\n<HEAD><TITLE>WRP %s</TITLE></HEAD>\n<BODY BGCOLOR=\"%s\">\n", w.U, bgcolor)
fmt.Fprintf(out, "<FORM ACTION=\"/\" METHOD=\"POST\">\n")
fmt.Fprintf(out, "<INPUT TYPE=\"TEXT\" NAME=\"url\" VALUE=\"%s\" SIZE=\"10\">", w.U)
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" VALUE=\"Go\">\n")
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"Bk\">\n")
2019-07-11 06:58:40 +00:00
fmt.Fprintf(out, "W <INPUT TYPE=\"TEXT\" NAME=\"w\" VALUE=\"%d\" SIZE=\"4\"> \n", w.W)
fmt.Fprintf(out, "H <INPUT TYPE=\"TEXT\" NAME=\"h\" VALUE=\"%d\" SIZE=\"4\"> \n", w.H)
fmt.Fprintf(out, "S <INPUT TYPE=\"TEXT\" NAME=\"s\" VALUE=\"%1.2f\" SIZE=\"3\"> \n", w.S)
fmt.Fprintf(out, "C <INPUT TYPE=\"TEXT\" NAME=\"c\" VALUE=\"%d\" SIZE=\"3\">\n", w.C)
fmt.Fprintf(out, "K <INPUT TYPE=\"TEXT\" NAME=\"k\" VALUE=\"\" SIZE=\"4\"> \n")
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"Bs\">\n")
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"Rt\">\n")
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"&lt;\">\n")
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"^\">\n")
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"v\">\n")
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"&gt;\" SIZE=\"1\">\n")
2019-06-04 08:20:41 +00:00
fmt.Fprintf(out, "</FORM><BR>\n")
2019-06-26 08:07:13 +00:00
}
2019-07-11 06:58:40 +00:00
func (w wrpReq) printFooter(out http.ResponseWriter) {
2019-08-04 16:08:23 +00:00
fmt.Fprintf(out, "\n<P><FONT SIZE=\"-2\"><A HREF=\"/?url=https://github.com/tenox7/wrp/&w=%d&h=%d&s=%1.2f&c=%d\">"+
"Web Rendering Proxy Version %s</A> | <A HREF=\"/shutdown/\">Shutdown WRP</A></FONT></BODY>\n</HTML>\n", w.W, w.H, w.S, w.C, version)
2019-06-26 08:07:13 +00:00
}
func pageServer(out http.ResponseWriter, req *http.Request) {
log.Printf("%s Page Request for %s [%+v]\n", req.RemoteAddr, req.URL.Path, req.URL.RawQuery)
2019-07-11 06:58:40 +00:00
var w wrpReq
w.parseForm(req)
2019-07-11 01:09:20 +00:00
2019-07-11 06:58:40 +00:00
if len(w.U) > 4 {
w.capture(req.RemoteAddr, out)
2019-07-11 01:09:20 +00:00
} else {
2019-08-13 06:35:29 +00:00
w.printPage(out, "#FFFFFF")
2019-07-11 06:58:40 +00:00
w.printFooter(out)
2019-06-26 08:07:13 +00:00
}
}
func mapServer(out http.ResponseWriter, req *http.Request) {
log.Printf("%s ISMAP Request for %s [%+v]\n", req.RemoteAddr, req.URL.Path, req.URL.RawQuery)
2019-07-11 06:58:40 +00:00
w, ok := ismap[req.URL.Path]
2019-06-26 08:07:13 +00:00
if !ok {
fmt.Fprintf(out, "Unable to find map %s\n", req.URL.Path)
log.Printf("Unable to find map %s\n", req.URL.Path)
return
}
if !nodel {
defer delete(ismap, req.URL.Path)
}
2019-07-11 06:58:40 +00:00
n, err := fmt.Sscanf(req.URL.RawQuery, "%d,%d", &w.X, &w.Y)
2019-07-10 08:01:40 +00:00
if err != nil || n != 2 {
fmt.Fprintf(out, "n=%d, err=%s\n", n, err)
log.Printf("%s ISMAP n=%d, err=%s\n", req.RemoteAddr, n, err)
return
}
2019-07-11 06:58:40 +00:00
log.Printf("%s WrpReq from ISMAP: %+v\n", req.RemoteAddr, w)
if len(w.U) > 4 {
w.capture(req.RemoteAddr, out)
2019-07-11 01:09:20 +00:00
} else {
2019-08-13 06:35:29 +00:00
w.printPage(out, "#FFFFFF")
2019-07-11 06:58:40 +00:00
w.printFooter(out)
2019-06-26 08:07:13 +00:00
}
2019-05-29 08:29:01 +00:00
}
func imgServer(out http.ResponseWriter, req *http.Request) {
2019-06-01 01:20:55 +00:00
log.Printf("%s IMG Request for %s\n", req.RemoteAddr, req.URL.Path)
2019-06-03 05:23:41 +00:00
gifbuf, ok := gifmap[req.URL.Path]
if !ok || gifbuf.Bytes() == nil {
fmt.Fprintf(out, "Unable to find image %s\n", req.URL.Path)
log.Printf("Unable to find image %s\n", req.URL.Path)
return
}
if !nodel {
defer delete(gifmap, req.URL.Path)
}
2019-05-30 01:02:29 +00:00
out.Header().Set("Content-Type", "image/gif")
out.Header().Set("Content-Length", strconv.Itoa(len(gifbuf.Bytes())))
2019-07-17 05:47:23 +00:00
out.Header().Set("Cache-Control", "max-age=0")
out.Header().Set("Expires", "-1")
out.Header().Set("Pragma", "no-cache")
2019-05-30 01:02:29 +00:00
out.Write(gifbuf.Bytes())
2019-05-30 09:03:17 +00:00
out.(http.Flusher).Flush()
2019-05-29 08:29:01 +00:00
}
2019-07-11 06:58:40 +00:00
func (w wrpReq) capture(c string, out http.ResponseWriter) {
2019-05-30 09:03:17 +00:00
var pngbuf []byte
var gifbuf bytes.Buffer
2019-07-10 08:01:40 +00:00
var err error
2019-08-13 06:35:29 +00:00
var styles []*css.ComputedProperty
var r, g, b int
2019-07-10 08:01:40 +00:00
2019-07-11 06:58:40 +00:00
if w.X > 0 && w.Y > 0 {
log.Printf("%s Mouse Click %d,%d\n", c, w.X, w.Y)
err = chromedp.Run(ctx, chromedp.MouseClickXY(int64(float64(w.X)/w.S), int64(float64(w.Y)/w.S)))
} else if len(w.F) > 0 {
log.Printf("%s Button %v\n", c, w.F)
switch w.F {
case "Bk":
err = chromedp.Run(ctx, chromedp.NavigateBack())
case "Bs":
err = chromedp.Run(ctx, chromedp.KeyEvent("\b"))
case "Rt":
err = chromedp.Run(ctx, chromedp.KeyEvent("\r"))
case "<":
err = chromedp.Run(ctx, chromedp.KeyEvent("\u0302"))
case "^":
err = chromedp.Run(ctx, chromedp.KeyEvent("\u0304"))
case "v":
err = chromedp.Run(ctx, chromedp.KeyEvent("\u0301"))
case ">":
err = chromedp.Run(ctx, chromedp.KeyEvent("\u0303"))
}
} else if len(w.K) > 0 {
log.Printf("%s Sending Keys: %#v\n", c, w.K)
2019-07-13 07:42:27 +00:00
err = chromedp.Run(ctx, chromedp.KeyEvent(w.K))
2019-07-10 08:01:40 +00:00
} else {
2019-07-11 06:58:40 +00:00
log.Printf("%s Processing Capture Request for %s\n", c, w.U)
2019-07-10 08:01:40 +00:00
err = chromedp.Run(ctx,
2019-07-11 06:58:40 +00:00
emulation.SetDeviceMetricsOverride(int64(float64(w.W)/w.S), int64(float64(w.H)/w.S), w.S, false),
chromedp.Navigate(w.U),
)
2019-07-10 08:01:40 +00:00
}
2019-05-31 07:41:46 +00:00
if err != nil {
if err.Error() == "context canceled" {
log.Printf("%s Contex cancelled, try again", c)
fmt.Fprintf(out, "<BR>%s<BR> -- restarting, try again", err)
ctx, cancel = chromedp.NewContext(context.Background())
} else {
log.Printf("%s %s", c, err)
fmt.Fprintf(out, "<BR>%s<BR>", err)
}
2019-06-17 07:21:32 +00:00
return
2019-05-31 07:41:46 +00:00
}
2019-08-13 06:35:29 +00:00
chromedp.Run(ctx,
chromedp.Sleep(time.Second*2),
chromedp.ComputedStyle("body", &styles, chromedp.ByQuery),
chromedp.Location(&w.U),
)
log.Printf("%s Landed on: %s\n", c, w.U)
2019-08-13 06:35:29 +00:00
for _, style := range styles {
if style.Name == "background-color" {
fmt.Sscanf(style.Value, "rgb(%d,%d,%d)", &r, &g, &b)
}
}
w.printPage(out, fmt.Sprintf("#%02X%02X%02X", r, g, b))
2019-05-30 01:48:07 +00:00
2019-05-30 09:03:17 +00:00
// Process Screenshot Image
2019-06-24 07:40:34 +00:00
err = chromedp.Run(ctx, chromedp.CaptureScreenshot(&pngbuf))
if err != nil {
log.Printf("%s Failed to capture screenshot: %s\n", c, err)
fmt.Fprintf(out, "<BR>Unable to capture screenshot:<BR>%s<BR>\n", err)
return
}
2019-05-30 09:15:52 +00:00
bytes.NewReader(pngbuf).Seek(0, 0)
2019-05-30 09:03:17 +00:00
img, err := png.Decode(bytes.NewReader(pngbuf))
2019-05-30 01:48:07 +00:00
if err != nil {
2019-06-02 23:05:36 +00:00
log.Printf("%s Failed to decode screenshot: %s\n", c, err)
fmt.Fprintf(out, "<BR>Unable to decode page screenshot:<BR>%s<BR>\n", err)
return
2019-05-30 01:48:07 +00:00
}
gifbuf.Reset()
2019-07-11 06:58:40 +00:00
err = gif.Encode(&gifbuf, img, &gif.Options{NumColors: int(w.C), Quantizer: quantize.MedianCutQuantizer{}})
2019-05-30 07:53:59 +00:00
if err != nil {
2019-06-02 23:05:36 +00:00
log.Printf("%s Failed to encode GIF: %s\n", c, err)
2019-05-30 07:53:59 +00:00
fmt.Fprintf(out, "<BR>Unable to encode GIF:<BR>%s<BR>\n", err)
return
}
2019-05-29 08:29:01 +00:00
2019-06-26 08:07:13 +00:00
// Compose map and gif
seq := rand.Intn(9999)
imgpath := fmt.Sprintf("/img/%04d.gif", seq)
mappath := fmt.Sprintf("/map/%04d.map", seq)
gifmap[imgpath] = gifbuf
2019-07-11 06:58:40 +00:00
ismap[mappath] = w
log.Printf("%s Encoded GIF image: %s, Size: %dKB, Colors: %d\n", c, imgpath, len(gifbuf.Bytes())/1024, w.C)
fmt.Fprintf(out, "<A HREF=\"%s\"><IMG SRC=\"%s\" BORDER=\"0\" ISMAP></A>", mappath, imgpath)
2019-07-11 06:58:40 +00:00
w.printFooter(out)
log.Printf("%s Done with caputure for %s\n", c, w.U)
2019-05-29 08:29:01 +00:00
}
2019-06-18 06:53:22 +00:00
func haltServer(out http.ResponseWriter, req *http.Request) {
log.Printf("%s Shutdown Request for %s\n", req.RemoteAddr, req.URL.Path)
2019-07-17 05:47:23 +00:00
out.Header().Set("Cache-Control", "max-age=0")
out.Header().Set("Expires", "-1")
out.Header().Set("Pragma", "no-cache")
2019-08-04 07:39:21 +00:00
out.Header().Set("Content-Type", "text/plain")
2019-07-17 05:29:35 +00:00
fmt.Fprintf(out, "Shutting down WRP...\n")
out.(http.Flusher).Flush()
time.Sleep(time.Second * 2)
cancel()
2019-06-18 06:53:22 +00:00
srv.Shutdown(context.Background())
2019-07-17 05:47:23 +00:00
os.Exit(1)
2019-06-18 06:53:22 +00:00
}
2019-05-29 08:29:01 +00:00
func main() {
2019-05-29 08:52:28 +00:00
var addr string
var head, headless bool
var debug bool
2019-05-29 08:52:28 +00:00
flag.StringVar(&addr, "l", ":8080", "Listen address:port, default :8080")
flag.BoolVar(&head, "h", false, "Headed mode - display browser window")
flag.BoolVar(&debug, "d", false, "Debug ChromeDP")
flag.BoolVar(&nodel, "n", false, "Do not delete maps and gif images in memory")
2019-05-29 08:52:28 +00:00
flag.Parse()
if head {
headless = false
} else {
headless = true
}
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", headless),
2019-07-11 06:58:40 +00:00
chromedp.Flag("hide-scrollbars", false),
)
2019-07-17 05:29:35 +00:00
actx, acancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer acancel()
if debug {
2019-06-04 08:23:46 +00:00
ctx, cancel = chromedp.NewContext(actx, chromedp.WithDebugf(log.Printf))
} else {
2019-06-04 08:23:46 +00:00
ctx, cancel = chromedp.NewContext(actx)
}
defer cancel()
2019-05-30 09:03:17 +00:00
rand.Seed(time.Now().UnixNano())
2019-07-17 05:29:35 +00:00
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
log.Printf("Interrupt - shutting down.")
cancel()
srv.Shutdown(context.Background())
os.Exit(1)
}()
2019-05-29 08:52:28 +00:00
http.HandleFunc("/", pageServer)
2019-06-26 08:07:13 +00:00
http.HandleFunc("/map/", mapServer)
2019-05-30 09:03:17 +00:00
http.HandleFunc("/img/", imgServer)
2019-06-18 06:53:22 +00:00
http.HandleFunc("/shutdown/", haltServer)
2019-05-30 01:47:03 +00:00
http.HandleFunc("/favicon.ico", http.NotFound)
2019-06-02 23:24:46 +00:00
log.Printf("Web Rendering Proxy Version %s\n", version)
2019-05-31 06:40:43 +00:00
log.Printf("Starting WRP http server on %s\n", addr)
2019-06-18 06:53:22 +00:00
srv.Addr = addr
err := srv.ListenAndServe()
if err != nil {
log.Fatal(err)
}
2019-05-29 08:29:01 +00:00
}