10 enable :inline_templates
12 set :upload_password, '0e5f7d398e6f9cd1f6bac5cc823e363aec636495'
13 set :default_expire, 60 # 1 hour
14 set :filename_length, 20
15 set :random_pass_length, 16
16 set :lockfile_options, { :timeout => 60,
21 class BadKey < StandardError; end
26 attr_reader :meta, :expire_at
28 def self.open(path, pass = nil)
29 StoredFile.new(path, pass)
34 yield @initial_content
35 @initial_content = nil
36 until (buf = @file.read(BUFFER_LEN)).nil?
37 yield @cipher.update(buf)
48 def self.create(src, pass, meta)
50 clear_meta = { "Coquelicot" => COQUELICOT_VERSION,
51 "Salt" => Base64.encode64(salt).strip,
52 "Expire-at" => meta.delete('Expire-at') }
53 yield YAML.dump(clear_meta) + YAML_START
55 cipher = get_cipher(pass, salt, :encrypt)
56 yield cipher.update(YAML.dump(meta) + YAML_START)
58 while not (buf = src.read(BUFFER_LEN)).nil?
59 yield cipher.update(buf)
67 CIPHER = 'AES-256-CBC'
69 COQUELICOT_VERSION = "1.0"
71 def self.get_cipher(pass, salt, method)
72 hmac = OpenSSL::PKCS5.pbkdf2_hmac_sha1(pass, salt, 2000, 48)
73 cipher = OpenSSL::Cipher.new CIPHER
74 cipher.method(method).call
75 cipher.key = hmac[0..31]
76 cipher.iv = hmac[32..-1]
81 OpenSSL::Random::random_bytes(SALT_LEN)
84 def initialize(path, pass)
85 @file = File.open(path)
86 if YAML_START != (buf = @file.read(YAML_START.length)) then
87 raise "unknown file, read #{buf.inspect}"
91 init_decrypt_cipher pass
97 until YAML_START == (line = @file.readline) do
100 @meta = YAML.load(meta)
101 if @meta["Coquelicot"].nil? or @meta["Coquelicot"] != COQUELICOT_VERSION then
104 @expire_at = Time.at(@meta['Expire-at'].to_i)
107 def init_decrypt_cipher(pass)
108 salt = Base64.decode64(@meta["Salt"])
109 @cipher = StoredFile::get_cipher(pass, salt, :decrypt)
114 buf = @file.read(BUFFER_LEN)
115 content = @cipher.update(buf)
116 raise BadKey unless content.start_with? YAML_START
118 block = content.split(YAML_START, 3)
120 if block.length == 3 then
121 @initial_content = block[2]
122 @meta.merge! YAML.load(yaml)
126 until (buf = @file.read(BUFFER_LEN)).nil? do
127 block = @cipher.update(buf).split(YAML_START, 3)
129 break if block.length == 2
131 @initial_content = block[1]
132 @meta.merge! YAML.load(yaml)
136 @cipher.reset unless @cipher.nil?
144 attr_accessor :path, :lockfile_options, :filename_length
146 def add_file(src, pass, options)
149 dst = gen_random_file_name
150 File.open(full_path(dst), 'w').close
153 File.open(full_path(dst), 'w') do |dest|
154 StoredFile.create(src, pass, options) { |data| dest.write data }
157 File.unlink full_path(dst)
160 link = gen_random_file_name
165 def get_file(link, pass)
166 name = read_link(link)
167 return nil if name.nil?
168 StoredFile::open(full_path(name), pass)
171 def file_exists?(link)
172 name = read_link(link)
178 remove_file(name) if Time.now > StoredFile::open(full_path(name)).expire_at
185 Lockfile.new "#{@path}/.lock", @lockfile_options
192 def add_link(src, dst)
194 File.open(links_path, 'a') do |f|
195 f.write("#{src} #{dst}\n")
200 def remove_from_links(&block)
203 File.open(links_path, 'r+') do |f|
204 f.readlines.each do |l|
205 links << l unless yield l
215 remove_from_links { |l| l.start_with? "#{src} " }
221 File.open(links_path) do |f|
224 if line.start_with? "#{src} " then
228 end until line.empty?
234 def remove_file(name)
235 # zero the content before unlinking
236 File.open(full_path(name), 'r+') do |f|
237 f.seek 0, IO::SEEK_END
241 write_len = [StoredFile::BUFFER_LEN, length].min
242 length -= f.write("\0" * write_len)
245 File.unlink full_path(name)
246 remove_from_links { |l| l.end_with? " #{name}" }
251 File.open(links_path) do |f|
252 f.readlines.collect { |l| l.split[1] }
257 def gen_random_file_name
259 name = gen_random_base32(@filename_length)
260 end while File.exists?(full_path(name))
265 raise "Wrong name" unless name.each_char.collect { |c| FILENAME_CHARS.include? c }.all?
270 @depot unless @depot.nil?
272 @depot = Depot.instance
273 @depot.path = options.depot_path if @depot.path.nil?
274 @depot.lockfile_options = options.lockfile_options if @depot.lockfile_options.nil?
275 @depot.filename_length = options.filename_length if @depot.filename_length.nil?
279 # Like RFC 4648 (Base32)
280 FILENAME_CHARS = %w(a b c d e f g h i j k l m n o p q r s t u v w x y z 2 3 4 5 6 7)
281 def gen_random_base32(length)
283 OpenSSL::Random::random_bytes(length).each_byte do |i|
284 name << FILENAME_CHARS[i % FILENAME_CHARS.length]
289 gen_random_base32(options.random_pass_length)
291 def remap_base32_extra_characters(str)
293 FILENAME_CHARS.each { |c| map[c] = c; map[c.upcase] = c }
294 map.merge!({ '1' => 'l', '0' => 'o' })
296 str.each_char { |c| result << map[c] }
300 def password_match?(password)
301 return TRUE if settings.upload_password.nil?
302 (not password.nil?) && Digest::SHA1.hexdigest(password) == settings.upload_password
306 content_type 'text/css', :charset => 'utf-8'
314 get '/ready/:link' do |link|
315 link, pass = link.split '-' if link.include? '-'
317 file = depot.get_file(link, nil)
318 rescue Errno::ENOENT => ex
321 @expire_at = file.expire_at
322 @base = request.url.gsub(/\/ready\/[^\/]*$/, '')
328 @url = "#{@base}/#{@name}"
333 unless password_match? params[:upload_password] then
336 if params[:file] then
337 tmpfile = params[:file][:tempfile]
338 name = params[:file][:filename]
340 if tmpfile.nil? || name.nil? then
341 @error = "No file selected"
344 if params[:expire].nil? or params[:expire].to_i == 0 then
345 params[:expire] = options.default_expire
347 expire_at = Time.now + 60 * params[:expire].to_i
348 if params[:file_key].nil? or params[:file_key].empty?then
349 pass = gen_random_pass
351 pass = params[:file_key]
353 src = params[:file][:tempfile]
354 link = depot.add_file(
356 { "Expire-at" => expire_at.strftime('%s'),
357 "Filename" => params[:file][:filename],
358 "Length" => src.stat.size,
359 "Content-Type" => params[:file][:type]
361 redirect "ready/#{link}-#{pass}" if params[:file_key].nil? or params[:file_key].empty?
362 redirect "ready/#{link}"
366 throw :halt, [410, haml(:expired)]
369 def send_stored_file(link, pass)
370 file = depot.get_file(link, pass)
371 return false if file.nil?
372 return expired if Time.now > file.expire_at
374 last_modified file.mtime.httpdate
375 attachment file.meta['Filename']
376 response['Content-Length'] = "#{file.meta['Length']}"
377 response['Content-Type'] = file.meta['Content-Type'] || 'application/octet-stream'
378 throw :halt, [200, file]
381 get '/:link-:pass' do |link, pass|
382 link = remap_base32_extra_characters(link)
383 pass = remap_base32_extra_characters(pass)
384 not_found unless send_stored_file(link, pass)
387 get '/:link' do |link|
388 link = remap_base32_extra_characters(link)
389 not_found unless depot.file_exists? link
394 post '/:link' do |link|
395 pass = params[:file_key]
396 return 403 if pass.nil? or pass.empty?
398 return 403 unless send_stored_file(link, pass)
406 url = request.scheme + "://"
408 if request.scheme == "https" && request.port != 443 ||
409 request.scheme == "http" && request.port != 80
410 url << ":#{request.port}"
412 url << request.script_name
425 %base{ :href => base_href }
426 %link{ :rel => 'stylesheet', :href => "style.css", :type => 'text/css',
427 :media => "screen, projection" }
428 %script{ :type => 'text/javascript', :src => 'javascripts/jquery.min.js' }
429 %script{ :type => 'text/javascript', :src => 'javascripts/jquery.lightBoxFu.js' }
430 %script{ :type => 'text/javascript', :src => 'javascripts/jquery.uploadProgress.js' }
431 %script{ :type => 'text/javascript', :src => 'javascripts/coquelicot.js' }
440 %form#upload{ :enctype => 'multipart/form-data',
441 :action => 'upload', :method => 'post' }
443 %label{ :for => 'upload_password' } Upload password:
444 %input.input{ :type => 'password', :id => 'upload_password', :name => 'upload_password' }
446 %label{ :for => 'file' } File:
447 %input.input{ :type => 'file', id => 'file', :name => 'file' }
449 %label{ :for => 'expire' } Available for:
450 %select.input{ :id => 'expire',:name => 'expire' }
451 %option{ :value => 5 } 5 minutes
452 %option{ :value => 60 } 1 hour
453 %option{ :value => 60 * 24 } 1 day
454 %option{ :value => 60 * 24 * 7 } 1 week
455 %option{ :value => 60 * 24 * 30 } 1 month
457 %label{ :for => 'file_key' } Download password:
458 %input.input{ :type => 'password', :id => 'file_key', :name => 'file_key' }
461 %input.submit{ :type => 'submit', :value => 'Share!' }
468 %span.base> #{@base}/
470 - unless @unprotected
471 %p A password is required to download this file.
472 %p The file will be available until #{@expire_at}.
474 %a{ :href => base_href } Share another file…
477 %h1 Enter download password…
479 %form{ :action => @link, :method => 'post' }
481 %label{ :for => 'file_key' } Password:
482 %input{ :type => 'text', :id => 'file_key', :name => 'file_key' }
485 %input{ :type => 'submit', :value => 'Get file' }
490 %p Sorry, file has expired.
496 background-color: $green
501 text-decoration: underline
505 background-color: red
507 border: black solid 1px
511 border-bottom: solid 1px #ccc
517 -moz-border-radius: 25px
518 -webkit-border-radius: 25px
520 border: solid 1px black
527 text-decoration: none
564 background: url('images/ajax-loader.gif') no-repeat