10 "github.com/Sirupsen/logrus"
11 "github.com/gin-contrib/static"
12 "github.com/gin-gonic/gin"
13 "github.com/googollee/go-socket.io"
14 "github.com/iotbzh/xds-agent/lib/apiv1"
18 type WebServer struct {
22 sIOServer *socketio.Server
23 webApp *gin.RouterGroup
24 stop chan struct{} // signals intentional stop
27 const indexFilename = "index.html"
29 // NewWebServer creates an instance of WebServer
30 func NewWebServer(ctx *Context) *WebServer {
32 // Setup logging for gin router
33 if ctx.Log.Level == logrus.DebugLevel {
34 gin.SetMode(gin.DebugMode)
36 gin.SetMode(gin.ReleaseMode)
39 // Redirect gin logs into another logger (LogVerboseOut may be stderr or a file)
40 gin.DefaultWriter = ctx.Config.LogVerboseOut
41 gin.DefaultErrorWriter = ctx.Config.LogVerboseOut
42 log.SetOutput(ctx.Config.LogVerboseOut)
53 stop: make(chan struct{}),
59 // Serve starts a new instance of the Web Server
60 func (s *WebServer) Serve() error {
64 s.router.Use(gin.Logger())
65 s.router.Use(gin.Recovery())
66 s.router.Use(s.middlewareCORS())
67 s.router.Use(s.middlewareXDSDetails())
68 s.router.Use(s.middlewareCSRF())
71 s.api = NewAPIV1(s.Context)
73 // Create connections to XDS Servers
74 // XXX - not sure there is no side effect to do it in background !
76 for _, svrCfg := range s.Config.FileConf.ServersConf {
77 if svr, err := s.api.AddXdsServer(svrCfg); err != nil {
78 // Just log error, don't consider as critical
79 s.Log.Infof("Cannot connect to XDS Server url=%s: %v", svr.BaseURL, err.Error())
85 s.sIOServer, err = socketio.NewServer(nil)
90 s.router.GET("/socket.io/", s.socketHandler)
91 s.router.POST("/socket.io/", s.socketHandler)
92 /* TODO: do we want to support ws://... ?
93 s.router.Handle("WS", "/socket.io/", s.socketHandler)
94 s.router.Handle("WSS", "/socket.io/", s.socketHandler)
97 // Web Application (serve on / )
98 idxFile := path.Join(s.Config.FileConf.WebAppDir, indexFilename)
99 if _, err := os.Stat(idxFile); err != nil {
100 s.Log.Fatalln("Web app directory not found, check/use webAppDir setting in config file: ", idxFile)
102 s.Log.Infof("Serve WEB app dir: %s", s.Config.FileConf.WebAppDir)
103 s.router.Use(static.Serve("/", static.LocalFile(s.Config.FileConf.WebAppDir, true)))
104 s.webApp = s.router.Group("/", s.serveIndexFile)
109 // Serve in the background
110 serveError := make(chan error, 1)
112 fmt.Printf("Web Server running on localhost:%s ...\n", s.Config.FileConf.HTTPPort)
113 serveError <- http.ListenAndServe(":"+s.Config.FileConf.HTTPPort, s.router)
116 fmt.Printf("XDS agent running...\n")
118 // Wait for stop, restart or error signals
121 // Shutting down permanently
123 s.Log.Infoln("shutting down (stop)")
124 case err = <-serveError:
125 // Error due to listen/serve failure
133 func (s *WebServer) Stop() {
138 // serveIndexFile provides initial file (eg. index.html) of webapp
139 func (s *WebServer) serveIndexFile(c *gin.Context) {
140 c.HTML(200, indexFilename, gin.H{})
143 // Add details in Header
144 func (s *WebServer) middlewareXDSDetails() gin.HandlerFunc {
145 return func(c *gin.Context) {
146 c.Header("XDS-Agent-Version", s.Config.Version)
147 c.Header("XDS-API-Version", s.Config.APIVersion)
152 func (s *WebServer) isValidAPIKey(key string) bool {
153 return (s.Config.FileConf.XDSAPIKey != "" && key == s.Config.FileConf.XDSAPIKey)
156 func (s *WebServer) middlewareCSRF() gin.HandlerFunc {
157 return func(c *gin.Context) {
158 // XXX - not used for now
162 // Allow requests carrying a valid API key
163 if s.isValidAPIKey(c.Request.Header.Get("X-API-Key")) {
164 // Set the access-control-allow-origin header for CORS requests
165 // since a valid API key has been provided
166 c.Header("Access-Control-Allow-Origin", "*")
171 // Allow io.socket request
172 if strings.HasPrefix(c.Request.URL.Path, "/socket.io") {
177 // FIXME Add really CSRF support
179 // Allow requests for anything not under the protected path prefix,
180 // and set a CSRF cookie if there isn't already a valid one.
181 //if !strings.HasPrefix(c.Request.URL.Path, prefix) {
182 // cookie, err := c.Cookie("CSRF-Token-" + unique)
183 // if err != nil || !validCsrfToken(cookie.Value) {
184 // s.Log.Debugln("new CSRF cookie in response to request for", c.Request.URL)
185 // c.SetCookie("CSRF-Token-"+unique, newCsrfToken(), 600, "/", "", false, false)
191 // Verify the CSRF token
192 //token := c.Request.Header.Get("X-CSRF-Token-" + unique)
193 //if !validCsrfToken(token) {
194 // c.AbortWithError(403, "CSRF Error")
200 c.AbortWithError(403, fmt.Errorf("Not valid API key"))
206 func (s *WebServer) middlewareCORS() gin.HandlerFunc {
207 return func(c *gin.Context) {
208 if c.Request.Method == "OPTIONS" {
209 c.Header("Access-Control-Allow-Origin", "*")
210 c.Header("Access-Control-Allow-Headers", "Content-Type, X-API-Key")
211 c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE")
212 c.Header("Access-Control-Max-Age", cookieMaxAge)
213 c.AbortWithStatus(204)
220 // socketHandler is the handler for the "main" websocket connection
221 func (s *WebServer) socketHandler(c *gin.Context) {
223 // Retrieve user session
224 sess := s.sessions.Get(c)
226 c.JSON(500, gin.H{"error": "Cannot retrieve session"})
230 s.sIOServer.On("connection", func(so socketio.Socket) {
231 s.Log.Debugf("WS Connected (WSID=%s, SID=%s)", so.Id(), sess.ID)
232 s.sessions.UpdateIOSocket(sess.ID, &so)
234 so.On("disconnection", func() {
235 s.Log.Debugf("WS disconnected (WSID=%s, SID=%s)", so.Id(), sess.ID)
236 s.events.UnRegister(apiv1.EVTAll, sess.ID)
237 s.sessions.UpdateIOSocket(sess.ID, nil)
241 s.sIOServer.On("error", func(so socketio.Socket, err error) {
242 s.Log.Errorf("WS SID=%v Error : %v", so.Id(), err.Error())
245 s.sIOServer.ServeHTTP(c.Writer, c.Request)