The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

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