]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_session.php
Imported Upstream version 0.7
[roundcube.git] / program / include / rcube_session.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_session.php                                     |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2005-2011, The Roundcube Dev Team                       |
9  | Copyright (C) 2011, Kolab Systems AG                                  |
10  | Licensed under the GNU GPL                                            |
11  |                                                                       |
12  | PURPOSE:                                                              |
13  |   Provide database supported session management                       |
14  |                                                                       |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  | Author: Aleksander Machniak <alec@alec.pl>                            |
18  +-----------------------------------------------------------------------+
19
20  $Id: session.inc 2932 2009-09-07 12:51:21Z alec $
21
22 */
23
24 /**
25  * Class to provide database supported session storage
26  *
27  * @package    Core
28  * @author     Thomas Bruederli <roundcube@gmail.com>
29  * @author     Aleksander Machniak <alec@alec.pl>
30  */
31 class rcube_session
32 {
33   private $db;
34   private $ip;
35   private $start;
36   private $changed;
37   private $unsets = array();
38   private $gc_handlers = array();
39   private $cookiename = 'roundcube_sessauth';
40   private $vars = false;
41   private $key;
42   private $now;
43   private $prev;
44   private $secret = '';
45   private $ip_check = false;
46   private $logging = false;
47   private $keep_alive = 0;
48   private $memcache;
49
50   /**
51    * Default constructor
52    */
53   public function __construct($db, $config)
54   {
55     $this->db      = $db;
56     $this->start   = microtime(true);
57     $this->ip      = $_SERVER['REMOTE_ADDR'];
58     $this->logging = $config->get('log_session', false);
59     $this->mc_debug = $config->get('memcache_debug', false);
60
61     $lifetime = $config->get('session_lifetime', 1) * 60;
62     $this->set_lifetime($lifetime);
63
64     // use memcache backend
65     if ($config->get('session_storage', 'db') == 'memcache') {
66       $this->memcache = rcmail::get_instance()->get_memcache();
67
68       // set custom functions for PHP session management if memcache is available
69       if ($this->memcache) {
70         session_set_save_handler(
71           array($this, 'open'),
72           array($this, 'close'),
73           array($this, 'mc_read'),
74           array($this, 'mc_write'),
75           array($this, 'mc_destroy'),
76           array($this, 'gc'));
77       }
78       else {
79         raise_error(array('code' => 604, 'type' => 'db',
80           'line' => __LINE__, 'file' => __FILE__,
81           'message' => "Failed to connect to memcached. Please check configuration"),
82           true, true);
83       }
84     }
85     else {
86       // set custom functions for PHP session management
87       session_set_save_handler(
88         array($this, 'open'),
89         array($this, 'close'),
90         array($this, 'db_read'),
91         array($this, 'db_write'),
92         array($this, 'db_destroy'),
93         array($this, 'db_gc'));
94       }
95   }
96
97
98   public function open($save_path, $session_name)
99   {
100     return true;
101   }
102
103
104   public function close()
105   {
106     return true;
107   }
108
109
110   /**
111    * Delete session data for the given key
112    *
113    * @param string Session ID
114    */
115   public function destroy($key)
116   {
117     return $this->memcache ? $this->mc_destroy($key) : $this->db_destroy($key);
118   }
119
120
121   /**
122    * Read session data from database
123    *
124    * @param string Session ID
125    * @return string Session vars
126    */
127   public function db_read($key)
128   {
129     $sql_result = $this->db->query(
130       "SELECT vars, ip, changed FROM ".get_table_name('session')
131       ." WHERE sess_id = ?", $key);
132
133     if ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
134       $this->changed = strtotime($sql_arr['changed']);
135       $this->ip      = $sql_arr['ip'];
136       $this->vars    = base64_decode($sql_arr['vars']);
137       $this->key     = $key;
138
139       if (!empty($this->vars))
140         return $this->vars;
141     }
142
143     return false;
144   }
145
146
147   /**
148    * Save session data.
149    * handler for session_read()
150    *
151    * @param string Session ID
152    * @param string Serialized session vars
153    * @return boolean True on success
154    */
155   public function db_write($key, $vars)
156   {
157     $ts = microtime(true);
158     $now = $this->db->fromunixtime((int)$ts);
159
160     // no session row in DB (db_read() returns false)
161     if (!$this->key) {
162       $oldvars = false;
163     }
164     // use internal data from read() for fast requests (up to 0.5 sec.)
165     else if ($key == $this->key && (!$this->vars || $ts - $this->start < 0.5)) {
166       $oldvars = $this->vars;
167     }
168     else { // else read data again from DB
169       $oldvars = $this->db_read($key);
170     }
171
172     if ($oldvars !== false) {
173       $newvars = $this->_fixvars($vars, $oldvars);
174
175       if ($newvars !== $oldvars) {
176         $this->db->query(
177           sprintf("UPDATE %s SET vars=?, changed=%s WHERE sess_id=?",
178             get_table_name('session'), $now),
179           base64_encode($newvars), $key);
180       }
181       else if ($ts - $this->changed > $this->lifetime / 2) {
182         $this->db->query("UPDATE ".get_table_name('session')." SET changed=$now WHERE sess_id=?", $key);
183       }
184     }
185     else {
186       $this->db->query(
187         sprintf("INSERT INTO %s (sess_id, vars, ip, created, changed) ".
188           "VALUES (?, ?, ?, %s, %s)",
189           get_table_name('session'), $now, $now),
190         $key, base64_encode($vars), (string)$this->ip);
191     }
192
193     return true;
194   }
195
196
197   /**
198    * Merge vars with old vars and apply unsets
199    */
200   private function _fixvars($vars, $oldvars)
201   {
202     if ($oldvars !== false) {
203       $a_oldvars = $this->unserialize($oldvars);
204       if (is_array($a_oldvars)) {
205         foreach ((array)$this->unsets as $k)
206           unset($a_oldvars[$k]);
207
208         $newvars = $this->serialize(array_merge(
209           (array)$a_oldvars, (array)$this->unserialize($vars)));
210       }
211       else
212         $newvars = $vars;
213     }
214
215     $this->unsets = array();
216     return $newvars;
217   }
218
219
220   /**
221    * Handler for session_destroy()
222    *
223    * @param string Session ID
224    * @return boolean True on success
225    */
226   public function db_destroy($key)
227   {
228     $this->db->query(
229       sprintf("DELETE FROM %s WHERE sess_id = ?", get_table_name('session')),
230       $key);
231
232     return true;
233   }
234
235
236   /**
237    * Garbage collecting function
238    *
239    * @param string Session lifetime in seconds
240    * @return boolean True on success
241    */
242   public function db_gc($maxlifetime)
243   {
244     // just delete all expired sessions
245     $this->db->query(
246       sprintf("DELETE FROM %s WHERE changed < %s",
247         get_table_name('session'), $this->db->fromunixtime(time() - $maxlifetime)));
248
249     $this->gc();
250
251     return true;
252   }
253
254
255   /**
256    * Read session data from memcache
257    *
258    * @param string Session ID
259    * @return string Session vars
260    */
261   public function mc_read($key)
262   {
263     $value = $this->memcache->get($key);
264     if ($this->mc_debug) write_log('memcache', "get($key): " . strlen($value));
265     if ($value && ($arr = unserialize($value))) {
266       $this->changed = $arr['changed'];
267       $this->ip      = $arr['ip'];
268       $this->vars    = $arr['vars'];
269       $this->key     = $key;
270
271       if (!empty($this->vars))
272         return $this->vars;
273     }
274
275     return false;
276   }
277
278   /**
279    * Save session data.
280    * handler for session_read()
281    *
282    * @param string Session ID
283    * @param string Serialized session vars
284    * @return boolean True on success
285    */
286   public function mc_write($key, $vars)
287   {
288     $ts = microtime(true);
289
290     // no session data in cache (mc_read() returns false)
291     if (!$this->key)
292       $oldvars = false;
293     // use internal data for fast requests (up to 0.5 sec.)
294     else if ($key == $this->key && (!$this->vars || $ts - $this->start < 0.5))
295       $oldvars = $this->vars;
296     else // else read data again
297       $oldvars = $this->mc_read($key);
298
299     $newvars = $oldvars !== false ? $this->_fixvars($vars, $oldvars) : $vars;
300     
301     if ($newvars !== $oldvars || $ts - $this->changed > $this->lifetime / 2) {
302       $value = serialize(array('changed' => time(), 'ip' => $this->ip, 'vars' => $newvars));
303       $ret = $this->memcache->set($key, $value, MEMCACHE_COMPRESSED, $this->lifetime);
304       if ($this->mc_debug) {
305         write_log('memcache', "set($key): " . strlen($value) . ": " . ($ret ? 'OK' : 'ERR'));
306         write_log('memcache', "... get($key): " . strlen($this->memcache->get($key)));
307       }
308       return $ret;
309     }
310     
311     return true;
312   }
313
314   /**
315    * Handler for session_destroy() with memcache backend
316    *
317    * @param string Session ID
318    * @return boolean True on success
319    */
320   public function mc_destroy($key)
321   {
322     $ret = $this->memcache->delete($key);
323     if ($this->mc_debug) write_log('memcache', "delete($key): " . ($ret ? 'OK' : 'ERR'));
324     return $ret;
325   }
326
327
328   /**
329    * Execute registered garbage collector routines
330    */
331   public function gc()
332   {
333     foreach ($this->gc_handlers as $fct)
334       call_user_func($fct);
335   }
336
337
338   /**
339    * Register additional garbage collector functions
340    *
341    * @param mixed Callback function
342    */
343   public function register_gc_handler($func_name)
344   {
345     if ($func_name && !in_array($func_name, $this->gc_handlers))
346       $this->gc_handlers[] = $func_name;
347   }
348
349
350   /**
351    * Generate and set new session id
352    *
353    * @param boolean $destroy If enabled the current session will be destroyed
354    */
355   public function regenerate_id($destroy=true)
356   {
357     session_regenerate_id($destroy);
358
359     $this->vars = false;
360     $this->key  = session_id();
361
362     return true;
363   }
364
365
366   /**
367    * Unset a session variable
368    *
369    * @param string Varibale name
370    * @return boolean True on success
371    */
372   public function remove($var=null)
373   {
374     if (empty($var))
375       return $this->destroy(session_id());
376
377     $this->unsets[] = $var;
378     unset($_SESSION[$var]);
379
380     return true;
381   }
382   
383   /**
384    * Kill this session
385    */
386   public function kill()
387   {
388     $this->vars = false;
389     $this->destroy(session_id());
390     rcmail::setcookie($this->cookiename, '-del-', time() - 60);
391   }
392
393
394   /**
395    * Re-read session data from storage backend
396    */
397   public function reload()
398   {
399     if ($this->key && $this->memcache)
400       $data = $this->mc_read($this->key);
401     else if ($this->key)
402       $data = $this->db_read($this->key);
403
404     if ($data)
405      session_decode($data);
406   }
407
408
409   /**
410    * Serialize session data
411    */
412   private function serialize($vars)
413   {
414     $data = '';
415     if (is_array($vars))
416       foreach ($vars as $var=>$value)
417         $data .= $var.'|'.serialize($value);
418     else
419       $data = 'b:0;';
420     return $data;
421   }
422
423
424   /**
425    * Unserialize session data
426    * http://www.php.net/manual/en/function.session-decode.php#56106
427    */
428   private function unserialize($str)
429   {
430     $str = (string)$str;
431     $endptr = strlen($str);
432     $p = 0;
433
434     $serialized = '';
435     $items = 0;
436     $level = 0;
437
438     while ($p < $endptr) {
439       $q = $p;
440       while ($str[$q] != '|')
441         if (++$q >= $endptr) break 2;
442
443       if ($str[$p] == '!') {
444         $p++;
445         $has_value = false;
446       } else {
447         $has_value = true;
448       }
449
450       $name = substr($str, $p, $q - $p);
451       $q++;
452
453       $serialized .= 's:' . strlen($name) . ':"' . $name . '";';
454
455       if ($has_value) {
456         for (;;) {
457           $p = $q;
458           switch (strtolower($str[$q])) {
459             case 'n': /* null */
460             case 'b': /* boolean */
461             case 'i': /* integer */
462             case 'd': /* decimal */
463               do $q++;
464               while ( ($q < $endptr) && ($str[$q] != ';') );
465               $q++;
466               $serialized .= substr($str, $p, $q - $p);
467               if ($level == 0) break 2;
468               break;
469             case 'r': /* reference  */
470               $q+= 2;
471               for ($id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++) $id .= $str[$q];
472               $q++;
473               $serialized .= 'R:' . ($id + 1) . ';'; /* increment pointer because of outer array */
474               if ($level == 0) break 2;
475               break;
476             case 's': /* string */
477               $q+=2;
478               for ($length=''; ($q < $endptr) && ($str[$q] != ':'); $q++) $length .= $str[$q];
479               $q+=2;
480               $q+= (int)$length + 2;
481               $serialized .= substr($str, $p, $q - $p);
482               if ($level == 0) break 2;
483               break;
484             case 'a': /* array */
485             case 'o': /* object */
486               do $q++;
487               while ( ($q < $endptr) && ($str[$q] != '{') );
488               $q++;
489               $level++;
490               $serialized .= substr($str, $p, $q - $p);
491               break;
492             case '}': /* end of array|object */
493               $q++;
494               $serialized .= substr($str, $p, $q - $p);
495               if (--$level == 0) break 2;
496               break;
497             default:
498               return false;
499           }
500         }
501       } else {
502         $serialized .= 'N;';
503         $q += 2;
504       }
505       $items++;
506       $p = $q;
507     }
508
509     return unserialize( 'a:' . $items . ':{' . $serialized . '}' );
510   }
511
512
513   /**
514    * Setter for session lifetime
515    */
516   public function set_lifetime($lifetime)
517   {
518       $this->lifetime = max(120, $lifetime);
519
520       // valid time range is now - 1/2 lifetime to now + 1/2 lifetime
521       $now = time();
522       $this->now = $now - ($now % ($this->lifetime / 2));
523       $this->prev = $this->now - ($this->lifetime / 2);
524   }
525
526   /**
527    * Setter for keep_alive interval
528    */
529   public function set_keep_alive($keep_alive)
530   {
531     $this->keep_alive = $keep_alive;
532     
533     if ($this->lifetime < $keep_alive)
534         $this->set_lifetime($keep_alive + 30);
535   }
536
537   /**
538    * Getter for keep_alive interval
539    */
540   public function get_keep_alive()
541   {
542     return $this->keep_alive;
543   }
544
545   /**
546    * Getter for remote IP saved with this session
547    */
548   public function get_ip()
549   {
550     return $this->ip;
551   }
552   
553   /**
554    * Setter for cookie encryption secret
555    */
556   function set_secret($secret)
557   {
558     $this->secret = $secret;
559   }
560
561
562   /**
563    * Enable/disable IP check
564    */
565   function set_ip_check($check)
566   {
567     $this->ip_check = $check;
568   }
569   
570   /**
571    * Setter for the cookie name used for session cookie
572    */
573   function set_cookiename($cookiename)
574   {
575     if ($cookiename)
576       $this->cookiename = $cookiename;
577   }
578
579
580   /**
581    * Check session authentication cookie
582    *
583    * @return boolean True if valid, False if not
584    */
585   function check_auth()
586   {
587     $this->cookie = $_COOKIE[$this->cookiename];
588     $result = $this->ip_check ? $_SERVER['REMOTE_ADDR'] == $this->ip : true;
589
590     if (!$result)
591       $this->log("IP check failed for " . $this->key . "; expected " . $this->ip . "; got " . $_SERVER['REMOTE_ADDR']);
592
593     if ($result && $this->_mkcookie($this->now) != $this->cookie) {
594       // Check if using id from previous time slot
595       if ($this->_mkcookie($this->prev) == $this->cookie) {
596         $this->set_auth_cookie();
597       }
598       else {
599         $result = false;
600         $this->log("Session authentication failed for " . $this->key . "; invalid auth cookie sent");
601       }
602     }
603
604     return $result;
605   }
606
607
608   /**
609    * Set session authentication cookie
610    */
611   function set_auth_cookie()
612   {
613     $this->cookie = $this->_mkcookie($this->now);
614     rcmail::setcookie($this->cookiename, $this->cookie, 0);
615     $_COOKIE[$this->cookiename] = $this->cookie;
616   }
617
618
619   /**
620    * Create session cookie from session data
621    *
622    * @param int Time slot to use
623    */
624   function _mkcookie($timeslot)
625   {
626     $auth_string = "$this->key,$this->secret,$timeslot";
627     return "S" . (function_exists('sha1') ? sha1($auth_string) : md5($auth_string));
628   }
629   
630   /**
631    * 
632    */
633   function log($line)
634   {
635     if ($this->logging)
636       write_log('session', $line);
637   }
638
639 }