request.rb 9.8 KB

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