<commit_before>require 'casserver/utils'
require 'casserver/cas'
require 'casserver/base'

module CASServer
  class Server < CASServer::Base
    if ENV['CONFIG_FILE']
      CONFIG_FILE = ENV['CONFIG_FILE']
    elsif !(c_file = File.dirname(__FILE__) + "/../../config.yml").nil? && File.exist?(c_file)
      CONFIG_FILE = c_file
    else
      CONFIG_FILE = "/etc/rubycas-server/config.yml"
    end

    include CASServer::CAS # CAS protocol helpers

    # Use :public_folder for Sinatra >= 1.3, and :public for older versions.
    def self.use_public_folder?
      Sinatra.const_defined?("VERSION") && Gem::Version.new(Sinatra::VERSION) >= Gem::Version.new("1.3.0")
    end

    set :app_file, __FILE__
    set( use_public_folder? ? :public_folder : :public, # Workaround for differences in Sinatra versions.
         Proc.new { settings.config[:public_dir] || File.join(root, "..", "..", "public") } )

    config = HashWithIndifferentAccess.new(
      :maximum_unused_login_ticket_lifetime => 5.minutes,
      :maximum_unused_service_ticket_lifetime => 5.minutes, # CAS Protocol Spec, sec. 3.2.1 (recommended expiry time)
      :maximum_session_lifetime => 2.days, # all tickets are deleted after this period of time
      :log => {:file => 'casserver.log', :level => 'DEBUG'},
      :uri_path => ""
    )
    set :config, config

    def self.uri_path
      config[:uri_path]
    end

    # Strip the config.uri_path from the request.path_info...
    # FIXME: do we really need to override all of Sinatra's #static! to make this happen?
    def static!
      # Workaround for differences in Sinatra versions.
      public_dir = Server.use_public_folder? ? settings.public_folder : settings.public
      return if public_dir.nil?
      public_dir = File.expand_path(public_dir)

      path = File.expand_path(public_dir + unescape(request.path_info.gsub(/^#{settings.config[:uri_path]}/,'')))
      return if path[0, public_dir.length] != public_dir
      return unless File.file?(path)

      env['sinatra.static_file'] = path
      send_file path, :disposition => nil
    end

    def self.run!(options={})
      set options

      handler      = detect_rack_handler
      handler_name = handler.name.gsub(/.*::/, '')

      puts "== RubyCAS-Server is starting up " +
        "on port #{config[:port] || port} for #{environment} with backup from #{handler_name}" unless handler_name =~/cgi/i

      begin
        opts = handler_options
      rescue Exception => e
        print_cli_message e, :error
        raise e
      end

      handler.run self, opts do |server|
        [:INT, :TERM].each { |sig| trap(sig) { quit!(server, handler_name) } }
        set :running, true
      end
    rescue Errno::EADDRINUSE => e
      puts "== Something is already running on port #{port}!"
    end

    def self.quit!(server, handler_name)
      ## Use thins' hard #stop! if available, otherwise just #stop
      server.respond_to?(:stop!) ? server.stop! : server.stop
      puts "\n== RubyCAS-Server is shutting down" unless handler_name =~/cgi/i
    end

    def self.print_cli_message(msg, type = :info)
      if respond_to?(:config) && config && config[:quiet]
        return
      end

      if type == :error
        io = $stderr
        prefix = "!!! "
      else
        io = $stdout
        prefix = ">>> "
      end

      io.puts
      io.puts "#{prefix}#{msg}"
      io.puts
    end

    def self.load_config_file(config_file)
      begin
        config_file = File.open(config_file)
      rescue Errno::ENOENT => e

        print_cli_message "Config file #{config_file} does not exist!", :error
        print_cli_message "Would you like the default config file copied to #{config_file.inspect}? [y/N]"
        if gets.strip.downcase == 'y'
          require 'fileutils'
          default_config = File.dirname(__FILE__) + '/../../config/config.example.yml'

          if !File.exists?(File.dirname(config_file))
            print_cli_message "Creating config directory..."
            FileUtils.mkdir_p(File.dirname(config_file), :verbose => true)
          end

          print_cli_message "Copying #{default_config.inspect} to #{config_file.inspect}..."
          FileUtils.cp(default_config, config_file, :verbose => true)
          print_cli_message "The default config has been copied. You should now edit it and try starting again."
          exit
        else
          print_cli_message "Cannot start RubyCAS-Server without a valid config file.", :error
          raise e
        end
      rescue Errno::EACCES => e
        print_cli_message "Config file #{config_file.inspect} is not readable (permission denied)!", :error
        raise e
      rescue => e
        print_cli_message "Config file #{config_file.inspect} could not be read!", :error
        raise e
      end

      config.merge! HashWithIndifferentAccess.new(YAML.load(config_file))
      set :server, config[:server] || 'webrick'
    end

    def self.handler_options
      handler_options = {
        :Host => bind || config[:bind_address],
        :Port => config[:port] || 443
      }

      handler_options.merge(handler_ssl_options).to_hash.symbolize_keys!
    end<commit_msg>use bind_address from config<commit_after>require 'casserver/utils'
require 'casserver/cas'
require 'casserver/base'

module CASServer
  class Server < CASServer::Base
    if ENV['CONFIG_FILE']
      CONFIG_FILE = ENV['CONFIG_FILE']
    elsif !(c_file = File.dirname(__FILE__) + "/../../config.yml").nil? && File.exist?(c_file)
      CONFIG_FILE = c_file
    else
      CONFIG_FILE = "/etc/rubycas-server/config.yml"
    end

    include CASServer::CAS # CAS protocol helpers

    # Use :public_folder for Sinatra >= 1.3, and :public for older versions.
    def self.use_public_folder?
      Sinatra.const_defined?("VERSION") && Gem::Version.new(Sinatra::VERSION) >= Gem::Version.new("1.3.0")
    end

    set :app_file, __FILE__
    set( use_public_folder? ? :public_folder : :public, # Workaround for differences in Sinatra versions.
         Proc.new { settings.config[:public_dir] || File.join(root, "..", "..", "public") } )

    config = HashWithIndifferentAccess.new(
      :maximum_unused_login_ticket_lifetime => 5.minutes,
      :maximum_unused_service_ticket_lifetime => 5.minutes, # CAS Protocol Spec, sec. 3.2.1 (recommended expiry time)
      :maximum_session_lifetime => 2.days, # all tickets are deleted after this period of time
      :log => {:file => 'casserver.log', :level => 'DEBUG'},
      :uri_path => ""
    )
    set :config, config

    def self.uri_path
      config[:uri_path]
    end

    # Strip the config.uri_path from the request.path_info...
    # FIXME: do we really need to override all of Sinatra's #static! to make this happen?
    def static!
      # Workaround for differences in Sinatra versions.
      public_dir = Server.use_public_folder? ? settings.public_folder : settings.public
      return if public_dir.nil?
      public_dir = File.expand_path(public_dir)

      path = File.expand_path(public_dir + unescape(request.path_info.gsub(/^#{settings.config[:uri_path]}/,'')))
      return if path[0, public_dir.length] != public_dir
      return unless File.file?(path)

      env['sinatra.static_file'] = path
      send_file path, :disposition => nil
    end

    def self.run!(options={})
      set options

      handler      = detect_rack_handler
      handler_name = handler.name.gsub(/.*::/, '')

      puts "== RubyCAS-Server is starting up " +
        "on port #{config[:port] || port} for #{environment} with backup from #{handler_name}" unless handler_name =~/cgi/i

      begin
        opts = handler_options
      rescue Exception => e
        print_cli_message e, :error
        raise e
      end

      handler.run self, opts do |server|
        [:INT, :TERM].each { |sig| trap(sig) { quit!(server, handler_name) } }
        set :running, true
      end
    rescue Errno::EADDRINUSE => e
      puts "== Something is already running on port #{port}!"
    end

    def self.quit!(server, handler_name)
      ## Use thins' hard #stop! if available, otherwise just #stop
      server.respond_to?(:stop!) ? server.stop! : server.stop
      puts "\n== RubyCAS-Server is shutting down" unless handler_name =~/cgi/i
    end

    def self.print_cli_message(msg, type = :info)
      if respond_to?(:config) && config && config[:quiet]
        return
      end

      if type == :error
        io = $stderr
        prefix = "!!! "
      else
        io = $stdout
        prefix = ">>> "
      end

      io.puts
      io.puts "#{prefix}#{msg}"
      io.puts
    end

    def self.load_config_file(config_file)
      begin
        config_file = File.open(config_file)
      rescue Errno::ENOENT => e

        print_cli_message "Config file #{config_file} does not exist!", :error
        print_cli_message "Would you like the default config file copied to #{config_file.inspect}? [y/N]"
        if gets.strip.downcase == 'y'
          require 'fileutils'
          default_config = File.dirname(__FILE__) + '/../../config/config.example.yml'

          if !File.exists?(File.dirname(config_file))
            print_cli_message "Creating config directory..."
            FileUtils.mkdir_p(File.dirname(config_file), :verbose => true)
          end

          print_cli_message "Copying #{default_config.inspect} to #{config_file.inspect}..."
          FileUtils.cp(default_config, config_file, :verbose => true)
          print_cli_message "The default config has been copied. You should now edit it and try starting again."
          exit
        else
          print_cli_message "Cannot start RubyCAS-Server without a valid config file.", :error
          raise e
        end
      rescue Errno::EACCES => e
        print_cli_message "Config file #{config_file.inspect} is not readable (permission denied)!", :error
        raise e
      rescue => e
        print_cli_message "Config file #{config_file.inspect} could not be read!", :error
        raise e
      end

      config.merge! HashWithIndifferentAccess.new(YAML.load(config_file))
      set :server, config[:server] || 'webrick'
    end

    def self.handler_options
      handler_options = {
        :Host => config[:bind_address] || '0.0.0.0',
        :Port => config[:port] || 443
      }

      handler_options.merge(handler_ssl_options).to_hash.symbolize_keys!
    end
{'fraction_non_alphanumeric': 0.11840324763193505, 'fraction_numerical': 0.003286294219988401, 'mean_word_length': 2.694037843627276, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1424358', 'n_tokens_mistral': 3216, 'n_tokens_neox': 3093, 'n_words': 818}