| 1 | package http_proxy |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net/http" |
| 6 | "strings" |
| 7 | "sync" |
| 8 | |
| 9 | "github.com/elazarl/goproxy" |
| 10 | "github.com/jpillora/go-tld" |
| 11 | ) |
| 12 | |
| 13 | type CookieTracker struct { |
| 14 | sync.RWMutex |
| 15 | set map[string]bool |
| 16 | } |
| 17 | |
| 18 | func NewCookieTracker() *CookieTracker { |
| 19 | return &CookieTracker{ |
| 20 | set: make(map[string]bool), |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | func (t *CookieTracker) domainOf(req *http.Request) string { |
| 25 | if parsed, err := tld.Parse(req.Host); err != nil { |
| 26 | return req.Host |
| 27 | } else { |
| 28 | return fmt.Sprintf("%s.%s", parsed.Domain, parsed.TLD) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | func (t *CookieTracker) keyOf(req *http.Request) string { |
| 33 | client := strings.Split(req.RemoteAddr, ":")[0] |
| 34 | domain := t.domainOf(req) |
| 35 | return fmt.Sprintf("%s-%s", client, domain) |
| 36 | } |
| 37 | |
| 38 | func (t *CookieTracker) IsClean(req *http.Request) bool { |
| 39 | // we only clean GET requests |
| 40 | if req.Method != "GET" { |
| 41 | return true |
| 42 | } |
| 43 | |
| 44 | // does the request have any cookie? |
| 45 | cookie := req.Header.Get("Cookie") |
| 46 | if cookie == "" { |
| 47 | return true |
| 48 | } |
| 49 | |
| 50 | t.RLock() |
| 51 | defer t.RUnlock() |
| 52 | |
| 53 | // was it already processed? |
| 54 | if _, found := t.set[t.keyOf(req)]; found { |
| 55 | return true |
| 56 | } |
| 57 | |
| 58 | // unknown session cookie |
| 59 | return false |
| 60 | } |
| 61 | |
| 62 | func (t *CookieTracker) Track(req *http.Request) { |
| 63 | t.Lock() |
| 64 | defer t.Unlock() |
| 65 | t.set[t.keyOf(req)] = true |
| 66 | } |
| 67 | |
| 68 | func (t *CookieTracker) Expire(req *http.Request) *http.Response { |
| 69 | domain := t.domainOf(req) |
| 70 | redir := goproxy.NewResponse(req, "text/plain", 302, "") |
| 71 | |
| 72 | for _, c := range req.Cookies() { |
| 73 | redir.Header.Add("Set-Cookie", fmt.Sprintf("%s=EXPIRED; path=/; domain=%s; Expires=Mon, 01-Jan-1990 00:00:00 GMT", c.Name, domain)) |
| 74 | redir.Header.Add("Set-Cookie", fmt.Sprintf("%s=EXPIRED; path=/; domain=%s; Expires=Mon, 01-Jan-1990 00:00:00 GMT", c.Name, c.Domain)) |
| 75 | } |
| 76 | |
| 77 | redir.Header.Add("Location", fmt.Sprintf("http://%s/", req.Host)) |
| 78 | redir.Header.Add("Connection", "close") |
| 79 | |
| 80 | return redir |
| 81 | } |