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.

server.rb 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. require 'nokogiri'
  2. require 'resolv'
  3. module CryptCheck
  4. module Tls
  5. module Xmpp
  6. TLS_NAMESPACE = 'urn:ietf:params:xml:ns:xmpp-tls'
  7. RESOLVER = Resolv::DNS.new
  8. class Server < Tls::TcpServer
  9. attr_reader :domain
  10. def initialize(domain, type=:s2s, hostname: nil)
  11. @type, @domain = type, domain
  12. service, port = case type
  13. when :s2s then ['_xmpp-server', 5269]
  14. when :c2s then ['_xmpp-client', 5222]
  15. end
  16. unless hostname
  17. srv = RESOLVER.getresources("#{service}._tcp.#{domain}", Resolv::DNS::Resource::IN::SRV).sort_by(&:priority).first
  18. if srv
  19. hostname, port = srv.target.to_s, srv.port
  20. else # DNS is not correctly set, guess config…
  21. hostname = domain
  22. end
  23. end
  24. super hostname, port
  25. end
  26. def ssl_connect(socket, context, method, &block)
  27. type = case @type
  28. when :s2s then 'jabber:server'
  29. when :c2s then 'jabber:client'
  30. end
  31. socket.write "<?xml version='1.0' ?><stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='#{type}' to='#{@domain}' version='1.0'>"
  32. response = ''
  33. loop do
  34. response += socket.recv 1024
  35. xml = ::Nokogiri::XML response
  36. unless xml.xpath('//stream:features').empty?
  37. response = xml
  38. break
  39. end
  40. end
  41. starttls = response.xpath '//tls:starttls', tls: TLS_NAMESPACE
  42. raise TLSNotAvailableException unless starttls
  43. @required = !starttls.xpath('//tls:required', tls: TLS_NAMESPACE).nil?
  44. socket.write "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls' />\r\n"
  45. response = ::Nokogiri::XML socket.recv 4096
  46. raise TLSNotAvailableException unless response.xpath '//tls:proceed', tls: TLS_NAMESPACE
  47. super
  48. end
  49. def required?
  50. @required
  51. end
  52. end
  53. end
  54. end
  55. end