cgi 0.3.3-java

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,88 @@
1
+ # frozen_string_literal: true
2
+ #
3
+ # cgi/session/pstore.rb - persistent storage of marshalled session data
4
+ #
5
+ # Documentation: William Webber (william@williamwebber.com)
6
+ #
7
+ # == Overview
8
+ #
9
+ # This file provides the CGI::Session::PStore class, which builds
10
+ # persistent of session data on top of the pstore library. See
11
+ # cgi/session.rb for more details on session storage managers.
12
+
13
+ require_relative '../session'
14
+ require 'pstore'
15
+
16
+ class CGI
17
+ class Session
18
+ # PStore-based session storage class.
19
+ #
20
+ # This builds upon the top-level PStore class provided by the
21
+ # library file pstore.rb. Session data is marshalled and stored
22
+ # in a file. File locking and transaction services are provided.
23
+ class PStore
24
+ # Create a new CGI::Session::PStore instance
25
+ #
26
+ # This constructor is used internally by CGI::Session. The
27
+ # user does not generally need to call it directly.
28
+ #
29
+ # +session+ is the session for which this instance is being
30
+ # created. The session id must only contain alphanumeric
31
+ # characters; automatically generated session ids observe
32
+ # this requirement.
33
+ #
34
+ # +option+ is a hash of options for the initializer. The
35
+ # following options are recognised:
36
+ #
37
+ # tmpdir:: the directory to use for storing the PStore
38
+ # file. Defaults to Dir::tmpdir (generally "/tmp"
39
+ # on Unix systems).
40
+ # prefix:: the prefix to add to the session id when generating
41
+ # the filename for this session's PStore file.
42
+ # Defaults to the empty string.
43
+ #
44
+ # This session's PStore file will be created if it does
45
+ # not exist, or opened if it does.
46
+ def initialize(session, option={})
47
+ option = {'suffix'=>''}.update(option)
48
+ path, @hash = session.new_store_file(option)
49
+ @p = ::PStore.new(path)
50
+ @p.transaction do |p|
51
+ File.chmod(0600, p.path)
52
+ end
53
+ end
54
+
55
+ # Restore session state from the session's PStore file.
56
+ #
57
+ # Returns the session state as a hash.
58
+ def restore
59
+ unless @hash
60
+ @p.transaction do
61
+ @hash = @p['hash'] || {}
62
+ end
63
+ end
64
+ @hash
65
+ end
66
+
67
+ # Save session state to the session's PStore file.
68
+ def update
69
+ @p.transaction do
70
+ @p['hash'] = @hash
71
+ end
72
+ end
73
+
74
+ # Update and close the session's PStore file.
75
+ def close
76
+ update
77
+ end
78
+
79
+ # Close and delete the session's PStore file.
80
+ def delete
81
+ path = @p.path
82
+ File::unlink path
83
+ end
84
+
85
+ end
86
+ end
87
+ end
88
+ # :enddoc:
@@ -0,0 +1,562 @@
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
+
193
+ # Create a new file to store the session data.
194
+ #
195
+ # This file will be created if it does not exist, or opened if it
196
+ # does.
197
+ #
198
+ # This path is generated under _tmpdir_ from _prefix_, the
199
+ # digested session id, and _suffix_.
200
+ #
201
+ # +option+ is a hash of options for the initializer. The
202
+ # following options are recognised:
203
+ #
204
+ # tmpdir:: the directory to use for storing the FileStore
205
+ # file. Defaults to Dir::tmpdir (generally "/tmp"
206
+ # on Unix systems).
207
+ # prefix:: the prefix to add to the session id when generating
208
+ # the filename for this session's FileStore file.
209
+ # Defaults to "cgi_sid_".
210
+ # suffix:: the prefix to add to the session id when generating
211
+ # the filename for this session's FileStore file.
212
+ # Defaults to the empty string.
213
+ def new_store_file(option={}) # :nodoc:
214
+ dir = option['tmpdir'] || Dir::tmpdir
215
+ prefix = option['prefix']
216
+ suffix = option['suffix']
217
+ require 'digest/md5'
218
+ md5 = Digest::MD5.hexdigest(session_id)[0,16]
219
+ path = dir+"/"
220
+ path << prefix if prefix
221
+ path << md5
222
+ path << suffix if suffix
223
+ if File::exist? path
224
+ hash = nil
225
+ elsif new_session
226
+ hash = {}
227
+ else
228
+ raise NoSession, "uninitialized session"
229
+ end
230
+ return path, hash
231
+ end
232
+
233
+ # Create a new CGI::Session object for +request+.
234
+ #
235
+ # +request+ is an instance of the +CGI+ class (see cgi.rb).
236
+ # +option+ is a hash of options for initialising this
237
+ # CGI::Session instance. The following options are
238
+ # recognised:
239
+ #
240
+ # session_key:: the parameter name used for the session id.
241
+ # Defaults to '_session_id'.
242
+ # session_id:: the session id to use. If not provided, then
243
+ # it is retrieved from the +session_key+ parameter
244
+ # of the request, or automatically generated for
245
+ # a new session.
246
+ # new_session:: if true, force creation of a new session. If not set,
247
+ # a new session is only created if none currently
248
+ # exists. If false, a new session is never created,
249
+ # and if none currently exists and the +session_id+
250
+ # option is not set, an ArgumentError is raised.
251
+ # database_manager:: the name of the class providing storage facilities
252
+ # for session state persistence. Built-in support
253
+ # is provided for +FileStore+ (the default),
254
+ # +MemoryStore+, and +PStore+ (from
255
+ # cgi/session/pstore.rb). See the documentation for
256
+ # these classes for more details.
257
+ #
258
+ # The following options are also recognised, but only apply if the
259
+ # session id is stored in a cookie.
260
+ #
261
+ # session_expires:: the time the current session expires, as a
262
+ # +Time+ object. If not set, the session will terminate
263
+ # when the user's browser is closed.
264
+ # session_domain:: the hostname domain for which this session is valid.
265
+ # If not set, defaults to the hostname of the server.
266
+ # session_secure:: if +true+, this session will only work over HTTPS.
267
+ # session_path:: the path for which this session applies. Defaults
268
+ # to the directory of the CGI script.
269
+ #
270
+ # +option+ is also passed on to the session storage class initializer; see
271
+ # the documentation for each session storage class for the options
272
+ # they support.
273
+ #
274
+ # The retrieved or created session is automatically added to +request+
275
+ # as a cookie, and also to its +output_hidden+ table, which is used
276
+ # to add hidden input elements to forms.
277
+ #
278
+ # *WARNING* the +output_hidden+
279
+ # fields are surrounded by a <fieldset> tag in HTML 4 generation, which
280
+ # is _not_ invisible on many browsers; you may wish to disable the
281
+ # use of fieldsets with code similar to the following
282
+ # (see http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/37805)
283
+ #
284
+ # cgi = CGI.new("html4")
285
+ # class << cgi
286
+ # undef_method :fieldset
287
+ # end
288
+ #
289
+ def initialize(request, option={})
290
+ @new_session = false
291
+ session_key = option['session_key'] || '_session_id'
292
+ session_id = option['session_id']
293
+ unless session_id
294
+ if option['new_session']
295
+ session_id = create_new_id
296
+ @new_session = true
297
+ end
298
+ end
299
+ unless session_id
300
+ if request.key?(session_key)
301
+ session_id = request[session_key]
302
+ session_id = session_id.read if session_id.respond_to?(:read)
303
+ end
304
+ unless session_id
305
+ session_id, = request.cookies[session_key]
306
+ end
307
+ unless session_id
308
+ unless option.fetch('new_session', true)
309
+ raise ArgumentError, "session_key `%s' should be supplied"%session_key
310
+ end
311
+ session_id = create_new_id
312
+ @new_session = true
313
+ end
314
+ end
315
+ @session_id = session_id
316
+ dbman = option['database_manager'] || FileStore
317
+ begin
318
+ @dbman = dbman::new(self, option)
319
+ rescue NoSession
320
+ unless option.fetch('new_session', true)
321
+ raise ArgumentError, "invalid session_id `%s'"%session_id
322
+ end
323
+ session_id = @session_id = create_new_id unless session_id
324
+ @new_session=true
325
+ retry
326
+ end
327
+ request.instance_eval do
328
+ @output_hidden = {session_key => session_id} unless option['no_hidden']
329
+ @output_cookies = [
330
+ Cookie::new("name" => session_key,
331
+ "value" => session_id,
332
+ "expires" => option['session_expires'],
333
+ "domain" => option['session_domain'],
334
+ "secure" => option['session_secure'],
335
+ "path" =>
336
+ if option['session_path']
337
+ option['session_path']
338
+ elsif ENV["SCRIPT_NAME"]
339
+ File::dirname(ENV["SCRIPT_NAME"])
340
+ else
341
+ ""
342
+ end)
343
+ ] unless option['no_cookies']
344
+ end
345
+ @dbprot = [@dbman]
346
+ ObjectSpace::define_finalizer(self, Session::callback(@dbprot))
347
+ end
348
+
349
+ # Retrieve the session data for key +key+.
350
+ def [](key)
351
+ @data ||= @dbman.restore
352
+ @data[key]
353
+ end
354
+
355
+ # Set the session data for key +key+.
356
+ def []=(key, val)
357
+ @write_lock ||= true
358
+ @data ||= @dbman.restore
359
+ @data[key] = val
360
+ end
361
+
362
+ # Store session data on the server. For some session storage types,
363
+ # this is a no-op.
364
+ def update
365
+ @dbman.update
366
+ end
367
+
368
+ # Store session data on the server and close the session storage.
369
+ # For some session storage types, this is a no-op.
370
+ def close
371
+ @dbman.close
372
+ @dbprot.clear
373
+ end
374
+
375
+ # Delete the session from storage. Also closes the storage.
376
+ #
377
+ # Note that the session's data is _not_ automatically deleted
378
+ # upon the session expiring.
379
+ def delete
380
+ @dbman.delete
381
+ @dbprot.clear
382
+ end
383
+
384
+ # File-based session storage class.
385
+ #
386
+ # Implements session storage as a flat file of 'key=value' values.
387
+ # This storage type only works directly with String values; the
388
+ # user is responsible for converting other types to Strings when
389
+ # storing and from Strings when retrieving.
390
+ class FileStore
391
+ # Create a new FileStore instance.
392
+ #
393
+ # This constructor is used internally by CGI::Session. The
394
+ # user does not generally need to call it directly.
395
+ #
396
+ # +session+ is the session for which this instance is being
397
+ # created. The session id must only contain alphanumeric
398
+ # characters; automatically generated session ids observe
399
+ # this requirement.
400
+ #
401
+ # +option+ is a hash of options for the initializer. The
402
+ # following options are recognised:
403
+ #
404
+ # tmpdir:: the directory to use for storing the FileStore
405
+ # file. Defaults to Dir::tmpdir (generally "/tmp"
406
+ # on Unix systems).
407
+ # prefix:: the prefix to add to the session id when generating
408
+ # the filename for this session's FileStore file.
409
+ # Defaults to "cgi_sid_".
410
+ # suffix:: the prefix to add to the session id when generating
411
+ # the filename for this session's FileStore file.
412
+ # Defaults to the empty string.
413
+ #
414
+ # This session's FileStore file will be created if it does
415
+ # not exist, or opened if it does.
416
+ def initialize(session, option={})
417
+ option = {'prefix' => 'cgi_sid_'}.update(option)
418
+ @path, @hash = session.new_store_file(option)
419
+ end
420
+
421
+ # Restore session state from the session's FileStore file.
422
+ #
423
+ # Returns the session state as a hash.
424
+ def restore
425
+ unless @hash
426
+ @hash = {}
427
+ begin
428
+ lockf = File.open(@path+".lock", "r")
429
+ lockf.flock File::LOCK_SH
430
+ f = File.open(@path, 'r')
431
+ for line in f
432
+ line.chomp!
433
+ k, v = line.split('=',2)
434
+ @hash[CGI.unescape(k)] = Marshal.restore(CGI.unescape(v))
435
+ end
436
+ ensure
437
+ f&.close
438
+ lockf&.close
439
+ end
440
+ end
441
+ @hash
442
+ end
443
+
444
+ # Save session state to the session's FileStore file.
445
+ def update
446
+ return unless @hash
447
+ begin
448
+ lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600)
449
+ lockf.flock File::LOCK_EX
450
+ f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600)
451
+ for k,v in @hash
452
+ f.printf "%s=%s\n", CGI.escape(k), CGI.escape(String(Marshal.dump(v)))
453
+ end
454
+ f.close
455
+ File.rename @path+".new", @path
456
+ ensure
457
+ f&.close
458
+ lockf&.close
459
+ end
460
+ end
461
+
462
+ # Update and close the session's FileStore file.
463
+ def close
464
+ update
465
+ end
466
+
467
+ # Close and delete the session's FileStore file.
468
+ def delete
469
+ File::unlink @path+".lock" rescue nil
470
+ File::unlink @path+".new" rescue nil
471
+ File::unlink @path rescue nil
472
+ end
473
+ end
474
+
475
+ # In-memory session storage class.
476
+ #
477
+ # Implements session storage as a global in-memory hash. Session
478
+ # data will only persist for as long as the Ruby interpreter
479
+ # instance does.
480
+ class MemoryStore
481
+ GLOBAL_HASH_TABLE = {} #:nodoc:
482
+
483
+ # Create a new MemoryStore instance.
484
+ #
485
+ # +session+ is the session this instance is associated with.
486
+ # +option+ is a list of initialisation options. None are
487
+ # currently recognized.
488
+ def initialize(session, option=nil)
489
+ @session_id = session.session_id
490
+ unless GLOBAL_HASH_TABLE.key?(@session_id)
491
+ unless session.new_session
492
+ raise CGI::Session::NoSession, "uninitialized session"
493
+ end
494
+ GLOBAL_HASH_TABLE[@session_id] = {}
495
+ end
496
+ end
497
+
498
+ # Restore session state.
499
+ #
500
+ # Returns session data as a hash.
501
+ def restore
502
+ GLOBAL_HASH_TABLE[@session_id]
503
+ end
504
+
505
+ # Update session state.
506
+ #
507
+ # A no-op.
508
+ def update
509
+ # don't need to update; hash is shared
510
+ end
511
+
512
+ # Close session storage.
513
+ #
514
+ # A no-op.
515
+ def close
516
+ # don't need to close
517
+ end
518
+
519
+ # Delete the session state.
520
+ def delete
521
+ GLOBAL_HASH_TABLE.delete(@session_id)
522
+ end
523
+ end
524
+
525
+ # Dummy session storage class.
526
+ #
527
+ # Implements session storage place holder. No actual storage
528
+ # will be done.
529
+ class NullStore
530
+ # Create a new NullStore instance.
531
+ #
532
+ # +session+ is the session this instance is associated with.
533
+ # +option+ is a list of initialisation options. None are
534
+ # currently recognised.
535
+ def initialize(session, option=nil)
536
+ end
537
+
538
+ # Restore (empty) session state.
539
+ def restore
540
+ {}
541
+ end
542
+
543
+ # Update session state.
544
+ #
545
+ # A no-op.
546
+ def update
547
+ end
548
+
549
+ # Close session storage.
550
+ #
551
+ # A no-op.
552
+ def close
553
+ end
554
+
555
+ # Delete the session state.
556
+ #
557
+ # A no-op.
558
+ def delete
559
+ end
560
+ end
561
+ end
562
+ end