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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/* Copyright 2016 Joshua Gentry
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */
use std::any::Any;
use std::collections::BTreeMap;
use std::fmt::{Debug, Formatter, Error, Write};
use std::sync::{Arc, Mutex};
use std::u32;

use cookie::{Cookie, CookieJar};
use iron::{Request, Response, IronResult};
use iron::error::IronError;
use iron::middleware::{AfterMiddleware, AroundMiddleware, BeforeMiddleware, Chain, Handler};
use iron::headers;
use iron::status::Status;
use rand;
use time;

use FeSessionState;
use fe_session_config::FeSessionConfig;
use fe_session_data::FeSessionData;
use fe_session_error::FeSessionError;
use fe_session_request::FeSessionRequest;
use fe_session_thread::FeSessionThread;
use fe_session::FeSession;

//*************************************************************************************************
/// Storage object that holds the mapping of session IDs to sessions.
///
/// This class is inserted into the iron handler change to provide session functionality to your
/// application.
///
/// # Examples
/// ```
/// # extern crate iron;
/// # extern crate fe_session;
/// use iron::{Iron, Request, Response};
/// use iron::middleware::Chain;
/// use iron::status::Status;
/// use fe_session::{FeSessionRequest, FeSessionStorage, FeConnection};
///
/// struct MySession  {
///     name : String
/// }
///
/// # fn main() {
/// let mut chain = Chain::new(|req : &mut Request| {
///     if req.url.path()[0] == "login" {
///         let name = String::from(req.url.query().unwrap());
///
///         req.create_session(MySession {
///             name : name
///         });
///         Ok(Response::with((Status::Ok, "Hello")))
///     }
///     else if req.url.path()[0] == "logout" {
///        req.clear_session::<MySession>();
///        Ok(Response::with((Status::Ok, "Goodbye")))
///     }
///     else {
///         let mut access = req.get_session::<MySession>();
///
///         if access.state().is_active() {
///             let session = access.get();
///             Ok(Response::with((Status::Ok, session.name.clone())))
///         } else {
///             Ok(Response::with((Status::Ok, "I don't know you.")))
///         }
///     }
/// });
///
/// chain.around(FeSessionStorage::<MySession>::new());
///
/// let mut iron = Iron::new(chain).http(("localhost", 3000)).unwrap();
///
/// let mut conn = FeConnection::new("localhost", 3000);
/// assert_eq!(conn.get_string("/login?bob"), "Hello");
/// assert_eq!(conn.get_string("/"), "bob");
/// assert_eq!(conn.get_string("/logout"), "Goodbye");
/// assert_eq!(conn.get_string("/"), "I don't know you.");
///
/// iron.close().unwrap();
/// # }
/// ```
pub struct FeSessionStorage<T : 'static>
{
    //---------------------------------------------------------------------------------------------
    /// The configuration for the sessions.
    config : Arc<FeSessionConfig>,

    //---------------------------------------------------------------------------------------------
    /// A mapping of session IDs to the sessions.
    sessions : Arc<Mutex<BTreeMap<u32, FeSessionData<T>>>>,

    //---------------------------------------------------------------------------------------------
    /// The thread that is expiring sessions.
    thread : Arc<FeSessionThread>
}

//*************************************************************************************************
/// Helper function to convert a u32 session key into a string that we can set as a cookie.
///
/// Returns a string with the u32 value in hex.
fn cookie(
    key : u32
    ) -> String
{
    let mut cookie = String::with_capacity(8);

    write!(cookie, "{:x}", key).unwrap();

    cookie
}

impl<T : Any + Send + Sync> FeSessionStorage<T>
{
    //*********************************************************************************************
    /// Create a new instance with default session values.  Please refer to
    /// FeSessionConfig::new() for what the default values are.
    ///
    /// Returns the newly created instance.
    pub fn new() -> FeSessionStorage<T>
    {
        FeSessionStorage::create(FeSessionConfig::new())
    }

    //*********************************************************************************************
    /// Create a new instance with custom configuration values.
    ///
    /// Returns the newly created instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use fe_session::{FeSessionConfig, FeSessionStorage};
    ///
    /// struct MySession;
    ///
    /// let config = FeSessionConfig::new();
    ///
    /// let sessions = FeSessionStorage::<MySession>::create(config);
    /// ```
    pub fn create(
        config : FeSessionConfig
        ) -> FeSessionStorage<T>
    {
        let config   = Arc::new(config);
        let sessions = Arc::new(Mutex::new(BTreeMap::new()));
        let thread   = FeSessionThread::new(config.clone(), sessions.clone());

        FeSessionStorage {
            config   : config,
            sessions : sessions,
            thread   : thread
        }
    }

    //*********************************************************************************************
    /// Adds a session to the session map.
    ///
    /// This method will acquire the mutex, then randomly generate session keys until it finds
    /// an unused one, then it will insert the sesion into the map with that session key.
    ///
    /// Returns the session key that was chosen.
    fn add_session(
        &self,
        session : Arc<Mutex<T>>
        ) -> Result<u32, ()>
    {
        if let Ok(mut guard) = self.sessions.lock()
        {
            loop {
                let key = rand::random::<u32>();

                if guard.contains_key(&key) == false
                {
                    guard.insert(key, FeSessionData::new(session));
                    return Ok(key);
                }
            }
        }
        else
        {
            Err(())
        }
    }

    //*********************************************************************************************
    /// Helper function to extract the session cookie from the HTTP request.
    ///
    /// Returns a CookieJar with the current cookies as well as an optional u32 session key if it
    /// was provided by the client.
    fn extact_cookie(
        &self,
        request : &Request
        ) -> (CookieJar, Option<u32>)
    {
        //-----------------------------------------------------------------------------------------
        // Create the cookie jar.
        let jar = match request.headers.get::<headers::Cookie>()
        {
            Some(cookies) => cookies.to_cookie_jar(self.config.cookie_key()),
            None          => CookieJar::new(self.config.cookie_key())
        };

        //-----------------------------------------------------------------------------------------
        // Extract the session cookie and convert it to a u32.
        let key = match jar.encrypted().find(self.config.cookie_name())
        {
            //-------------------------------------------------------------------------------------
            // Got the cookie, convert it.
            Some(cookie) => {
                if let Ok(val) = u32::from_str_radix(&cookie.value, 16)
                {
                    Some(val)
                }
                else
                {
                    None
                }
            }
            //-------------------------------------------------------------------------------------
            // No cookie, no session value.
            None => None
        };

        (jar, key)
    }
}

impl<T : Any + Send + Sync> AroundMiddleware for FeSessionStorage<T>
{
    //*********************************************************************************************
    /// Wrap the FeSessionStorage instance around the handler.
    ///
    /// Returns a new chain that contains FeSessionStorage wrapped around the existing chain.
    fn around(
        self,
        handler : Box<Handler>
        ) -> Box<Handler>
    {
        let mut chain = Chain::new(handler);

        chain.link_before(self.clone());
        chain.link_after(self);

        Box::new(chain)
    }
}

impl<T : Any + Send + Sync> BeforeMiddleware for FeSessionStorage<T>
{
    //*********************************************************************************************
    /// Called by the iron framework to allow us to process an incoming request.
    ///
    /// The goal of this method is to add an FeSession object to the extensions element of the
    /// request.  If the session key is expired or not provided then an empty FeSession object is
    /// created and inserted. If the session exists then an FeSession object is created with it
    /// and it's last accessed time is updated.
    ///
    /// Usually returns Ok(()).  However if we've crashed while holding the mutex protecting the
    /// session map then an error is generated.
    fn before(
        &self,
        request : &mut Request
        ) ->  IronResult<()>
    {
        let (_, key) = self.extact_cookie(request);

        //-----------------------------------------------------------------------------------------
        // If we have a session key, we need to check the sessions map to see if a session maps
        // to the key.
        let session = if let Some(key) = key
        {
            //-------------------------------------------------------------------------------------
            // Grab the mutex lock to access the sessions map.
            if let Ok(mut guard) = self.sessions.lock()
            {
                //---------------------------------------------------------------------------------
                // If the session exists, create a FeSession object from it.
                if let Some(mut data) = guard.get_mut(&key)
                {
                    data.session(key)
                }
                //---------------------------------------------------------------------------------
                // The session doesn't exist, so the session must have expired.
                else
                {
                    FeSession::new(
                        Some(key),
                        FeSessionState::Expired,
                        time::get_time(),
                        None
                        )
                }
            }
            //-------------------------------------------------------------------------------------
            // Our mutex is poisoned, this is bad, very bad.
            else
            {
                error!("Sessions mutex is poisoned.");
                return Err(IronError::new(FeSessionError::StorageMutexPoisoned, Status::InternalServerError));
            }
        }
        //-----------------------------------------------------------------------------------------
        // No session key provided, so no session has been created.
        else
        {
            FeSession::new(
                None,
                FeSessionState::None,
                time::get_time(),
                None
                )
        };

        //-----------------------------------------------------------------------------------------
        // Update the extensions in the request so the handler can get at the state.
        request.extensions.insert::<FeSession<T>>(session);

        Ok(())
    }
}

impl<T : Any + Send + Sync> AfterMiddleware for FeSessionStorage<T>
{
    //*********************************************************************************************
    /// Called by the Iron framework after a request has been handled.
    ///
    /// This class does a bunch of work to make sure the cookie headers are correct based on the
    /// state of the session.  So if the session is active and the client didn't give us a session
    /// key or gave us an old session key, then the response is updated so it provides the correct
    /// session key in the next request.  If the session doesn't exist and the client gave us a
    /// session key, it's told to stop.
    ///
    /// This method also updates the session map, if a new session is replacing an old session
    /// then the old session is removed from the map.  If the new session does not have a key
    /// (i.e. it hasn't been added to the session map) it is added.
    ///
    /// This method usually returns Ok(response) however if the mutex protecting the session map
    /// is poisoned then it returns an error.
    fn after(
        &self,
        request : &mut Request,
        mut response : Response
        ) ->  IronResult<Response>
    {
        let (jar, old_key) = self.extact_cookie(request);
        let session        = request.get_session();

        match session.state()
        {
            FeSessionState::Active => {
                //---------------------------------------------------------------------------------
                // If the old key doesn't match the current key or if there was no old key then we
                // need to add this session into our storage map and give the client the new
                // session key.
                if old_key != session.key() || old_key.is_none()
                {
                    if old_key.is_some()
                    {
                        if let Ok(mut guard) = self.sessions.lock()
                        {
                            guard.remove(&old_key.unwrap());
                        }
                        else
                        {
                            error!("Sessions mutex is poisoned.");
                            return Err(IronError::new(FeSessionError::StorageMutexPoisoned, Status::InternalServerError));
                        }
                    }

                    match self.add_session(session.raw())
                    {
                        Ok(new_key) => {
                            jar.encrypted().add(
                                Cookie::new(self.config.cookie_name().clone(), cookie(new_key))
                                );
                            response.headers.set(headers::SetCookie(jar.delta()));
                            Ok(response)
                        }
                        Err(_) => {
                            Err(IronError::new(FeSessionError::StorageMutexPoisoned, Status::InternalServerError))
                        }
                    }
                }
                //---------------------------------------------------------------------------------
                // The session is fine, just return response.
                else
                {
                    Ok(response)
                }
            },
            //-------------------------------------------------------------------------------------
            // There is no current session and the client gave us a session key tell them to stop.
            _ => {
                if old_key.is_some()
                {
                    jar.remove(self.config.cookie_name());
                    response.headers.set(headers::SetCookie(jar.delta()));

                    if let Ok(mut guard) = self.sessions.lock()
                    {
                        guard.remove(&old_key.unwrap());
                        Ok(response)
                    }
                    else
                    {
                        error!("Sessions mutex is poisoned.");
                        Err(IronError::new(FeSessionError::StorageMutexPoisoned, Status::InternalServerError))
                    }
                }
                else
                {
                    Ok(response)
                }
            }
        }
    }
}

impl<T> Drop for FeSessionStorage<T>
{
    //*********************************************************************************************
    /// Called by the system when the object is being destroyed.  Tell the expire thread to
    /// shutdown as well.
    fn drop(&mut self)
    {
        self.thread.shutdown();
    }
}

impl<T> Clone for FeSessionStorage<T>
{
    //*********************************************************************************************
    /// Implementation of Clone.
    fn clone(&self) -> FeSessionStorage<T>
    {
        FeSessionStorage {
            config   : self.config.clone(),
            sessions : self.sessions.clone(),
            thread   : self.thread.clone()
        }
    }

    //*********************************************************************************************
    /// Implementation of Clone.
    fn clone_from(
        &mut self,
        source: &FeSessionStorage<T>
        )
    {
        self.config   = source.config.clone();
        self.sessions = source.sessions.clone();
        self.thread   = source.thread.clone();
    }
}

impl<T> Debug for FeSessionStorage<T>
{
    //*********************************************************************************************
    /// Implementation of Debug for the object so we can print out some useful information for
    /// debugging purposes.
    ///
    /// fmt - The formatter to write to.
    ///
    /// Returns Ok is the information was written with without and error otherwise it returns Err.
    fn fmt(
        &self,
        fmt : &mut Formatter
        ) -> Result<(), Error>
    {
        let mut count = 0;

        if let Ok(sessions) = self.sessions.lock()
        {
            count = sessions.len();
        }

        fmt.debug_struct("Sessions")
            .field("config", &self.config)
            .field("sessions", &count)
            .finish()
        }
}