Beispiel #1
0
def directives(conn: HTTP20Connection):
    stream = conn.request('GET', '/dcs/v1/directives', headers=get_headers())
    while True:
        for push in conn.get_pushes(stream):
            logger.info('Directive: %s', push.push)
        time.sleep(2)
    logger.info('DIRECTIVE QUIT')
Beispiel #2
0
 def get_connection(self):
     if self.h2:
         if not self.proxy:
             return HTTP20Connection(self.host,
                                     self.port,
                                     self.secure,
                                     timeout=self.timeout)
         else:
             return HTTP20Connection('http2bin.org',
                                     secure=self.secure,
                                     proxy_host=self.host,
                                     proxy_port=self.port,
                                     timeout=self.timeout)
     else:
         if not self.proxy:
             return HTTP11Connection(self.host,
                                     self.port,
                                     self.secure,
                                     timeout=self.timeout)
         else:
             return HTTP11Connection('httpbin.org',
                                     secure=self.secure,
                                     proxy_host=self.host,
                                     proxy_port=self.port,
                                     timeout=self.timeout)
Beispiel #3
0
def ping(conn: HTTP20Connection):
    stream = conn.request('GET', '/dcs/v1/ping', headers=get_headers())
    response = conn.get_response(stream)
    if response.status != 200:
        get_conn(force_create=True)
    logger.info('PING %s', response.status)

    time.sleep(60)
    executor.submit(ping, conn)
Beispiel #4
0
    def translate(self):
        with HTTP20Connection(self.url, port=443) as conn:
            conn.request('GET', '/?' + urlencode(self.build_params()))
            data = conn.get_response().read()

        soup = BeautifulSoup(data, 'html.parser')
        return soup.select_one('#result_box').text
Beispiel #5
0
    def init_connection(self):
        """ Opens and maintains the connection with AVS. This starts the thread that runs
            for the duration of the object's life. Sends required requests to initialize
            connection correctly. This should be called anytime the connection needs to be
            reestablished.

        """
        # Open connection
        self.connection = HTTP20Connection(self.url,
                                           port=443,
                                           secure=True,
                                           force_proto="h2",
                                           enable_push=True)

        # First start downstream
        self.start_downstream()

        # Send sync state message (required)
        header = {'namespace': "System", 'name': "SynchronizeState"}
        stream_id = self.send_event(header)
        # Manually handle this response for now
        data = self.get_response(stream_id)
        # Should be 204 response (no content)
        if data.status != 204:
            print("PUSH" + str(data.read()))
            raise NameError("Bad status (%s)" % data.status)

        # Start ping thread
        ping_thread = threading.Thread(target=self.ping_thread)
        ping_thread.start()
Beispiel #6
0
def _http2(url):
    '''
        Determines if a given url supports HTTP/2 protocol

        Ths function serves as the function run by the shell within the
            '__init__.py' file of this module. To run multiple tests concurrently,
            send a list of urls to the 'http2' function found there.

        Example:

            In [1]:    from seo_tools.generic import _http2

                       _http2('https://www.example.com')

            Out [1]:   True

        Attributes:

            url (str): A url whose HTTP/2 support status is to be determined

        Returns:

            Supports HTTP/2? (boolean):
                A boolean of if the domain is supported or not.

                True, if supported
                False, if not supported
    '''
    url = clean_url(url)
    c = HTTP20Connection(url)
    try:
        c.request('GET', '/')
        return True
    except AssertionError:
        return False
Beispiel #7
0
    def connection(self) -> HTTP20Connection:
        """
        Open an apple connection
        requires a ssl context

        :return: an hyper.http20.connection.HTTP20Connection object
        """
        host = self.url_push
        port = self.port
        ssl_context = self.ssl_context

        connection = HTTP20Connection(host=host,
                                      port=port,
                                      ssl_context=ssl_context,
                                      force_proto=tls.H2C_PROTOCOL)

        cert_file_name = self.cert_file.split('/')[-1]
        key_file_name = self.key_file.split('/')[-1] if self.key_file else None

        if key_file_name:
            msg = f'{self.app_name.capitalize()} app: Connecting to {host}:{port} ' \
                    f'using {cert_file_name} certificate ' \
                    f'and {key_file_name} key files'
        else:
            msg = f'{self.app_name.capitalize()} app: Connecting to {host}:{port} ' \
                    f'using {cert_file_name} certificate'

        log_event(loggers=self.loggers, msg=msg, level='deb')

        return connection
Beispiel #8
0
 def __init__(self, push_certificate):
     self.push_certificate = push_certificate
     self.conn = HTTP20Connection(self.APNs_PRODUCTION_SERVER,
                                  force_proto="h2",
                                  port=443,
                                  secure=True,
                                  ssl_context=self.get_ssl_context())
Beispiel #9
0
 def connect_to_apn_if_needed(self):
     if self.__connection is None:
         self.__connection = HTTP20Connection(self.server,
                                              self.port,
                                              ssl_context=self.ssl_context,
                                              force_proto=self.proto
                                              or 'h2')
Beispiel #10
0
    def test_closed_responses_remove_their_streams_from_conn(self):
        self.set_up()

        recv_event = threading.Event()

        def socket_handler(listener):
            sock = listener.accept()[0]

            # We're going to get the two messages for the connection open, then
            # a headers frame.
            receive_preamble(sock)

            # Now, send the headers for the response.
            f = build_headers_frame([(':status', '200')])
            f.stream_id = 1
            sock.send(f.serialize())

            # Wait for the message from the main thread.
            recv_event.wait()
            sock.close()

        self._start_server(socket_handler)
        conn = HTTP20Connection(self.host, self.port)
        conn.request('GET', '/')
        resp = conn.getresponse()

        # Close the response.
        resp.close()

        recv_event.set()

        assert not conn.streams

        self.tear_down()
Beispiel #11
0
    def test_connection_context_manager(self):
        self.set_up()

        data = []
        send_event = threading.Event()

        def socket_handler(listener):
            sock = listener.accept()[0]

            # We should get two packets: one connection header string, one
            # SettingsFrame.
            first = sock.recv(65535)
            second = sock.recv(65535)
            data.append(first)
            data.append(second)

            # We need to send back a SettingsFrame.
            f = SettingsFrame(0)
            sock.send(f.serialize())

            send_event.set()
            sock.close()

        self._start_server(socket_handler)
        with HTTP20Connection(self.host, self.port) as conn:
            conn.connect()
            send_event.wait()

        # Check that we closed the connection.
        assert conn._sock == None

        self.tear_down()
Beispiel #12
0
    def test_connection_string(self):
        self.set_up()

        # Confirm that we send the connection upgrade string and the initial
        # SettingsFrame.
        data = []
        send_event = threading.Event()

        def socket_handler(listener):
            sock = listener.accept()[0]

            # We should get two packets: one connection header string, one
            # SettingsFrame.
            first = sock.recv(65535)
            second = sock.recv(65535)
            data.append(first)
            data.append(second)

            # We need to send back a SettingsFrame.
            f = SettingsFrame(0)
            sock.send(f.serialize())

            send_event.set()
            sock.close()

        self._start_server(socket_handler)
        conn = HTTP20Connection(self.host, self.port)
        conn.connect()
        send_event.wait()

        assert data[0] == b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'

        self.tear_down()
Beispiel #13
0
def sm_policies_sm_policy_id_get(sm_policy_id):  # noqa: E501
    """sm_policies_sm_policy_id_get

     # noqa: E501

    :param sm_policy_id: Identifier of a policy association
    :type sm_policy_id: str

    :rtype: SmPolicyControl
    """
    print("In sm_policies_sm_policy_id_get")
    data = connexion.request.data  # noqa: E501
    print("sm_policy_id=",data)
    #ldapc = ldap.initialize(ldap_server)
    final_dn = 'uid='+sm_policy_id+','+base_dn

    udrcon = HTTP20Connection(conf_json['udr_policy_ip_address']+":"+"7003")
    streamid = udrcon.request('GET', "/nudr-dr/v1/policy-data/ues/imsi-2620020000092/sessionblob/262002000009210")
    #print("streamid: "+str(streamid))
    resp = udrcon.get_response()
    print(resp.read())
    #if r.status_code == 200:
    if resp.status == 200:
       return "sessionBlobDataReceived"
    else:
        print("[PCF][ERROR]: GET "+"/nudr-dr/v1/policy-data/ues/uid-imsi-2620020000092/sm-data"+" Failed")
        return response,201,{'Location': 'http://'+get_ip()+':8081/npcf-smpolicycontrol/v1/sm-policies/'}
Beispiel #14
0
    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()
Beispiel #15
0
    def loadPopOrder(self, data, serviceType):
        result = ""
        for item in data:
            result += item + "=" + data[item] + "&"
        result = result[:-1]
        # 修改路径
        realpath = os.path.dirname(os.path.realpath(sys.argv[0]))
        print("realpath>>>>", realpath)
        cafile = os.path.join(realpath, "resource", 'pem', "certs.pem")
        print("cert_loc cafile>>>", cafile)
        conn = HTTP20Connection(host='opn.jd.com',
                                port=443,
                                ssl_context=init_context(cafile))

        headers = self.headers.copy()
        headers['Referer'] = "https://opn.jd.com/bill/search?billStatus=5"
        headers['Host'] = "opn.jd.com"
        headers['Origin'] = "https://opn.jd.com"
        headers[':authority'] = 'opn.jd.com'
        headers[':method'] = 'POST'
        headers[':path'] = '/bill/query.json'
        headers[':scheme'] = 'https'
        response = conn.request(method='POST',
                                url=self.popurl,
                                body=result,
                                headers=headers)
        resp = conn.get_response(response)
        if resp.status != 200:
            print("请求{}失败,返回:{},请使用谷歌浏览器重新登录京东系统".format(
                response.url, response.text))
            return self.dataverify
        res = resp.read()
        # print(res)
        return list(self.parseOrders(json.loads(res), serviceType))
Beispiel #16
0
    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
Beispiel #17
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.base_address = self.get_option('target')
     logger.info("Initialized http2 gun with target '%s'", self.base_address)
     context = tls.init_context()
     context.check_hostname = False
     context.verify_mode = ssl.CERT_NONE
     self.conn = HTTP20Connection(self.base_address, secure=True, ssl_context=context)
Beispiel #18
0
 def __init__(self):
     '''
     Constructor
     '''
     self.conn = HTTP20Connection(host)
     self.headers={'authorization':authorization, \
              'dueros-device-id':dueros_device_id, \
              'content-type':'multipart/form-data; boundary={0}'.format(boundary)}
Beispiel #19
0
 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 check_serverh2(self):
     try:
         conn = HTTP20Connection(self.address, port=self.port)
         conn.request("GET","/")
         resp = conn.get_response()
         return resp.status == 200
     except ConnectionError as error:
         return False
def get(resource):
    logging.disable(logging.INFO)
    try:
        connection = HTTP20Connection(
            target.lstrip("http://").lstrip("https://"))
        connection.request("GET", f"/{resource}")
        return connection.get_response().read()
    finally:
        logging.disable(logging.DEBUG)
Beispiel #22
0
def request(host, method, path, headers=None, body=None):
    if headers is None:
        headers = {}
    headers['Accept'] = '*/*'
    headers['Connection'] = 'keep-alive'
    c = HTTP20Connection(host)
    response = c.request(method, path, headers=headers, body=body)
    resp = c.get_response(response)
    return resp.read().decode('utf-8')
Beispiel #23
0
    def __init__(self, ssl_context, sandbox=True, port=DEFAULT_PORT):
        self.sandbox = sandbox

        assert port in (DEFAULT_PORT, ALTERNATE_PORT), 'Invalid port number'
        self._port = port

        self._connection = HTTP20Connection(self.host,
                                            port=self.port,
                                            ssl_context=ssl_context)
Beispiel #24
0
 def get_prediction(self):
     c = HTTP20Connection('http2bin.org')
     c.request('GET', '/')
     start_time = time.time()
     try:
         resp = c.get_response()
         print resp
     except Exception,e:
         total_time = int((time.time() - start_time) * 1000)
         events.request_failure.fire(request_type="grpc", name=HOST, response_time=total_time, exception=e)
Beispiel #25
0
    def make_call(self, req):
        c = HTTP20Connection(host=req.host, force_proto='h2')
        c.request(req.get_method(),
                  urllib.parse.urlparse(req.full_url).path, req.data,
                  req.headers)

        resp = c.get_response()
        resp.getcode = lambda: resp.status
        resp.info = lambda: resp.headers
        return resp
Beispiel #26
0
 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")
Beispiel #27
0
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)
Beispiel #28
0
 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())
Beispiel #29
0
    def get_connection(self, netloc):
        """
        Gets an appropriate HTTP/2.0 connection object based on netloc.
        """
        try:
            conn = self.connections[netloc]
        except KeyError:
            conn = HTTP20Connection(netloc)
            self.connections[netloc] = conn

        return conn
Beispiel #30
0
    def send_message(self, thread_id, message_text = "", attachment = "", message_type = 1, audio_length = ""):

        boundary = "---------------------------"+str(random.sample(range(10000, 99999), 1)[0])
        header = {
            'origin': 'https://my.playstation.com',
            'Authorization': 'Bearer ' + self.oauth,
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:59.0) Gecko/20100101 Firefox/59.0',
            'Content-Type': 'multipart/mixed; boundary='+boundary,
            'accept-encoding': 'gzip, deflate, br',
            'accept': '*/*',
            'dnt': '1',

        }

        headers_auth = {
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:59.0) Gecko/20100101 Firefox/59.0',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'accept-language': 'es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3',
            'accept-encoding': 'gzip, deflate, br',
            'access-control-request-method': 'POST',
            'access-control-request-headers': 'authorization,content-type',
            'origin': 'https://my.playstation.com',
            'dnt': '1'
        }

        message_body = {
            "message": {
                "messageKind": 1,
                "body": message_text
            }
        }

        message = "\r\n"
        message += boundary+"\r\n"
        message += "Content-Type: application/json; charset=utf-8\r\n"
        message += "Content-Description: message\r\n"
        message += "\r\n"
        message += json.dumps(message_body) + "\r\n"
        message += boundary + "--\r\n"


        conn = HTTP20Connection("es-gmsg.np.community.playstation.net:443")
        auth = conn.request('OPTIONS', "/groupMessaging/v1/messageGroups/"+thread_id+"/messages", headers=headers_auth)
        auth_response = conn.get_response(auth)
        request = conn.request('POST', "/groupMessaging/v1/messageGroups/"+thread_id+"/messages", headers=header, body=message)
        response = conn.get_response(request)
        print(response.read())

        return response


        '''
Beispiel #31
0
 def __init__(self, host, **kwargs):
     HTTP20Connection.__init__(self, host, **kwargs)
     self.__init_state()