1
0

request.rb 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # frozen_string_literal: true
  2. require 'ipaddr'
  3. require 'socket'
  4. require 'resolv'
  5. # Use our own timeout class to avoid using HTTP.rb's timeout block
  6. # around the Socket#open method, since we use our own timeout blocks inside
  7. # that method
  8. #
  9. # Also changes how the read timeout behaves so that it is cumulative (closer
  10. # to HTTP::Timeout::Global, but still having distinct timeouts for other
  11. # operation types)
  12. class PerOperationWithDeadline < HTTP::Timeout::PerOperation
  13. READ_DEADLINE = 30
  14. def initialize(*args)
  15. super
  16. @read_deadline = options.fetch(:read_deadline, READ_DEADLINE)
  17. end
  18. def connect(socket_class, host, port, nodelay = false)
  19. @socket = socket_class.open(host, port)
  20. @socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) if nodelay
  21. end
  22. # Reset deadline when the connection is re-used for different requests
  23. def reset_counter
  24. @deadline = nil
  25. end
  26. # Read data from the socket
  27. def readpartial(size, buffer = nil)
  28. @deadline ||= Process.clock_gettime(Process::CLOCK_MONOTONIC) + @read_deadline
  29. timeout = false
  30. loop do
  31. result = @socket.read_nonblock(size, buffer, exception: false)
  32. return :eof if result.nil?
  33. remaining_time = @deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
  34. raise HTTP::TimeoutError, "Read timed out after #{@read_timeout} seconds" if timeout
  35. raise HTTP::TimeoutError, "Read timed out after a total of #{@read_deadline} seconds" if remaining_time <= 0
  36. return result if result != :wait_readable
  37. # marking the socket for timeout. Why is this not being raised immediately?
  38. # it seems there is some race-condition on the network level between calling
  39. # #read_nonblock and #wait_readable, in which #read_nonblock signalizes waiting
  40. # for reads, and when waiting for x seconds, it returns nil suddenly without completing
  41. # the x seconds. In a normal case this would be a timeout on wait/read, but it can
  42. # also mean that the socket has been closed by the server. Therefore we "mark" the
  43. # socket for timeout and try to read more bytes. If it returns :eof, it's all good, no
  44. # timeout. Else, the first timeout was a proper timeout.
  45. # This hack has to be done because io/wait#wait_readable doesn't provide a value for when
  46. # the socket is closed by the server, and HTTP::Parser doesn't provide the limit for the chunks.
  47. timeout = true unless @socket.to_io.wait_readable([remaining_time, @read_timeout].min)
  48. end
  49. end
  50. end
  51. class Request
  52. REQUEST_TARGET = '(request-target)'
  53. # We enforce a 5s timeout on DNS resolving, 5s timeout on socket opening
  54. # and 5s timeout on the TLS handshake, meaning the worst case should take
  55. # about 15s in total
  56. TIMEOUT = { connect_timeout: 5, read_timeout: 10, write_timeout: 10, read_deadline: 30 }.freeze
  57. include RoutingHelper
  58. def initialize(verb, url, **options)
  59. raise ArgumentError if url.blank?
  60. @verb = verb
  61. @url = Addressable::URI.parse(url).normalize
  62. @http_client = options.delete(:http_client)
  63. @options = options.merge(socket_class: use_proxy? ? ProxySocket : Socket)
  64. @options = @options.merge(timeout_class: PerOperationWithDeadline, timeout_options: TIMEOUT)
  65. @options = @options.merge(proxy_url) if use_proxy?
  66. @headers = {}
  67. raise Mastodon::HostValidationError, 'Instance does not support hidden service connections' if block_hidden_service?
  68. set_common_headers!
  69. set_digest! if options.key?(:body)
  70. end
  71. def on_behalf_of(actor, sign_with: nil)
  72. raise ArgumentError, 'actor must not be nil' if actor.nil?
  73. @actor = actor
  74. @keypair = sign_with.present? ? OpenSSL::PKey::RSA.new(sign_with) : @actor.keypair
  75. self
  76. end
  77. def add_headers(new_headers)
  78. @headers.merge!(new_headers)
  79. self
  80. end
  81. def perform
  82. begin
  83. response = http_client.public_send(@verb, @url.to_s, @options.merge(headers: headers))
  84. rescue => e
  85. raise e.class, "#{e.message} on #{@url}", e.backtrace[0]
  86. end
  87. begin
  88. # If we are using a persistent connection, we have to
  89. # read every response to be able to move forward at all.
  90. # However, simply calling #to_s or #flush may not be safe,
  91. # as the response body, if malicious, could be too big
  92. # for our memory. So we use the #body_with_limit method
  93. response.body_with_limit if http_client.persistent?
  94. yield response if block_given?
  95. ensure
  96. http_client.close unless http_client.persistent?
  97. end
  98. end
  99. def headers
  100. (@actor ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
  101. end
  102. class << self
  103. def valid_url?(url)
  104. begin
  105. parsed_url = Addressable::URI.parse(url)
  106. rescue Addressable::URI::InvalidURIError
  107. return false
  108. end
  109. %w(http https).include?(parsed_url.scheme) && parsed_url.host.present?
  110. end
  111. def http_client
  112. HTTP.use(:auto_inflate).follow(max_hops: 3)
  113. end
  114. end
  115. private
  116. def set_common_headers!
  117. @headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
  118. @headers['User-Agent'] = Mastodon::Version.user_agent
  119. @headers['Host'] = @url.host
  120. @headers['Date'] = Time.now.utc.httpdate
  121. @headers['Accept-Encoding'] = 'gzip' if @verb != :head
  122. end
  123. def set_digest!
  124. @headers['Digest'] = "SHA-256=#{Digest::SHA256.base64digest(@options[:body])}"
  125. end
  126. def signature
  127. algorithm = 'rsa-sha256'
  128. signature = Base64.strict_encode64(@keypair.sign(OpenSSL::Digest.new('SHA256'), signed_string))
  129. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers.keys.join(' ').downcase}\",signature=\"#{signature}\""
  130. end
  131. def signed_string
  132. signed_headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  133. end
  134. def signed_headers
  135. @headers.without('User-Agent', 'Accept-Encoding')
  136. end
  137. def key_id
  138. ActivityPub::TagManager.instance.key_uri_for(@actor)
  139. end
  140. def http_client
  141. @http_client ||= Request.http_client
  142. end
  143. def use_proxy?
  144. proxy_url.present?
  145. end
  146. def proxy_url
  147. if hidden_service? && Rails.configuration.x.http_client_hidden_proxy.present?
  148. Rails.configuration.x.http_client_hidden_proxy
  149. else
  150. Rails.configuration.x.http_client_proxy
  151. end
  152. end
  153. def block_hidden_service?
  154. !Rails.configuration.x.access_to_hidden_service && hidden_service?
  155. end
  156. def hidden_service?
  157. /\.(onion|i2p)$/.match?(@url.host)
  158. end
  159. module ClientLimit
  160. def body_with_limit(limit = 1.megabyte)
  161. raise Mastodon::LengthValidationError if content_length.present? && content_length > limit
  162. if charset.nil?
  163. encoding = Encoding::BINARY
  164. else
  165. begin
  166. encoding = Encoding.find(charset)
  167. rescue ArgumentError
  168. encoding = Encoding::BINARY
  169. end
  170. end
  171. contents = String.new(encoding: encoding)
  172. while (chunk = readpartial)
  173. contents << chunk
  174. chunk.clear
  175. raise Mastodon::LengthValidationError if contents.bytesize > limit
  176. end
  177. contents
  178. end
  179. end
  180. if ::HTTP::Response.methods.include?(:body_with_limit) && !Rails.env.production?
  181. abort 'HTTP::Response#body_with_limit is already defined, the monkey patch will not be applied'
  182. else
  183. class ::HTTP::Response
  184. include Request::ClientLimit
  185. end
  186. end
  187. class Socket < TCPSocket
  188. class << self
  189. def open(host, *args)
  190. outer_e = nil
  191. port = args.first
  192. addresses = []
  193. begin
  194. addresses = [IPAddr.new(host)]
  195. rescue IPAddr::InvalidAddressError
  196. Resolv::DNS.open do |dns|
  197. dns.timeouts = 5
  198. addresses = dns.getaddresses(host)
  199. addresses = addresses.filter { |addr| addr.is_a?(Resolv::IPv6) }.take(2) + addresses.filter { |addr| !addr.is_a?(Resolv::IPv6) }.take(2)
  200. end
  201. end
  202. socks = []
  203. addr_by_socket = {}
  204. addresses.each do |address|
  205. begin
  206. check_private_address(address, host)
  207. sock = ::Socket.new(address.is_a?(Resolv::IPv6) ? ::Socket::AF_INET6 : ::Socket::AF_INET, ::Socket::SOCK_STREAM, 0)
  208. sockaddr = ::Socket.pack_sockaddr_in(port, address.to_s)
  209. sock.setsockopt(::Socket::IPPROTO_TCP, ::Socket::TCP_NODELAY, 1)
  210. sock.connect_nonblock(sockaddr)
  211. # If that hasn't raised an exception, we somehow managed to connect
  212. # immediately, close pending sockets and return immediately
  213. socks.each(&:close)
  214. return sock
  215. rescue IO::WaitWritable
  216. socks << sock
  217. addr_by_socket[sock] = sockaddr
  218. rescue => e
  219. outer_e = e
  220. end
  221. end
  222. until socks.empty?
  223. _, available_socks, = IO.select(nil, socks, nil, Request::TIMEOUT[:connect_timeout])
  224. if available_socks.nil?
  225. socks.each(&:close)
  226. raise HTTP::TimeoutError, "Connect timed out after #{Request::TIMEOUT[:connect_timeout]} seconds"
  227. end
  228. available_socks.each do |sock|
  229. socks.delete(sock)
  230. begin
  231. sock.connect_nonblock(addr_by_socket[sock])
  232. rescue Errno::EISCONN
  233. # Do nothing
  234. rescue => e
  235. sock.close
  236. outer_e = e
  237. next
  238. end
  239. socks.each(&:close)
  240. return sock
  241. end
  242. end
  243. if outer_e
  244. raise outer_e
  245. else
  246. raise SocketError, "No address for #{host}"
  247. end
  248. end
  249. alias new open
  250. def check_private_address(address, host)
  251. addr = IPAddr.new(address.to_s)
  252. return if private_address_exceptions.any? { |range| range.include?(addr) }
  253. raise Mastodon::PrivateNetworkAddressError, host if PrivateAddressCheck.private_address?(addr)
  254. end
  255. def private_address_exceptions
  256. @private_address_exceptions = begin
  257. (ENV['ALLOWED_PRIVATE_ADDRESSES'] || '').split(',').map { |addr| IPAddr.new(addr) }
  258. end
  259. end
  260. end
  261. end
  262. class ProxySocket < Socket
  263. class << self
  264. def check_private_address(_address, _host)
  265. # Accept connections to private addresses as HTTP proxies will usually
  266. # be on local addresses
  267. nil
  268. end
  269. end
  270. end
  271. private_constant :ClientLimit, :Socket, :ProxySocket
  272. end