def __init__(self, cert_file, use_sandbox=False, use_alternative_port=False, proto=None, json_encoder=None): server = 'api.development.push.apple.com' if use_sandbox else 'api.push.apple.com' port = 2197 if use_alternative_port else 443 ssl_context = init_context() ssl_context.load_cert_chain(cert_file) self.__connection = HTTP20Connection(server, port, ssl_context=ssl_context, force_proto=proto or 'h2') self.__json_encoder = json_encoder
def test_client_certificate(self, context_kwargs): # Don't have the server thread do TLS: we'll do it ourselves. self.set_up(secure=False) evt = threading.Event() data = [] def socket_handler(listener): sock = listener.accept()[0] sock = ssl.wrap_socket( sock, ssl_version=ssl.PROTOCOL_SSLv23, certfile=SERVER_CERT_FILE, keyfile=SERVER_KEY_FILE, cert_reqs=ssl.CERT_REQUIRED, ca_certs=CLIENT_PEM_FILE, server_side=True ) data.append(sock.recv(65535)) evt.wait(5) sock.close() self._start_server(socket_handler) # Set up the client context. Don't validate the server cert though. context = init_context(**context_kwargs) context.check_hostname = False context.verify_mode = ssl.CERT_NONE s = socket.create_connection((self.host, self.port)) s, proto = wrap_socket(s, "localhost", ssl_context=context) s.sendall(b'hi') s.close() evt.set() self.tear_down()
def get_connection(self, host, port, scheme, cert=None): """ Gets an appropriate HTTP/2 connection object based on host/port/scheme/cert tuples. """ secure = (scheme == 'https') if port is None: # pragma: no cover port = 80 if not secure else 443 ssl_context = None if cert is not None: ssl_context = init_context(cert=cert) try: conn = self.connections[(host, port, scheme, cert)] except KeyError: conn = HTTPConnection( host, port, secure=secure, ssl_context=ssl_context) self.connections[(host, port, scheme, cert)] = conn return conn
def __init__(self, cert_file, use_sandbox=False, use_alternative_port=False): server = 'api.development.push.apple.com' if use_sandbox else 'api.push.apple.com' port = 2197 if use_alternative_port else 443 ssl_context = init_context() ssl_context.load_cert_chain(cert_file) self._connection = HTTP20Connection(server, port, ssl_context=ssl_context) self._max_concurrent_streams = None self._previous_server_max_concurrent_streams = None
def __init__(self, cert_file, use_sandbox=False, use_alternate_port=False): server = 'api.development.push.apple.com' if use_sandbox else 'api.push.apple.com' port = 2197 if use_alternate_port else 443 ssl_context = init_context() ssl_context.load_cert_chain(cert_file) self.__connection = HTTP20Connection(server, port, ssl_context=ssl_context)
def __init__(self, cert_file: Optional[str] = None, password: Optional[str] = None, cert_chain: Optional[str] = None) -> None: ssl_context = init_context(cert=cert_file, cert_password=password) if cert_chain: ssl_context.load_cert_chain(cert_chain) super(CertificateCredentials, self).__init__(ssl_context)
def __init__(self, cert_file, log, use_sandbox=False, use_alternative_port=False, proto=None): self.log = log self.server = 'api.development.push.apple.com' if use_sandbox else 'api.push.apple.com' self.port = 2197 if use_alternative_port else 443 self.ssl_context = init_context() self.ssl_context.load_cert_chain(cert_file) self.proto = proto self.__connection = None self.connect_to_apn_if_needed()
def sendApns2(cert, token, payload, headers): conn = HTTP20Connection('api.push.apple.com:443', ssl_context=tls.init_context(cert='/path/' + cert), cert_password=123456) conn.request('POST', '/3/device/%s' % token, body=json.dumps(payload), headers=headers) resp = conn.get_response() return make_response(resp)
def __init__(self, uri, certfile): self.conn = None """ :uri: apns push uri :certfile: cert file """ self._uri = uri self._certfile = certfile self._conn = HTTP20Connection(self._uri, ssl_context= tls.init_context(cert=self._certfile), force_proto="h2")
def ping(self): """ :returns: TODO """ try: self._conn.ping(struct.pack('l', 0)) except Exception as e: logger.warn("reconnecting APNs server") self._conn = HTTP20Connection(self._uri, ssl_context= tls.init_context(cert=self._certfile), force_proto="h2") logger.error(traceback.format_exc())
def get_credentials(self): context = init_context( cert=( WALLETPASS_CONF['CERT_PATH'], WALLETPASS_CONF['KEY_PATH'], ), # cert_path=WALLETPASS_CONF['APPLE_WWDRCA_PEM_PATH'], cert_password=WALLETPASS_CONF['KEY_PASSWORD'], ) return Credentials(context)
def __init__(self, cert_file, log, use_sandbox=False, use_alternative_port=False, proto=None): self.log = log self.server = 'api.development.push.apple.com' if use_sandbox else 'api.push.apple.com' self.port = 2197 if use_alternative_port else 443 self.ssl_context = init_context() self.ssl_context.load_cert_chain(cert_file) self.proto = proto self.__connection = None self.connect_to_apn_if_needed()
def __init__(self, mode, client_cert, password=None): if mode == MODE_PROD: self.host = u"api.push.apple.com" elif mode == MODE_DEV: self.host = u"api.development.push.apple.com" else: raise ValueError(u"invalid mode: {}".format(mode)) self.conn = HTTP20Connection( host=self.host, port=443, secure=True, ssl_context=init_context(cert=client_cert, cert_password=password), )
def url_check_http2(url): conn = HTTPConnection(url, port=443, secure=True, ssl_context=tls.init_context(cert_path=None, cert=None)) try: r = conn.request('GET', '/') if r == None: return 3 else: return 1 except: return 5
def __init__(self, cert_file, use_sandbox=False, use_alternative_port=False, proto=None, json_encoder=None): server = 'api.development.push.apple.com' if use_sandbox else 'api.push.apple.com' port = 2197 if use_alternative_port else 443 ssl_context = init_context() ssl_context.load_cert_chain(cert_file) self.__connection = HTTP20Connection(server, port, ssl_context=ssl_context, force_proto=proto or 'h2') self.__json_encoder = json_encoder
def get_apns_client(push_certificate): # sadly have to materialize the certificate for apns2 and the ssl context tmp_cert_fd, tmp_cert = tempfile.mkstemp() with os.fdopen(tmp_cert_fd, "wb") as f: f.write(push_certificate.certificate) tmp_key_fd, tmp_key = tempfile.mkstemp() with os.fdopen(tmp_key_fd, "wb") as f: f.write(push_certificate.private_key) ssl_context = init_context() ssl_context.load_cert_chain(tmp_cert, tmp_key) os.unlink(tmp_cert) os.unlink(tmp_key) return HTTP20Connection(APNs_PRODUCTION_SERVER, force_proto="h2", port=443, secure=True, ssl_context=ssl_context)
def send(data, addr, s): global d global path start = micro() writeLog("param=" + data) if getParms(data) is True: # continue return else: ParamErr, sound, cert, remark, token, topic, message = getParms(data) isfile = os.path.isfile(path + cert) if isfile is False: s.sendto('400|{"reason":"certNotExit"}|0.0', addr) #证书不存在 writeLog('400|{"reason":"certNotExit"}|0.0') # continue return payload, headers = getPayloadAndHeaders(message, sound, remark, topic) connName = cert.replace('.pem', '') try: if connName in d: writeLog("复用链接:" + connName) d[connName].request('POST', '/3/device/%s' % token, body=json.dumps(payload), headers=headers) resp = d[connName].get_response() status, data = make_response(resp) else: writeLog("开启一个新链接") d[connName] = HTTP20Connection( 'api.push.apple.com:443', ssl_context=tls.init_context(cert=path + cert), cert_password=123456) conn = d[connName] status, data = sendApns2(cert, token, payload, headers, conn) if data == '': data = 'sucess' except: del d[connName] writeLog("清空链接:" + connName) status = 500 data = "apns2 connect error" s.close elapsed = (micro() - start) writeLog(str(status) + '|' + data + '|' + str(elapsed)) s.sendto(str(status) + '|' + data + '|' + str(elapsed), addr) writeLog('PUSH END~~~~~~~~~~~~~~~~') writeLog("PUSH TIME=" + str(elapsed))
def send_push(input): topic = getOrRaise(input, "topic") token = getOrRaise(input, "token_hex") apnsPayload = getOrRaise(input, "apns") environment = getEnvironment(input) if environment in devEnvironments: host = "api.development.push.apple.com" pushCert = "cert/pushcert_dev.p12" if environment in prodEnvironments: host = "api.push.apple.com" pushCert = "cert/pushcert_prod.p12" print(host) method = "POST" path = "/3/device/{}".format(token) # Build headers headers = {"apns-topic": topic} if input.get("apns-push-type"): headers["apns-push-type"] = input.get("apns-push-type") if input.get("apns-id"): headers["apns-id"] = input.get("apns-id") if input.get("apns-expiration"): headers["apns-expiration"] = input.get("apns-expiration") if input.get("apns-priority"): headers["apns-priority"] = input.get("apns-priority") if input.get("apns-collapse-id"): headers["apns-collapse-id"] = input.get("apns-collapse-id") conn = HTTPConnection( host=host, secure=True, port=443, ssl_context=init_context(cert=pushCert) ) conn.request( method=method, url=path, body=json.dumps(apnsPayload).encode("utf-8"), headers=headers ) return conn.get_response()
def __init__(self, cert_file=None, key_file=None, team=None, key_id=None, use_sandbox=False, use_alternative_port=False, http_client_key=None, proto=None, json_encoder=None, request_timeout=20, pool_size=5, connect_timeout=20): server = 'api.development.push.apple.com' if use_sandbox else 'api.push.apple.com' port = 2197 if use_alternative_port else 443 self._auth_token = None self.auth_token_expired = False self.json_payload = None self.headers = None ssl_context = None if cert_file and key_file: ssl_context = init_context() ssl_context.load_cert_chain(cert_file) self.auth_type = 'cert' elif team and key_id and key_file: self._team = team with open(key_file, 'r') as tmp: self._auth_key = tmp.read() self._key_id = key_id self._auth_token = self.get_auth_token() self._header_format = 'bearer %s' self.auth_type = 'token' self.cert_file = cert_file self.__url_pattern = '/3/device/{token}' self.__connection = HTTP20Connection(server, port, ssl_context=ssl_context, force_proto=proto or 'h2') self.__json_encoder = json_encoder self.__max_concurrent_streams = None self.__previous_server_max_concurrent_streams = None self.open_streams = collections.deque()
def main(sock, addr): global d sock.send("start revice data") while True: data = sock.recv(1024) writeLog("push start") writeLog("param="+data) start = micro() if data == 'exit' or not data: break if getParms(data) is True: break else: ParamErr,sound,cert,remark,token,topic,message = getParms(data) isfile = os.path.isfile(path+cert) if isfile is False: sock.send('400|{"reason":"certNotExit"}|0.0') writeLog('400|{"reason":"certNotExit"}|0.0') break payload,headers = getPayloadAndHeaders(message,sound,remark,topic) connName = cert.replace('.pem','') try: if connName in d: writeLog("复用链接:"+connName) d[connName].request('POST', '/3/device/%s' % token, body=json.dumps(payload), headers=headers) resp = d[connName].get_response() status,data = make_response(resp) else: writeLog("开启一个新链接") d[connName] = HTTP20Connection('api.push.apple.com:443', ssl_context=tls.init_context(cert=path+cert),cert_password=123456) conn = d[connName] status,data = sendApns2(cert,token,payload,headers,conn) if data=='': data = 'sucess' except: del d[connName] writeLog("清空链接:"+connName) status = 500 data = "apns2 connect error" sock.close elapsed = (micro() - start) writeLog(str(status)+'|'+data+'|'+str(elapsed)) sock.send(str(status)+'|'+data+'|'+str(elapsed)) sock.close() print 'Connection from %s:%s closed.' % addr
def _get_ssl_context(ssl_verify): try: from hyper import tls import ssl, os context = tls.init_context(None, None, None) context.check_hostname = False if ssl_verify: cafile = to_string(ssl_verify) if os.path.isfile(cafile): context.load_verify_locations(cafile) context.verify_mode = ssl.CERT_REQUIRED else: context.verify_mode = ssl.CERT_NONE return context except Exception: import traceback print(traceback.format_exc())
def setup_method(self, test_method): self.server = wptserve.server.WebTestHttpd(host="localhost", port=0, use_ssl=True, doc_root=doc_root, key_file=os.path.join(repo_root, "tools", "certs", "web-platform.test.key"), certificate=os.path.join(repo_root, "tools", "certs", "web-platform.test.pem"), handler_cls=wptserve.server.Http2WebTestRequestHandler, http2=True) self.server.start(False) context = tls.init_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE context.set_alpn_protocols(['h2']) self.conn = HTTP20Connection('%s:%i' % (self.server.host, self.server.port), enable_push=True, secure=True, ssl_context=context) self.conn.connect()
def send(token_hex, message, **kwargs): """ Site: https://apple.com API: https://developer.apple.com Desc: iOS notifications Installation and usage: pip install hyper """ priority = kwargs.pop('priority', 10) topic = kwargs.pop('topic', None) alert = { "title": kwargs.pop("event"), "body": message, "action": kwargs.pop( 'apns_action', defaults.APNS_PROVIDER_DEFAULT_ACTION) } data = { "aps": { 'alert': alert, 'content-available': kwargs.pop('content_available', 0) and 1 } } data['aps'].update(kwargs) payload = dumps(data, separators=(',', ':')) headers = { 'apns-priority': priority } if topic is not None: headers['apns-topic'] = topic ssl_context = init_context() ssl_context.load_cert_chain(settings.APNS_CERT_FILE) connection = HTTP20Connection( settings.APNS_GW_HOST, settings.APNS_GW_PORT, ssl_context=ssl_context) stream_id = connection.request( 'POST', '/3/device/{}'.format(token_hex), payload, headers) response = connection.get_response(stream_id) if response.status != 200: raise APNsError(response.read()) return True
def setup_method(self, test_method): self.server = wptserve.server.WebTestHttpd(host="localhost", port=0, use_ssl=True, doc_root=doc_root, key_file=os.path.join(repo_root, "tools", "certs", "web-platform.test.key"), certificate=os.path.join(repo_root, "tools", "certs", "web-platform.test.pem"), handler_cls=wptserve.server.Http2WebTestRequestHandler, http2=True) self.server.start(False) context = tls.init_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE context.set_alpn_protocols(['h2']) self.conn = HTTP20Connection('%s:%i' % (self.server.host, self.server.port), enable_push=True, secure=True, ssl_context=context) self.conn.connect()
def send(token_hex, message, **kwargs): """ Site: https://apple.com API: https://developer.apple.com Desc: iOS notifications Installation and usage: pip install hyper """ priority = kwargs.pop('priority', 10) topic = kwargs.pop('topic', None) alert = { "title": kwargs.pop("event"), "body": message, "action": kwargs.pop('apns_action', defaults.APNS_PROVIDER_DEFAULT_ACTION) } data = { "aps": { 'alert': alert, 'content-available': kwargs.pop('content_available', 0) and 1 } } data['aps'].update(kwargs) payload = dumps(data, separators=(',', ':')) headers = {'apns-priority': priority} if topic is not None: headers['apns-topic'] = topic ssl_context = init_context() ssl_context.load_cert_chain(settings.APNS_CERT_FILE) connection = HTTP20Connection(settings.APNS_GW_HOST, settings.APNS_GW_PORT, ssl_context=ssl_context) stream_id = connection.request('POST', '/3/device/{}'.format(token_hex), payload, headers) response = connection.get_response(stream_id) if response.status != 200: raise APNsError(response.read()) return True
def __init__(self, cert_file, use_sandbox=False, use_alternative_port=False, proto=None): if use_sandbox: self.server = 'api.development.push.apple.com' else: self.server = 'api.push.apple.com' self.port = 2197 if use_alternative_port else 443 self.ssl_context = init_context() self.ssl_context.load_cert_chain(cert_file) self.proto = proto self.connection = HTTP20Connection(self.server, self.port, ssl_context=self.ssl_context, force_proto=self.proto or 'h2') self.response = {}
def get_credentials(self): if WALLETPASS_CONF['PUSH_AUTH_STRATEGY'] == 'token': return TokenCredentials( auth_key_path=WALLETPASS_CONF['TOKEN_AUTH_KEY_PATH'], auth_key_id=WALLETPASS_CONF['TOKEN_AUTH_KEY_ID'], team_id=WALLETPASS_CONF['TEAM_ID'], ) # legacy cert/key auth context = init_context( cert=( WALLETPASS_CONF['CERT_PATH'], WALLETPASS_CONF['KEY_PATH'], ), # cert_path=WALLETPASS_CONF['APPLE_WWDRCA_PEM_PATH'], cert_password=WALLETPASS_CONF['KEY_PASSWORD'], ) return Credentials(context)
def get_ssl_context(self): # sadly have to materialize the certificate for apns2 and the ssl context # TODO: verify tmp_cert_fd, tmp_cert = tempfile.mkstemp() with os.fdopen(tmp_cert_fd, "wb") as f: f.write(self.push_certificate.certificate) tmp_key_fd, tmp_key = tempfile.mkstemp() with os.fdopen(tmp_key_fd, "wb") as f: f.write(self.push_certificate.private_key) # load the certificates in a ssl context ssl_context = init_context() ssl_context.load_cert_chain(tmp_cert, tmp_key) # remove the temp files os.unlink(tmp_cert) os.unlink(tmp_key) return ssl_context
def __init__( self, push_mode='dev', secure=True, cert_location=None, cert_password=None, conn_timeout, request_timeout): if push_mode == 'dev': self.apns_host = Client.dev_apns_host elif push_mode == 'prd': self.apns_host = Client.prd_apns_host else: err_msg = ( 'The push_mode param must be "dev" or "prd", not {0}'.format( push_mode)) raise ValueError(err_msg) if cert_location: ssl_context_obj = tls.init_context( cert=cert_location, cert_password=cert_password) else: ssl_context_obj = None self.conn = HTTP20Connection( self.apns_host, secure=secure, ssl_context=ssl_context_obj, timeout=(conn_timeout, request_timeout))
def post_method(self, url, json_data, retry_count=0): host_port = self.ROOT_URL.replace("https://", "").split(":") context = tls.init_context(self.CLIENT_CERT) context.check_hostname = False context.verify_mode = ssl.CERT_NONE if type(json_data) == dict: json_payload = json.dumps(json_data) else: json_payload = json_data logger.info(type(json_payload)) conn = HTTP20Connection(host_port[0], host_port[1], 'https', ssl_context=context, force_proto="h2") log_str = """ ============================= Request =============================== [CURL POST] {} BODY: {} """.format(url, json_payload) logger.info(log_str) try: stream_id = conn.request('POST', url, json_payload) except socket.error as e: if e.errno != errno.ECONNREFUSED: raise e result = { "error": { "title": _(u"연결실패"), "message": _(u"Security Controller와 연결을 실패했습니다."), "code": 500 } } else: response = conn.get_response(stream_id=stream_id) result = self.confirm_status(response, url, "POST", json_data=json_data) return result
def single_push(self, token, alert, badge=1): """ 发送单个设备 :param token:设备 :param alert:弹出的消息 :param badge:红点数字 :return: """ token = self.handle_token(token) payload = { 'aps': { 'alert': alert, 'sound': 'default', 'badge': badge, } } conn = HTTPConnection(self.api_url, ssl_context=tls.init_context(cert=self.cert)) conn.request('POST', self.get_api_path(token), body=json.dumps(payload), headers=self.headers) resp = conn.get_response() return self.make_response(resp)
def get_connection(self, host, port, scheme, cert=None): """ Gets an appropriate HTTP/2 connection object based on host/port/scheme/cert tuples. """ secure = (scheme == 'https') if port is None: # pragma: no cover port = 80 if not secure else 443 ssl_context = None if cert is not None: ssl_context = init_context(cert=cert) try: conn = self.connections[(host, port, scheme, cert)] except KeyError: conn = HTTPConnection(host, port, secure=secure, ssl_context=ssl_context) self.connections[(host, port, scheme, cert)] = conn return conn
def __init__(self, cert_chain=None, cert=None, use_sandbox=False, use_alternative_port=False, proto=None, json_encoder=None): """ Create a new ``APNsClient`` that is used to send push notifications. Provide your own certificate chain file or cert file :param cert_chain: (optional) The path to the certificate chain file If you do not provide the cert parameter, this is required :param cert: (optional) if string, path to ssl client cert file (.pem). If tuple, ('cert', 'key') pair. The certfile string must be the path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate’s authenticity. The keyfile string, if present, must point to a file containing the private key in. If not used, then the cert_chain must be provided :param use_sandbox: (optional) :param use_alternative_port: (optional) :param proto: (optional) :param json_encoder: (optional) :returns: An ``APNsClient`` """ server = 'api.development.push.apple.com' if use_sandbox else 'api.push.apple.com' port = 2197 if use_alternative_port else 443 ssl_context = init_context(cert=cert) if cert_chain: ssl_context.load_cert_chain(cert_chain) self.__connection = HTTP20Connection(server, port, ssl_context=ssl_context, force_proto=proto or 'h2') self.__json_encoder = json_encoder
# code, errmsg = reason # print(token,errmsg) # # """ 使用http2连接一直连接不上apns服务器 """ from hyper import HTTPConnection, tls import json token = 'ac16e5344c0de2a626e2d3789a18c054e380060fb3165779a173a1d4bd8f905b' payload = { 'aps': { 'alert': '测试推送', 'sound': 'default', 'badge': 1, } } headers = { "apns-topic": 'com.csdigit.movesx', } conn = HTTPConnection('api.development.push.apple.com:443', ssl_context=tls.init_context(cert_path=apn_dev_cert_path)) conn.request('POST', '/3/device/%s' % token, body=json.dumps(payload), headers=headers) resp = conn.get_response() d = resp.status print(d)
def __init__(self, cert_file, use_sandbox=False, use_alternate_port=False): server = 'api.development.push.apple.com' if use_sandbox else 'api.push.apple.com' port = 2197 if use_alternate_port else 443 ssl_context = init_context() ssl_context.load_cert_chain(cert_file) self.__connection = HTTP20Connection(server, port, ssl_context=ssl_context)
import ssl import hyper from hyper.tls import init_context # Custom SSLCONTEXT for not verifying SSLCertificate and Hostname ssl_context = init_context() hyper.tls._context = ssl_context hyper.tls._context.check_hostname = False hyper.tls._context.verify_mode = ssl.CERT_NONE conn = hyper.HTTP20Connection('localhost', port=7100, secure=True, ssl_context=ssl_context) conn.request('GET', '/') print(conn.get_response())
apns_priority = "10" # payload payload = {"aps": {"alert": "Hello from Python!"}} json_payload = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode( "utf-8" ) # configure headers headers = {} headers["apns-topic"] = apns_topic headers["apns-push-type"] = apns_push_type headers["apns-priority"] = apns_priority # ssl context ssl_context = init_context(cert=cert_file) # connection connection = HTTP20Connection( host=host, port=port, ssl_context=ssl_context, force_proto="h2", secure=True, ) # connection.connect() # stream stread_id = connection.request("POST", url, json_payload, headers) # result with connection.get_response(stread_id) as response: if response.status == 200: print("success") else:
def __init__(self, cert_file=None, password=None, cert_chain=None): ssl_context = init_context(cert=cert_file, cert_password=password) if cert_chain: ssl_context.load_cert_chain(cert_chain) super(CertificateCredentials, self).__init__(ssl_context)