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.

196 lines
5.1 KiB

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