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.

101 lines
2.0KB

  1. require 'timeout'
  2. module CryptCheck
  3. module Tls
  4. class AnalysisFailure
  5. attr_reader :error
  6. def initialize(error)
  7. @error = error
  8. end
  9. def to_s
  10. @error.to_s
  11. end
  12. end
  13. class TooLongAnalysis < AnalysisFailure
  14. def initialize
  15. super "Too long analysis (max #{Host::MAX_ANALYSIS_DURATION.humanize})"
  16. end
  17. end
  18. class Host
  19. MAX_ANALYSIS_DURATION = 600
  20. attr_reader :servers, :error
  21. def initialize(hostname, port)
  22. @hostname, @port = hostname, port
  23. first = true
  24. @servers = resolve.collect do |args|
  25. _, ip, _, _ = args
  26. first ? (first = false) : Logger.info { '' }
  27. result = begin
  28. server = ::Timeout.timeout MAX_ANALYSIS_DURATION do
  29. server(*args)
  30. end
  31. grade server
  32. rescue Engine::TLSException, Engine::ConnectionError, Engine::Timeout => e
  33. AnalysisFailure.new e
  34. rescue ::Timeout::Error
  35. TooLongAnalysis.new
  36. end
  37. [[@hostname, ip, @port], result]
  38. end.to_h
  39. # rescue StandardError
  40. # raise
  41. rescue => e
  42. @error = e
  43. end
  44. def to_h
  45. target = {
  46. target: { hostname: @hostname, port: @port },
  47. }
  48. if @error
  49. target[:error] = @error
  50. else
  51. target[:hosts] = @servers.collect do |host, grade|
  52. hostname, ip, port = host
  53. host = {
  54. hostname: hostname,
  55. ip: ip,
  56. port: port
  57. }
  58. case grade
  59. when Grade
  60. host[:analysis] = grade.server.to_h
  61. host[:status] = grade.to_h
  62. else
  63. host[:error] = grade.message
  64. end
  65. host
  66. end
  67. end
  68. target
  69. end
  70. private
  71. def resolve
  72. begin
  73. ip = IPAddr.new @hostname
  74. return [[nil, ip.to_s, ip.family]]
  75. rescue IPAddr::InvalidAddressError
  76. end
  77. ::Addrinfo.getaddrinfo(@hostname, nil, nil, :STREAM)
  78. .collect { |a| [@hostname, a.ip_address, a.afamily, @port] }
  79. end
  80. def server(*args)
  81. TcpServer.new *args
  82. end
  83. def grade(server)
  84. Grade.new server
  85. end
  86. end
  87. end
  88. end