-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsession.go
299 lines (253 loc) · 7.22 KB
/
session.go
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
/*
* Copyright 2017-2019 Kopano and its licensors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kcc
import (
"context"
"fmt"
"strconv"
"sync"
"time"
)
var (
// SessionAutorefreshInterval defines the interval when sessions are auto
// refreshed automatically.
SessionAutorefreshInterval = 4 * time.Minute
// SessionExpirationGrace defines the duration after SessionAutorefreshInterval
// when a session was not refreshed and can be considered non active.
SessionExpirationGrace = 2 * time.Minute
)
// KCSessionID is the type for Kopano Core session IDs.
type KCSessionID uint64
func (sid KCSessionID) String() string {
return strconv.FormatUint(uint64(sid), 10)
}
// KCNoSessionID define the value to use for KCSessionID when there is no session.
const KCNoSessionID KCSessionID = 0
// Session holds the data structures to keep a session open on the accociated
// Kopano server.
type Session struct {
id KCSessionID
serverGUID string
active bool
when time.Time
mutex sync.RWMutex
ctx context.Context
ctxCancel context.CancelFunc
c *KCC
autoRefresh (chan bool)
}
// NewSession connects to the provided server with the provided parameters,
// creates a new Session which will be automatically refreshed until detroyed.
func NewSession(ctx context.Context, c *KCC, username, password string) (*Session, error) {
if c == nil {
c = NewKCC(nil)
}
if ctx == nil {
ctx = context.Background()
}
resp, err := c.Logon(ctx, username, password, 0)
if err != nil {
return nil, fmt.Errorf("create session logon failed: %v", err)
}
if resp.Er != KCSuccess {
return nil, fmt.Errorf("create session logon mapi error: %v", resp.Er)
}
if resp.SessionID == KCNoSessionID {
return nil, fmt.Errorf("create session logon returned invalid session ID")
}
if resp.ServerGUID == "" {
return nil, fmt.Errorf("create session logon return invalid server GUID")
}
sessionCtx, cancel := context.WithCancel(ctx)
s := &Session{
id: resp.SessionID,
serverGUID: resp.ServerGUID,
active: true,
when: time.Now(),
ctx: sessionCtx,
ctxCancel: cancel,
c: c,
}
err = s.StartAutoRefresh()
return s, err
}
// NewSSOSession connects to the provided server with the provided parameters,
// creates a new Session which will be automatically refreshed until detroyed.
func NewSSOSession(ctx context.Context, c *KCC, prefix SSOType, username string, input []byte, sessionID KCSessionID) (*Session, error) {
if c == nil {
c = NewKCC(nil)
}
if ctx == nil {
ctx = context.Background()
}
resp, err := c.SSOLogon(ctx, prefix, username, input, sessionID, 0)
if err != nil {
return nil, fmt.Errorf("create session sso logon failed: %v", err)
}
if resp.Er != KCSuccess {
return nil, fmt.Errorf("create session sso logon mapi error: %v", resp.Er)
}
if resp.SessionID == KCNoSessionID {
return nil, fmt.Errorf("create session sso logon returned invalid session ID")
}
if resp.ServerGUID == "" {
return nil, fmt.Errorf("create session sso logon return invalid server GUID")
}
sessionCtx, cancel := context.WithCancel(ctx)
s := &Session{
id: resp.SessionID,
serverGUID: resp.ServerGUID,
active: true,
when: time.Now(),
ctx: sessionCtx,
ctxCancel: cancel,
c: c,
}
err = s.StartAutoRefresh()
return s, err
}
// CreateSession creates a new Session without the server using the provided
// data.
func CreateSession(ctx context.Context, c *KCC, id KCSessionID, serverGUID string, active bool) (*Session, error) {
if id == KCNoSessionID {
return nil, fmt.Errorf("create session with invalid session ID")
}
if serverGUID == "" {
return nil, fmt.Errorf("create session with invalid server GUID")
}
if ctx == nil {
ctx = context.Background()
}
sessionCtx, cancel := context.WithCancel(ctx)
s := &Session{
id: id,
serverGUID: serverGUID,
active: active,
ctx: sessionCtx,
ctxCancel: cancel,
c: c,
}
if active {
s.when = time.Now()
}
return s, nil
}
// Context returns the accociated Session's context.
func (s *Session) Context() context.Context {
return s.ctx
}
// IsActive retruns true when the accociated Session is not destroyed, if the
// last refresh was successful and if the last activity is recent enough.
func (s *Session) IsActive() bool {
s.mutex.RLock()
active := s.active
when := s.when
s.mutex.RUnlock()
return active && !when.Before(time.Now().Add(-(SessionAutorefreshInterval + SessionExpirationGrace)))
}
// ID returns the accociated Session's ID.
func (s *Session) ID() KCSessionID {
return s.id
}
// Destroy logs off the accociated Session at the accociated Server and stops
// auto refreshing by canceling the accociated Session's Context. An error is
// retruned if the logoff request fails.
func (s *Session) Destroy(ctx context.Context, logoff bool) error {
s.mutex.Lock()
if !s.active {
s.mutex.Unlock()
return nil
}
s.active = false
s.mutex.Unlock()
s.ctxCancel()
if logoff {
resp, err := s.c.Logoff(ctx, s.id)
if err != nil {
return fmt.Errorf("logoff session logoff failed: %v", err)
}
if resp.Er != KCSuccess {
return fmt.Errorf("logoff session logoff error: %v", resp.Er)
}
}
return nil
}
func (s *Session) String() string {
return fmt.Sprintf("Session(%s@%s)", s.id, s.serverGUID)
}
// Refresh triggers a server call to let the server know that the accociated
// session is still active.
func (s *Session) Refresh() error {
s.mutex.RLock()
active := s.active
s.mutex.RUnlock()
if !active {
return nil
}
resp, err := s.c.ResolveUsername(s.ctx, "SYSTEM", s.id)
if err != nil {
return fmt.Errorf("refresh session resolveUsername failed: %v", err)
}
if resp.Er != KCSuccess {
return fmt.Errorf("refresh session resolveUsername mapi error: %v", resp.Er)
}
s.mutex.Lock()
s.when = time.Now()
s.mutex.Unlock()
return nil
}
// StartAutoRefresh enables auto refresh of the accociated session.
func (s *Session) StartAutoRefresh() error {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.autoRefresh != nil {
close(s.autoRefresh)
}
s.autoRefresh = make(chan bool, 1)
return s.runAutoRefresh(s.autoRefresh)
}
// StopAutoRefresh stops a running auto refresh of the accociated session.
func (s *Session) StopAutoRefresh() error {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.autoRefresh != nil {
close(s.autoRefresh)
s.autoRefresh = nil
}
return nil
}
func (s *Session) runAutoRefresh(stop chan bool) error {
ctx := s.Context()
ticker := time.NewTicker(SessionAutorefreshInterval)
go func() {
for {
select {
case <-ctx.Done():
s.StopAutoRefresh()
return
case <-ticker.C:
err := s.Refresh()
if err != nil {
s.Destroy(ctx, err != KCERR_END_OF_SESSION)
s.StopAutoRefresh()
}
case <-stop:
return
}
}
}()
return nil
}