8 "github.com/gin-gonic/gin"
9 "github.com/googollee/go-socket.io"
10 uuid "github.com/satori/go.uuid"
11 "github.com/syncthing/syncthing/lib/sync"
14 const sessionCookieName = "xds-agent-sid"
15 const sessionHeaderName = "XDS-AGENT-SID"
17 const sessionMonitorTime = 10 // Time (in seconds) to schedule monitoring session tasks
19 const initSessionMaxAge = 10 // Initial session max age in seconds
20 const maxSessions = 100000 // Maximum number of sessions in sessMap map
22 const secureCookie = false // TODO: see https://github.com/astaxie/beego/blob/master/session/session.go#L218
24 // ClientSession contains the info of a user/client session
25 type ClientSession struct {
27 WSID string // only one WebSocket per client/session
29 IOSocket *socketio.Socket
36 // Sessions holds client sessions
37 type Sessions struct {
40 sessMap map[string]ClientSession
42 stop chan struct{} // signals intentional stop
45 // NewClientSessions .
46 func NewClientSessions(ctx *Context, cookieMaxAge string) *Sessions {
47 ckMaxAge, err := strconv.ParseInt(cookieMaxAge, 10, 0)
53 cookieMaxAge: ckMaxAge,
54 sessMap: make(map[string]ClientSession),
55 mutex: sync.NewMutex(),
56 stop: make(chan struct{}),
58 s.webServer.router.Use(s.Middleware())
60 // Start monitoring of sessions Map (use to manage expiration and cleanup)
66 // Stop sessions management
67 func (s *Sessions) Stop() {
71 // Middleware is used to managed session
72 func (s *Sessions) Middleware() gin.HandlerFunc {
73 return func(c *gin.Context) {
74 // FIXME Add CSRF management
79 // Allocate a new session key and put in cookie
80 sess = s.newSession("")
85 // Set session in cookie and in header
86 // Do not set Domain to localhost (http://stackoverflow.com/questions/1134290/cookies-on-localhost-with-explicit-domain)
87 c.SetCookie(sessionCookieName, sess.ID, int(sess.MaxAge), "/", "",
89 c.Header(sessionHeaderName, sess.ID)
91 // Save session id in gin metadata
92 c.Set(sessionCookieName, sess.ID)
98 // Get returns the client session for a specific ID
99 func (s *Sessions) Get(c *gin.Context) *ClientSession {
102 // First get from gin metadata
103 v, exist := c.Get(sessionCookieName)
108 // Then look in cookie
109 if !exist || sid == "" {
110 sid, _ = c.Cookie(sessionCookieName)
113 // Then look in Header
115 sid = c.Request.Header.Get(sessionCookieName)
119 defer s.mutex.Unlock()
120 if key, ok := s.sessMap[sid]; ok {
121 // TODO: return a copy ???
128 // IOSocketGet Get socketio definition from sid
129 func (s *Sessions) IOSocketGet(sid string) *socketio.Socket {
131 defer s.mutex.Unlock()
132 sess, ok := s.sessMap[sid]
139 // UpdateIOSocket updates the IO Socket definition for of a session
140 func (s *Sessions) UpdateIOSocket(sid string, so *socketio.Socket) error {
142 defer s.mutex.Unlock()
143 if _, ok := s.sessMap[sid]; ok {
144 sess := s.sessMap[sid]
146 // Could be the case when socketio is closed/disconnected
149 sess.WSID = (*so).Id()
152 s.sessMap[sid] = sess
157 // newSession Allocate a new client session
158 func (s *Sessions) newSession(prefix string) *ClientSession {
159 uuid := prefix + uuid.NewV4().String()
160 id := base64.URLEncoding.EncodeToString([]byte(uuid))
164 MaxAge: initSessionMaxAge,
166 expireAt: time.Now().Add(time.Duration(initSessionMaxAge) * time.Second),
170 defer s.mutex.Unlock()
172 s.sessMap[se.ID] = se
174 s.Log.Debugf("NEW session (%d): %s", len(s.sessMap), id)
178 // refresh Move this session ID to the head of the list
179 func (s *Sessions) refresh(sid string) {
181 defer s.mutex.Unlock()
183 sess := s.sessMap[sid]
185 if sess.MaxAge < s.cookieMaxAge && sess.useCount > 1 {
186 sess.MaxAge = s.cookieMaxAge
187 sess.expireAt = time.Now().Add(time.Duration(sess.MaxAge) * time.Second)
190 // TODO - Add flood detection (like limit_req of nginx)
191 // (delayed request when to much requests in a short period of time)
193 s.sessMap[sid] = sess
196 func (s *Sessions) monitorSessMap() {
200 s.Log.Debugln("Stop monitorSessMap")
202 case <-time.After(sessionMonitorTime * time.Second):
204 s.Log.Debugf("Sessions Map size: %d", len(s.sessMap))
205 s.Log.Debugf("Sessions Map : %v", s.sessMap)
208 if len(s.sessMap) > maxSessions {
209 s.Log.Errorln("TOO MUCH sessions, cleanup old ones !")
213 for _, ss := range s.sessMap {
214 if ss.expireAt.Sub(time.Now()) < 0 {
216 s.Log.Debugf("Delete expired session id: %s", ss.ID)
218 delete(s.sessMap, ss.ID)