You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

182 lines
4.5 KiB

  1. # frozen_string_literal: true
  2. require 'ipaddr'
  3. require 'socket'
  4. require 'resolv'
  5. class Request
  6. REQUEST_TARGET = '(request-target)'
  7. include RoutingHelper
  8. def initialize(verb, url, **options)
  9. raise ArgumentError if url.blank?
  10. @verb = verb
  11. @url = Addressable::URI.parse(url).normalize
  12. @options = options.merge(use_proxy? ? Rails.configuration.x.http_client_proxy : { socket_class: Socket })
  13. @headers = {}
  14. raise Mastodon::HostValidationError, 'Instance does not support hidden service connections' if block_hidden_service?
  15. set_common_headers!
  16. set_digest! if options.key?(:body)
  17. end
  18. def on_behalf_of(account, key_id_format = :acct, sign_with: nil)
  19. raise ArgumentError unless account.local?
  20. @account = account
  21. @keypair = sign_with.present? ? OpenSSL::PKey::RSA.new(sign_with) : @account.keypair
  22. @key_id_format = key_id_format
  23. self
  24. end
  25. def add_headers(new_headers)
  26. @headers.merge!(new_headers)
  27. self
  28. end
  29. def perform
  30. begin
  31. response = http_client.headers(headers).public_send(@verb, @url.to_s, @options)
  32. rescue => e
  33. raise e.class, "#{e.message} on #{@url}", e.backtrace[0]
  34. end
  35. begin
  36. yield response.extend(ClientLimit) if block_given?
  37. ensure
  38. http_client.close
  39. end
  40. end
  41. def headers
  42. (@account ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
  43. end
  44. private
  45. def set_common_headers!
  46. @headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
  47. @headers['User-Agent'] = Mastodon::Version.user_agent
  48. @headers['Host'] = @url.host
  49. @headers['Date'] = Time.now.utc.httpdate
  50. @headers['Accept-Encoding'] = 'gzip' if @verb != :head
  51. end
  52. def set_digest!
  53. @headers['Digest'] = "SHA-256=#{Digest::SHA256.base64digest(@options[:body])}"
  54. end
  55. def signature
  56. algorithm = 'rsa-sha256'
  57. signature = Base64.strict_encode64(@keypair.sign(OpenSSL::Digest::SHA256.new, signed_string))
  58. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers.keys.join(' ').downcase}\",signature=\"#{signature}\""
  59. end
  60. def signed_string
  61. signed_headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  62. end
  63. def signed_headers
  64. @headers.without('User-Agent', 'Accept-Encoding')
  65. end
  66. def key_id
  67. case @key_id_format
  68. when :acct
  69. @account.to_webfinger_s
  70. when :uri
  71. [ActivityPub::TagManager.instance.uri_for(@account), '#main-key'].join
  72. end
  73. end
  74. def timeout
  75. { connect: nil, read: 10, write: 10 }
  76. end
  77. def http_client
  78. @http_client ||= HTTP.use(:auto_inflate).timeout(:per_operation, timeout).follow(max_hops: 2)
  79. end
  80. def use_proxy?
  81. Rails.configuration.x.http_client_proxy.present?
  82. end
  83. def block_hidden_service?
  84. !Rails.configuration.x.access_to_hidden_service && /\.(onion|i2p)$/.match(@url.host)
  85. end
  86. module ClientLimit
  87. def body_with_limit(limit = 1.megabyte)
  88. raise Mastodon::LengthValidationError if content_length.present? && content_length > limit
  89. if charset.nil?
  90. encoding = Encoding::BINARY
  91. else
  92. begin
  93. encoding = Encoding.find(charset)
  94. rescue ArgumentError
  95. encoding = Encoding::BINARY
  96. end
  97. end
  98. contents = String.new(encoding: encoding)
  99. while (chunk = readpartial)
  100. contents << chunk
  101. chunk.clear
  102. raise Mastodon::LengthValidationError if contents.bytesize > limit
  103. end
  104. contents
  105. end
  106. end
  107. class Socket < TCPSocket
  108. class << self
  109. def open(host, *args)
  110. return super(host, *args) if thru_hidden_service?(host)
  111. outer_e = nil
  112. Resolv::DNS.open do |dns|
  113. dns.timeouts = 1
  114. addresses = dns.getaddresses(host).take(2)
  115. time_slot = 10.0 / addresses.size
  116. addresses.each do |address|
  117. begin
  118. raise Mastodon::HostValidationError if PrivateAddressCheck.private_address?(IPAddr.new(address.to_s))
  119. ::Timeout.timeout(time_slot, HTTP::TimeoutError) do
  120. return super(address.to_s, *args)
  121. end
  122. rescue => e
  123. outer_e = e
  124. end
  125. end
  126. end
  127. if outer_e
  128. raise outer_e
  129. else
  130. raise SocketError, "No address for #{host}"
  131. end
  132. end
  133. alias new open
  134. def thru_hidden_service?(host)
  135. Rails.configuration.x.access_to_hidden_service && /\.(onion|i2p)$/.match(host)
  136. end
  137. end
  138. end
  139. private_constant :ClientLimit, :Socket
  140. end