-
Notifications
You must be signed in to change notification settings - Fork 16
/
remote.go
91 lines (70 loc) · 1.7 KB
/
remote.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
package ipsw
import (
"archive/zip"
"fmt"
"io"
"log"
"net/http"
"net/url"
"time"
"github.com/cj123/ranger"
)
var MaxDownloadTries = 10
var DefaultClient HTTPClient = &http.Client{
Timeout: 30 * time.Second,
}
// HTTPClient is a wrapper for client
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
Get(string) (*http.Response, error)
Head(string) (*http.Response, error)
Post(string, string, io.Reader) (*http.Response, error)
PostForm(string, url.Values) (*http.Response, error)
}
func bufferedDownload(file *zip.File, writer io.Writer) error {
rc, err := file.Open()
if err != nil {
return err
}
defer rc.Close()
_, err = io.Copy(writer, rc)
return err
}
func DownloadFile(resource, file string, w io.Writer) error {
u, err := url.Parse(resource)
if err != nil {
return err
}
var zipReader *zip.Reader
for downloadCount := 1; downloadCount <= MaxDownloadTries; downloadCount++ {
reader, err := ranger.NewReader(
&ranger.HTTPRanger{
URL: u,
Client: DefaultClient,
DisableAcceptRangesHeaderCheck: true,
},
)
if err != nil {
return err
}
readerLen, err := reader.Length()
if err != nil {
return err
}
zipReader, err = zip.NewReader(reader, readerLen)
if err == zip.ErrFormat && downloadCount != MaxDownloadTries {
log.Printf("Caught error, %s, trying again (%d of %d)", err, downloadCount, MaxDownloadTries)
continue
} else if err != nil {
return err
} else { // err == nil
break
}
}
for _, f := range zipReader.File {
if f.Name == file {
return bufferedDownload(f, w)
}
}
return fmt.Errorf("pwn: file '%s' not found in resource '%s'", file, resource)
}