/
file.go
177 lines (166 loc) · 4.79 KB
/
file.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
package api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/OPSWAT/mdcloud-go/pkg/utils"
"github.com/google/go-cmp/cmp"
"github.com/sirupsen/logrus"
)
// RescanReq used for rescan body
type RescanReq struct {
FileIDs []string `json:"file_ids"`
}
type ScanResp struct {
DataID string `json:"data_id"`
ScanResults struct {
ProgressPercentage int `json:"progress_percentage"`
} `json:"scan_results"`
Error ApiError `json:"error"`
}
// ScanFile sends to API
func (api *API) ScanFile(path string, headers []string, poll bool) (string, error) {
url := fmt.Sprintf("%s/file", api.URL)
file, err := os.Open(path)
if err != nil {
logrus.Errorln(err)
return "", err
}
defer file.Close()
req, err := http.NewRequest(http.MethodPost, url, file)
if err != nil {
logrus.Errorln(err)
return "", err
}
req.Header.Add("apikey", api.Token)
req.Header.Add("Content-Type", "application/octet-stream")
req.Header.Add("x-filename", filepath.Base(path))
if len(headers) > 0 {
for _, v := range headers {
h := strings.Split(v, "=")
req.Header.Add(h[0], h[1])
}
}
resp, err := api.Client.Do(req)
if err != nil {
logrus.Errorln(err)
return "", err
}
var s = new(ScanResp)
progress, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(progress, &s)
filterHeaders := func(s string) bool { return strings.HasPrefix(s, "X-") }
rateLimits := utils.FilterMap(resp.Header, filterHeaders)
api.Limits = rateLimits
if err != nil {
logrus.Errorln(err)
return "", err
}
if resp.StatusCode != 200 {
logrus.WithFields(logrus.Fields{"status_code": resp.StatusCode, "error_code": s.Error.Code, "error_message": strings.Join(s.Error.Messages, ",")}).Errorln(resp.Status)
return "", nil
} else {
logrus.WithFields(logrus.Fields{"result": string(progress)}).Infoln(fmt.Sprintf("Uploaded %s", filepath.Base(path)))
}
defer resp.Body.Close()
if !poll {
logrus.WithField("data_id", s.DataID).Infoln("Result data_id")
if r, e := json.Marshal(s); e == nil {
return string(r), nil
}
logrus.Errorln(err)
return "", err
}
var jsonResult string
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
done := make(chan bool)
for {
select {
case <-ticker.C:
result := new(ScanResp)
resDataID, err := api.ResultsByDataID(s.DataID)
if err != nil {
return "", errors.New("Failed to get results for: " + resDataID)
}
json.NewDecoder(strings.NewReader(resDataID)).Decode(&result)
response, _ := json.Marshal(resDataID)
jsonResult, _ = strconv.Unquote(string(response))
if result.ScanResults.ProgressPercentage == 100 {
go func() { done <- true }()
}
logrus.WithFields(logrus.Fields{
"data_id": s.DataID,
"progress_percentage": result.ScanResults.ProgressPercentage,
}).Info("Scan progress")
case <-done:
close(done)
return jsonResult, nil
}
}
}
// ResultsByDataID by data_id
func (api *API) ResultsByDataID(dataID string) (string, error) {
url := fmt.Sprintf("%s/file/%s", api.URL, dataID)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
req.Header.Add("apikey", api.Token)
return fmtResponse(api.Client.Do(req))
}
// RescanFile by file_id
func (api *API) RescanFile(fileID string) (string, error) {
url := fmt.Sprintf("%s/file/%s/rescan", api.URL, fileID)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
req.Header.Add("apikey", api.Token)
return fmtResponse(api.Client.Do(req))
}
// RescanFiles by file_ids
func (api *API) RescanFiles(fileIDs []string) (string, error) {
url := fmt.Sprintf("%s/file/rescan", api.URL)
payload := &RescanReq{FileIDs: fileIDs}
j, _ := json.Marshal(payload)
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(j))
if err != nil {
return "", err
}
req.Header.Add("apikey", api.Token)
req.Header.Add("content-type", "application/json")
return fmtResponse(api.Client.Do(req))
}
// GetSanitizedLink Retrieve the download link for a sanitized file
func (api *API) GetSanitizedLink(fileID string) (string, error) {
url := fmt.Sprintf("%s/file/%s/sanitizedLink", api.URL, fileID)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
req.Header.Add("apikey", api.Token)
return fmtResponse(api.Client.Do(req))
}
// FindOrScan file by hash
func (api *API) FindOrScan(path, hash string, headers []string, lookup, poll bool) (string, error) {
if !lookup {
return api.ScanFile(path, headers, poll)
}
result := new(ScanResp)
strRes, err := api.HashDetails(hash)
json.NewDecoder(strings.NewReader(strRes)).Decode(&result)
if cmp.Equal(result.Error, ApiError{}) {
logrus.WithField("hash", hash).Info("Hash not found sending to scan")
return api.ScanFile(path, headers, poll)
}
return strRes, err
}