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.

240 lines
6.6 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. # We enforce a 5s timeout on DNS resolving, 5s timeout on socket opening
  17. # and 5s timeout on the TLS handshake, meaning the worst case should take
  18. # about 15s in total
  19. TIMEOUT = { connect: 5, read: 10, write: 10 }.freeze
  20. include RoutingHelper
  21. def initialize(verb, url, **options)
  22. raise ArgumentError if url.blank?
  23. @verb = verb
  24. @url = Addressable::URI.parse(url).normalize
  25. @http_client = options.delete(:http_client)
  26. @options = options.merge(use_proxy? ? Rails.configuration.x.http_client_proxy : { socket_class: Socket })
  27. @headers = {}
  28. raise Mastodon::HostValidationError, 'Instance does not support hidden service connections' if block_hidden_service?
  29. set_common_headers!
  30. set_digest! if options.key?(:body)
  31. end
  32. def on_behalf_of(account, key_id_format = :acct, sign_with: nil)
  33. raise ArgumentError unless account.local?
  34. @account = account
  35. @keypair = sign_with.present? ? OpenSSL::PKey::RSA.new(sign_with) : @account.keypair
  36. @key_id_format = key_id_format
  37. self
  38. end
  39. def add_headers(new_headers)
  40. @headers.merge!(new_headers)
  41. self
  42. end
  43. def perform
  44. begin
  45. response = http_client.public_send(@verb, @url.to_s, @options.merge(headers: headers))
  46. rescue => e
  47. raise e.class, "#{e.message} on #{@url}", e.backtrace[0]
  48. end
  49. begin
  50. response = response.extend(ClientLimit)
  51. # If we are using a persistent connection, we have to
  52. # read every response to be able to move forward at all.
  53. # However, simply calling #to_s or #flush may not be safe,
  54. # as the response body, if malicious, could be too big
  55. # for our memory. So we use the #body_with_limit method
  56. response.body_with_limit if http_client.persistent?
  57. yield response if block_given?
  58. ensure
  59. http_client.close unless http_client.persistent?
  60. end
  61. end
  62. def headers
  63. (@account ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
  64. end
  65. class << self
  66. def valid_url?(url)
  67. begin
  68. parsed_url = Addressable::URI.parse(url)
  69. rescue Addressable::URI::InvalidURIError
  70. return false
  71. end
  72. %w(http https).include?(parsed_url.scheme) && parsed_url.host.present?
  73. end
  74. def http_client
  75. HTTP.use(:auto_inflate).timeout(:per_operation, TIMEOUT.dup).follow(max_hops: 2)
  76. end
  77. end
  78. private
  79. def set_common_headers!
  80. @headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
  81. @headers['User-Agent'] = Mastodon::Version.user_agent
  82. @headers['Host'] = @url.host
  83. @headers['Date'] = Time.now.utc.httpdate
  84. @headers['Accept-Encoding'] = 'gzip' if @verb != :head
  85. end
  86. def set_digest!
  87. @headers['Digest'] = "SHA-256=#{Digest::SHA256.base64digest(@options[:body])}"
  88. end
  89. def signature
  90. algorithm = 'rsa-sha256'
  91. signature = Base64.strict_encode64(@keypair.sign(OpenSSL::Digest::SHA256.new, signed_string))
  92. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers.keys.join(' ').downcase}\",signature=\"#{signature}\""
  93. end
  94. def signed_string
  95. signed_headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  96. end
  97. def signed_headers
  98. @headers.without('User-Agent', 'Accept-Encoding')
  99. end
  100. def key_id
  101. case @key_id_format
  102. when :acct
  103. @account.to_webfinger_s
  104. when :uri
  105. [ActivityPub::TagManager.instance.uri_for(@account), '#main-key'].join
  106. end
  107. end
  108. def http_client
  109. @http_client ||= Request.http_client
  110. end
  111. def use_proxy?
  112. Rails.configuration.x.http_client_proxy.present?
  113. end
  114. def block_hidden_service?
  115. !Rails.configuration.x.access_to_hidden_service && /\.(onion|i2p)$/.match(@url.host)
  116. end
  117. module ClientLimit
  118. def body_with_limit(limit = 1.megabyte)
  119. raise Mastodon::LengthValidationError if content_length.present? && content_length > limit
  120. if charset.nil?
  121. encoding = Encoding::BINARY
  122. else
  123. begin
  124. encoding = Encoding.find(charset)
  125. rescue ArgumentError
  126. encoding = Encoding::BINARY
  127. end
  128. end
  129. contents = String.new(encoding: encoding)
  130. while (chunk = readpartial)
  131. contents << chunk
  132. chunk.clear
  133. raise Mastodon::LengthValidationError if contents.bytesize > limit
  134. end
  135. contents
  136. end
  137. end
  138. class Socket < TCPSocket
  139. class << self
  140. def open(host, *args)
  141. return super(host, *args) if thru_hidden_service?(host)
  142. outer_e = nil
  143. port = args.first
  144. Resolv::DNS.open do |dns|
  145. dns.timeouts = 5
  146. addresses = dns.getaddresses(host).take(2)
  147. addresses.each do |address|
  148. begin
  149. raise Mastodon::HostValidationError if PrivateAddressCheck.private_address?(IPAddr.new(address.to_s))
  150. sock = ::Socket.new(::Socket::AF_INET, ::Socket::SOCK_STREAM, 0)
  151. sockaddr = ::Socket.pack_sockaddr_in(port, address.to_s)
  152. sock.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, 1)
  153. begin
  154. sock.connect_nonblock(sockaddr)
  155. rescue IO::WaitWritable
  156. if IO.select(nil, [sock], nil, Request::TIMEOUT[:connect])
  157. begin
  158. sock.connect_nonblock(sockaddr)
  159. rescue Errno::EISCONN
  160. # Yippee!
  161. rescue
  162. sock.close
  163. raise
  164. end
  165. else
  166. sock.close
  167. raise HTTP::TimeoutError, "Connect timed out after #{Request::TIMEOUT[:connect]} seconds"
  168. end
  169. end
  170. return sock
  171. rescue => e
  172. outer_e = e
  173. end
  174. end
  175. end
  176. if outer_e
  177. raise outer_e
  178. else
  179. raise SocketError, "No address for #{host}"
  180. end
  181. end
  182. alias new open
  183. def thru_hidden_service?(host)
  184. Rails.configuration.x.access_to_hidden_service && /\.(onion|i2p)$/.match(host)
  185. end
  186. end
  187. end
  188. private_constant :ClientLimit, :Socket
  189. end