-
Notifications
You must be signed in to change notification settings - Fork 0
/
s8td.go
241 lines (193 loc) · 4.34 KB
/
s8td.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
package main
import (
"bufio"
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"flag"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
)
var port int
var uploadRoot string
var keyFile string
var keys map[string][]byte
func init() {
flag.IntVar(&port, "port", 8080, "http listen port")
flag.StringVar(&uploadRoot, "uploadRoot", "/tmp", "root path for uploads")
flag.StringVar(&keyFile, "keyFile", "", "Path to file with id:key pairs")
}
func main() {
flag.Parse()
rand.Seed(time.Now().UnixNano())
loadKeys()
http.HandleFunc("/upload", uploadHandler)
http.HandleFunc("/", getHandler)
fmt.Printf("Listening on port %d\n", port)
fmt.Printf("Upload root is %s\n", uploadRoot)
portString := fmt.Sprintf(":%d", port)
err := http.ListenAndServe(portString, nil)
if err != nil {
fmt.Printf("Unable to start HTTP server: %s", err)
os.Exit(1)
}
}
func loadKeys() {
file, err := os.Open(keyFile)
if err != nil {
fmt.Print("Unable to load keys, file missing")
os.Exit(2)
}
tmp := map[string][]byte{}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
parts := strings.Split(":", scanner.Text())
if len(parts) != 2 {
fmt.Print("Unable to load keys, bad file format")
os.Exit(2)
}
tmp[parts[0]] = []byte(parts[1])
}
if err := scanner.Err(); err != nil {
fmt.Print("Unable to load keys, err reading file: ", err)
}
keys = tmp
}
func lookupKey(id string) ([]byte, error) {
k, ok := keys[id]
if !ok {
return nil, fmt.Errorf("ID: '%s' not found", id)
}
return k, nil
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
func randString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func checkSig(data string, sig []byte, key []byte) bool {
mac := hmac.New(sha1.New, key)
_, err := io.WriteString(mac, data)
if err != nil {
return false
}
expectedMAC := mac.Sum(nil)
return hmac.Equal(sig, expectedMAC)
}
func getHandler(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) != 2 {
http.Error(w, "not found", 404)
return
}
id := parts[1]
filePath := path.Join(uploadRoot, id)
file, err := os.Open(filePath)
if err != nil {
http.Error(w, "not found", 404)
return
}
defer func() {
closeErr := file.Close()
if closeErr != nil {
fmt.Printf("Unable to close file %s", closeErr)
}
}()
_, err = io.Copy(w, file)
if err != nil {
http.Error(w, "not found", 404)
return
}
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
id := r.FormValue("id")
tsStr := r.FormValue("ts")
sigStr := r.FormValue("sig")
fmt.Printf("id: %s ts: %s sig: %s\n", id, tsStr, sigStr)
sig, err := hex.DecodeString(sigStr)
if err != nil {
http.Error(w, "couldnt decode sig", 400)
return
}
ts, err := strconv.ParseInt(tsStr, 10, 0)
if err != nil {
http.Error(w, "ts might not be a number?", 400)
return
}
key, err := lookupKey(id)
if err != nil {
http.Error(w, "Err: id not found", 400)
return
}
if !validateTimestamp(ts) {
fmt.Println("Err: Request too old")
http.Error(w, "Request too old", 400)
return
}
if !checkSig(tsStr, sig, key) {
fmt.Println("Err: sig no match")
http.Error(w, "Sig no match", 400)
return
}
fmt.Println("all ok")
uploadedFile, _, err := r.FormFile("file")
if err != nil {
fmt.Fprintln(w, err)
return
}
defer func() {
upldErr := uploadedFile.Close()
if upldErr != nil {
fmt.Printf("Unable to close uploaded file %s", upldErr)
}
}()
fid := randString(8)
filePath := path.Join(uploadRoot, fid)
out, err := os.Create(filePath)
if err != nil {
fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
return
}
defer func() {
outErr := out.Close()
if outErr != nil {
fmt.Printf("Unable to close save destination for uplaoded file %s", outErr)
}
}()
// write the content from POST to the file
_, err = io.Copy(out, uploadedFile)
if err != nil {
fmt.Fprintln(w, err)
}
url := fmt.Sprintf("http://%s/%s", r.Host, fid)
fmt.Fprintf(w, url)
}
func abs(x int64) int64 {
if x < 0 {
return -x
}
if x == 0 {
return 0
}
return x
}
func validateTimestamp(checkTs int64) bool {
t := time.Now().Unix()
tolerance := int64(30)
d := abs(t - checkTs)
if d > tolerance {
return false
} else {
return true
}
}