cgi 0.1.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of cgi might be problematic. Click here for more details.

@@ -0,0 +1,534 @@
1
+ # frozen_string_literal: true
2
+ #
3
+ # cgi/session.rb - session support for cgi scripts
4
+ #
5
+ # Copyright (C) 2001 Yukihiro "Matz" Matsumoto
6
+ # Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
7
+ # Copyright (C) 2000 Information-technology Promotion Agency, Japan
8
+ #
9
+ # Author: Yukihiro "Matz" Matsumoto
10
+ #
11
+ # Documentation: William Webber (william@williamwebber.com)
12
+
13
+ require 'cgi'
14
+ require 'tmpdir'
15
+
16
+ class CGI
17
+
18
+ # == Overview
19
+ #
20
+ # This file provides the CGI::Session class, which provides session
21
+ # support for CGI scripts. A session is a sequence of HTTP requests
22
+ # and responses linked together and associated with a single client.
23
+ # Information associated with the session is stored
24
+ # on the server between requests. A session id is passed between client
25
+ # and server with every request and response, transparently
26
+ # to the user. This adds state information to the otherwise stateless
27
+ # HTTP request/response protocol.
28
+ #
29
+ # == Lifecycle
30
+ #
31
+ # A CGI::Session instance is created from a CGI object. By default,
32
+ # this CGI::Session instance will start a new session if none currently
33
+ # exists, or continue the current session for this client if one does
34
+ # exist. The +new_session+ option can be used to either always or
35
+ # never create a new session. See #new() for more details.
36
+ #
37
+ # #delete() deletes a session from session storage. It
38
+ # does not however remove the session id from the client. If the client
39
+ # makes another request with the same id, the effect will be to start
40
+ # a new session with the old session's id.
41
+ #
42
+ # == Setting and retrieving session data.
43
+ #
44
+ # The Session class associates data with a session as key-value pairs.
45
+ # This data can be set and retrieved by indexing the Session instance
46
+ # using '[]', much the same as hashes (although other hash methods
47
+ # are not supported).
48
+ #
49
+ # When session processing has been completed for a request, the
50
+ # session should be closed using the close() method. This will
51
+ # store the session's state to persistent storage. If you want
52
+ # to store the session's state to persistent storage without
53
+ # finishing session processing for this request, call the update()
54
+ # method.
55
+ #
56
+ # == Storing session state
57
+ #
58
+ # The caller can specify what form of storage to use for the session's
59
+ # data with the +database_manager+ option to CGI::Session::new. The
60
+ # following storage classes are provided as part of the standard library:
61
+ #
62
+ # CGI::Session::FileStore:: stores data as plain text in a flat file. Only
63
+ # works with String data. This is the default
64
+ # storage type.
65
+ # CGI::Session::MemoryStore:: stores data in an in-memory hash. The data
66
+ # only persists for as long as the current Ruby
67
+ # interpreter instance does.
68
+ # CGI::Session::PStore:: stores data in Marshalled format. Provided by
69
+ # cgi/session/pstore.rb. Supports data of any type,
70
+ # and provides file-locking and transaction support.
71
+ #
72
+ # Custom storage types can also be created by defining a class with
73
+ # the following methods:
74
+ #
75
+ # new(session, options)
76
+ # restore # returns hash of session data.
77
+ # update
78
+ # close
79
+ # delete
80
+ #
81
+ # Changing storage type mid-session does not work. Note in particular
82
+ # that by default the FileStore and PStore session data files have the
83
+ # same name. If your application switches from one to the other without
84
+ # making sure that filenames will be different
85
+ # and clients still have old sessions lying around in cookies, then
86
+ # things will break nastily!
87
+ #
88
+ # == Maintaining the session id.
89
+ #
90
+ # Most session state is maintained on the server. However, a session
91
+ # id must be passed backwards and forwards between client and server
92
+ # to maintain a reference to this session state.
93
+ #
94
+ # The simplest way to do this is via cookies. The CGI::Session class
95
+ # provides transparent support for session id communication via cookies
96
+ # if the client has cookies enabled.
97
+ #
98
+ # If the client has cookies disabled, the session id must be included
99
+ # as a parameter of all requests sent by the client to the server. The
100
+ # CGI::Session class in conjunction with the CGI class will transparently
101
+ # add the session id as a hidden input field to all forms generated
102
+ # using the CGI#form() HTML generation method. No built-in support is
103
+ # provided for other mechanisms, such as URL re-writing. The caller is
104
+ # responsible for extracting the session id from the session_id
105
+ # attribute and manually encoding it in URLs and adding it as a hidden
106
+ # input to HTML forms created by other mechanisms. Also, session expiry
107
+ # is not automatically handled.
108
+ #
109
+ # == Examples of use
110
+ #
111
+ # === Setting the user's name
112
+ #
113
+ # require 'cgi'
114
+ # require 'cgi/session'
115
+ # require 'cgi/session/pstore' # provides CGI::Session::PStore
116
+ #
117
+ # cgi = CGI.new("html4")
118
+ #
119
+ # session = CGI::Session.new(cgi,
120
+ # 'database_manager' => CGI::Session::PStore, # use PStore
121
+ # 'session_key' => '_rb_sess_id', # custom session key
122
+ # 'session_expires' => Time.now + 30 * 60, # 30 minute timeout
123
+ # 'prefix' => 'pstore_sid_') # PStore option
124
+ # if cgi.has_key?('user_name') and cgi['user_name'] != ''
125
+ # # coerce to String: cgi[] returns the
126
+ # # string-like CGI::QueryExtension::Value
127
+ # session['user_name'] = cgi['user_name'].to_s
128
+ # elsif !session['user_name']
129
+ # session['user_name'] = "guest"
130
+ # end
131
+ # session.close
132
+ #
133
+ # === Creating a new session safely
134
+ #
135
+ # require 'cgi'
136
+ # require 'cgi/session'
137
+ #
138
+ # cgi = CGI.new("html4")
139
+ #
140
+ # # We make sure to delete an old session if one exists,
141
+ # # not just to free resources, but to prevent the session
142
+ # # from being maliciously hijacked later on.
143
+ # begin
144
+ # session = CGI::Session.new(cgi, 'new_session' => false)
145
+ # session.delete
146
+ # rescue ArgumentError # if no old session
147
+ # end
148
+ # session = CGI::Session.new(cgi, 'new_session' => true)
149
+ # session.close
150
+ #
151
+ class Session
152
+
153
+ class NoSession < RuntimeError #:nodoc:
154
+ end
155
+
156
+ # The id of this session.
157
+ attr_reader :session_id, :new_session
158
+
159
+ def Session::callback(dbman) #:nodoc:
160
+ Proc.new{
161
+ dbman[0].close unless dbman.empty?
162
+ }
163
+ end
164
+
165
+ # Create a new session id.
166
+ #
167
+ # The session id is a secure random number by SecureRandom
168
+ # if possible, otherwise an SHA512 hash based upon the time,
169
+ # a random number, and a constant string. This routine is
170
+ # used internally for automatically generated session ids.
171
+ def create_new_id
172
+ require 'securerandom'
173
+ begin
174
+ # by OpenSSL, or system provided entropy pool
175
+ session_id = SecureRandom.hex(16)
176
+ rescue NotImplementedError
177
+ # never happens on modern systems
178
+ require 'digest'
179
+ d = Digest('SHA512').new
180
+ now = Time::now
181
+ d.update(now.to_s)
182
+ d.update(String(now.usec))
183
+ d.update(String(rand(0)))
184
+ d.update(String($$))
185
+ d.update('foobar')
186
+ session_id = d.hexdigest[0, 32]
187
+ end
188
+ session_id
189
+ end
190
+ private :create_new_id
191
+
192
+ # Create a new CGI::Session object for +request+.
193
+ #
194
+ # +request+ is an instance of the +CGI+ class (see cgi.rb).
195
+ # +option+ is a hash of options for initialising this
196
+ # CGI::Session instance. The following options are
197
+ # recognised:
198
+ #
199
+ # session_key:: the parameter name used for the session id.
200
+ # Defaults to '_session_id'.
201
+ # session_id:: the session id to use. If not provided, then
202
+ # it is retrieved from the +session_key+ parameter
203
+ # of the request, or automatically generated for
204
+ # a new session.
205
+ # new_session:: if true, force creation of a new session. If not set,
206
+ # a new session is only created if none currently
207
+ # exists. If false, a new session is never created,
208
+ # and if none currently exists and the +session_id+
209
+ # option is not set, an ArgumentError is raised.
210
+ # database_manager:: the name of the class providing storage facilities
211
+ # for session state persistence. Built-in support
212
+ # is provided for +FileStore+ (the default),
213
+ # +MemoryStore+, and +PStore+ (from
214
+ # cgi/session/pstore.rb). See the documentation for
215
+ # these classes for more details.
216
+ #
217
+ # The following options are also recognised, but only apply if the
218
+ # session id is stored in a cookie.
219
+ #
220
+ # session_expires:: the time the current session expires, as a
221
+ # +Time+ object. If not set, the session will terminate
222
+ # when the user's browser is closed.
223
+ # session_domain:: the hostname domain for which this session is valid.
224
+ # If not set, defaults to the hostname of the server.
225
+ # session_secure:: if +true+, this session will only work over HTTPS.
226
+ # session_path:: the path for which this session applies. Defaults
227
+ # to the directory of the CGI script.
228
+ #
229
+ # +option+ is also passed on to the session storage class initializer; see
230
+ # the documentation for each session storage class for the options
231
+ # they support.
232
+ #
233
+ # The retrieved or created session is automatically added to +request+
234
+ # as a cookie, and also to its +output_hidden+ table, which is used
235
+ # to add hidden input elements to forms.
236
+ #
237
+ # *WARNING* the +output_hidden+
238
+ # fields are surrounded by a <fieldset> tag in HTML 4 generation, which
239
+ # is _not_ invisible on many browsers; you may wish to disable the
240
+ # use of fieldsets with code similar to the following
241
+ # (see http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/37805)
242
+ #
243
+ # cgi = CGI.new("html4")
244
+ # class << cgi
245
+ # undef_method :fieldset
246
+ # end
247
+ #
248
+ def initialize(request, option={})
249
+ @new_session = false
250
+ session_key = option['session_key'] || '_session_id'
251
+ session_id = option['session_id']
252
+ unless session_id
253
+ if option['new_session']
254
+ session_id = create_new_id
255
+ @new_session = true
256
+ end
257
+ end
258
+ unless session_id
259
+ if request.key?(session_key)
260
+ session_id = request[session_key]
261
+ session_id = session_id.read if session_id.respond_to?(:read)
262
+ end
263
+ unless session_id
264
+ session_id, = request.cookies[session_key]
265
+ end
266
+ unless session_id
267
+ unless option.fetch('new_session', true)
268
+ raise ArgumentError, "session_key `%s' should be supplied"%session_key
269
+ end
270
+ session_id = create_new_id
271
+ @new_session = true
272
+ end
273
+ end
274
+ @session_id = session_id
275
+ dbman = option['database_manager'] || FileStore
276
+ begin
277
+ @dbman = dbman::new(self, option)
278
+ rescue NoSession
279
+ unless option.fetch('new_session', true)
280
+ raise ArgumentError, "invalid session_id `%s'"%session_id
281
+ end
282
+ session_id = @session_id = create_new_id unless session_id
283
+ @new_session=true
284
+ retry
285
+ end
286
+ request.instance_eval do
287
+ @output_hidden = {session_key => session_id} unless option['no_hidden']
288
+ @output_cookies = [
289
+ Cookie::new("name" => session_key,
290
+ "value" => session_id,
291
+ "expires" => option['session_expires'],
292
+ "domain" => option['session_domain'],
293
+ "secure" => option['session_secure'],
294
+ "path" =>
295
+ if option['session_path']
296
+ option['session_path']
297
+ elsif ENV["SCRIPT_NAME"]
298
+ File::dirname(ENV["SCRIPT_NAME"])
299
+ else
300
+ ""
301
+ end)
302
+ ] unless option['no_cookies']
303
+ end
304
+ @dbprot = [@dbman]
305
+ ObjectSpace::define_finalizer(self, Session::callback(@dbprot))
306
+ end
307
+
308
+ # Retrieve the session data for key +key+.
309
+ def [](key)
310
+ @data ||= @dbman.restore
311
+ @data[key]
312
+ end
313
+
314
+ # Set the session data for key +key+.
315
+ def []=(key, val)
316
+ @write_lock ||= true
317
+ @data ||= @dbman.restore
318
+ @data[key] = val
319
+ end
320
+
321
+ # Store session data on the server. For some session storage types,
322
+ # this is a no-op.
323
+ def update
324
+ @dbman.update
325
+ end
326
+
327
+ # Store session data on the server and close the session storage.
328
+ # For some session storage types, this is a no-op.
329
+ def close
330
+ @dbman.close
331
+ @dbprot.clear
332
+ end
333
+
334
+ # Delete the session from storage. Also closes the storage.
335
+ #
336
+ # Note that the session's data is _not_ automatically deleted
337
+ # upon the session expiring.
338
+ def delete
339
+ @dbman.delete
340
+ @dbprot.clear
341
+ end
342
+
343
+ # File-based session storage class.
344
+ #
345
+ # Implements session storage as a flat file of 'key=value' values.
346
+ # This storage type only works directly with String values; the
347
+ # user is responsible for converting other types to Strings when
348
+ # storing and from Strings when retrieving.
349
+ class FileStore
350
+ # Create a new FileStore instance.
351
+ #
352
+ # This constructor is used internally by CGI::Session. The
353
+ # user does not generally need to call it directly.
354
+ #
355
+ # +session+ is the session for which this instance is being
356
+ # created. The session id must only contain alphanumeric
357
+ # characters; automatically generated session ids observe
358
+ # this requirement.
359
+ #
360
+ # +option+ is a hash of options for the initializer. The
361
+ # following options are recognised:
362
+ #
363
+ # tmpdir:: the directory to use for storing the FileStore
364
+ # file. Defaults to Dir::tmpdir (generally "/tmp"
365
+ # on Unix systems).
366
+ # prefix:: the prefix to add to the session id when generating
367
+ # the filename for this session's FileStore file.
368
+ # Defaults to "cgi_sid_".
369
+ # suffix:: the prefix to add to the session id when generating
370
+ # the filename for this session's FileStore file.
371
+ # Defaults to the empty string.
372
+ #
373
+ # This session's FileStore file will be created if it does
374
+ # not exist, or opened if it does.
375
+ def initialize(session, option={})
376
+ dir = option['tmpdir'] || Dir::tmpdir
377
+ prefix = option['prefix'] || 'cgi_sid_'
378
+ suffix = option['suffix'] || ''
379
+ id = session.session_id
380
+ require 'digest/md5'
381
+ md5 = Digest::MD5.hexdigest(id)[0,16]
382
+ @path = dir+"/"+prefix+md5+suffix
383
+ if File::exist? @path
384
+ @hash = nil
385
+ else
386
+ unless session.new_session
387
+ raise CGI::Session::NoSession, "uninitialized session"
388
+ end
389
+ @hash = {}
390
+ end
391
+ end
392
+
393
+ # Restore session state from the session's FileStore file.
394
+ #
395
+ # Returns the session state as a hash.
396
+ def restore
397
+ unless @hash
398
+ @hash = {}
399
+ begin
400
+ lockf = File.open(@path+".lock", "r")
401
+ lockf.flock File::LOCK_SH
402
+ f = File.open(@path, 'r')
403
+ for line in f
404
+ line.chomp!
405
+ k, v = line.split('=',2)
406
+ @hash[CGI::unescape(k)] = Marshal.restore(CGI::unescape(v))
407
+ end
408
+ ensure
409
+ f&.close
410
+ lockf&.close
411
+ end
412
+ end
413
+ @hash
414
+ end
415
+
416
+ # Save session state to the session's FileStore file.
417
+ def update
418
+ return unless @hash
419
+ begin
420
+ lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600)
421
+ lockf.flock File::LOCK_EX
422
+ f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600)
423
+ for k,v in @hash
424
+ f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(Marshal.dump(v)))
425
+ end
426
+ f.close
427
+ File.rename @path+".new", @path
428
+ ensure
429
+ f&.close
430
+ lockf&.close
431
+ end
432
+ end
433
+
434
+ # Update and close the session's FileStore file.
435
+ def close
436
+ update
437
+ end
438
+
439
+ # Close and delete the session's FileStore file.
440
+ def delete
441
+ File::unlink @path+".lock" rescue nil
442
+ File::unlink @path+".new" rescue nil
443
+ File::unlink @path rescue nil
444
+ end
445
+ end
446
+
447
+ # In-memory session storage class.
448
+ #
449
+ # Implements session storage as a global in-memory hash. Session
450
+ # data will only persist for as long as the Ruby interpreter
451
+ # instance does.
452
+ class MemoryStore
453
+ GLOBAL_HASH_TABLE = {} #:nodoc:
454
+
455
+ # Create a new MemoryStore instance.
456
+ #
457
+ # +session+ is the session this instance is associated with.
458
+ # +option+ is a list of initialisation options. None are
459
+ # currently recognized.
460
+ def initialize(session, option=nil)
461
+ @session_id = session.session_id
462
+ unless GLOBAL_HASH_TABLE.key?(@session_id)
463
+ unless session.new_session
464
+ raise CGI::Session::NoSession, "uninitialized session"
465
+ end
466
+ GLOBAL_HASH_TABLE[@session_id] = {}
467
+ end
468
+ end
469
+
470
+ # Restore session state.
471
+ #
472
+ # Returns session data as a hash.
473
+ def restore
474
+ GLOBAL_HASH_TABLE[@session_id]
475
+ end
476
+
477
+ # Update session state.
478
+ #
479
+ # A no-op.
480
+ def update
481
+ # don't need to update; hash is shared
482
+ end
483
+
484
+ # Close session storage.
485
+ #
486
+ # A no-op.
487
+ def close
488
+ # don't need to close
489
+ end
490
+
491
+ # Delete the session state.
492
+ def delete
493
+ GLOBAL_HASH_TABLE.delete(@session_id)
494
+ end
495
+ end
496
+
497
+ # Dummy session storage class.
498
+ #
499
+ # Implements session storage place holder. No actual storage
500
+ # will be done.
501
+ class NullStore
502
+ # Create a new NullStore instance.
503
+ #
504
+ # +session+ is the session this instance is associated with.
505
+ # +option+ is a list of initialisation options. None are
506
+ # currently recognised.
507
+ def initialize(session, option=nil)
508
+ end
509
+
510
+ # Restore (empty) session state.
511
+ def restore
512
+ {}
513
+ end
514
+
515
+ # Update session state.
516
+ #
517
+ # A no-op.
518
+ def update
519
+ end
520
+
521
+ # Close session storage.
522
+ #
523
+ # A no-op.
524
+ def close
525
+ end
526
+
527
+ # Delete the session state.
528
+ #
529
+ # A no-op.
530
+ def delete
531
+ end
532
+ end
533
+ end
534
+ end