forked from browserutils/kooky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
netscape.go
100 lines (84 loc) · 2.22 KB
/
netscape.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
99
100
package netscape
import (
"bufio"
"errors"
"io"
"strconv"
"strings"
"time"
"github.com/favbox/kooky"
)
const httpOnlyPrefix = `#HttpOnly_`
func (s *CookieStore) ReadCookies(filters ...kooky.Filter) ([]*kooky.Cookie, error) {
if s == nil {
return nil, errors.New(`cookie store is nil`)
}
if err := s.Open(); err != nil {
return nil, err
} else if s.File == nil {
return nil, errors.New(`file is nil`)
}
cookies, isStrict, err := ReadCookies(s.File, filters...)
s.IsStrictBool = isStrict
return cookies, err
}
func ReadCookies(file io.Reader, filters ...kooky.Filter) (c []*kooky.Cookie, strict bool, e error) {
// http://web.archive.org/web/20080520061150/wp.netscape.com/newsref/std/cookie_spec.html
// https://github.com/Rob--W/cookie-manager/blob/83c04b74b79cb7768a33c4a93fbdfd04b90fa931/cookie-manager.js#L975
// https://hg.python.org/cpython/file/5470dc81caf9/Lib/http/cookiejar.py#l1981
if file == nil {
return nil, false, errors.New(`file is nil`)
}
var ret []*kooky.Cookie
var lineNr uint
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if lineNr == 0 && (line == `# HTTP Cookie File` || line == `# Netscape HTTP Cookie File`) {
strict = true
}
// split line into fields
sp := strings.Split(line, "\t")
if len(sp) != 7 {
continue
}
var exp int64
if len(sp[4]) > 0 {
e, err := strconv.ParseInt(sp[4], 10, 64)
if err != nil {
continue
} else {
exp = e
}
} else {
// allow empty expiry field for uzbl's "session-cookies.txt" file
strict = false
}
cookie := &kooky.Cookie{}
switch sp[3] {
case `TRUE`:
cookie.Secure = true
case `FALSE`:
default:
continue
}
// https://github.com/curl/curl/blob/curl-7_39_0/lib/cookie.c#L644
// https://bugs.python.org/issue2190#msg233571
// also in original Netscape cookies
if strings.HasPrefix(sp[0], httpOnlyPrefix) {
cookie.Domain = sp[0][len(httpOnlyPrefix):]
cookie.HttpOnly = true
} else {
cookie.Domain = sp[0]
}
cookie.Path = sp[2]
cookie.Name = sp[5]
cookie.Value = strings.TrimSpace(sp[6])
cookie.Expires = time.Unix(exp, 0)
if !kooky.FilterCookie(cookie, filters...) {
continue
}
ret = append(ret, cookie)
}
return ret, strict, nil
}