Repository navigation
Expand file tree
/
Copy pathclient.go
More file actions
502 lines (452 loc) · 15.2 KB
/
Copy pathclient.go
File metadata and controls
502 lines (452 loc) · 15.2 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package warc
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/maypok86/otter"
"github.com/miekg/dns"
http "github.com/saveweb/fhttp"
"github.com/saveweb/tls-client/profiles"
)
type Error struct {
Err error
Func string
}
type HTTPClientSettings struct {
RotatorSettings *RotatorSettings
TempDir string
DNSServers []string
DNSFallback *dns.ClientConfig
DedupeOptions DedupeOptions
DialTimeout time.Duration
ResponseHeaderTimeout time.Duration
DNSResolutionTimeout time.Duration
DNSRecordsTTL time.Duration
DNSCacheSize int
DNSConcurrency int
TLSHandshakeTimeout time.Duration
ConnReadDeadline time.Duration
DecompressBody bool
FollowRedirects bool
InsecureSkipVerifyCerts bool
RandomLocalIP bool
DisableIPv4 bool
DisableIPv6 bool
IPv6AnyIP bool
DigestAlgorithm DigestAlgorithm
DisableKeepAlives bool
DefaultUserAgent string
ClientProfile profiles.ClientProfile
RandomTLSExtensionOrder bool
MaxIdleConns int
MaxIdleConnsPerHost int
IdleConnTimeout time.Duration
EarlyCloseDrainLimit int64
EarlyCloseDrainTimeout time.Duration
MaxConcurrentDrains int
EnableHTTP2 bool
EnableHTTP3 bool
ForceProtocol string // "http/1.1", "h2", "h3"
}
type CustomHTTPClient struct {
interfacesWatcherStop chan bool
WaitGroup *WaitGroupWithCount
dedupeHashTable *otter.Cache[string, revisitRecord]
ErrChan chan *Error
WARCWriter chan *RecordBatch
interfacesWatcherStarted chan bool
protoClient protocolClient
TempDir string
warcWriterDoneChannels []chan bool
writerResults []<-chan writerResult
dedupeOptions DedupeOptions
TLSHandshakeTimeout time.Duration
ResponseHeaderTimeout time.Duration
ConnReadDeadline time.Duration
insecureSkipVerifyCerts bool
DigestAlgorithm DigestAlgorithm
recordIDVersion UUIDVersion
closeDNSCache func()
closeDedupeCache func()
randomLocalIP bool
DataTotal *atomic.Int64
disableKeepAlives bool
keepAliveMaxIdle int
keepAliveMaxIdlePerHost int
keepAliveIdleTimeout time.Duration
earlyCloseDrainLimit int64
earlyCloseDrainTimeout time.Duration
drainSlots chan struct{}
DecompressBody bool
defaultUserAgent string
followRedirects bool
randomTLSExtensionOrder bool
compatWG sync.WaitGroup
lifecycleMu sync.Mutex
closing bool
shutdownOnce sync.Once
shutdownDone chan struct{}
shutdownResult FinalizeResult
pendingExchanges map[*exchangeState]struct{}
CDXDedupeTotalBytes *atomic.Int64
DoppelgangerDedupeTotalBytes *atomic.Int64
LocalDedupeTotalBytes *atomic.Int64
CDXDedupeTotal *atomic.Int64
DoppelgangerDedupeTotal *atomic.Int64
LocalDedupeTotal *atomic.Int64
dialTimeout time.Duration
dnsRecordsTTL time.Duration
dnsResolutionTimeout time.Duration
dnsCacheSize int
dnsServers []string
dnsFallback *dns.ClientConfig
dnsConcurrency int
disableIPv4 bool
disableIPv6 bool
tlsProfile *TLSProfile
}
type FinalizeResult struct {
FinalizedFiles []string
Err error
}
// Shutdown stops new work and waits for every active capture and WARC writer
// to finish. The returned filenames have been flushed, closed and renamed.
// ctx controls only how long the caller waits; shutdown itself continues.
func (c *CustomHTTPClient) Shutdown(ctx context.Context) (FinalizeResult, error) {
c.shutdownOnce.Do(func() {
c.lifecycleMu.Lock()
c.closing = true
pending := make([]*exchangeState, 0, len(c.pendingExchanges))
for state := range c.pendingExchanges {
pending = append(pending, state)
}
c.lifecycleMu.Unlock()
stopTransportEarly := false
for _, state := range pending {
stopTransportEarly = state.closeForShutdown() || stopTransportEarly
}
go c.runShutdown(stopTransportEarly)
})
select {
case <-c.shutdownDone:
result := c.shutdownResult
result.FinalizedFiles = append([]string(nil), result.FinalizedFiles...)
return result, result.Err
case <-ctx.Done():
return FinalizeResult{}, context.Cause(ctx)
}
}
func (c *CustomHTTPClient) runShutdown(stopTransportEarly bool) {
defer close(c.shutdownDone)
var wg sync.WaitGroup
if stopTransportEarly && c.protoClient != nil {
c.protoClient.Shutdown()
}
c.WaitGroup.Wait()
c.compatWG.Wait()
if !stopTransportEarly && c.protoClient != nil {
c.protoClient.Shutdown()
}
close(c.WARCWriter)
wg.Add(len(c.warcWriterDoneChannels))
for _, doneChan := range c.warcWriterDoneChannels {
go func(done <-chan bool) {
defer wg.Done()
<-done
}(doneChan)
}
wg.Wait()
var writerErrs []error
var finalizedFiles []string
for _, resultChan := range c.writerResults {
result := <-resultChan
writerErrs = append(writerErrs, result.Err)
finalizedFiles = append(finalizedFiles, result.FinalizedFiles...)
}
close(c.ErrChan)
if c.randomLocalIP {
c.interfacesWatcherStop <- true
close(c.interfacesWatcherStop)
}
c.closeDedupeCache()
c.shutdownResult = FinalizeResult{FinalizedFiles: finalizedFiles, Err: errors.Join(writerErrs...)}
}
// Close is the compatibility form of Shutdown.
func (c *CustomHTTPClient) Close() error {
_, err := c.Shutdown(context.Background())
return err
}
func (c *CustomHTTPClient) Do(req *http.Request) (*http.Response, error) {
c.lifecycleMu.Lock()
if c.closing {
c.lifecycleMu.Unlock()
return nil, errors.New("warc: client is closing")
}
c.compatWG.Add(1)
c.lifecycleMu.Unlock()
exchange, err := c.start(req, exchangeCommit)
if exchange == nil {
c.compatWG.Done()
return nil, err
}
go func() {
defer c.compatWG.Done()
result, _ := exchange.wait(context.Background())
var archiveErrs []error
for _, attempt := range result.Attempts {
archiveErrs = append(archiveErrs, attempt.Err)
}
archiveErr := errors.Join(archiveErrs...)
if archiveErr == nil {
return
}
select {
case c.ErrChan <- &Error{Err: archiveErr, Func: "Exchange.Commit"}:
default:
}
}()
return exchange.Response, err
}
// Start executes req and returns an Exchange that the caller must finish with
// Commit or Discard after inspecting the response. Start can return both a
// non-nil Exchange and an error when a failed transport attempt was captured.
// Commit includes that Start error in its complete result, so callers must not
// join the two errors.
func (c *CustomHTTPClient) Start(req *http.Request) (*Exchange, error) {
return c.start(req, exchangeUndecided)
}
func (c *CustomHTTPClient) start(req *http.Request, decision exchangeDecision) (*Exchange, error) {
if req == nil {
return nil, errors.New("warc: nil request")
}
c.lifecycleMu.Lock()
if c.closing {
c.lifecycleMu.Unlock()
return nil, errors.New("warc: client is closing")
}
var feedback chan FeedbackEvent
if value := req.Context().Value(ContextKeyFeedback); value != nil {
var ok bool
feedback, ok = value.(chan FeedbackEvent)
if !ok {
c.lifecycleMu.Unlock()
return nil, errors.New("warc: feedback channel has invalid type")
}
if cap(feedback) == 0 {
c.lifecycleMu.Unlock()
return nil, errors.New("warc: feedback channel must be buffered")
}
}
state := newExchangeState(c, feedback, decision)
c.pendingExchanges[state] = struct{}{}
ctx := context.WithValue(req.Context(), exchangeContextKey{}, state)
req = req.Clone(ctx)
req.URL.Scheme = strings.ToLower(req.URL.Scheme)
c.WaitGroup.Add(1)
c.lifecycleMu.Unlock()
resp, err := c.protoClient.Do(ctx, req)
c.WaitGroup.Done()
state.attachResponse(resp)
exchange := &Exchange{Response: resp, state: state}
return exchange, err
}
func (c *CustomHTTPClient) unregisterExchange(state *exchangeState) {
c.lifecycleMu.Lock()
delete(c.pendingExchanges, state)
c.lifecycleMu.Unlock()
}
func (c *CustomHTTPClient) Get(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
func (c *CustomHTTPClient) Head(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodHead, url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
func (c *CustomHTTPClient) Post(url, contentType string, body interface{}) (*http.Response, error) {
reader, ok := body.(io.Reader)
if body != nil && !ok {
return nil, fmt.Errorf("warc: POST body has type %T, want io.Reader", body)
}
req, err := http.NewRequest(http.MethodPost, url, reader)
if err != nil {
return nil, err
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
return c.Do(req)
}
func (c *CustomHTTPClient) CloseIdleConnections() {
if c.protoClient != nil {
c.protoClient.CloseIdleConnections()
}
}
func NewWARCWritingHTTPClient(HTTPClientSettings HTTPClientSettings) (httpClient *CustomHTTPClient, err error) {
if HTTPClientSettings.RotatorSettings == nil {
return nil, errors.New("warc: RotatorSettings is required")
}
if err := checkRotatorSettings(HTTPClientSettings.RotatorSettings); err != nil {
return nil, err
}
httpClient = new(CustomHTTPClient)
httpClient.shutdownDone = make(chan struct{})
httpClient.pendingExchanges = make(map[*exchangeState]struct{})
httpClient.DataTotal = &DataTotal
httpClient.CDXDedupeTotalBytes = &CDXDedupeTotalBytes
httpClient.DoppelgangerDedupeTotalBytes = &DoppelgangerDedupeTotalBytes
httpClient.LocalDedupeTotalBytes = &LocalDedupeTotalBytes
httpClient.CDXDedupeTotal = &CDXDedupeTotal
httpClient.DoppelgangerDedupeTotal = &DoppelgangerDedupeTotal
httpClient.LocalDedupeTotal = &LocalDedupeTotal
httpClient.randomLocalIP = HTTPClientSettings.RandomLocalIP
httpClient.DigestAlgorithm = HTTPClientSettings.DigestAlgorithm
httpClient.recordIDVersion = HTTPClientSettings.RotatorSettings.RecordIDVersion
HTTPClientSettings.RotatorSettings.digestAlgorithm = HTTPClientSettings.DigestAlgorithm
httpClient.dedupeOptions = HTTPClientSettings.DedupeOptions
dedupeCacheSize := HTTPClientSettings.DedupeOptions.DedupeCacheSize
if dedupeCacheSize == 0 {
dedupeCacheSize = 1_000_000
}
dedupeCache, err := otter.MustBuilder[string, revisitRecord](dedupeCacheSize).Build()
if err != nil {
return nil, err
}
httpClient.dedupeHashTable = &dedupeCache
httpClient.closeDedupeCache = func() {
httpClient.dedupeHashTable.Close()
}
constructed := false
defer func() {
if constructed {
return
}
if httpClient.protoClient != nil {
httpClient.protoClient.Shutdown()
}
httpClient.closeDedupeCache()
}()
if httpClient.dedupeOptions.SizeThreshold == 0 {
httpClient.dedupeOptions.SizeThreshold = 2048
}
httpClient.ErrChan = make(chan *Error, 64)
httpClient.insecureSkipVerifyCerts = HTTPClientSettings.InsecureSkipVerifyCerts
if HTTPClientSettings.TempDir != "" {
httpClient.TempDir = HTTPClientSettings.TempDir
err = os.MkdirAll(httpClient.TempDir, os.ModePerm)
if err != nil {
return nil, err
}
}
httpClient.WaitGroup = new(WaitGroupWithCount)
if HTTPClientSettings.DialTimeout == 0 {
HTTPClientSettings.DialTimeout = 10 * time.Second
}
if HTTPClientSettings.ResponseHeaderTimeout == 0 {
HTTPClientSettings.ResponseHeaderTimeout = 10 * time.Second
}
if HTTPClientSettings.TLSHandshakeTimeout == 0 {
HTTPClientSettings.TLSHandshakeTimeout = 10 * time.Second
}
if HTTPClientSettings.DNSResolutionTimeout == 0 {
HTTPClientSettings.DNSResolutionTimeout = 5 * time.Second
}
if HTTPClientSettings.DNSRecordsTTL == 0 {
HTTPClientSettings.DNSRecordsTTL = 5 * time.Minute
}
if HTTPClientSettings.DNSCacheSize == 0 {
HTTPClientSettings.DNSCacheSize = 10_000
}
httpClient.TLSHandshakeTimeout = HTTPClientSettings.TLSHandshakeTimeout
httpClient.ResponseHeaderTimeout = HTTPClientSettings.ResponseHeaderTimeout
httpClient.ConnReadDeadline = HTTPClientSettings.ConnReadDeadline
httpClient.DecompressBody = HTTPClientSettings.DecompressBody
httpClient.disableKeepAlives = HTTPClientSettings.DisableKeepAlives
httpClient.keepAliveMaxIdle = HTTPClientSettings.MaxIdleConns
httpClient.keepAliveMaxIdlePerHost = HTTPClientSettings.MaxIdleConnsPerHost
httpClient.keepAliveIdleTimeout = HTTPClientSettings.IdleConnTimeout
if HTTPClientSettings.EarlyCloseDrainLimit == 0 {
HTTPClientSettings.EarlyCloseDrainLimit = 1 << 20
}
if HTTPClientSettings.EarlyCloseDrainTimeout == 0 {
HTTPClientSettings.EarlyCloseDrainTimeout = 2 * time.Second
}
if HTTPClientSettings.MaxConcurrentDrains == 0 {
HTTPClientSettings.MaxConcurrentDrains = 32
}
httpClient.earlyCloseDrainLimit = HTTPClientSettings.EarlyCloseDrainLimit
httpClient.earlyCloseDrainTimeout = HTTPClientSettings.EarlyCloseDrainTimeout
if HTTPClientSettings.MaxConcurrentDrains > 0 {
httpClient.drainSlots = make(chan struct{}, HTTPClientSettings.MaxConcurrentDrains)
}
httpClient.defaultUserAgent = HTTPClientSettings.DefaultUserAgent
httpClient.followRedirects = HTTPClientSettings.FollowRedirects
httpClient.randomTLSExtensionOrder = HTTPClientSettings.RandomTLSExtensionOrder
httpClient.dialTimeout = HTTPClientSettings.DialTimeout
httpClient.dnsRecordsTTL = HTTPClientSettings.DNSRecordsTTL
httpClient.dnsResolutionTimeout = HTTPClientSettings.DNSResolutionTimeout
httpClient.dnsCacheSize = HTTPClientSettings.DNSCacheSize
httpClient.dnsServers = HTTPClientSettings.DNSServers
httpClient.dnsFallback = HTTPClientSettings.DNSFallback
httpClient.dnsConcurrency = HTTPClientSettings.DNSConcurrency
httpClient.disableIPv4 = HTTPClientSettings.DisableIPv4
httpClient.disableIPv6 = HTTPClientSettings.DisableIPv6
httpClient.tlsProfile = NewTLSProfile(HTTPClientSettings.ClientProfile, HTTPClientSettings.RandomTLSExtensionOrder)
switch HTTPClientSettings.ForceProtocol {
case "h2":
h2c, err := newHTTP2Client(httpClient, false, false, false)
if err != nil {
return nil, err
}
httpClient.protoClient = h2c
case "h3":
h3c, err := newHTTP2Client(httpClient, false, true, false)
if err != nil {
return nil, err
}
httpClient.protoClient = h3c
default:
if HTTPClientSettings.EnableHTTP2 || HTTPClientSettings.EnableHTTP3 {
h2c, err := newHTTP2Client(httpClient, HTTPClientSettings.EnableHTTP3, false, false)
if err != nil {
return nil, err
}
httpClient.protoClient = h2c
} else {
h1c, err := newHTTP2Client(httpClient, false, false, true)
if err != nil {
return nil, err
}
httpClient.protoClient = h1c
}
}
httpClient.closeDNSCache = func() {
if transport, ok := httpClient.protoClient.(*http2Client); ok && transport.dialer != nil {
transport.dialer.close()
}
}
httpClient.WARCWriter, httpClient.warcWriterDoneChannels, httpClient.writerResults, err = HTTPClientSettings.RotatorSettings.newWARCRotator()
if err != nil {
return nil, err
}
if httpClient.randomLocalIP {
httpClient.interfacesWatcherStop = make(chan bool)
httpClient.interfacesWatcherStarted = make(chan bool)
go httpClient.getAvailableIPs(HTTPClientSettings.IPv6AnyIP)
<-httpClient.interfacesWatcherStarted
}
constructed = true
return httpClient, nil
}