-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathapi.go
More file actions
235 lines (199 loc) · 6.14 KB
/
Copy pathapi.go
File metadata and controls
235 lines (199 loc) · 6.14 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
package api
import (
"context"
"fmt"
"io/fs"
"net"
"net/http"
http_pprof "net/http/pprof"
"runtime/pprof"
"strings"
"github.com/go-playground/validator/v10"
"github.com/ipfs/go-log/v2"
"github.com/labstack/echo-contrib/echoprometheus"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/anywherelan/awl/config"
"github.com/anywherelan/awl/p2p"
"github.com/anywherelan/awl/ringbuffer"
"github.com/anywherelan/awl/service"
)
type DNSService interface {
AwlDNSAddress() string
IsAwlDNSSetAsSystem() bool
}
type Handler struct {
conf *config.Config
logger *log.ZapEventLogger
p2p *p2p.P2p
authStatus *service.AuthStatus
tunnel *service.Tunnel
socks5 *service.SOCKS5
dns DNSService
logBuffer *ringbuffer.RingBuffer
echo *echo.Echo
echoAdmin *echo.Echo
ctx context.Context
ctxCancel context.CancelFunc
}
func NewHandler(conf *config.Config, p2p *p2p.P2p, authStatus *service.AuthStatus, tunnel *service.Tunnel, socks5 *service.SOCKS5,
logBuffer *ringbuffer.RingBuffer, dns DNSService) *Handler {
ctx, ctxCancel := context.WithCancel(context.Background())
return &Handler{
conf: conf,
p2p: p2p,
authStatus: authStatus,
tunnel: tunnel,
socks5: socks5,
dns: dns,
logBuffer: logBuffer,
logger: log.Logger("awl/api"),
ctx: ctx,
ctxCancel: ctxCancel,
}
}
func (h *Handler) SetupAPI() error {
e1, err := h.setupRouter(h.conf.HttpListenAddress)
if err != nil {
return err
}
h.echo = e1
if h.conf.HttpListenOnAdminHost {
echoAdmin, err := h.setupRouter(config.AdminHttpServerListenAddress)
if err != nil {
h.logger.Errorf("unable to bind web server on admin host %s: %v", config.AdminHttpServerListenAddress, err)
} else {
h.echoAdmin = echoAdmin
}
}
return nil
}
// use global to register metric only once
var metricsMiddleware = echoprometheus.NewMiddlewareWithConfig(
echoprometheus.MiddlewareConfig{
Namespace: "awl",
Subsystem: "api",
},
)
var metricsHandler = echoprometheus.NewHandler()
func (h *Handler) setupRouter(address string) (*echo.Echo, error) {
e := echo.New()
e.HideBanner = true
e.HidePort = true
val := validator.New()
err := val.RegisterValidation("trimmed_str_not_empty", validateTrimmedStringNotEmpty, false)
if err != nil {
return nil, err
}
e.Validator = &customValidator{validator: val}
// Middleware
if !h.conf.DevMode() {
e.Use(middleware.Recover())
}
if h.conf.HttpBasicAuth.Password != "" {
username := h.conf.HttpBasicAuth.Username
password := h.conf.HttpBasicAuth.Password
e.Use(middleware.BasicAuth(func(u, p string, _ echo.Context) (bool, error) {
return u == username && p == password, nil
}))
}
// Routes
// Metrics
e.Use(metricsMiddleware)
e.GET("/metrics", metricsHandler)
// Peers
e.GET(GetKnownPeersPath, h.GetKnownPeers)
e.POST(GetKnownPeerSettingsPath, h.GetKnownPeerSettings)
e.POST(SendFriendRequestPath, h.SendFriendRequest)
e.POST(AcceptPeerInvitationPath, h.AcceptFriend)
e.POST(UpdatePeerSettingsPath, h.UpdatePeerSettings)
e.POST(RemovePeerSettingsPath, h.RemovePeer)
e.GET(GetAuthRequestsPath, h.GetAuthRequests)
e.GET(GetBlockedPeersPath, h.GetBlockedPeers)
// Settings
e.GET(GetMyPeerInfoPath, h.GetMyPeerInfo)
e.POST(UpdateMyInfoPath, h.UpdateMySettings)
e.GET(ListAvailableProxiesPath, h.ListAvailableProxies)
e.POST(UpdateProxySettingsPath, h.UpdateProxySettings)
e.GET(ExportServerConfigPath, h.ExportServerConfiguration)
// Debug
e.GET(GetP2pDebugInfoPath, h.GetP2pDebugInfo)
e.GET(GetDebugLogPath, h.GetLog)
e.Any(V0Prefix+"debug/pprof/", echo.WrapHandler(http.HandlerFunc(http_pprof.Index)))
e.Any(V0Prefix+"debug/pprof/profile", echo.WrapHandler(http.HandlerFunc(http_pprof.Profile)))
e.Any(V0Prefix+"debug/pprof/trace", echo.WrapHandler(http.HandlerFunc(http_pprof.Trace)))
e.Any(V0Prefix+"debug/pprof/cmdline", echo.WrapHandler(http.HandlerFunc(http_pprof.Cmdline)))
e.Any(V0Prefix+"debug/pprof/symbol", echo.WrapHandler(http.HandlerFunc(http_pprof.Symbol)))
for _, p := range pprof.Profiles() {
name := p.Name()
e.Any(V0Prefix+"debug/pprof/"+name, echo.WrapHandler(http_pprof.Handler(name)))
}
// Start
listener, err := net.Listen("tcp", address)
if err != nil {
return nil, fmt.Errorf("unable to bind address %s: %v", address, err)
}
e.Listener = listener
h.logger.Infof("starting web server on http://%s", listener.Addr().String())
go func() {
if err := e.StartServer(e.Server); err != nil && err != http.ErrServerClosed {
h.logger.Warnf("shutting down web server %s: %v", address, err)
}
}()
return e, nil
}
func (h *Handler) SetupFrontend(fsys fs.FS) {
fileServer := http.FileServer(http.FS(fsys))
h.echo.GET("/*", echo.WrapHandler(fileServer))
if h.echoAdmin != nil {
h.echoAdmin.GET("/*", echo.WrapHandler(fileServer))
}
}
func (h *Handler) Shutdown(ctx context.Context) error {
if h.echoAdmin != nil {
err := h.echoAdmin.Server.Shutdown(ctx)
if err != nil {
h.logger.Errorf("error shutting down web server on admin host %s: %v", config.AdminHttpServerListenAddress, err)
}
}
return h.echo.Server.Shutdown(ctx)
}
func (h *Handler) Address() string {
address := h.echo.Listener.Addr().String()
host, port, err := net.SplitHostPort(address)
if err != nil {
panic(err)
}
ip := net.ParseIP(host)
if ip == nil {
return address
} else if ip.IsUnspecified() {
return net.JoinHostPort("127.0.0.1", port)
}
return net.JoinHostPort(ip.String(), port)
}
type customValidator struct {
validator *validator.Validate
}
func (cv *customValidator) Validate(i interface{}) error {
return cv.validator.Struct(i)
}
type Error struct {
Message string `json:"error"`
// AuthMessage is an error from Echo framework, particularly from Basic Auth middleware
AuthMessage string `json:"message"`
}
func (e Error) Error() string {
if e.Message != "" && e.AuthMessage != "" {
return fmt.Sprintf("error: %s; message: %s", e.Message, e.AuthMessage)
}
return e.Message + e.AuthMessage
}
func ErrorMessage(message string) Error {
return Error{Message: message}
}
func validateTrimmedStringNotEmpty(fl validator.FieldLevel) bool {
str := fl.Field().String()
str = strings.TrimSpace(str)
return len(str) > 0
}