-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
1525 lines (1388 loc) · 46 KB
/
server.go
File metadata and controls
1525 lines (1388 loc) · 46 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 fangyousong(方友松). All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package paddy
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math"
"net"
"net/http"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/golang/glog"
"github.com/truexf/goutil"
"github.com/truexf/goutil/jsonexp"
"github.com/truexf/goutil/lblhttpclient"
)
// 插件接口
type Plugin interface {
// 唯一身份ID
ID() string
// 收到请求后介入
// hijacked 是否劫持:true则必须实现respWriter写响应;false时不准向respWriter写响应,可以返回backend(此时框架直接去请求backend而不再走location匹配流程,否则框架执行location匹配)
RequestHeaderCompleted(req *http.Request, respWriter http.ResponseWriter, context goutil.Context) (hijacked bool, proxyPass, backend string, err goutil.Error)
// 框架在得到响应后,给客户端发送响应之前介入
// hijacked 是否劫持:true则必须实现respWriter写响应;false时,不准向respWriter写响应,可以返回newResponse(此时框架以newResponse写响应,否则以originResponse写响应)
ResponseHeaderCompleted(originResponse *http.Response, respWriter http.ResponseWriter, context goutil.Context) (hijacked bool, newResponse *http.Response, err goutil.Error)
}
type Backend struct {
Ip string
Port uint16
Weight int
}
type BackendGroup struct {
Name string
BackendList []Backend
}
type BackendDef struct {
Alias string
BackendList []Backend
backendGroupList []string
Method string
ParamKey string
MaxIdleConn int
WaitResponseTiemout time.Duration
lbClient *lblhttpclient.LblHttpClient
}
func (m *BackendDef) createLbClient() {
m.lbClient = lblhttpclient.NewLoadBalanceClient(
MethodStrToI(m.Method),
m.MaxIdleConn,
m.ParamKey,
time.Millisecond*time.Duration(DefaultBackendConnTimeout),
m.WaitResponseTiemout,
)
for _, v := range m.BackendList {
for i := 0; i < v.Weight; i++ {
m.lbClient.AddBackend(fmt.Sprintf("%s:%d", v.Ip, v.Port), fmt.Sprintf("%s:%d:%d", v.Ip, v.Port, i), nil)
}
}
}
type RegexpLocationItem struct {
uriRegexp *regexp.Regexp
backend string
fileRoot string
proxyPass string
requestFilter *jsonexp.JsonExpGroup
responseFilter *jsonexp.JsonExpGroup
}
// 基于正则表达式的location配置
type RegexpLocation struct {
Items []*RegexpLocationItem
}
// 基于jsonexp的location配置项
type JsonexpLocation struct {
Exp *jsonexp.JsonExpGroup
requestFilter *jsonexp.JsonExpGroup
responseFilter *jsonexp.JsonExpGroup
}
type Listener struct {
port uint16
tls bool
tcpListener *net.TCPListener
httpServer *http.Server
}
// 虚拟服务器配置
type VirtualServer struct {
listenPorts map[uint16]bool // value is tls
hosts map[string][]byte
tlsCert string
tlsCertKey string
regexpLocation *RegexpLocation
jsonexpLocation *JsonexpLocation
}
func (m *VirtualServer) init() {
m.listenPorts = make(map[uint16]bool)
m.hosts = make(map[string][]byte)
}
// tcp server
type TcpServer struct {
paddy *Paddy
ready bool
listeners map[uint16]*net.TCPListener
upstream string
upstreamObj *TcpLbClient
}
func (m *TcpServer) startListen() error {
inheritedPortsEnvVar := EnvVarInheritedListenerTcp
inheritedFds, inheritedPorts := m.paddy.GetInheritedPortsFromEnv(inheritedPortsEnvVar)
findInheritedListener := func(port uint16) (*net.TCPListener, bool) {
for i, v := range inheritedPorts {
if port == v {
lsn, _ := newInheritedListener(inheritedFds[i])
return lsn, true
}
}
return nil, false
}
mp := make(map[uint16]*net.TCPListener)
for port := range m.listeners {
var err error
var lsn net.Listener
found := false
lsn, found = findInheritedListener(port)
if !found {
lsn, err = net.Listen("tcp4", fmt.Sprintf(":%d", port))
if err != nil {
return err
}
}
mp[port] = lsn.(*net.TCPListener)
}
m.listeners = mp
for port, lsn := range mp {
m.serve(port, lsn)
}
m.ready = true
return nil
}
func (m *TcpServer) serve(port uint16, listener *net.TCPListener) {
go func() {
for {
if clientConn, err := m.acceptConn(port, listener); err != nil {
glog.Errorf("accept connection fail, %s", err.Error())
return
} else {
clientAddr := clientConn.RemoteAddr().String()
backendConn, err := m.upstreamObj.ConnectBackend(clientAddr)
if err != nil {
glog.Errorf("connect upstream: %s fail, %s", m.upstream, err.Error())
clientConn.Close()
}
backAddr := backendConn.RemoteAddr().String()
// client => backend
go func(client, backend *net.TCPConn) {
if _, err := io.Copy(backend, client); err != nil {
glog.Errorf("client %s => backend %s, connection closed unnormal, %s", clientAddr, backAddr, err.Error())
}
clientConn.Close()
backendConn.Close()
m.upstreamObj.removeConn(clientAddr)
}(clientConn, backendConn)
// backend => client
go func(client, backend *net.TCPConn) {
if _, err := io.Copy(client, backend); err != nil {
glog.Errorf("backend %s => client %s, connection closed unnormal, %s", backAddr, clientAddr, err.Error())
}
clientConn.Close()
backendConn.Close()
m.upstreamObj.removeConn(clientAddr)
}(clientConn, backendConn)
}
}
}()
}
func (m *TcpServer) acceptConn(port uint16, listener *net.TCPListener) (*net.TCPConn, error) {
for {
netConn, err := listener.Accept()
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
time.Sleep(time.Second)
continue
} else {
return nil, err
}
}
glog.Infof("listen port %d, accepted new connection: %s", port, netConn.RemoteAddr().String())
return netConn.(*net.TCPConn), nil
}
}
type PaddyHandler struct {
paddy *Paddy
}
func (m *PaddyHandler) pluginRequestAdapter(plugin Plugin, req *http.Request, respWriter http.ResponseWriter, context goutil.Context) (hijacked bool, proxyPass string, backend string, err goutil.Error) {
defer func() {
if err := recover(); err != nil {
glog.Errorf("%s plugin request panic: %s", time.Now().String(), err)
buf := make([]byte, 81920)
n := runtime.Stack(buf, true)
if n > 0 {
buf = buf[:n]
glog.Errorln(goutil.UnsafeBytesToString(buf))
} else {
glog.Errorln("no stack trace")
}
glog.Flush()
}
}()
return plugin.RequestHeaderCompleted(req, respWriter, context)
}
func (m *PaddyHandler) pluginResponseAdapter(plugin Plugin, originResponse *http.Response, respWriter http.ResponseWriter, context goutil.Context) (hijacked bool, newResponse *http.Response, err goutil.Error) {
defer func() {
if err := recover(); err != nil {
glog.Errorf("%s plugin response panic: %s", time.Now().String(), err)
buf := make([]byte, 81920)
n := runtime.Stack(buf, true)
if n > 0 {
buf = buf[:n]
glog.Errorln(goutil.UnsafeBytesToString(buf))
} else {
glog.Errorln("no stack trace")
}
glog.Flush()
}
}()
return plugin.ResponseHeaderCompleted(originResponse, respWriter, context)
}
type Upstream struct {
alias string
method string
backendList []string
connTimeout time.Duration
}
func (m *PaddyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !m.paddy.ready {
w.WriteHeader(500)
w.Write(goutil.UnsafeStringToBytes("not ready"))
return
}
context := &goutil.DefaultContext{}
var hijacked bool
var done bool
var backend string
var proxyPass string
var err goutil.Error
var resp *http.Response
for _, plugin := range m.paddy.plugin {
hijacked, proxyPass, backend, err = m.pluginRequestAdapter(plugin, r, w, context)
if err.Code != ErrCodeNoError {
glog.Errorf("call plugin request: %s fail,%d, %s", plugin.ID(), err.Code, err.Error())
w.WriteHeader(500)
return
}
if hijacked {
return
}
if backend != "" || proxyPass != "" {
break
}
}
resp = &http.Response{StatusCode: 404}
m.paddy.jsonexpDict.RegisterObjectInContext(JsonExpObjRequestInstance, newRequestObj(r), context)
m.paddy.jsonexpDict.RegisterObjectInContext(JsonExpObjRequestHeaderInstance, newRequestHeaderObj(r), context)
m.paddy.jsonexpDict.RegisterObjectInContext(JsonExpObjRequestParamInstance, newRequestParamObj(r), context)
m.paddy.jsonexpDict.RegisterObjectInContext(JsonExpObjResponseInstance, newResponseObj(resp), context)
m.paddy.jsonexpDict.RegisterObjectInContext(JsonExpObjResponseHeaderInstance, newResponseHeaderObj(resp), context)
doLoop := true
for {
// only onece
if !doLoop {
break
} else {
doLoop = !doLoop
}
if backend == "" {
var response *http.Response
done, proxyPass, backend, response, err = m.paddy.doLocation(r, w, context)
if response != nil {
resp = response
}
if err.Code != ErrCodeNoError {
glog.Errorf("uri: %s, do location fail, %d, %s", r.RequestURI, err.Code, err.Error())
break
}
if done {
return
}
if backend == "" && proxyPass == "" {
break
}
}
if !done && (backend != "" || proxyPass != "") {
resp, err = m.paddy.doBackend(proxyPass, backend, r, context)
if err.Code != ErrCodeNoError {
glog.Errorf("uri: %s, do backend: %s fail, %d, %s", r.RequestURI, backend, err.Code, err.Error())
break
}
}
}
if err.Code != ErrCodeNoError {
w.WriteHeader(500)
return
}
if resp != nil {
if respFilter, ok := context.GetCtxData(ContextVarResponseFilter); ok && respFilter != nil {
if err := respFilter.(*jsonexp.JsonExpGroup).Execute(context); err != nil {
glog.Errorf("execute response filter fail for uri: %s", r.RequestURI)
w.WriteHeader(500)
return
}
}
rewriteResponseUseContext(resp, context)
}
for _, plugin := range m.paddy.plugin {
hijacked, resp, err = m.pluginResponseAdapter(plugin, resp, w, context)
if err.Code != ErrCodeNoError {
glog.Errorf("call plugin response: %s fail,%d, %s", plugin.ID(), err.Code, err.Error())
w.WriteHeader(500)
return
}
if hijacked {
return
}
}
if resp == nil {
w.WriteHeader(404)
} else {
w.WriteHeader(resp.StatusCode)
wHeader := w.Header()
for k, v := range resp.Header {
if len(v) > 0 {
wHeader.Set(k, v[0])
}
}
if resp.Body != nil {
if _, err := io.Copy(w, resp.Body); err != nil {
glog.Errorf("uri: %s, write response body fail, %s", r.RequestURI, err.Error())
}
}
}
}
// paddy web server
type Paddy struct {
pidFile string
noneBackendHttpClient *http.Client
handler *PaddyHandler
jsonexpDict *jsonexp.Dictionary
fileServer *FileServer
upstreams map[string]*Upstream
tcpServers []*TcpServer //map[port]*TcpServer
backendGroups map[string]*BackendGroup
backendDefs map[string]*BackendDef
listeners map[uint16]*Listener
vServers map[uint16]map[string]*VirtualServer // map[port]map[host]*VirtualServer
configFile string
plugin []Plugin
ready bool
}
func NewPaddy(configFile string) (*Paddy, goutil.Error) {
ret := &Paddy{}
ret.init()
ret.configFile = configFile
loadedMap := make(map[string]bool)
err := ret.loadConfig("", configFile, true, loadedMap)
if err.Code != ErrCodeNoError {
return nil, err
}
return ret, ErrorNoError
}
func (m *Paddy) init() {
m.noneBackendHttpClient = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: time.Duration(DefaultBackendConnTimeout) * time.Millisecond,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
// MaxIdleConns: maxIdleConns,
MaxIdleConnsPerHost: DefaultBackendMaxIdleConn,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ResponseHeaderTimeout: time.Duration(DefaultBackendWaitResponseTimeout) * time.Millisecond,
},
}
m.fileServer = NewFileServer(10 << 30)
m.handler = &PaddyHandler{paddy: m}
m.jsonexpDict = jsonexp.NewDictionary()
m.initJsonexpDict()
m.backendGroups = make(map[string]*BackendGroup)
m.backendDefs = make(map[string]*BackendDef)
m.listeners = make(map[uint16]*Listener)
m.vServers = make(map[uint16]map[string]*VirtualServer)
m.plugin = make([]Plugin, 0)
m.tcpServers = make([]*TcpServer, 0)
m.upstreams = make(map[string]*Upstream)
}
func (m *Paddy) initJsonexpDict() {
m.jsonexpDict.RegisterVar(JsonExpVarProxyPass, nil)
m.jsonexpDict.RegisterVar(JsonExpVarBackend, nil)
m.jsonexpDict.RegisterVar(JsonExpVarFileRoot, nil)
m.jsonexpDict.RegisterVar(JsonExpVarSetResponse, nil)
}
func (m *Paddy) GetConfigFile() string {
return m.configFile
}
func (m *Paddy) RegisterPlugin(plugin Plugin) goutil.Error {
for _, v := range m.plugin {
if v.ID() == plugin.ID() {
return goutil.NewErrorf(ErrCodePluginDup, ErrMsgPluginDup, v.ID())
}
}
m.plugin = append(m.plugin, plugin)
return ErrorNoError
}
func (m *Paddy) findVServer(host string) *VirtualServer {
host = strings.ToLower(host)
var port uint16 = 80
lst := strings.Split(host, ":")
if len(lst) > 1 {
i, err := strconv.Atoi(lst[1])
if err == nil && i >= 0 && i < math.MaxUint16 {
port = uint16(i)
}
}
if svrList, ok := m.vServers[port]; ok {
for _, v := range svrList {
if _, ok := v.hosts[lst[0]]; ok {
return v
}
}
}
return nil
}
func (m *Paddy) doLocation(r *http.Request, w http.ResponseWriter, context goutil.Context) (done bool, proxyPass string, backend string, response *http.Response, err goutil.Error) {
vSvr := m.findVServer(r.Host)
if vSvr == nil {
return false, "", "", nil, ErrorNoError
}
var reItem *RegexpLocationItem = nil
if vSvr.regexpLocation != nil {
for _, v := range vSvr.regexpLocation.Items {
loc := v.uriRegexp.FindStringIndex(r.RequestURI)
if loc != nil && loc[0] == 0 && loc[1] == len(r.RequestURI) {
reItem = v
break
}
}
if reItem != nil {
if reItem.requestFilter != nil {
if err := reItem.requestFilter.Execute(context); err != nil {
glog.Errorf("execute request filter fail for uri: %s", r.RequestURI)
return false, "", "", nil, goutil.NewErrorf(ErrCodeJsonexpExecute, ErrMsgJsonexpExecute, err.Error())
}
}
if i, ok := context.GetCtxData(JsonExpVarSetResponse); ok && goutil.GetIntValueDefault(i, 0) == 1 {
if writeResponseUseContext(w, context) {
return true, "", "", nil, ErrorNoError
}
}
rewriteRequestUseContext(r, context)
if reItem.responseFilter != nil {
context.SetCtxData(ContextVarResponseFilter, reItem.responseFilter)
}
fileRoot := reItem.fileRoot
if fileRoot == "" {
if i, ok := context.GetCtxData(JsonExpVarFileRoot); ok {
fileRoot = goutil.GetStringValue(i)
}
}
if fileRoot != "" {
done, err := m.fileServer.serve(fileRoot, r, w)
if err.Code != ErrCodeNoError {
return false, "", "", nil, err
} else if done {
return true, "", "", nil, ErrorNoError
}
}
proxyPass := reItem.proxyPass
if proxyPass == "" {
if i, ok := context.GetCtxData(JsonExpVarProxyPass); ok {
proxyPass = goutil.GetStringValue(i)
}
}
backend := reItem.backend
if backend == "" {
if i, ok := context.GetCtxData(JsonExpVarBackend); ok {
backend = goutil.GetStringValue(i)
}
}
return false, proxyPass, backend, nil, ErrorNoError
}
}
if vSvr.jsonexpLocation != nil && vSvr.jsonexpLocation.Exp != nil {
if err := vSvr.jsonexpLocation.Exp.Execute(context); err != nil {
glog.Errorf("execute Exp fail for uri: %s", r.RequestURI)
return false, "", "", nil, goutil.NewErrorf(ErrCodeJsonexpExecute, ErrMsgJsonexpExecute, err.Error())
}
if vSvr.jsonexpLocation.requestFilter != nil {
if err := vSvr.jsonexpLocation.requestFilter.Execute(context); err != nil {
glog.Errorf("execute request filter fail for uri: %s", r.RequestURI)
return false, "", "", nil, goutil.NewErrorf(ErrCodeJsonexpExecute, ErrMsgJsonexpExecute, err.Error())
}
}
if i, ok := context.GetCtxData(JsonExpVarSetResponse); ok && goutil.GetIntValueDefault(i, 0) == 1 {
if writeResponseUseContext(w, context) {
return true, "", "", nil, ErrorNoError
}
}
rewriteRequestUseContext(r, context)
if vSvr.jsonexpLocation.responseFilter != nil {
context.SetCtxData(ContextVarResponseFilter, vSvr.jsonexpLocation.responseFilter)
}
fileRoot := ""
if i, ok := context.GetCtxData(JsonExpVarFileRoot); ok {
fileRoot = goutil.GetStringValue(i)
}
if fileRoot != "" {
done, err := m.fileServer.serve(fileRoot, r, w)
if err.Code != ErrCodeNoError {
return false, "", "", nil, err
} else if done {
return true, "", "", nil, ErrorNoError
}
}
proxyPass := ""
if i, ok := context.GetCtxData(JsonExpVarProxyPass); ok {
proxyPass = goutil.GetStringValue(i)
}
backend := ""
if i, ok := context.GetCtxData(JsonExpVarBackend); ok {
backend = goutil.GetStringValue(i)
}
return false, proxyPass, backend, nil, ErrorNoError
}
return false, "", "", nil, ErrorNoError
}
func (m *Paddy) doBackend(proxyPass string, backend string, r *http.Request, context goutil.Context) (response *http.Response, e goutil.Error) {
if proxyPass == "" && backend == "" {
return nil, goutil.NewErrorf(ErrCodeBackendRequestFail, ErrMsgBackendRequestFail, "", "no backend no proxy")
}
var err error
var resp *http.Response
var noneBackend bool
var backendObj *BackendDef
if backend != "" {
ok := false
backendObj, ok = m.backendDefs[backend]
if !ok {
return nil, goutil.NewErrorf(ErrCodeBackendNotFound, ErrMsgBackendNotFound, backend)
}
}
if proxyPass != "" {
noneBackend = true
proxyPass = strings.ReplaceAll(proxyPass, MacroBackend, backend)
domain := ""
port := "80"
hostsParts := strings.Split(r.Host, ":")
if len(hostsParts) > 1 {
domain = hostsParts[0]
port = hostsParts[1]
}
proxyPass = strings.ReplaceAll(proxyPass, MacroHost, r.Host)
proxyPass = strings.ReplaceAll(proxyPass, MacroDomain, domain)
proxyPass = strings.ReplaceAll(proxyPass, MacroPort, port)
proxyPass = strings.ReplaceAll(proxyPass, MacroPath, r.URL.Path)
proxyPass = strings.ReplaceAll(proxyPass, MacroParams, r.URL.Query().Encode())
proxyPass = strings.ReplaceAll(proxyPass, MacroURI, r.URL.RequestURI())
if len(proxyPass) < len("http") || !strings.EqualFold(proxyPass[:len("http")], "http") {
proxyPass = "http://" + proxyPass
}
if reqTemp, err := http.NewRequest(r.Method, proxyPass, nil); err != nil {
return nil, goutil.NewErrorf(ErrCodeBackendRequestFail, ErrMsgBackendRequestFail, backend, err.Error())
} else {
if reqTemp.Host == backend {
noneBackend = false
}
reqTemp.Body = r.Body
reqTemp.Header = r.Header
*r = *reqTemp
}
} else {
if reqTemp, err := http.NewRequest(r.Method, "http://backend"+r.RequestURI, nil); err != nil {
return nil, goutil.NewErrorf(ErrCodeBackendRequestFail, ErrMsgBackendRequestFail, backend, err.Error())
} else {
noneBackend = false
reqTemp.Body = r.Body
reqTemp.Header = r.Header
*r = *reqTemp
}
}
remoteIP := RemoteIp(r)
r.Header.Set("X-Forwarded-For", remoteIP)
if noneBackend {
resp, err = m.noneBackendHttpClient.Do(r)
} else {
resp, err = backendObj.lbClient.DoRequest(remoteIP, r)
}
if err != nil {
return nil, goutil.NewErrorf(ErrCodeBackendRequestFail, ErrMsgBackendRequestFail, backend, err.Error())
} else {
return resp, ErrorNoError
}
}
func (m *Paddy) loadConfig(configDir string, configFile string, rootCfg bool, loadedMap map[string]bool) goutil.Error {
if configDir != "" && !filepath.IsAbs(configFile) {
configFile = filepath.Join(configDir, configFile)
} else {
configFile, _ = filepath.Abs(configFile)
}
if ok := loadedMap[configFile]; ok {
return goutil.NewError(ErrCodeCommonError, "circular config "+configFile)
}
loadedMap[configFile] = true
if !goutil.FileExists(configFile) {
return goutil.NewErrorf(ErrCodeConfigNotExist, ErrMsgConfigNotExist, configFile)
}
bts, err := os.ReadFile(configFile)
if err != nil {
return goutil.NewErrorf(ErrCodeConfigReadFail, ErrMsgConfigReadFail, configFile, err.Error())
}
bts = []byte(TrimJsonComment(goutil.UnsafeBytesToString(bts)))
cfgMap := make(map[string]interface{})
err = json.Unmarshal(bts, &cfgMap)
if err != nil {
return goutil.NewErrorf(ErrCodeConfigReadFail, ErrMsgConfigReadFail, configFile, err.Error())
}
// pid file
if pidFile, ok := cfgMap[CfgPidFile]; ok {
s := goutil.GetStringValue(pidFile)
if m.pidFile, err = filepath.Abs(s); err != nil {
return goutil.NewErrorf(ErrCodeConfigReadFail, ErrMsgConfigReadFail, configFile, "invalid pid_file")
}
}
// include
if includeFiles, includeOk := cfgMap[CfgInclude]; includeOk {
// load includeFiles
rv := reflect.ValueOf(includeFiles)
if rv.Kind() != reflect.Slice {
return goutil.NewErrorf(ErrCodeCfgItemInvalid, ErrMsgCfgItemInvalid, CfgInclude)
}
files := includeFiles.([]interface{})
for _, v := range files {
vStr := goutil.GetStringValue(v)
gErr := m.loadConfig(filepath.Dir(configFile), vStr, false, loadedMap)
if gErr.Code != ErrCodeNoError {
return gErr
}
}
}
// upstream
if upstream, ok := cfgMap[CfgUpstream]; ok {
if rv := reflect.ValueOf(upstream); rv.Kind() != reflect.Slice {
return goutil.NewErrorf(ErrCodeCfgItemInvalid, ErrMsgCfgItemInvalid, CfgUpstream)
}
list := upstream.([]interface{})
for _, v := range list {
if rv := reflect.ValueOf(v); rv.Kind() != reflect.Map {
return goutil.NewErrorf(ErrCodeCfgItemInvalid, ErrMsgCfgItemInvalid, CfgUpstream)
}
obj := v.(map[string]interface{})
if gErr := m.newUpstream(obj); gErr.Code != ErrCodeNoError {
return gErr
}
}
}
// backend_group
if backendGroup, bgOk := cfgMap[CfgBackendGroup]; bgOk {
if rv := reflect.ValueOf(backendGroup); rv.Kind() != reflect.Map {
return goutil.NewErrorf(ErrCodeCfgItemInvalid, ErrMsgCfgItemInvalid, CfgBackendGroup)
}
bgMap := backendGroup.(map[string]interface{})
for grpName, v := range bgMap {
if rv := reflect.ValueOf(v); rv.Kind() != reflect.Slice {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgBackendGroup, grpName)
}
addrI := v.([]interface{})
if gErr := m.newBackendGroup(grpName, addrI); gErr.Code != ErrCodeNoError {
return gErr
}
}
}
// backend_def
if backendDef, bdOk := cfgMap[CfgBackendDef]; bdOk {
if rv := reflect.ValueOf(backendDef); rv.Kind() != reflect.Slice {
return goutil.NewErrorf(ErrCodeCfgItemInvalid, ErrMsgCfgItemInvalid, CfgBackendDef)
}
bdArr := backendDef.([]interface{})
for _, v := range bdArr {
if rv := reflect.ValueOf(v); rv.Kind() != reflect.Map {
return goutil.NewErrorf(ErrCodeCfgItemInvalid, ErrMsgCfgItemInvalid, CfgBackendDef)
}
if gErr := m.newBackendDef(v.(map[string]interface{})); gErr.Code != ErrCodeNoError {
return gErr
}
}
}
// server
if server, ok := cfgMap[CfgServer]; ok {
if rv := reflect.ValueOf(server); rv.Kind() != reflect.Map {
return goutil.NewErrorf(ErrCodeCfgItemInvalid, ErrMsgCfgItemInvalid, CfgServer)
}
if gErr := m.newVirtualServer(filepath.Dir(configFile), server.(map[string]interface{})); gErr.Code != ErrCodeNoError {
return gErr
}
}
// tcp_server
if server, ok := cfgMap[CfgTcpServer]; ok {
if rv := reflect.ValueOf(server); rv.Kind() != reflect.Map {
return goutil.NewErrorf(ErrCodeCfgItemInvalid, ErrMsgCfgItemInvalid, CfgTcpServer)
}
if gErr := m.newTcpServer(server.(map[string]interface{})); gErr.Code != ErrCodeNoError {
return gErr
}
}
// net tcp_server.tcpLbClient & validate port duplicate
if rootCfg {
for _, v := range m.tcpServers {
for port := range v.listeners {
for httpPort := range m.vServers {
if httpPort == port {
return goutil.NewErrorf(ErrCodeListenPortDup, ErrMsgListenPortDup, port)
}
}
}
if us, ok := m.upstreams[v.upstream]; !ok {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgTcpServer, CfgTcpServerUpstream)
} else {
if o, err := newTcpLbClient(us.backendList, us.method, us.connTimeout); err != nil {
return goutil.NewErrorf(ErrCodeNewUpstream, ErrMsgNewUpstream, err.Error())
} else {
v.upstreamObj = o
}
}
}
}
// append backend from backendGroup
if rootCfg {
for _, def := range m.backendDefs {
for _, grpStr := range def.backendGroupList {
if grp, ok := m.backendGroups[grpStr]; ok {
for _, gBackend := range grp.BackendList {
exists := false
for _, backend := range def.BackendList {
if backend.Ip == gBackend.Ip && backend.Port == gBackend.Port {
exists = true
break
}
}
if !exists {
def.BackendList = append(def.BackendList, gBackend)
}
}
}
}
}
for k, def := range m.backendDefs {
if len(def.BackendList) == 0 {
delete(m.backendDefs, k)
}
}
}
// create backend loadbalance client
if rootCfg {
for _, v := range m.backendDefs {
v.createLbClient()
}
}
return ErrorNoError
}
func (m *Paddy) newTcpServer(cfg map[string]interface{}) goutil.Error {
if cfg == nil {
return goutil.NewErrorf(ErrCodeNewTcpServerFail, "cfg map is nil")
}
svr := &TcpServer{paddy: m, listeners: make(map[uint16]*net.TCPListener)}
if listen, ok := cfg[CfgTcpServerListen]; ok {
if rv := reflect.ValueOf(listen); rv.Kind() != reflect.Slice {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgTcpServer, CfgTcpServerListen)
}
for _, v := range listen.([]interface{}) {
port := goutil.GetIntValueDefault(v, 0)
if port <= 0 || port >= int64(math.MaxUint16) {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgTcpServer, CfgTcpServerListen)
}
if _, ok := svr.listeners[uint16(port)]; ok {
return goutil.NewErrorf(ErrCodeListenPortDup, ErrMsgListenPortDup, port)
}
for _, ts := range m.tcpServers {
if _, ok := ts.listeners[uint16(port)]; ok {
return goutil.NewErrorf(ErrCodeListenPortDup, ErrMsgListenPortDup, port)
}
}
svr.listeners[uint16(port)] = nil
}
}
if upstream, ok := cfg["upstream"]; ok {
svr.upstream = goutil.GetStringValue(upstream)
}
if svr.upstream != "" && len(svr.listeners) > 0 {
m.tcpServers = append(m.tcpServers, svr)
}
return ErrorNoError
}
func (m *Paddy) newVirtualServer(configDir string, cfg map[string]interface{}) goutil.Error {
if cfg == nil {
return goutil.NewErrorf(ErrCodeNewTcpServerFail, "cfg map is nil")
}
vs := &VirtualServer{}
vs.init()
// listen
if listen, ok := cfg[CfgServerListen]; ok {
if rv := reflect.ValueOf(listen); rv.Kind() != reflect.Slice {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerListen)
}
for _, v := range listen.([]interface{}) {
if rv := reflect.ValueOf(v); rv.Kind() != reflect.String {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerListen)
}
lst := strings.Split(v.(string), ",")
if len(lst) > 2 {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerListen)
}
port, err := strconv.Atoi(lst[0])
if err != nil || port <= 0 || port >= int(math.MaxUint16) {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerListen)
}
if len(lst) == 2 {
if lst[1] != "tls" && lst[1] != "ssl" {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerListen)
}
vs.listenPorts[uint16(port)] = true
} else {
vs.listenPorts[uint16(port)] = false
}
}
}
// hosts
if hosts, ok := cfg[CfgServerHosts]; ok {
if rv := reflect.ValueOf(hosts); rv.Kind() != reflect.Slice {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerHosts)
}
for _, v := range hosts.([]interface{}) {
if rv := reflect.ValueOf(v); rv.Kind() != reflect.String || v.(string) == "" {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerHosts)
}
vStr := v.(string)
if _, ok := vs.hosts[vStr]; ok {
return goutil.NewErrorf(ErrCodeHostDup, ErrMsgHostDup, v)
}
vs.hosts[vStr] = nil
}
}
// tls_cert
if cert, ok := cfg[CfgServerTlsCert]; ok {
if rv := reflect.ValueOf(cert); rv.Kind() != reflect.String || cert.(string) == "" {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerTlsCert)
}
fn := cert.(string)
if configDir != "" && !filepath.IsAbs(fn) {
fn = filepath.Join(configDir, fn)
}
if !goutil.FileExists(fn) {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerTlsCert)
}
vs.tlsCert = fn
}
// tls_certkey
if cert, ok := cfg[CfgServerTlsCertKey]; ok {
if rv := reflect.ValueOf(cert); rv.Kind() != reflect.String || cert.(string) == "" {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerTlsCertKey)
}
fn := cert.(string)
if configDir != "" && !filepath.IsAbs(fn) {
fn = filepath.Join(configDir, fn)
}
if !goutil.FileExists(fn) {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerTlsCertKey)
}
vs.tlsCertKey = fn
}
// location_regexp
if rex, ok := cfg[CfgServerLocationRegexp]; ok {
if rv := reflect.ValueOf(rex); rv.Kind() != reflect.Slice {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerLocationRegexp)
}
rexSlice := rex.([]interface{})
for _, vItem := range rexSlice {
if rv := reflect.ValueOf(vItem); rv.Kind() != reflect.Map {
return goutil.NewErrorf(ErrCodeCfgItem2Invalid, ErrMsgCfgItem2Invalid, CfgServer, CfgServerLocationRegexp)
}
item := &RegexpLocationItem{}
vMap := vItem.(map[string]interface{})
for k, v := range vMap {