-
Notifications
You must be signed in to change notification settings - Fork 10
/
cdnize.go
231 lines (179 loc) · 5.31 KB
/
cdnize.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
/**
*
* AnsCDN Copyright (C) 2010 Robin Syihab (r [at] nosql.asia)
* Simple CDN server written in Golang.
*
* License: General Public License v2 (GPLv2)
*
* Copyright (c) 2009 The Go Authors. All rights reserved.
*
**/
package cdnize
import (
"fmt"
"http"
"rand"
"time"
"path"
"crypto/hmac"
"os"
"syscall"
"json"
"./anlog"
"./config"
"./downloader"
)
var Cfg *config.AnscdnConf
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123567890abcdefghijklmnopqrstuvwxyz_";
func RandStrings(N int) string {
rand.Seed(time.Nanoseconds())
buf := make([]byte, N + 1)
for i := 0; i < N; i++ {
buf[i] = chars[rand.Intn(len(chars))]
}
return string(buf[0:N])
}
func write(c http.ResponseWriter, f string, v ...interface{}){fmt.Fprintf(c,f,v...);}
func Jsonize(data interface{}) string{
rv, err := json.Marshal(&data)
if err != nil{
anlog.Error("Cannot jsonize `%v`\n", data)
return ""
}
return string(rv)
}
func jsonError(status, info string) string{
return Jsonize(map[string]string{"Status":status,"Info":info})
}
func Handler(c http.ResponseWriter, r *http.Request){
c.Header().Set("Content-Type", "application/json")
api_key := r.FormValue("api_key")
//base_url := r.FormValue("base_url")
if api_key != Cfg.ApiKey{
write(c,jsonError("failed","Invalid api key"))
return
}
requested_url := r.FormValue("u")
if requested_url == ""{
r.ParseForm()
file_name := r.FormValue("file_name")
if file_name == ""{
write(c,jsonError("failed","no `file_name` parameter"))
return
}
fmt.Printf("file_name: %v\n", file_name)
file, err := r.MultipartReader()
if err != nil{
write(c,jsonError("failed","cannot get multipart reader"))
return
}
part, err := file.NextPart()
if err != nil{
write(c,jsonError("failed","no `u` nor `file`"))
return
}
var data [1000]byte
var i int = 0
var data_size int64 = 0
md5ed := hmac.NewMD5([]byte("cdnized-2194"))
abs_path := "/tmp/" + RandStrings(100)
dst_file, err := os.OpenFile(abs_path,os.O_WRONLY | os.O_CREATE,0755)
if err != nil {
anlog.Error("Cannot create file `%s`. error: %s\n", abs_path,err.String())
write(c,jsonError("failed",fmt.Sprintf("cannot create temporary data. %v\n",err)))
return
}
for data_size < r.ContentLength{
i, err = part.Read(data[0:999])
if err !=nil{
break
}
_, err := md5ed.Write(data[0:i])
if err != nil{
anlog.Error("Cannot calculate MD5 hash")
write(c,jsonError("failed","cannot calculate checksum"))
break
}
_, err = dst_file.Write(data[0:i])
if err != nil{
anlog.Error("Cannot write %d bytes data in file `%s`. error: %s\n", data_size, abs_path, err.String())
}
data_size += int64(i)
}
dst_file.Close()
//fmt.Printf("content-length: %v, file: %v, file-length: %v, i: %v\n", r.ContentLength, string(data[0:]), i, i)
hash := fmt.Sprintf("%x", md5ed.Sum())
file_ext := path.Ext(file_name)
file_name = hash + RandStrings(9) + file_ext
new_path, err := os.Getwd()
new_path = path.Join(new_path, Cfg.StoreDir[2:], Cfg.ApiStorePrefix, file_name)
if err != nil {
anlog.Error("Cannot getwd\n")
write(c,jsonError("failed","internal error"))
return
}
//fmt.Printf("abs_path: %v, new_path: %v\n", abs_path, new_path)
if err := syscall.Rename(abs_path, new_path); err != 0{
anlog.Error("Cannot move from file `%s` to `%s`. %v.\n", abs_path, new_path, err)
write(c,jsonError("failed","internal error"))
return
}
cdnized_url := fmt.Sprintf("http://%s/%s/%s/%s", Cfg.CdnServerName, Cfg.StoreDir[2:], Cfg.ApiStorePrefix, file_name)
anlog.Info("cdnized_url: %s\n", cdnized_url)
os.Remove(abs_path)
type success struct{
Status string
Size int64
Cdnized_url string
}
write(c, Jsonize(&success{"ok", data_size, cdnized_url}))
return
}
//write(c, fmt.Sprintf("{Status: 'ok', url_path: '%s', gen: '%s'}", requested_url, x))
file_ext := path.Ext(requested_url)
abs_path, _ := os.Getwd()
abs_path = path.Join(abs_path, Cfg.StoreDir[2:], Cfg.ApiStorePrefix, RandStrings(64) + file_ext)
fmt.Printf("abs_path: %s\n", abs_path)
var data []byte;
rv, lm, tsize := downloader.Download(requested_url, abs_path, true, &data)
if rv != true{
write(c,jsonError("failed","Cannot fetch from source url"))
return
}
md5ed := hmac.NewMD5([]byte("cdnized-2194"))
for {
brw, err := md5ed.Write(data)
if err != nil{
anlog.Error("Cannot calculate MD5 hash")
write(c,jsonError("failed","Internal error"))
return
}
if brw >= tsize{
break;
}
}
hash := fmt.Sprintf("%x", md5ed.Sum())
dir, _ := path.Split(abs_path)
file_name := hash + RandStrings(8) + file_ext
new_path := path.Join(dir, file_name)
if err := syscall.Rename(abs_path, new_path); err != 0{
anlog.Error("Cannot rename from file `%s` to `%s`", abs_path, new_path)
write(c,jsonError("failed","Internal error"))
return
}
cdnized_url := fmt.Sprintf("http://%s/%s/%s/%s", Cfg.CdnServerName, Cfg.StoreDir[2:], Cfg.ApiStorePrefix, file_name)
anlog.Info("cdnized_url: %s", cdnized_url)
type success struct{
Status string
Lm string
Size int
Original string
Cdnized_url string
}
write(c, Jsonize(&success{"ok", lm, tsize, requested_url, cdnized_url}))
}
func StaticHandler(c http.ResponseWriter, r *http.Request){
path := r.URL.Path
root, _ := os.Getwd()
http.ServeFile(c, r, root + "/" + path)
}