diff --git a/lib/pushmeup/apns/core.rb b/lib/pushmeup/apns/core.rb index fe9d79a..9a480a9 100644 --- a/lib/pushmeup/apns/core.rb +++ b/lib/pushmeup/apns/core.rb @@ -7,7 +7,7 @@ module APNS @host = 'gateway.sandbox.push.apple.com' @port = 2195 # openssl pkcs12 -in mycert.p12 -out client-cert.pem -nodes -clcerts - @pem = nil # this should be the path of the pem file not the contentes + @pem = nil @pass = nil @persistent = false @@ -20,7 +20,7 @@ module APNS class << self attr_accessor :host, :pem, :port, :pass end - + def self.start_persistence @persistent = true end @@ -69,24 +69,25 @@ def self.feedback def self.with_connection attempts = 1 - begin + begin # If no @ssl is created or if @ssl is closed we need to start it if @ssl.nil? || @sock.nil? || @ssl.closed? || @sock.closed? @sock, @ssl = self.open_connection end yield - + rescue OpenSSL::X509::CertificateError + raise "Your pem is not a valid file or certificate. (APNS.pem = /path/to/cert.pem)" + rescue StandardError, Errno::EPIPE raise unless attempts < @retries - @ssl.close @sock.close - + attempts += 1 retry end - + # Only force close if not persistent unless @persistent @ssl.close @@ -97,13 +98,6 @@ def self.with_connection end def self.open_connection - raise "The path to your pem file is not set. (APNS.pem = /path/to/cert.pem)" unless self.pem - raise "The path to your pem file does not exist!" unless File.exist?(self.pem) - - context = OpenSSL::SSL::SSLContext.new - context.cert = OpenSSL::X509::Certificate.new(File.read(self.pem)) - context.key = OpenSSL::PKey::RSA.new(File.read(self.pem), self.pass) - sock = TCPSocket.new(self.host, self.port) ssl = OpenSSL::SSL::SSLSocket.new(sock,context) ssl.connect @@ -112,20 +106,30 @@ def self.open_connection end def self.feedback_connection - raise "The path to your pem file is not set. (APNS.pem = /path/to/cert.pem)" unless self.pem - raise "The path to your pem file does not exist!" unless File.exist?(self.pem) - - context = OpenSSL::SSL::SSLContext.new - context.cert = OpenSSL::X509::Certificate.new(File.read(self.pem)) - context.key = OpenSSL::PKey::RSA.new(File.read(self.pem), self.pass) - fhost = self.host.gsub('gateway','feedback') - + sock = TCPSocket.new(fhost, 2196) ssl = OpenSSL::SSL::SSLSocket.new(sock, context) ssl.connect return sock, ssl end - + + def self.certificate + @certificate ||= begin + if File.file?(@pem) + File.read(@pem) + else + @pem + end + end + end + + def self.context + @context ||= OpenSSL::SSL::SSLContext.new.tap do |context| + context.cert = OpenSSL::X509::Certificate.new(certificate) + context.key = OpenSSL::PKey::RSA.new(certificate, self.pass) + end + end + end