forked from hidu/pproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.go
217 lines (180 loc) · 4.91 KB
/
serve.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
package serve
import (
"fmt"
"github.com/hidu/goutils"
"log"
"math/rand"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
)
type ProxyServe struct {
httpProxy *HttpProxy
wsproxy *WebsocketProxy
mydb *TieDb
wsSer *wsServer
startTime time.Time
MaxResSaveLength int64
mu sync.RWMutex
Debug bool
conf *Config
configDir string
hosts configHosts
Users map[string]*User
ProxyClients map[string]*clientSession
reqNum int64
reqMod *requestModifier
}
type KvType map[string]interface{}
func (ser *ProxyServe) ServeHTTP(w http.ResponseWriter, req *http.Request) {
host, port_int, err := getHostPortFromReq(req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("bad request"))
log.Println("bad request,err", err)
return
}
atomic.AddInt64(&ser.reqNum, 1)
if req.Host == "p.info" || req.Host == "proxy.info" {
ser.handleUserInfo(w, req)
return
}
isLocalReq := port_int == ser.conf.Port
if isLocalReq {
isLocalReq = IsLocalIp(host)
}
if isLocalReq {
ser.handleLocalReq(w, req)
} else {
if ser.Debug {
req_dump_debug, _ := httputil.DumpRequest(req, req.Method == "GET")
log.Println("DEBUG req BEFORE:\nurl_full:", req.URL.String(), "\nschema:", req.URL.Scheme, "\n", string(req_dump_debug), "\n\n")
}
isWebSocket := strings.ToLower(req.Header.Get("Upgrade")) == "websocket"
if isWebSocket {
ser.wsproxy.ServeHTTP(w, req)
} else {
if req.Method != "CONNECT" && !req.URL.IsAbs() {
urlOrigin := req.URL.String()
urlStr := "http://" + req.Host + req.URL.Path
if req.URL.RawQuery != "" {
urlStr += "?" + req.URL.RawQuery
}
var err error
req.URL, err = url.Parse(urlStr)
if err != nil {
log.Println("fix url failed,originUrl:", urlOrigin, "err:", err)
return
}
}
ser.httpProxy.ServeHTTP(w, req)
}
}
}
func (ser *ProxyServe) Start() {
ser.httpProxy = NewHttpProxy(ser)
ser.wsproxy = NewWsProxy(ser)
addr := fmt.Sprintf("%s:%d", "", ser.conf.Port)
fmt.Println("proxy listen at ", addr)
ser.ws_init()
err := http.ListenAndServe(addr, ser)
log.Println(err)
fmt.Println(err)
}
func (ser *ProxyServe) GetNewDocid() int {
id_str := fmt.Sprintf("%s%d", time.Now().Format("200601021504"), ser.reqNum)
id, err := parseDocId(id_str)
if err == nil {
return id
}
log.Println("GetNewDocid failed", id_str, err)
return int(time.Now().UnixNano() + ser.reqNum)
}
func (ser *ProxyServe) GetResponseByDocid(docid int) (res_data KvType) {
res_data, err := ser.mydb.ResponseTable.GetByKey(docid)
if err != nil {
log.Println("read res by docid failed,docid=", docid, err)
}
// fmt.Println(docid,res_data)
return res_data
}
func (ser *ProxyServe) GetRequestByDocid(docid int) (req_data KvType) {
req_data, err := ser.mydb.RequestTable.GetByKey(docid)
if err != nil {
log.Println("read req by docid failed,docid=", docid, err)
}
return req_data
}
func (ser *ProxyServe) GetRewriteJsPath() string {
return fmt.Sprintf("%s/req_rewrite_%d.js", ser.configDir, ser.conf.Port)
}
func (ser *ProxyServe) GetHostsFilePath() string {
return fmt.Sprintf("%s/hosts_%d", ser.configDir, ser.conf.Port)
}
func (ser *ProxyServe) loadHosts() {
ser.mu.Lock()
defer ser.mu.Unlock()
hosts_path := ser.GetHostsFilePath()
log.Println("load hosts:", hosts_path)
ser.hosts, _ = loadHosts(hosts_path)
}
func NewProxyServe(confPath string, port int) (*ProxyServe, error) {
conf, err := LoadConfig(confPath)
if err != nil {
log.Println("load config faield", err)
return nil, err
}
if port > 0 && port < 65535 {
conf.Port = port
}
absPath, err := filepath.Abs(confPath)
if err != nil {
log.Println("get config path failed", confPath)
return nil, err
}
GetVersion()
os.Chdir(filepath.Dir(absPath))
proxy := new(ProxyServe)
proxy.configDir = filepath.Dir(absPath)
proxy.Users, _ = loadUsers(proxy.configDir + "/users")
proxy.conf = conf
proxy.reqMod = NewRequestModifier(proxy)
err = proxy.reqMod.tryLoadJs()
if err != nil {
return nil, err
}
setupLog(conf.DataDir, conf.Port)
proxy.loadHosts()
proxy.mydb = NewTieDb(fmt.Sprintf("%s/%d/", conf.DataDir, conf.Port), conf.DataStoreDay)
proxy.startTime = time.Now()
proxy.MaxResSaveLength = 2 * 1024 * 1024
rand.Seed(time.Now().UnixNano())
proxy.ProxyClients = make(map[string]*clientSession)
utils.SetInterval(func() {
proxy.cleanExpiredSession()
}, 60)
// proxy.mydb.StartGcTimer(60,store_time)
return proxy, nil
}
func setupLog(dataDir string, port int) {
logPath := fmt.Sprintf("%s/%d.log", dataDir, port)
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
if err != nil {
log.Println("create log file failed [", logPath, "]", err)
os.Exit(2)
}
log.SetOutput(logFile)
utils.SetInterval(func() {
if !utils.File_exists(logPath) {
logFile.Close()
logFile, _ = os.OpenFile(logPath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)
log.SetOutput(logFile)
}
}, 30)
}