source: code/trunk/morty.go@ 49

Last change on this file since 49 was 47, checked in by asciimoo, 9 years ago

Merge pull request #36 from dalf/head

svg, math, link and meta tags

File size: 18.9 KB
RevLine 
[1]1package main
2
3import (
4 "bytes"
5 "crypto/hmac"
6 "crypto/sha256"
7 "encoding/hex"
8 "errors"
9 "flag"
10 "fmt"
11 "io"
12 "log"
13 "net/url"
14 "regexp"
15 "strings"
[4]16 "time"
[1]17
18 "github.com/valyala/fasthttp"
19 "golang.org/x/net/html"
[45]20 "golang.org/x/net/html/charset"
21 "golang.org/x/text/encoding"
[1]22)
23
24const (
25 STATE_DEFAULT int = 0
26 STATE_IN_STYLE int = 1
27 STATE_IN_NOSCRIPT int = 2
28)
29
30var CLIENT *fasthttp.Client = &fasthttp.Client{
31 MaxResponseBodySize: 10 * 1024 * 1024, // 10M
32}
33
[27]34var CSS_URL_REGEXP *regexp.Regexp = regexp.MustCompile("url\\((['\"]?)[ \\t\\f]*([\u0009\u0021\u0023-\u0026\u0028\u002a-\u007E]+)(['\"]?)\\)?")
[1]35
36var UNSAFE_ELEMENTS [][]byte = [][]byte{
37 []byte("applet"),
38 []byte("canvas"),
39 []byte("embed"),
40 //[]byte("iframe"),
[46]41 []byte("math"),
[1]42 []byte("script"),
[46]43 []byte("svg"),
[1]44}
45
46var SAFE_ATTRIBUTES [][]byte = [][]byte{
47 []byte("abbr"),
48 []byte("accesskey"),
49 []byte("align"),
50 []byte("alt"),
[13]51 []byte("as"),
[1]52 []byte("autocomplete"),
53 []byte("charset"),
54 []byte("checked"),
55 []byte("class"),
56 []byte("content"),
57 []byte("contenteditable"),
58 []byte("contextmenu"),
59 []byte("dir"),
60 []byte("for"),
61 []byte("height"),
62 []byte("hidden"),
[46]63 []byte("hreflang"),
[1]64 []byte("id"),
65 []byte("lang"),
66 []byte("media"),
67 []byte("method"),
68 []byte("name"),
69 []byte("nowrap"),
70 []byte("placeholder"),
71 []byte("property"),
72 []byte("rel"),
73 []byte("spellcheck"),
74 []byte("tabindex"),
75 []byte("target"),
76 []byte("title"),
77 []byte("translate"),
78 []byte("type"),
79 []byte("value"),
80 []byte("width"),
81}
82
83var SELF_CLOSING_ELEMENTS [][]byte = [][]byte{
84 []byte("area"),
85 []byte("base"),
86 []byte("br"),
87 []byte("col"),
88 []byte("embed"),
89 []byte("hr"),
90 []byte("img"),
91 []byte("input"),
92 []byte("keygen"),
93 []byte("link"),
94 []byte("meta"),
95 []byte("param"),
96 []byte("source"),
97 []byte("track"),
98 []byte("wbr"),
99}
100
[46]101var LINK_REL_SAFE_VALUES [][]byte = [][]byte{
102 []byte("alternate"),
103 []byte("archives"),
104 []byte("author"),
105 []byte("copyright"),
106 []byte("first"),
107 []byte("help"),
108 []byte("icon"),
109 []byte("index"),
110 []byte("last"),
111 []byte("license"),
112 []byte("manifest"),
113 []byte("next"),
114 []byte("pingback"),
115 []byte("prev"),
116 []byte("publisher"),
117 []byte("search"),
118 []byte("shortcut icon"),
119 []byte("stylesheet"),
120 []byte("up"),
121}
122
123var LINK_HTTP_EQUIV_SAFE_VALUES [][]byte = [][]byte{
124 // X-UA-Compatible will be added automaticaly, so it can be skipped
125 []byte("date"),
126 []byte("last-modified"),
127 []byte("refresh"), // URL rewrite
128 // []byte("location"), TODO URL rewrite
129 []byte("content-language"),
130}
131
[1]132type Proxy struct {
[4]133 Key []byte
134 RequestTimeout time.Duration
[1]135}
136
137type RequestConfig struct {
138 Key []byte
[23]139 BaseURL *url.URL
[1]140}
141
[2]142var HTML_FORM_EXTENSION string = `<input type="hidden" name="mortyurl" value="%s" /><input type="hidden" name="mortyhash" value="%s" />`
[1]143
144var HTML_BODY_EXTENSION string = `
145<div id="mortyheader">
146 <input type="checkbox" id="mortytoggle" autocomplete="off" />
[36]147 <div><p>This is a proxified and sanitized view of the page,<br />visit <a href="%s" rel="noreferrer">original site</a>.</p><p><label for="mortytoggle">hide</label></p></div>
[1]148</div>
149<style>
[36]150#mortyheader { position: fixed; padding: 12px 12px 12px 0; margin: 0; box-sizing: content-box; top: 15%%; left: 0; max-width: 140px; color: #444; overflow: hidden; z-index: 110000; font-size: 12px; line-height: normal; }
151#mortyheader a { color: #3498db; font-weight: bold; }
152#mortyheader p { padding: 0 0 0.7em 0; margin: 0; }
153#mortyheader > div { padding: 8px; font-size: 12px !important; font-family: sans !important; border-width: 4px 4px 4px 0; border-style: solid; border-color: #1abc9c; background: #FFF; line-height: 1em; }
[5]154#mortyheader label { text-align: right; cursor: pointer; display: block; color: #444; padding: 0; margin: 0; }
[1]155input[type=checkbox]#mortytoggle { display: none; }
156input[type=checkbox]#mortytoggle:checked ~ div { display: none; }
157</style>
158`
159
[46]160var HTML_HEAD_CONTENT_TYPE string = `<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
161<meta http-equiv="X-UA-Compatible" content="IE=edge">
162`
[45]163
[1]164func (p *Proxy) RequestHandler(ctx *fasthttp.RequestCtx) {
[10]165
166 if appRequestHandler(ctx) {
167 return
168 }
169
[1]170 requestHash := popRequestParam(ctx, []byte("mortyhash"))
171
172 requestURI := popRequestParam(ctx, []byte("mortyurl"))
173
174 if requestURI == nil {
[35]175 p.serveMainPage(ctx, 200, nil)
[1]176 return
177 }
178
179 if p.Key != nil {
180 if !verifyRequestURI(requestURI, requestHash, p.Key) {
[35]181 // HTTP status code 403 : Forbidden
182 p.serveMainPage(ctx, 403, errors.New(`invalid "mortyhash" parameter`))
[1]183 return
184 }
185 }
186
187 parsedURI, err := url.Parse(string(requestURI))
188
[18]189 if strings.HasSuffix(parsedURI.Host, ".onion") {
[35]190 // HTTP status code 501 : Not Implemented
191 p.serveMainPage(ctx, 501, errors.New("Tor urls are not supported yet"))
[18]192 return
193 }
194
[11]195 if err != nil {
[35]196 // HTTP status code 500 : Internal Server Error
197 p.serveMainPage(ctx, 500, err)
[1]198 return
199 }
200
201 req := fasthttp.AcquireRequest()
202 defer fasthttp.ReleaseRequest(req)
[12]203 req.SetConnectionClose()
[1]204
[47]205 requestURIStr := string(requestURI)
[1]206
[47]207 log.Println("getting", requestURIStr)
[1]208
[47]209 req.SetRequestURI(requestURIStr)
[1]210 req.Header.SetUserAgentBytes([]byte("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"))
211
212 resp := fasthttp.AcquireResponse()
213 defer fasthttp.ReleaseResponse(resp)
214
215 req.Header.SetMethodBytes(ctx.Method())
216 if ctx.IsPost() || ctx.IsPut() {
217 req.SetBody(ctx.PostBody())
218 }
219
[11]220 err = CLIENT.DoTimeout(req, resp, p.RequestTimeout)
221
222 if err != nil {
[35]223 if err == fasthttp.ErrTimeout {
224 // HTTP status code 504 : Gateway Time-Out
225 p.serveMainPage(ctx, 504, err)
226 } else {
227 // HTTP status code 500 : Internal Server Error
228 p.serveMainPage(ctx, 500, err)
229 }
[1]230 return
231 }
232
233 if resp.StatusCode() != 200 {
234 switch resp.StatusCode() {
[7]235 case 301, 302, 303, 307, 308:
[1]236 loc := resp.Header.Peek("Location")
237 if loc != nil {
[23]238 rc := &RequestConfig{Key: p.Key, BaseURL: parsedURI}
239 url, err := rc.ProxifyURI(string(loc))
[1]240 if err == nil {
241 ctx.SetStatusCode(resp.StatusCode())
242 ctx.Response.Header.Add("Location", url)
243 log.Println("redirect to", string(loc))
244 return
245 }
246 }
247 }
[47]248 error_message := fmt.Sprintf("invalid response: %d (%s)", resp.StatusCode(), requestURIStr)
[37]249 p.serveMainPage(ctx, resp.StatusCode(), errors.New(error_message))
[1]250 return
251 }
252
253 contentType := resp.Header.Peek("Content-Type")
254
255 if contentType == nil {
[35]256 // HTTP status code 503 : Service Unavailable
257 p.serveMainPage(ctx, 503, errors.New("invalid content type"))
[1]258 return
259 }
260
[17]261 if bytes.Contains(bytes.ToLower(contentType), []byte("javascript")) {
[35]262 // HTTP status code 403 : Forbidden
263 p.serveMainPage(ctx, 403, errors.New("forbidden content type"))
[17]264 return
265 }
266
[1]267 contentInfo := bytes.SplitN(contentType, []byte(";"), 2)
268
269 var responseBody []byte
270
[45]271 if len(contentInfo) == 2 && bytes.Contains(contentInfo[0], []byte("text")) {
272 e, ename, _ := charset.DetermineEncoding(resp.Body(), string(contentType))
273 if (e != encoding.Nop) && (!strings.EqualFold("utf-8", ename)) {
274 responseBody, err = e.NewDecoder().Bytes(resp.Body())
275 if err != nil {
276 // HTTP status code 503 : Service Unavailable
277 p.serveMainPage(ctx, 503, err)
278 return
279 }
280 } else {
281 responseBody = resp.Body()
[1]282 }
283 } else {
284 responseBody = resp.Body()
285 }
286
287 ctx.SetContentType(fmt.Sprintf("%s; charset=UTF-8", contentInfo[0]))
288
289 switch {
290 case bytes.Contains(contentType, []byte("css")):
[23]291 sanitizeCSS(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
[1]292 case bytes.Contains(contentType, []byte("html")):
[23]293 sanitizeHTML(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
[1]294 default:
[39]295 if ctx.Request.Header.Peek("Content-Disposition") != nil {
296 ctx.Response.Header.AddBytesV("Content-Disposition", ctx.Request.Header.Peek("Content-Disposition"))
297 }
[1]298 ctx.Write(responseBody)
299 }
300}
301
[10]302func appRequestHandler(ctx *fasthttp.RequestCtx) bool {
[11]303 // serve robots.txt
[10]304 if bytes.Equal(ctx.Path(), []byte("/robots.txt")) {
305 ctx.SetContentType("text/plain")
306 ctx.Write([]byte("User-Agent: *\nDisallow: /\n"))
307 return true
308 }
[11]309
[10]310 return false
311}
312
[1]313func popRequestParam(ctx *fasthttp.RequestCtx, paramName []byte) []byte {
314 param := ctx.QueryArgs().PeekBytes(paramName)
315
316 if param == nil {
317 param = ctx.PostArgs().PeekBytes(paramName)
318 if param != nil {
319 ctx.PostArgs().DelBytes(paramName)
320 }
321 } else {
322 ctx.QueryArgs().DelBytes(paramName)
323 }
324
325 return param
326}
327
[9]328func sanitizeCSS(rc *RequestConfig, out io.Writer, css []byte) {
[1]329 // TODO
330
331 urlSlices := CSS_URL_REGEXP.FindAllSubmatchIndex(css, -1)
332
333 if urlSlices == nil {
[9]334 out.Write(css)
[1]335 return
336 }
337
338 startIndex := 0
339
340 for _, s := range urlSlices {
[15]341 urlStart := s[4]
342 urlEnd := s[5]
[1]343
[23]344 if uri, err := rc.ProxifyURI(string(css[urlStart:urlEnd])); err == nil {
[9]345 out.Write(css[startIndex:urlStart])
346 out.Write([]byte(uri))
[1]347 startIndex = urlEnd
348 } else {
[36]349 log.Println("cannot proxify css uri:", string(css[urlStart:urlEnd]))
[1]350 }
351 }
352 if startIndex < len(css) {
[9]353 out.Write(css[startIndex:len(css)])
[1]354 }
355}
356
[9]357func sanitizeHTML(rc *RequestConfig, out io.Writer, htmlDoc []byte) {
[1]358 r := bytes.NewReader(htmlDoc)
359 decoder := html.NewTokenizer(r)
360 decoder.AllowCDATA(true)
361
362 unsafeElements := make([][]byte, 0, 8)
363 state := STATE_DEFAULT
364 for {
365 token := decoder.Next()
366 if token == html.ErrorToken {
367 err := decoder.Err()
368 if err != io.EOF {
369 log.Println("failed to parse HTML:")
370 }
371 break
372 }
373
374 if len(unsafeElements) == 0 {
375
376 switch token {
377 case html.StartTagToken, html.SelfClosingTagToken:
378 tag, hasAttrs := decoder.TagName()
379 safe := !inArray(tag, UNSAFE_ELEMENTS)
380 if !safe {
381 if !inArray(tag, SELF_CLOSING_ELEMENTS) {
382 var unsafeTag []byte = make([]byte, len(tag))
383 copy(unsafeTag, tag)
384 unsafeElements = append(unsafeElements, unsafeTag)
385 }
386 break
387 }
[38]388 if bytes.Equal(tag, []byte("base")) {
389 for {
390 attrName, attrValue, moreAttr := decoder.TagAttr()
[45]391 if bytes.Equal(attrName, []byte("href")) {
392 parsedURI, err := url.Parse(string(attrValue))
393 if err == nil {
394 rc.BaseURL = parsedURI
395 }
[38]396 }
397 if !moreAttr {
398 break
399 }
400 }
401 break
402 }
[1]403 if bytes.Equal(tag, []byte("noscript")) {
404 state = STATE_IN_NOSCRIPT
405 break
406 }
407 var attrs [][][]byte
408 if hasAttrs {
409 for {
410 attrName, attrValue, moreAttr := decoder.TagAttr()
[21]411 attrs = append(attrs, [][]byte{
412 attrName,
413 attrValue,
414 []byte(html.EscapeString(string(attrValue))),
415 })
[1]416 if !moreAttr {
417 break
418 }
419 }
[13]420 }
421 if bytes.Equal(tag, []byte("link")) {
422 sanitizeLinkTag(rc, out, attrs)
423 break
424 }
425
[45]426 if bytes.Equal(tag, []byte("meta")) {
427 sanitizeMetaTag(rc, out, attrs)
428 break
429 }
430
[13]431 fmt.Fprintf(out, "<%s", tag)
432
433 if hasAttrs {
[45]434 sanitizeAttrs(rc, out, attrs)
[1]435 }
[13]436
[1]437 if token == html.SelfClosingTagToken {
[9]438 fmt.Fprintf(out, " />")
[1]439 } else {
[9]440 fmt.Fprintf(out, ">")
[1]441 if bytes.Equal(tag, []byte("style")) {
442 state = STATE_IN_STYLE
443 }
444 }
[13]445
[45]446 if bytes.Equal(tag, []byte("head")) {
[46]447 fmt.Fprintf(out, HTML_HEAD_CONTENT_TYPE)
[45]448 }
449
[1]450 if bytes.Equal(tag, []byte("form")) {
451 var formURL *url.URL
452 for _, attr := range attrs {
453 if bytes.Equal(attr[0], []byte("action")) {
454 formURL, _ = url.Parse(string(attr[1]))
[28]455 formURL = mergeURIs(rc.BaseURL, formURL)
[1]456 break
457 }
458 }
459 if formURL == nil {
[23]460 formURL = rc.BaseURL
[1]461 }
[2]462 urlStr := formURL.String()
463 var key string
464 if rc.Key != nil {
465 key = hash(urlStr, rc.Key)
466 }
[9]467 fmt.Fprintf(out, HTML_FORM_EXTENSION, urlStr, key)
[1]468
469 }
470
471 case html.EndTagToken:
472 tag, _ := decoder.TagName()
473 writeEndTag := true
474 switch string(tag) {
475 case "body":
[23]476 fmt.Fprintf(out, HTML_BODY_EXTENSION, rc.BaseURL.String())
[1]477 case "style":
478 state = STATE_DEFAULT
479 case "noscript":
480 state = STATE_DEFAULT
481 writeEndTag = false
482 }
483 // skip noscript tags - only the tag, not the content, because javascript is sanitized
484 if writeEndTag {
[9]485 fmt.Fprintf(out, "</%s>", tag)
[1]486 }
487
488 case html.TextToken:
489 switch state {
490 case STATE_DEFAULT:
[9]491 fmt.Fprintf(out, "%s", decoder.Raw())
[1]492 case STATE_IN_STYLE:
[9]493 sanitizeCSS(rc, out, decoder.Raw())
[1]494 case STATE_IN_NOSCRIPT:
[9]495 sanitizeHTML(rc, out, decoder.Raw())
[1]496 }
497
498 case html.DoctypeToken, html.CommentToken:
[9]499 out.Write(decoder.Raw())
[1]500 }
501 } else {
502 switch token {
503 case html.StartTagToken:
504 tag, _ := decoder.TagName()
505 if inArray(tag, UNSAFE_ELEMENTS) {
506 unsafeElements = append(unsafeElements, tag)
507 }
508
509 case html.EndTagToken:
510 tag, _ := decoder.TagName()
511 if bytes.Equal(unsafeElements[len(unsafeElements)-1], tag) {
512 unsafeElements = unsafeElements[:len(unsafeElements)-1]
513 }
514 }
515 }
516 }
517}
518
[13]519func sanitizeLinkTag(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
520 exclude := false
521 for _, attr := range attrs {
522 attrName := attr[0]
523 attrValue := attr[1]
524 if bytes.Equal(attrName, []byte("rel")) {
[46]525 if !inArray(attrValue, LINK_REL_SAFE_VALUES) {
[13]526 exclude = true
527 break
528 }
529 }
530 if bytes.Equal(attrName, []byte("as")) {
531 if bytes.Equal(attrValue, []byte("script")) {
532 exclude = true
533 break
534 }
535 }
536 }
537
538 if !exclude {
539 out.Write([]byte("<link"))
540 for _, attr := range attrs {
[21]541 sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
[13]542 }
543 out.Write([]byte(">"))
544 }
545}
546
[45]547func sanitizeMetaTag(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
[1]548 var http_equiv []byte
549 var content []byte
550
551 for _, attr := range attrs {
552 attrName := attr[0]
553 attrValue := attr[1]
554 if bytes.Equal(attrName, []byte("http-equiv")) {
555 http_equiv = bytes.ToLower(attrValue)
[46]556 // exclude some <meta http-equiv="..." ..>
557 if !inArray(http_equiv, LINK_HTTP_EQUIV_SAFE_VALUES) {
558 return
559 }
[1]560 }
561 if bytes.Equal(attrName, []byte("content")) {
562 content = attrValue
563 }
[45]564 if bytes.Equal(attrName, []byte("charset")) {
565 // exclude <meta charset="...">
566 return
567 }
[1]568 }
569
[45]570 out.Write([]byte("<meta"))
[14]571 urlIndex := bytes.Index(bytes.ToLower(content), []byte("url="))
572 if bytes.Equal(http_equiv, []byte("refresh")) && urlIndex != -1 {
573 contentUrl := content[urlIndex+4:]
[36]574 // special case of <meta http-equiv="refresh" content="0; url='example.com/url.with.quote.outside'">
[37]575 if len(contentUrl) >= 2 && (contentUrl[0] == byte('\'') || contentUrl[0] == byte('"')) {
[36]576 if contentUrl[0] == contentUrl[len(contentUrl)-1] {
[37]577 contentUrl = contentUrl[1 : len(contentUrl)-1]
[36]578 }
579 }
580 // output proxify result
[23]581 if uri, err := rc.ProxifyURI(string(contentUrl)); err == nil {
[14]582 fmt.Fprintf(out, ` http-equiv="refresh" content="%surl=%s"`, content[:urlIndex], uri)
[1]583 }
584 } else {
[46]585 if len(http_equiv) > 0 {
586 fmt.Fprintf(out, ` http-equiv="%s"`, http_equiv)
587 }
[9]588 sanitizeAttrs(rc, out, attrs)
[1]589 }
[45]590 out.Write([]byte(">"))
[1]591}
592
[9]593func sanitizeAttrs(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
[1]594 for _, attr := range attrs {
[21]595 sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
[1]596 }
597}
598
[21]599func sanitizeAttr(rc *RequestConfig, out io.Writer, attrName, attrValue, escapedAttrValue []byte) {
[1]600 if inArray(attrName, SAFE_ATTRIBUTES) {
[21]601 fmt.Fprintf(out, " %s=\"%s\"", attrName, escapedAttrValue)
[1]602 return
603 }
604 switch string(attrName) {
605 case "src", "href", "action":
[23]606 if uri, err := rc.ProxifyURI(string(attrValue)); err == nil {
[9]607 fmt.Fprintf(out, " %s=\"%s\"", attrName, uri)
[1]608 } else {
[36]609 log.Println("cannot proxify uri:", string(attrValue))
[1]610 }
611 case "style":
[21]612 cssAttr := bytes.NewBuffer(nil)
613 sanitizeCSS(rc, cssAttr, attrValue)
614 fmt.Fprintf(out, " %s=\"%s\"", attrName, html.EscapeString(string(cssAttr.Bytes())))
[1]615 }
616}
617
[36]618func mergeURIs(u1, u2 *url.URL) *url.URL {
[28]619 return u1.ResolveReference(u2)
[1]620}
621
[23]622func (rc *RequestConfig) ProxifyURI(uri string) (string, error) {
[28]623 // remove javascript protocol
624 if strings.HasPrefix(uri, "javascript:") {
625 return "", nil
626 }
[1]627 // TODO check malicious data: - e.g. data:script
628 if strings.HasPrefix(uri, "data:") {
629 return uri, nil
630 }
631
632 if len(uri) > 0 && uri[0] == '#' {
633 return uri, nil
634 }
635
636 u, err := url.Parse(uri)
637 if err != nil {
638 return "", err
639 }
[28]640 u = mergeURIs(rc.BaseURL, u)
[1]641
642 uri = u.String()
643
644 if rc.Key == nil {
645 return fmt.Sprintf("./?mortyurl=%s", url.QueryEscape(uri)), nil
646 }
[47]647
[1]648 return fmt.Sprintf("./?mortyhash=%s&mortyurl=%s", hash(uri, rc.Key), url.QueryEscape(uri)), nil
649}
650
651func inArray(b []byte, a [][]byte) bool {
652 for _, b2 := range a {
653 if bytes.Equal(b, b2) {
654 return true
655 }
656 }
657 return false
658}
659
660func hash(msg string, key []byte) string {
661 mac := hmac.New(sha256.New, key)
662 mac.Write([]byte(msg))
663 return hex.EncodeToString(mac.Sum(nil))
664}
665
666func verifyRequestURI(uri, hashMsg, key []byte) bool {
667 h := make([]byte, hex.DecodedLen(len(hashMsg)))
668 _, err := hex.Decode(h, hashMsg)
669 if err != nil {
670 log.Println("hmac error:", err)
671 return false
672 }
673 mac := hmac.New(sha256.New, key)
674 mac.Write(uri)
675 return hmac.Equal(h, mac.Sum(nil))
676}
677
[35]678func (p *Proxy) serveMainPage(ctx *fasthttp.RequestCtx, statusCode int, err error) {
[1]679 ctx.SetContentType("text/html")
[35]680 ctx.SetStatusCode(statusCode)
[1]681 ctx.Write([]byte(`<!doctype html>
682<head>
[11]683<title>MortyProxy</title>
[36]684<meta name="viewport" content="width=device-width, initial-scale=1 , maximum-scale=1.0, user-scalable=1" />
[11]685<style>
[36]686html { height: 100%; }
687body { min-height : 100%; display: flex; flex-direction:column; font-family: 'Garamond', 'Georgia', serif; text-align: center; color: #444; background: #FAFAFA; margin: 0; padding: 0; font-size: 1.1em; }
[11]688input { border: 1px solid #888; padding: 0.3em; color: #444; background: #FFF; font-size: 1.1em; }
[36]689input[placeholder] { width:80%; }
[11]690a { text-decoration: none; #2980b9; }
691h1, h2 { font-weight: 200; margin-bottom: 2rem; }
692h1 { font-size: 3em; }
[36]693.container { flex:1; min-height: 100%; margin-bottom: 1em; }
694.footer { margin: 1em; }
[11]695.footer p { font-size: 0.8em; }
696</style>
[1]697</head>
[11]698<body>
[36]699 <div class="container">
700 <h1>MortyProxy</h1>
701`))
[11]702 if err != nil {
703 log.Println("error:", err)
704 ctx.Write([]byte("<h2>Error: "))
705 ctx.Write([]byte(html.EscapeString(err.Error())))
706 ctx.Write([]byte("</h2>"))
707 }
[1]708 if p.Key == nil {
709 ctx.Write([]byte(`
[36]710 <form action="post">
711 Visit url: <input placeholder="https://url.." name="mortyurl" autofocus />
712 <input type="submit" value="go" />
713 </form>`))
[11]714 } else {
715 ctx.Write([]byte(`<h3>Warning! This instance does not support direct URL opening.</h3>`))
[1]716 }
717 ctx.Write([]byte(`
[36]718 </div>
719 <div class="footer">
720 <p>Morty rewrites web pages to exclude malicious HTML tags and CSS/HTML attributes. It also replaces external resource references to prevent third-party information leaks.<br />
721 <a href="https://github.com/asciimoo/morty">view on github</a>
722 </p>
723 </div>
[1]724</body>
725</html>`))
726}
727
728func main() {
729
[2]730 listen := flag.String("listen", "127.0.0.1:3000", "Listen address")
[1]731 key := flag.String("key", "", "HMAC url validation key (hexadecimal encoded) - leave blank to disable")
[24]732 ipv6 := flag.Bool("ipv6", false, "Allow IPv6 HTTP requests")
[4]733 requestTimeout := flag.Uint("timeout", 2, "Request timeout")
[1]734 flag.Parse()
735
[24]736 if *ipv6 {
737 CLIENT.Dial = fasthttp.DialDualStack
738 }
739
[4]740 p := &Proxy{RequestTimeout: time.Duration(*requestTimeout) * time.Second}
[1]741
742 if *key != "" {
743 p.Key = []byte(*key)
744 }
745
746 log.Println("listening on", *listen)
747
748 if err := fasthttp.ListenAndServe(*listen, p.RequestHandler); err != nil {
749 log.Fatal("Error in ListenAndServe:", err)
750 }
751}
Note: See TracBrowser for help on using the repository browser.