# -*- coding: binary -*-

module Msf::Exploit::Remote::HTTP::Gitea::Base
  # Checks if the site is online and running gitea
  #
  # @return [String,nil] if the site is online and running gitea, nil or raise
  #   UnknownError, VersionError and ::Rex exceptions otherwise
  def get_gitea_version
    unless datastore['GITEACHECK']
      vprint_status 'Skipping Gitea check...'
      return true
    end

    gitea_detect_regexes = [
      /i_like_gitea=\w+/,
    ]

    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path)
    })

    raise Msf::Exploit::Remote::HTTP::Gitea::Error::UnknownError.new('Check TARGETURI - Unexpected HTTP response code') if res&.code != 200

    if gitea_detect_regexes.none? { |r| res.get_cookies =~ r }
      raise Msf::Exploit::Remote::HTTP::Gitea::Error::UnknownError.new('No web server or gitea instance found')
    end

    version = gitea_version(res)
    raise Msf::Exploit::Remote::HTTP::Gitea::Error::VersionError.new unless version
    version

  rescue ::Rex::ConnectionError, ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout
    raise Msf::Exploit::Remote::HTTP::Gitea::Error::UnknownError.new('Could not connect to the web service')
  end
end
