forked from Kethsar/ytarchive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
netscape_cookies.go
98 lines (82 loc) · 1.94 KB
/
netscape_cookies.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"bufio"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"strconv"
"strings"
"time"
"golang.org/x/net/publicsuffix"
)
const (
CookieDomain = iota
CookieHostOnly
CookiePath
CookieSecure
CookieExpiration
CookieName
CookieValue
CookiePieces
)
/*
Assume provided cookie file only contains cookies for a single site
Maybe fix that later, not that we need to for this particular program
*/
func (di *DownloadInfo) ParseNetscapeCookiesFile(fname string) (*cookiejar.Jar, error) {
jar, err := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
if err != nil {
return nil, err
}
file, err := os.Open(fname)
if err != nil {
return nil, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
var cookies []*http.Cookie
for scanner.Scan() {
// Could move everything in this loop into its own function
cookieParts := strings.Split(scanner.Text(), "\t")
secure := false
httpOnly := false
var expire int64
var domain string
// Netscape cookie entries should always have 7 pieces to them
if len(cookieParts) != CookiePieces {
continue
}
domain = strings.ToLower(cookieParts[CookieDomain])
expire, _ = strconv.ParseInt(cookieParts[CookieExpiration], 10, 64)
expireTime := time.Unix(expire, 0)
if strings.HasPrefix(domain, "#httponly_") {
httpOnly = true
domain = strings.TrimPrefix(domain, "#httponly_")
}
if strings.ToLower(cookieParts[CookieSecure]) == "true" {
secure = true
}
cookie := &http.Cookie{
Domain: domain,
Path: cookieParts[CookiePath],
Secure: secure,
Expires: expireTime,
Name: cookieParts[CookieName],
Value: cookieParts[CookieValue],
HttpOnly: httpOnly,
}
cookies = append(cookies, cookie)
}
if len(cookies) > 0 {
url, err := url.Parse(fmt.Sprintf("https://%s", cookies[0].Domain))
if err == nil {
jar.SetCookies(url, cookies)
di.CookiesURL = url
}
}
return jar, nil
}