source: code/trunk/morty.go@ 39

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

[enh] forward content-disposition header

closes #21

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