source: code/trunk/morty.go@ 51

Last change on this file since 51 was 51, checked in by alex, 9 years ago

[fix] URI fragment are not encoded in the mortyurl but are encoded as usual fragment so the browser can use them.

File size: 19.7 KB
Line 
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"
16 "time"
17
18 "github.com/valyala/fasthttp"
19 "golang.org/x/net/html"
20 "golang.org/x/net/html/charset"
21 "golang.org/x/text/encoding"
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
34var CSS_URL_REGEXP *regexp.Regexp = regexp.MustCompile("url\\((['\"]?)[ \\t\\f]*([\u0009\u0021\u0023-\u0026\u0028\u002a-\u007E]+)(['\"]?)\\)?")
35
36var UNSAFE_ELEMENTS [][]byte = [][]byte{
37 []byte("applet"),
38 []byte("canvas"),
39 []byte("embed"),
40 //[]byte("iframe"),
41 []byte("math"),
42 []byte("script"),
43 []byte("svg"),
44}
45
46var SAFE_ATTRIBUTES [][]byte = [][]byte{
47 []byte("abbr"),
48 []byte("accesskey"),
49 []byte("align"),
50 []byte("alt"),
51 []byte("as"),
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"),
63 []byte("hreflang"),
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
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
132type Proxy struct {
133 Key []byte
134 RequestTimeout time.Duration
135}
136
137type RequestConfig struct {
138 Key []byte
139 BaseURL *url.URL
140}
141
142var HTML_FORM_EXTENSION string = `<input type="hidden" name="mortyurl" value="%s" /><input type="hidden" name="mortyhash" value="%s" />`
143
144var HTML_BODY_EXTENSION string = `
145<div id="mortyheader">
146 <input type="checkbox" id="mortytoggle" autocomplete="off" />
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>
148</div>
149<style>
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; }
154#mortyheader label { text-align: right; cursor: pointer; display: block; color: #444; padding: 0; margin: 0; }
155input[type=checkbox]#mortytoggle { display: none; }
156input[type=checkbox]#mortytoggle:checked ~ div { display: none; }
157</style>
158`
159
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`
163
164func (p *Proxy) RequestHandler(ctx *fasthttp.RequestCtx) {
165
166 if appRequestHandler(ctx) {
167 return
168 }
169
170 requestHash := popRequestParam(ctx, []byte("mortyhash"))
171
172 requestURI := popRequestParam(ctx, []byte("mortyurl"))
173
174 if requestURI == nil {
175 p.serveMainPage(ctx, 200, nil)
176 return
177 }
178
179 if p.Key != nil {
180 if !verifyRequestURI(requestURI, requestHash, p.Key) {
181 // HTTP status code 403 : Forbidden
182 p.serveMainPage(ctx, 403, errors.New(`invalid "mortyhash" parameter`))
183 return
184 }
185 }
186
187 parsedURI, err := url.Parse(string(requestURI))
188
189 if strings.HasSuffix(parsedURI.Host, ".onion") {
190 // HTTP status code 501 : Not Implemented
191 p.serveMainPage(ctx, 501, errors.New("Tor urls are not supported yet"))
192 return
193 }
194
195 if err != nil {
196 // HTTP status code 500 : Internal Server Error
197 p.serveMainPage(ctx, 500, err)
198 return
199 }
200
201 req := fasthttp.AcquireRequest()
202 defer fasthttp.ReleaseRequest(req)
203 req.SetConnectionClose()
204
205 requestURIStr := string(requestURI)
206
207 log.Println("getting", requestURIStr)
208
209 req.SetRequestURI(requestURIStr)
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
220 err = CLIENT.DoTimeout(req, resp, p.RequestTimeout)
221
222 if err != nil {
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 }
230 return
231 }
232
233 if resp.StatusCode() != 200 {
234 switch resp.StatusCode() {
235 case 301, 302, 303, 307, 308:
236 loc := resp.Header.Peek("Location")
237 if loc != nil {
238 rc := &RequestConfig{Key: p.Key, BaseURL: parsedURI}
239 url, err := rc.ProxifyURI(string(loc))
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 }
248 error_message := fmt.Sprintf("invalid response: %d (%s)", resp.StatusCode(), requestURIStr)
249 p.serveMainPage(ctx, resp.StatusCode(), errors.New(error_message))
250 return
251 }
252
253 contentType := resp.Header.Peek("Content-Type")
254
255 if contentType == nil {
256 // HTTP status code 503 : Service Unavailable
257 p.serveMainPage(ctx, 503, errors.New("invalid content type"))
258 return
259 }
260
261 if bytes.Contains(bytes.ToLower(contentType), []byte("javascript")) {
262 // HTTP status code 403 : Forbidden
263 p.serveMainPage(ctx, 403, errors.New("forbidden content type"))
264 return
265 }
266
267 contentInfo := bytes.SplitN(contentType, []byte(";"), 2)
268
269 var responseBody []byte
270
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()
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")):
291 sanitizeCSS(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
292 case bytes.Contains(contentType, []byte("html")):
293 sanitizeHTML(&RequestConfig{Key: p.Key, BaseURL: parsedURI}, ctx, responseBody)
294 default:
295 if ctx.Request.Header.Peek("Content-Disposition") != nil {
296 ctx.Response.Header.AddBytesV("Content-Disposition", ctx.Request.Header.Peek("Content-Disposition"))
297 }
298 ctx.Write(responseBody)
299 }
300}
301
302func appRequestHandler(ctx *fasthttp.RequestCtx) bool {
303 // serve robots.txt
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 }
309
310 return false
311}
312
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
328func sanitizeCSS(rc *RequestConfig, out io.Writer, css []byte) {
329 // TODO
330
331 urlSlices := CSS_URL_REGEXP.FindAllSubmatchIndex(css, -1)
332
333 if urlSlices == nil {
334 out.Write(css)
335 return
336 }
337
338 startIndex := 0
339
340 for _, s := range urlSlices {
341 urlStart := s[4]
342 urlEnd := s[5]
343
344 if uri, err := rc.ProxifyURI(string(css[urlStart:urlEnd])); err == nil {
345 out.Write(css[startIndex:urlStart])
346 out.Write([]byte(uri))
347 startIndex = urlEnd
348 } else {
349 log.Println("cannot proxify css uri:", string(css[urlStart:urlEnd]))
350 }
351 }
352 if startIndex < len(css) {
353 out.Write(css[startIndex:len(css)])
354 }
355}
356
357func sanitizeHTML(rc *RequestConfig, out io.Writer, htmlDoc []byte) {
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 }
388 if bytes.Equal(tag, []byte("base")) {
389 for {
390 attrName, attrValue, moreAttr := decoder.TagAttr()
391 if bytes.Equal(attrName, []byte("href")) {
392 parsedURI, err := url.Parse(string(attrValue))
393 if err == nil {
394 rc.BaseURL = parsedURI
395 }
396 }
397 if !moreAttr {
398 break
399 }
400 }
401 break
402 }
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()
411 attrs = append(attrs, [][]byte{
412 attrName,
413 attrValue,
414 []byte(html.EscapeString(string(attrValue))),
415 })
416 if !moreAttr {
417 break
418 }
419 }
420 }
421 if bytes.Equal(tag, []byte("link")) {
422 sanitizeLinkTag(rc, out, attrs)
423 break
424 }
425
426 if bytes.Equal(tag, []byte("meta")) {
427 sanitizeMetaTag(rc, out, attrs)
428 break
429 }
430
431 fmt.Fprintf(out, "<%s", tag)
432
433 if hasAttrs {
434 sanitizeAttrs(rc, out, attrs)
435 }
436
437 if token == html.SelfClosingTagToken {
438 fmt.Fprintf(out, " />")
439 } else {
440 fmt.Fprintf(out, ">")
441 if bytes.Equal(tag, []byte("style")) {
442 state = STATE_IN_STYLE
443 }
444 }
445
446 if bytes.Equal(tag, []byte("head")) {
447 fmt.Fprintf(out, HTML_HEAD_CONTENT_TYPE)
448 }
449
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]))
455 formURL = mergeURIs(rc.BaseURL, formURL)
456 break
457 }
458 }
459 if formURL == nil {
460 formURL = rc.BaseURL
461 }
462 urlStr := formURL.String()
463 var key string
464 if rc.Key != nil {
465 key = hash(urlStr, rc.Key)
466 }
467 fmt.Fprintf(out, HTML_FORM_EXTENSION, urlStr, key)
468
469 }
470
471 case html.EndTagToken:
472 tag, _ := decoder.TagName()
473 writeEndTag := true
474 switch string(tag) {
475 case "body":
476 fmt.Fprintf(out, HTML_BODY_EXTENSION, rc.BaseURL.String())
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 {
485 fmt.Fprintf(out, "</%s>", tag)
486 }
487
488 case html.TextToken:
489 switch state {
490 case STATE_DEFAULT:
491 fmt.Fprintf(out, "%s", decoder.Raw())
492 case STATE_IN_STYLE:
493 sanitizeCSS(rc, out, decoder.Raw())
494 case STATE_IN_NOSCRIPT:
495 sanitizeHTML(rc, out, decoder.Raw())
496 }
497
498 case html.DoctypeToken, html.CommentToken:
499 out.Write(decoder.Raw())
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
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")) {
525 if !inArray(attrValue, LINK_REL_SAFE_VALUES) {
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 {
541 sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
542 }
543 out.Write([]byte(">"))
544 }
545}
546
547func sanitizeMetaTag(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
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)
556 // exclude some <meta http-equiv="..." ..>
557 if !inArray(http_equiv, LINK_HTTP_EQUIV_SAFE_VALUES) {
558 return
559 }
560 }
561 if bytes.Equal(attrName, []byte("content")) {
562 content = attrValue
563 }
564 if bytes.Equal(attrName, []byte("charset")) {
565 // exclude <meta charset="...">
566 return
567 }
568 }
569
570 out.Write([]byte("<meta"))
571 urlIndex := bytes.Index(bytes.ToLower(content), []byte("url="))
572 if bytes.Equal(http_equiv, []byte("refresh")) && urlIndex != -1 {
573 contentUrl := content[urlIndex+4:]
574 // special case of <meta http-equiv="refresh" content="0; url='example.com/url.with.quote.outside'">
575 if len(contentUrl) >= 2 && (contentUrl[0] == byte('\'') || contentUrl[0] == byte('"')) {
576 if contentUrl[0] == contentUrl[len(contentUrl)-1] {
577 contentUrl = contentUrl[1 : len(contentUrl)-1]
578 }
579 }
580 // output proxify result
581 if uri, err := rc.ProxifyURI(string(contentUrl)); err == nil {
582 fmt.Fprintf(out, ` http-equiv="refresh" content="%surl=%s"`, content[:urlIndex], uri)
583 }
584 } else {
585 if len(http_equiv) > 0 {
586 fmt.Fprintf(out, ` http-equiv="%s"`, http_equiv)
587 }
588 sanitizeAttrs(rc, out, attrs)
589 }
590 out.Write([]byte(">"))
591}
592
593func sanitizeAttrs(rc *RequestConfig, out io.Writer, attrs [][][]byte) {
594 for _, attr := range attrs {
595 sanitizeAttr(rc, out, attr[0], attr[1], attr[2])
596 }
597}
598
599func sanitizeAttr(rc *RequestConfig, out io.Writer, attrName, attrValue, escapedAttrValue []byte) {
600 if inArray(attrName, SAFE_ATTRIBUTES) {
601 fmt.Fprintf(out, " %s=\"%s\"", attrName, escapedAttrValue)
602 return
603 }
604 switch string(attrName) {
605 case "src", "href", "action":
606 if uri, err := rc.ProxifyURI(string(attrValue)); err == nil {
607 fmt.Fprintf(out, " %s=\"%s\"", attrName, uri)
608 } else {
609 log.Println("cannot proxify uri:", string(attrValue))
610 }
611 case "style":
612 cssAttr := bytes.NewBuffer(nil)
613 sanitizeCSS(rc, cssAttr, attrValue)
614 fmt.Fprintf(out, " %s=\"%s\"", attrName, html.EscapeString(string(cssAttr.Bytes())))
615 }
616}
617
618func mergeURIs(u1, u2 *url.URL) *url.URL {
619 return u1.ResolveReference(u2)
620}
621
622func (rc *RequestConfig) ProxifyURI(uri string) (string, error) {
623 // remove javascript protocol
624 if strings.HasPrefix(uri, "javascript:") {
625 return "", nil
626 }
627
628 // TODO check malicious data: - e.g. data:script
629 if strings.HasPrefix(uri, "data:") {
630 return uri, nil
631 }
632
633 // parse the uri
634 u, err := url.Parse(uri)
635 if err != nil {
636 return "", err
637 }
638
639 // get the fragment (with the prefix "#")
640 fragment := ""
641 if len(u.Fragment) > 0 {
642 fragment = "#" + u.Fragment
643 }
644
645 // reset the fragment: it is not included in the mortyurl
646 u.Fragment = ""
647
648 // merge the URI with the document URI
649 u = mergeURIs(rc.BaseURL, u)
650
651 // simple internal link ?
652 // some web pages describe the whole link https://same:auth@same.host/same.path?same.query#new.fragment
653 if u.Scheme == rc.BaseURL.Scheme &&
654 ((u.User == nil && rc.BaseURL.User == nil) || (u.User.String() == rc.BaseURL.User.String())) &&
655 u.Host == rc.BaseURL.Host &&
656 u.Path == rc.BaseURL.Path &&
657 u.RawQuery == rc.BaseURL.RawQuery {
658 // the fragment is the only difference between the document URI and the uri parameter
659 return fragment, nil
660 }
661
662 // return full URI and fragment (if not empty)
663 uri = u.String()
664
665 if rc.Key == nil {
666 return fmt.Sprintf("./?mortyurl=%s%s", url.QueryEscape(uri), fragment), nil
667 }
668 return fmt.Sprintf("./?mortyhash=%s&mortyurl=%s%s", hash(uri, rc.Key), url.QueryEscape(uri), fragment), nil
669}
670
671func inArray(b []byte, a [][]byte) bool {
672 for _, b2 := range a {
673 if bytes.Equal(b, b2) {
674 return true
675 }
676 }
677 return false
678}
679
680func hash(msg string, key []byte) string {
681 mac := hmac.New(sha256.New, key)
682 mac.Write([]byte(msg))
683 return hex.EncodeToString(mac.Sum(nil))
684}
685
686func verifyRequestURI(uri, hashMsg, key []byte) bool {
687 h := make([]byte, hex.DecodedLen(len(hashMsg)))
688 _, err := hex.Decode(h, hashMsg)
689 if err != nil {
690 log.Println("hmac error:", err)
691 return false
692 }
693 mac := hmac.New(sha256.New, key)
694 mac.Write(uri)
695 return hmac.Equal(h, mac.Sum(nil))
696}
697
698func (p *Proxy) serveMainPage(ctx *fasthttp.RequestCtx, statusCode int, err error) {
699 ctx.SetContentType("text/html")
700 ctx.SetStatusCode(statusCode)
701 ctx.Write([]byte(`<!doctype html>
702<head>
703<title>MortyProxy</title>
704<meta name="viewport" content="width=device-width, initial-scale=1 , maximum-scale=1.0, user-scalable=1" />
705<style>
706html { height: 100%; }
707body { 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; }
708input { border: 1px solid #888; padding: 0.3em; color: #444; background: #FFF; font-size: 1.1em; }
709input[placeholder] { width:80%; }
710a { text-decoration: none; #2980b9; }
711h1, h2 { font-weight: 200; margin-bottom: 2rem; }
712h1 { font-size: 3em; }
713.container { flex:1; min-height: 100%; margin-bottom: 1em; }
714.footer { margin: 1em; }
715.footer p { font-size: 0.8em; }
716</style>
717</head>
718<body>
719 <div class="container">
720 <h1>MortyProxy</h1>
721`))
722 if err != nil {
723 log.Println("error:", err)
724 ctx.Write([]byte("<h2>Error: "))
725 ctx.Write([]byte(html.EscapeString(err.Error())))
726 ctx.Write([]byte("</h2>"))
727 }
728 if p.Key == nil {
729 ctx.Write([]byte(`
730 <form action="post">
731 Visit url: <input placeholder="https://url.." name="mortyurl" autofocus />
732 <input type="submit" value="go" />
733 </form>`))
734 } else {
735 ctx.Write([]byte(`<h3>Warning! This instance does not support direct URL opening.</h3>`))
736 }
737 ctx.Write([]byte(`
738 </div>
739 <div class="footer">
740 <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 />
741 <a href="https://github.com/asciimoo/morty">view on github</a>
742 </p>
743 </div>
744</body>
745</html>`))
746}
747
748func main() {
749
750 listen := flag.String("listen", "127.0.0.1:3000", "Listen address")
751 key := flag.String("key", "", "HMAC url validation key (hexadecimal encoded) - leave blank to disable")
752 ipv6 := flag.Bool("ipv6", false, "Allow IPv6 HTTP requests")
753 requestTimeout := flag.Uint("timeout", 2, "Request timeout")
754 flag.Parse()
755
756 if *ipv6 {
757 CLIENT.Dial = fasthttp.DialDualStack
758 }
759
760 p := &Proxy{RequestTimeout: time.Duration(*requestTimeout) * time.Second}
761
762 if *key != "" {
763 p.Key = []byte(*key)
764 }
765
766 log.Println("listening on", *listen)
767
768 if err := fasthttp.ListenAndServe(*listen, p.RequestHandler); err != nil {
769 log.Fatal("Error in ListenAndServe:", err)
770 }
771}
Note: See TracBrowser for help on using the repository browser.