request.rb 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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(socket_class: use_proxy? ? ProxySocket : Socket)
  27. @options = @options.merge(proxy_url) if use_proxy?
  28. @headers = {}
  29. raise Mastodon::HostValidationError, 'Instance does not support hidden service connections' if block_hidden_service?
  30. set_common_headers!
  31. set_digest! if options.key?(:body)
  32. end
  33. def on_behalf_of(actor, sign_with: nil)
  34. raise ArgumentError, 'actor must not be nil' if actor.nil?
  35. @actor = actor
  36. @keypair = sign_with.present? ? OpenSSL::PKey::RSA.new(sign_with) : @actor.keypair
  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. # If we are using a persistent connection, we have to
  51. # read every response to be able to move forward at all.
  52. # However, simply calling #to_s or #flush may not be safe,
  53. # as the response body, if malicious, could be too big
  54. # for our memory. So we use the #body_with_limit method
  55. response.body_with_limit if http_client.persistent?
  56. yield response if block_given?
  57. ensure
  58. http_client.close unless http_client.persistent?
  59. end
  60. end
  61. def headers
  62. (@actor ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
  63. end
  64. class << self
  65. def valid_url?(url)
  66. begin
  67. parsed_url = Addressable::URI.parse(url)
  68. rescue Addressable::URI::InvalidURIError
  69. return false
  70. end
  71. %w(http https).include?(parsed_url.scheme) && parsed_url.host.present?
  72. end
  73. def http_client
  74. HTTP.use(:auto_inflate).timeout(TIMEOUT.dup).follow(max_hops: 3)
  75. end
  76. end
  77. private
  78. def set_common_headers!
  79. @headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
  80. @headers['User-Agent'] = Mastodon::Version.user_agent
  81. @headers['Host'] = @url.host
  82. @headers['Date'] = Time.now.utc.httpdate
  83. @headers['Accept-Encoding'] = 'gzip' if @verb != :head
  84. end
  85. def set_digest!
  86. @headers['Digest'] = "SHA-256=#{Digest::SHA256.base64digest(@options[:body])}"
  87. end
  88. def signature
  89. algorithm = 'rsa-sha256'
  90. signature = Base64.strict_encode64(@keypair.sign(OpenSSL::Digest.new('SHA256'), signed_string))
  91. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers.keys.join(' ').downcase}\",signature=\"#{signature}\""
  92. end
  93. def signed_string
  94. signed_headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  95. end
  96. def signed_headers
  97. @headers.without('User-Agent', 'Accept-Encoding')
  98. end
  99. def key_id
  100. ActivityPub::TagManager.instance.key_uri_for(@actor)
  101. end
  102. def http_client
  103. @http_client ||= Request.http_client
  104. end
  105. def use_proxy?
  106. proxy_url.present?
  107. end
  108. def proxy_url
  109. if hidden_service? && Rails.configuration.x.http_client_hidden_proxy.present?
  110. Rails.configuration.x.http_client_hidden_proxy
  111. else
  112. Rails.configuration.x.http_client_proxy
  113. end
  114. end
  115. def block_hidden_service?
  116. !Rails.configuration.x.access_to_hidden_service && hidden_service?
  117. end
  118. def hidden_service?
  119. /\.(onion|i2p)$/.match?(@url.host)
  120. end
  121. module ClientLimit
  122. def body_with_limit(limit = 1.megabyte)
  123. raise Mastodon::LengthValidationError if content_length.present? && content_length > limit
  124. if charset.nil?
  125. encoding = Encoding::BINARY
  126. else
  127. begin
  128. encoding = Encoding.find(charset)
  129. rescue ArgumentError
  130. encoding = Encoding::BINARY
  131. end
  132. end
  133. contents = String.new(encoding: encoding)
  134. while (chunk = readpartial)
  135. contents << chunk
  136. chunk.clear
  137. raise Mastodon::LengthValidationError if contents.bytesize > limit
  138. end
  139. contents
  140. end
  141. end
  142. if ::HTTP::Response.methods.include?(:body_with_limit) && !Rails.env.production?
  143. abort 'HTTP::Response#body_with_limit is already defined, the monkey patch will not be applied'
  144. else
  145. class ::HTTP::Response
  146. include Request::ClientLimit
  147. end
  148. end
  149. class Socket < TCPSocket
  150. class << self
  151. def open(host, *args)
  152. outer_e = nil
  153. port = args.first
  154. addresses = []
  155. begin
  156. addresses = [IPAddr.new(host)]
  157. rescue IPAddr::InvalidAddressError
  158. Resolv::DNS.open do |dns|
  159. dns.timeouts = 5
  160. addresses = dns.getaddresses(host)
  161. addresses = addresses.filter { |addr| addr.is_a?(Resolv::IPv6) }.take(2) + addresses.filter { |addr| !addr.is_a?(Resolv::IPv6) }.take(2)
  162. end
  163. end
  164. socks = []
  165. addr_by_socket = {}
  166. addresses.each do |address|
  167. begin
  168. check_private_address(address, host)
  169. sock = ::Socket.new(address.is_a?(Resolv::IPv6) ? ::Socket::AF_INET6 : ::Socket::AF_INET, ::Socket::SOCK_STREAM, 0)
  170. sockaddr = ::Socket.pack_sockaddr_in(port, address.to_s)
  171. sock.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, 1)
  172. sock.connect_nonblock(sockaddr)
  173. # If that hasn't raised an exception, we somehow managed to connect
  174. # immediately, close pending sockets and return immediately
  175. socks.each(&:close)
  176. return sock
  177. rescue IO::WaitWritable
  178. socks << sock
  179. addr_by_socket[sock] = sockaddr
  180. rescue => e
  181. outer_e = e
  182. end
  183. end
  184. until socks.empty?
  185. _, available_socks, = IO.select(nil, socks, nil, Request::TIMEOUT[:connect])
  186. if available_socks.nil?
  187. socks.each(&:close)
  188. raise HTTP::TimeoutError, "Connect timed out after #{Request::TIMEOUT[:connect]} seconds"
  189. end
  190. available_socks.each do |sock|
  191. socks.delete(sock)
  192. begin
  193. sock.connect_nonblock(addr_by_socket[sock])
  194. rescue Errno::EISCONN
  195. # Do nothing
  196. rescue => e
  197. sock.close
  198. outer_e = e
  199. next
  200. end
  201. socks.each(&:close)
  202. return sock
  203. end
  204. end
  205. if outer_e
  206. raise outer_e
  207. else
  208. raise SocketError, "No address for #{host}"
  209. end
  210. end
  211. alias new open
  212. def check_private_address(address, host)
  213. addr = IPAddr.new(address.to_s)
  214. return if private_address_exceptions.any? { |range| range.include?(addr) }
  215. raise Mastodon::PrivateNetworkAddressError, host if PrivateAddressCheck.private_address?(addr)
  216. end
  217. def private_address_exceptions
  218. @private_address_exceptions = begin
  219. (ENV['ALLOWED_PRIVATE_ADDRESSES'] || '').split(',').map { |addr| IPAddr.new(addr) }
  220. end
  221. end
  222. end
  223. end
  224. class ProxySocket < Socket
  225. class << self
  226. def check_private_address(_address, _host)
  227. # Accept connections to private addresses as HTTP proxies will usually
  228. # be on local addresses
  229. nil
  230. end
  231. end
  232. end
  233. private_constant :ClientLimit, :Socket, :ProxySocket
  234. end