8 "github.com/Sirupsen/logrus"
9 "github.com/gin-gonic/gin"
10 "github.com/googollee/go-socket.io"
11 uuid "github.com/satori/go.uuid"
12 "github.com/syncthing/syncthing/lib/sync"
15 const sessionCookieName = "xds-sid"
16 const sessionHeaderName = "XDS-SID"
18 const sessionMonitorTime = 10 // Time (in seconds) to schedule monitoring session tasks
20 const initSessionMaxAge = 10 // Initial session max age in seconds
21 const maxSessions = 100000 // Maximum number of sessions in sessMap map
23 const secureCookie = false // TODO: see https://github.com/astaxie/beego/blob/master/session/session.go#L218
25 // ClientSession contains the info of a user/client session
26 type ClientSession struct {
28 WSID string // only one WebSocket per client/session
30 IOSocket *socketio.Socket
37 // Sessions holds client sessions
38 type Sessions struct {
41 sessMap map[string]ClientSession
44 stop chan struct{} // signals intentional stop
47 // NewClientSessions .
48 func NewClientSessions(router *gin.Engine, log *logrus.Logger, cookieMaxAge string) *Sessions {
49 ckMaxAge, err := strconv.ParseInt(cookieMaxAge, 10, 0)
55 cookieMaxAge: ckMaxAge,
56 sessMap: make(map[string]ClientSession),
57 mutex: sync.NewMutex(),
59 stop: make(chan struct{}),
61 s.router.Use(s.Middleware())
63 // Start monitoring of sessions Map (use to manage expiration and cleanup)
69 // Stop sessions management
70 func (s *Sessions) Stop() {
74 // Middleware is used to managed session
75 func (s *Sessions) Middleware() gin.HandlerFunc {
76 return func(c *gin.Context) {
77 // FIXME Add CSRF management
82 // Allocate a new session key and put in cookie
83 sess = s.newSession("")
88 // Set session in cookie and in header
89 // Do not set Domain to localhost (http://stackoverflow.com/questions/1134290/cookies-on-localhost-with-explicit-domain)
90 c.SetCookie(sessionCookieName, sess.ID, int(sess.MaxAge), "/", "",
92 c.Header(sessionHeaderName, sess.ID)
94 // Save session id in gin metadata
95 c.Set(sessionCookieName, sess.ID)
101 // Get returns the client session for a specific ID
102 func (s *Sessions) Get(c *gin.Context) *ClientSession {
105 // First get from gin metadata
106 v, exist := c.Get(sessionCookieName)
111 // Then look in cookie
112 if !exist || sid == "" {
113 sid, _ = c.Cookie(sessionCookieName)
116 // Then look in Header
118 sid = c.Request.Header.Get(sessionCookieName)
122 defer s.mutex.Unlock()
123 if key, ok := s.sessMap[sid]; ok {
124 // TODO: return a copy ???
131 // IOSocketGet Get socketio definition from sid
132 func (s *Sessions) IOSocketGet(sid string) *socketio.Socket {
134 defer s.mutex.Unlock()
135 sess, ok := s.sessMap[sid]
142 // UpdateIOSocket updates the IO Socket definition for of a session
143 func (s *Sessions) UpdateIOSocket(sid string, so *socketio.Socket) error {
145 defer s.mutex.Unlock()
146 if _, ok := s.sessMap[sid]; ok {
147 sess := s.sessMap[sid]
149 // Could be the case when socketio is closed/disconnected
152 sess.WSID = (*so).Id()
155 s.sessMap[sid] = sess
160 // nesSession Allocate a new client session
161 func (s *Sessions) newSession(prefix string) *ClientSession {
162 uuid := prefix + uuid.NewV4().String()
163 id := base64.URLEncoding.EncodeToString([]byte(uuid))
167 MaxAge: initSessionMaxAge,
169 expireAt: time.Now().Add(time.Duration(initSessionMaxAge) * time.Second),
173 defer s.mutex.Unlock()
175 s.sessMap[se.ID] = se
177 s.log.Debugf("NEW session (%d): %s", len(s.sessMap), id)
181 // refresh Move this session ID to the head of the list
182 func (s *Sessions) refresh(sid string) {
184 defer s.mutex.Unlock()
186 sess := s.sessMap[sid]
188 if sess.MaxAge < s.cookieMaxAge && sess.useCount > 1 {
189 sess.MaxAge = s.cookieMaxAge
190 sess.expireAt = time.Now().Add(time.Duration(sess.MaxAge) * time.Second)
193 // TODO - Add flood detection (like limit_req of nginx)
194 // (delayed request when to much requests in a short period of time)
196 s.sessMap[sid] = sess
199 func (s *Sessions) monitorSessMap() {
200 const dbgFullTrace = false // for debugging
205 s.log.Debugln("Stop monitorSessMap")
207 case <-time.After(sessionMonitorTime * time.Second):
209 s.log.Debugf("Sessions Map size: %d", len(s.sessMap))
210 s.log.Debugf("Sessions Map : %v", s.sessMap)
213 if len(s.sessMap) > maxSessions {
214 s.log.Errorln("TOO MUCH sessions, cleanup old ones !")
218 for _, ss := range s.sessMap {
219 if ss.expireAt.Sub(time.Now()) < 0 {
220 s.log.Debugf("Delete expired session id: %s", ss.ID)
221 delete(s.sessMap, ss.ID)