#
# https.rb -- SSL/TLS enhancement for HTTPServer
#
# Author: IPR -- Internet Programming with Ruby -- writers
# Copyright (C) 2001 GOTOU Yuuzou
#
# $IPR: https.rb,v 1.4 2002/02/05 20:20:31 gotoyuzo Exp $

require 'webrick'
require 'openssl'

module WEBrick
  module Config
    HTTP.update(
      :SSLEnable            => true,
      :SSLCertificate       => nil, 
      :SSLPrivateKey        => nil,
      :SSLCACertificate     => nil,
      :SSLCACertificatePath => nil,
      :SSLVerifyClient      => ::OpenSSL::SSL::VERIFY_NONE, 
      :SSLVerifyDepth       => nil,
      :SSLVerifyCallback    => nil,   # custom verification
      # Must specify if you use auto generated certificate.
      :SSLCertName          => nil,
      :SSLCertComment       => "Generated by Ruby/OpenSSL"
    )

    r_osslv = ::OpenSSL::VERSION
    osslv = ::OpenSSL::OPENSSL_VERSION.split[1]
    HTTP[:ServerSoftware] << " Ruby-OpenSSL/#{r_osslv}"
    HTTP[:ServerSoftware] << " OpenSSL/#{osslv}"
  end

  class HTTPServer
    alias orig_init initialize

    def initialize(*args)
      orig_init(*args)

      if @config[:SSLEnable] 
        unless @config[:SSLCertificate]
          rsa = OpenSSL::PKey::RSA.new(512){|p, n|
            case p
            when 0; $stderr.putc "."  # BN_generate_prime
            when 1; $stderr.putc "+"  # BN_generate_prime
            when 2; $stderr.putc "*"  # searching good prime,
                                      # n = #of try,
                                      # but also data from BN_generate_prime
            when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q,
                                      # but also data from BN_generate_prime
            else;   $stderr.putc "*"  # BN_generate_prime
            end
          }
          cert = OpenSSL::X509::Certificate.new
          cert.version = 3
          cert.serial = 0
          name = OpenSSL::X509::Name.new(@config[:SSLCertName])
          cert.subject = name
          cert.issuer = name
          cert.not_before = Time.now
          cert.not_after = Time.now + (365*24*60*60)
          cert.public_key = rsa.public_key

          ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
          cert.extensions = [
            ef.create_extension("basicConstraints","CA:FALSE"),
            ef.create_extension("subjectKeyIdentifier", "hash") ]
          ef.issuer_certificate = cert
          cert.add_extension(ef.create_extension("authorityKeyIdentifier",
                                                 "keyid:always,issuer:always"))
          if comment = @config[:SSLCertComment]
            cert.add_extension(ef.create_extension("nsComment", comment))
          end
          cert.sign(rsa, OpenSSL::Digest::SHA1.new)

          @config[:SSLPrivateKey] = rsa
          @config[:SSLCertificate] = cert
          @logger.info cert.to_str
        end
      end
    end

    alias orig_run run

    def run(sock)
      if @config[:SSLEnable] 
        ssl = OpenSSL::SSL::SSLSocket.new(sock,
                @config[:SSLCertificate],
                @config[:SSLPrivateKey])
        ssl.ca_cert         = @config[:SSLCACertificate]
        ssl.ca_path         = @config[:SSLCACertificatePath]
        ssl.verify_mode     = @config[:SSLVerifyClient]
        ssl.verify_depth    = @config[:SSLVerifyDepth]
        ssl.verify_callback = @config[:SSLVerifyCallback]
        def ssl.peeraddr; @io.peeraddr; end
        ssl.accept
        orig_run(ssl)
        ssl.close
      else
        orig_run(sock)
      end
    end

  end
end
