-
Notifications
You must be signed in to change notification settings - Fork 50
/
api.go
292 lines (250 loc) · 6.68 KB
/
api.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
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
package proxy
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sync"
"time"
)
type apiStruct struct {
Name string `json:"-"`
ConfPath string `json:"-"`
Path string `json:"path"`
Note string `json:"note"`
TimeoutMs int `json:"timeout_ms"`
Hosts Hosts `json:"hosts"`
Enable bool `json:"enable"`
Caller Caller `json:"caller"`
rw sync.RWMutex `json:"-"`
Exists bool `json:"-"`
HostAsProxy bool `json:"host_as_proxy"` //是否把后端当作代理
Pv uint64 `json:"-"`
LastVisit time.Time `json:"-"` //最后访问时间
Version int64 `json:"version"` //配置文件的版本号
apiServer *APIServer
Users users `json:"users"`
Proxy string `json:"proxy"` //使用父代理
proxyURL *url.URL `json:"-"` //父代理的URL object
analysisClientNum int `json:"-"` //进行协议分析的客户端数量
}
// init new api for server
func newAPI(apiServer *APIServer, apiName string) *apiStruct {
api := &apiStruct{
Name: apiName,
Hosts: newHosts(),
apiServer: apiServer,
}
api.ConfPath = api.getConfPath()
return api
}
func (api *apiStruct) getConfPath() string {
return fmt.Sprintf("%s/%s.json", api.apiServer.getConfDir(), api.Name)
}
func (api *apiStruct) init() (err error) {
log.Println("start load api [", api.Name, "] conf")
if api.TimeoutMs < 1 {
api.TimeoutMs = 5000
}
if api.Caller == nil {
api.Caller = newCaller()
item, _ := newCallerItem(ipAll)
item.Enable = true
item.Note = "default all"
api.Caller.addNewCallerItem(item)
}
if api.Path != "" {
api.Path = URLPathClean(api.Path)
}
if api.Proxy != "" {
api.proxyURL, _ = url.Parse(api.Proxy)
}
api.Caller.Sort()
err = api.Caller.init()
api.Exists = true
return err
}
var pathReg = regexp.MustCompile(`^/([\w-/]+/?)*$`)
var apiNameReg = regexp.MustCompile(`^[\w-]+$`)
func (api *apiStruct) isValidPath(myPath string) bool {
return pathReg.MatchString(myPath)
}
func (api *apiStruct) save() error {
api.rw.Lock()
defer api.rw.Unlock()
data, err := json.MarshalIndent(api, "", " ")
if err != nil {
return err
}
oldData, _ := ioutil.ReadFile(api.ConfPath)
if string(oldData) != string(data) {
backPath := filepath.Dir(api.ConfPath) + "/_back/" + filepath.Base(api.ConfPath) + "." + time.Now().Format(timeFormatInt)
DirCheck(backPath)
err = ioutil.WriteFile(backPath, oldData, 0644)
log.Println("backup ", backPath, err)
}
err = ioutil.WriteFile(api.ConfPath, data, 0644)
return err
}
func (api *apiStruct) delete() error {
api.rw.Lock()
defer api.rw.Unlock()
backPath := filepath.Dir(api.ConfPath) + "/_back/" + filepath.Base(api.ConfPath) + "." + time.Now().Format(timeFormatInt)
DirCheck(backPath)
err := os.Rename(api.ConfPath, backPath)
log.Println("backup ", backPath, err)
return err
}
func (api *apiStruct) reName(newName string) error {
if api.Name == newName {
log.Println("rename skip,not change,newName:", newName)
return nil
}
err := api.delete()
if err != nil {
return err
}
api.Name = newName
api.ConfPath = api.getConfPath()
return api.save()
}
func (api *apiStruct) clone() *apiStruct {
api.rw.RLock()
defer api.rw.RUnlock()
data, _ := json.Marshal(api)
var newAPI *apiStruct
json.Unmarshal(data, &newAPI)
newAPI.Name = api.Name
newAPI.ConfPath = api.ConfPath
newAPI.Exists = api.Exists
newAPI.init()
newAPI.apiServer = api.apiServer
newAPI.Hosts.init()
return newAPI
}
func (api *apiStruct) hostRename(origName, newName string) {
if origName == "" || origName == newName {
return
}
api.rw.Lock()
defer api.rw.Unlock()
if _, has := api.Hosts[origName]; has {
delete(api.Hosts, origName)
}
}
func (api *apiStruct) hostCheckDelete(hostNames []string) {
api.rw.Lock()
defer api.rw.Unlock()
tmpMap := make(map[string]int)
for _, v := range hostNames {
tmpMap[v] = 1
}
for n := range api.Hosts {
if _, has := tmpMap[n]; !has {
delete(api.Hosts, n)
}
}
}
func (api *apiStruct) getMasterHostName(cpf *CallerPrefConf) string {
api.rw.RLock()
defer api.rw.RUnlock()
var names []string
for name, host := range api.Hosts {
if host.Enable {
names = append(names, name)
}
}
return api.Caller.getPrefHostName(names, cpf)
}
func (api *apiStruct) cookieName() string {
return apiCookieName(api.Name)
}
func loadAPIByConf(apiServer *APIServer, apiName string) (*apiStruct, error) {
api := newAPI(apiServer, apiName)
relName, _ := filepath.Rel(filepath.Dir(apiServer.getConfDir()), api.ConfPath)
logMsg := fmt.Sprint("load api [", apiName, "],[", relName, "]")
log.Println(logMsg, "start")
data, err := ioutil.ReadFile(api.ConfPath)
if err != nil {
log.Println(logMsg, "failed,", err)
return api, err
}
err = json.Unmarshal(data, &api)
if err != nil {
log.Println(logMsg, "failed,", err)
return api, err
}
api.Hosts.init()
log.Println(logMsg, "success")
if api.Path == "" {
api.Path = fmt.Sprintf("/%s/", apiName)
}
if !api.isValidPath(api.Path) {
return api, fmt.Errorf("path wrong:%s", api.Path)
}
err = api.init()
api.Exists = true
return api, err
}
func (api *apiStruct) pvInc() uint64 {
return api.apiServer.GetCounter().pvInc(api.Name)
}
func (api *apiStruct) GetPv() uint64 {
return api.apiServer.GetCounter().GetPv(api.Name)
}
func (api *apiStruct) uniqID() string {
sc := api.apiServer.ServerVhostConf
return fmt.Sprintf("api|%s|%d|%s", sc.Id, sc.Port, api.Name)
}
func apiCookieName(apiName string) string {
return fmt.Sprintf("%s_%s", apiPrefParamName, apiName)
}
/**
* get sorted hosts,master is at first
*/
func (api *apiStruct) getAPIHostsByReq(req *http.Request) (hs []*Host, master string, cpf *CallerPrefConf) {
cpf = newCallerPrefConfByHTTPRequest(req, api)
caller := api.Caller.getCallerItemByIP(cpf.GetIP())
masterHost := api.getMasterHostName(cpf)
hs = make([]*Host, 0)
var hsTmp []*Host
for _, apiHost := range api.Hosts {
if !apiHost.Enable || caller.isHostIgnore(apiHost.Name, cpf) {
continue
}
if apiHost.Name == masterHost {
hs = append(hs, apiHost)
} else {
hsTmp = append(hsTmp, apiHost)
}
}
hs = append(hs, hsTmp...)
return hs, masterHost, cpf
}
func (api *apiStruct) userCanEditById(id string) bool {
if api.Users != nil && api.Users.hasUser(id) {
return true
}
return api.apiServer.hasUser(id)
}
func (api *apiStruct) userCanEdit(u *User) bool {
var id string
if u != nil {
id = u.ID
}
return api.userCanEditById(id)
}
func (api *apiStruct) analysisClientNumInc(num int) int {
api.rw.Lock()
defer api.rw.Unlock()
api.analysisClientNum += num
if api.analysisClientNum < 0 {
api.analysisClientNum = 0
}
return api.analysisClientNum
}