-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathutils.go
293 lines (249 loc) · 7.55 KB
/
utils.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package warc
import (
"bufio"
"bytes"
"crypto/sha1"
"crypto/sha256"
"encoding/base32"
"encoding/binary"
"encoding/hex"
"errors"
"io"
"os"
"strings"
"time"
"github.com/CorentinB/warc/pkg/spooledtempfile"
gzip "github.com/klauspost/compress/gzip"
"github.com/klauspost/compress/zstd"
)
func GetSHA1(r io.Reader) string {
sha := sha1.New()
block := make([]byte, 256)
for {
n, err := r.Read(block)
if n > 0 {
sha.Write(block[:n])
}
if err == io.EOF {
break
}
if err != nil {
return "ERROR: " + err.Error()
}
}
return base32.StdEncoding.EncodeToString(sha.Sum(nil))
}
func GetSHA256(r io.Reader) string {
sha := sha256.New()
block := make([]byte, 256)
for {
n, err := r.Read(block)
if n > 0 {
sha.Write(block[:n])
}
if err == io.EOF {
break
}
if err != nil {
return "ERROR: " + err.Error()
}
}
return base32.StdEncoding.EncodeToString(sha.Sum(nil))
}
func GetSHA256Base16(r io.Reader) string {
sha := sha256.New()
block := make([]byte, 256)
for {
n, err := r.Read(block)
if n > 0 {
sha.Write(block[:n])
}
if err == io.EOF {
break
}
if err != nil {
return "ERROR: " + err.Error()
}
}
return hex.EncodeToString(sha.Sum(nil))
}
// splitKeyValue parses WARC record header fields.
func splitKeyValue(line string) (string, string) {
parts := strings.SplitN(line, ":", 2)
if len(parts) != 2 {
return "", ""
}
return parts[0], strings.TrimSpace(parts[1])
}
func isHTTPRequest(line string) bool {
httpMethods := []string{"GET ", "HEAD ", "POST ", "PUT ", "DELETE ", "CONNECT ", "OPTIONS ", "TRACE ", "PATCH "}
protocols := []string{"HTTP/1.0\r", "HTTP/1.1\r"}
for _, method := range httpMethods {
if strings.HasPrefix(line, method) {
for _, protocol := range protocols {
if strings.HasSuffix(line, protocol) {
return true
}
}
}
}
return false
}
// NewWriter creates a new WARC writer.
func NewWriter(writer io.Writer, fileName string, compression string, contentLengthHeader string, newFileCreation bool, dictionary []byte) (*Writer, error) {
if compression != "" {
if compression == "GZIP" {
gzipWriter := gzip.NewWriter(writer)
return &Writer{
FileName: fileName,
Compression: compression,
GZIPWriter: gzipWriter,
FileWriter: bufio.NewWriter(gzipWriter),
}, nil
} else if compression == "ZSTD" {
if newFileCreation && len(dictionary) > 0 {
dictionaryZstdwriter, err := zstd.NewWriter(nil, zstd.WithEncoderLevel(zstd.SpeedBetterCompression))
if err != nil {
return nil, err
}
// Compress dictionary with ZSTD.
// TODO: Option to allow uncompressed dictionary (maybe? not sure there's any need.)
payload := dictionaryZstdwriter.EncodeAll(dictionary, nil)
// Magic number for skippable dictionary frame (0x184D2A5D).
// https://github.com/ArchiveTeam/wget-lua/releases/tag/v1.20.3-at.20200401.01
// https://iipc.github.io/warc-specifications/specifications/warc-zstd/
magic := uint32(0x184D2A5D)
// Create the frame header (magic + payload size)
header := make([]byte, 8)
binary.LittleEndian.PutUint32(header[:4], magic)
binary.LittleEndian.PutUint32(header[4:], uint32(len(payload)))
// Combine header and payload together into a full frame.
frame := append(header, payload...)
// Write generated frame directly to WARC file.
// The regular ZStandard writer will continue afterwards with normal ZStandard frames.
writer.Write(frame)
}
// Create ZStandard writer either with or without the encoder dictionary and return it.
if len(dictionary) > 0 {
zstdWriter, err := zstd.NewWriter(writer, zstd.WithEncoderLevel(zstd.SpeedBetterCompression), zstd.WithEncoderDict(dictionary))
if err != nil {
return nil, err
}
return &Writer{
FileName: fileName,
Compression: compression,
ZSTDWriter: zstdWriter,
FileWriter: bufio.NewWriter(zstdWriter),
}, nil
} else {
zstdWriter, err := zstd.NewWriter(writer, zstd.WithEncoderLevel(zstd.SpeedBetterCompression))
if err != nil {
return nil, err
}
return &Writer{
FileName: fileName,
Compression: compression,
ZSTDWriter: zstdWriter,
FileWriter: bufio.NewWriter(zstdWriter),
}, nil
}
}
return nil, errors.New("invalid compression algorithm: " + compression)
}
return &Writer{
FileName: fileName,
Compression: "",
FileWriter: bufio.NewWriter(writer),
}, nil
}
// NewRecord creates a new WARC record.
func NewRecord(tempDir string, fullOnDisk bool) *Record {
return &Record{
Header: NewHeader(),
Content: spooledtempfile.NewSpooledTempFile("warc", tempDir, -1, fullOnDisk, -1),
}
}
// NewRecordBatch creates a record batch,
// it also initialize the capture time
func NewRecordBatch() *RecordBatch {
return &RecordBatch{
CaptureTime: time.Now().UTC().Format(time.RFC3339Nano),
}
}
// NewRotatorSettings creates a RotatorSettings structure
// and initialize it with default values
func NewRotatorSettings() *RotatorSettings {
return &RotatorSettings{
WarcinfoContent: NewHeader(),
Prefix: "WARC",
WarcSize: 1000,
Compression: "GZIP",
CompressionDictionary: "",
OutputDirectory: "./",
}
}
// checkRotatorSettings validate RotatorSettings settings, and set
// default values if needed
func checkRotatorSettings(settings *RotatorSettings) (err error) {
// Get host name as reported by the kernel
hostName, err := os.Hostname()
if err != nil {
panic(err)
}
// Check if output directory is specified, if not, set it to the current directory
if settings.OutputDirectory == "" {
settings.OutputDirectory = "./"
} else {
// If it is specified, check if output directory exist
if _, err := os.Stat(settings.OutputDirectory); os.IsNotExist(err) {
// If it doesn't exist, create it
// MkdirAll will create all parent directories if needed
err = os.MkdirAll(settings.OutputDirectory, os.ModePerm)
if err != nil {
return err
}
}
}
if settings.WARCWriterPoolSize == 0 {
settings.WARCWriterPoolSize = 1
}
// Add a trailing slash to the output directory
if settings.OutputDirectory[len(settings.OutputDirectory)-1:] != "/" {
settings.OutputDirectory = settings.OutputDirectory + "/"
}
// If prefix isn't specified, set it to "WARC"
if settings.Prefix == "" {
settings.Prefix = "WARC"
}
// If WARC size isn't specified, set it to 1GB (10^9 bytes) by default
if settings.WarcSize == 0 {
settings.WarcSize = 1000
}
// Check if the specified compression algorithm is valid
if settings.Compression != "" && settings.Compression != "GZIP" && settings.Compression != "ZSTD" {
return errors.New("invalid compression algorithm: " + settings.Compression)
}
// Add few headers to the warcinfo payload, to not have it empty
settings.WarcinfoContent.Set("hostname", hostName)
settings.WarcinfoContent.Set("format", "WARC file version 1.1")
settings.WarcinfoContent.Set("conformsTo", "http://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.1/")
return nil
}
func getContentLength(rwsc spooledtempfile.ReadWriteSeekCloser) int {
// If the FileName leads to no existing file, it means that the SpooledTempFile
// never had the chance to buffer to disk instead of memory, in which case we can
// just read the buffer (which should be <= 2MB) and return the length
if rwsc.FileName() == "" {
rwsc.Seek(0, 0)
buf := new(bytes.Buffer)
buf.ReadFrom(rwsc)
return buf.Len()
} else {
// Else, we return the size of the file on disk
fileInfo, err := os.Stat(rwsc.FileName())
if err != nil {
panic(err)
}
return int(fileInfo.Size())
}
}