Esempio n. 1
0
    def test_td_coap_core_13(self):
        print "TD_COAP_CORE_13"
        path = "/query?first=1&second=2&third=3"
        req = Request()

        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = "Test Resource"

        self.current_mid += 1
        self._test_with_client([(req, expected)])
Esempio n. 2
0
    def _handle_post(self, transaction):
        """
        Handle POST requests

        :type transaction: Transaction
        :param transaction: the transaction that owns the request
        :rtype : Transaction
        :return: the edited transaction with the response to the request
        """
        path = str("/" + transaction.request.uri_path)
        transaction.response = Response()
        transaction.response.destination = transaction.request.source
        transaction.response.token = transaction.request.token
        if path == "/":
            transaction.response.code = defines.Codes.FORBIDDEN.number
            return transaction
        # Create request
        transaction = self._server.resourceLayer.create_resource(
            path, transaction)
        return transaction
    def _handle_post(self, transaction):
        """
        Handle POST requests

        :type transaction: Transaction
        :param transaction: the transaction that owns the request
        :rtype : Transaction
        :return: the edited transaction with the response to the request
        """
        path = str("/" + transaction.request.uri_path)
        if path.startswith("/rd/"):
            path = "/rd"
        transaction.response = Response()
        transaction.response.destination = transaction.request.source
        transaction.response.token = transaction.request.token

        # Create request
        transaction = self._server.resourceLayer.create_resource(
            path, transaction)
        return transaction
Esempio n. 4
0
    def test_td_coap_core_08(self):
        print "TD_COAP_CORE_08"
        path = "/test"
        req = Request()

        req.code = defines.Codes.DELETE.number
        req.uri_path = path
        req.type = defines.Types["NON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["NON"]
        expected._mid = None
        expected.code = defines.Codes.DELETED.number
        expected.token = None
        expected.payload = None

        self.current_mid += 1
        self._test_with_client([(req, expected)])
Esempio n. 5
0
    def test_td_coap_core_05(self):
        six.print_("TD_COAP_CORE_05")
        path = "/test"
        req = Request()

        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["NON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["NON"]
        expected._mid = None
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = "Test Resource"

        self.current_mid += 1
        self._test_with_client([(req, expected)])
Esempio n. 6
0
    def test_td_coap_link_01(self):
        print "TD_COAP_LINK_01"
        path = "/.well-known/core"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.content_type = defines.Content_types["application/link-format"]
        expected.payload = """</separate>;ct=0;if="separate",</large-update>;</seg1/seg2/seg3>;rt="Type1";sz="13",</large>;</seg1/seg2>;rt="Type1";sz="13",</test>;rt="Type1";sz="13",</obs>;</long>;</seg1>;rt="Type1";sz="13",</query>;rt="Type1";sz="13","""

        self.current_mid += 1
        self._test_with_client([(req, expected)])
Esempio n. 7
0
    def test_duplicate(self):
        print("TEST_DUPLICATE")
        path = "/test"

        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None

        self.current_mid += 1

        self._test_plugtest([(req, expected), (req, expected)])
Esempio n. 8
0
    def _handle_put(self, transaction):
        """
        Handle PUT requests

        :type transaction: Transaction
        :param transaction: the transaction that owns the request
        :rtype : Transaction
        :return: the edited transaction with the response to the request
        """
        path = str("/" + transaction.request.uri_path)
        transaction.response = Response()
        transaction.response.destination = transaction.request.source
        transaction.response.token = transaction.request.token
        try:
            resource = self._server.root[path]
        except KeyError:
            resource = None
        if resource is None and not path.startswith("/ps"):
            transaction.response.code = defines.Codes.NOT_FOUND.number
        elif resource is None and path.startswith("/ps"):
            #transaction = self._server.resourceLayer.create_resource(path, transaction)
            path_el = path.split("/");
            create_item = path_el[-1]
            del path_el[-1];
            new_path = '/'.join(path_el);
            parent_resource = self._server.root[new_path]
            print("[BROKER] Creating topic "+path+" on PUT request")
            payload = "<"+create_item+">;ct=0;";
            resource = parent_resource.createResFromPayload(payload,new_path)
            parent_resource.children.append(resource)
            parent_resource.cs.add_resource(resource.name,resource)
            print("[BROKER] Created")
            transaction.response.code = defines.Codes.CREATED.number
            transaction.resource = resource
            transaction = self._server.resourceLayer.update_resource(transaction)
        else:
            transaction.resource = resource
            # Update request
            transaction = self._server.resourceLayer.update_resource(transaction)
        return transaction
Esempio n. 9
0
    def test_edit_resource(self):
        print("TEST_EDIT_RESOURCE")
        path = "/obs"
        req = Request()

        req.code = defines.Codes.POST.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.payload = "<value>test</value>"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CHANGED.number
        expected.token = None
        expected.payload = None
        expected.location_path = "/obs"

        self.current_mid += 1
        self._test_with_client([(req, expected)])
    def test_delete_res_not_found(self):
        print("Resource not found on delete")
        path = "rd/4521"
        req = Request()
        req.code = defines.Codes.DELETE.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.content_type = 0
        req.payload = None

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.NOT_FOUND.number
        expected.token = None
        expected.content_type = 0
        expected.payload = None

        self.current_mid += 1
        self._test_check([(req, expected)])
Esempio n. 11
0
    def test_td_coap_core_07(self):
        print("TD_COAP_CORE_07")
        path = "/test"
        req = Request()

        req.code = defines.Codes.PUT.number
        req.uri_path = path
        req.type = defines.Types["NON"]
        req.content_type = defines.Content_types["application/xml"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.payload = "<value>test</value>"

        expected = Response()
        expected.type = defines.Types["NON"]
        expected._mid = None
        expected.code = defines.Codes.CHANGED.number
        expected.token = None
        expected.payload = None

        self.current_mid += 1
        self._test_with_client([(req, expected)])
Esempio n. 12
0
 def receive_request_reverse(self, transaction):
     """
     Setup the transaction for forwarding purposes on Reverse Proxies.
      
     :type transaction: Transaction
     :param transaction: the transaction that owns the request
     :rtype : Transaction
     :return: the edited transaction
     """
     wkc_resource_is_defined = defines.DISCOVERY_URL in self._server.root
     path = str("/" + transaction.request.uri_path)
     transaction.response = Response()
     transaction.response.destination = transaction.request.source
     transaction.response.token = transaction.request.token
     if path == defines.DISCOVERY_URL and not wkc_resource_is_defined:
         transaction = self._server.resourceLayer.discover(transaction)
     else:
         new = False
         if transaction.request.code == defines.Codes.POST.number:
             new_paths = self._server.root.with_prefix(path)
             new_path = "/"
             for tmp in new_paths:
                 if len(tmp) > len(new_path):
                     new_path = tmp
             if path != new_path:
                 new = True
             path = new_path
         try:
             resource = self._server.root[path]
         except KeyError:
             resource = None
         if resource is None or path == '/':
             # Not Found
             transaction.response.code = defines.Codes.NOT_FOUND.number
         else:
             transaction.resource = resource
             transaction = self._handle_request(transaction, new)
     return transaction
    def test_wildcard_ep(self):
        print("Use wildcard * to find endpoints")
        client = HelperClient(self.server_address)
        path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683"
        ct = {'content_type': defines.Content_types["application/link-format"]}
        payload = '</sensors/temp>;ct=41;rt="temperature-c";if="sensor";anchor="coap://spurious.example.com:5683",' \
                  '</sensors/light>;ct=41;rt="light-lux";if="sensor"'
        response = client.post(path, payload, None, None, **ct)
        loc_path1 = response.location_path
        path = "rd?ep=node2&con=coap://[2001:db8:3::123]:61616"
        payload = '</temp>;rt="temperature";anchor="coap://[2001:db8:3::123]:61616"'
        response = client.post(path, payload, None, None, **ct)
        loc_path2 = response.location_path
        client.stop()

        path = "rd-lookup/ep?rt=temp*"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.content_type = 0
        req.payload = None

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.content_type = defines.Content_types[
            "application/link-format"]
        expected.payload = '</' + loc_path1 + '>;con="coap://local-proxy-old.example.com:5683";ep="node1";lt=500,' \
                                              '</' + loc_path2 + '>;con="coap://[2001:db8:3::123]:61616";' \
                                                                 'ep="node2";lt=500'

        self.current_mid += 1
        self._test_check([(req, expected)])
Esempio n. 14
0
    def _handle_put(self, transaction):
        """

        :type transaction: Transaction
        :param transaction:
        :rtype : Transaction
        """
        path = str("/" + transaction.request.uri_path)
        transaction.response = Response()
        transaction.response.destination = transaction.request.source
        transaction.response.token = transaction.request.token
        try:
            resource = self._server.root[path]
        except KeyError:
            resource = None
        if resource is None:
            transaction.response.code = defines.Codes.NOT_FOUND.number
        else:
            transaction.resource = resource
            # Update request
            transaction = self._server.resourceLayer.update_resource(
                transaction)
        return transaction
    def test_no_ep(self):
        print("Registration without endpoint name")
        path = "rd?con=coap://local-proxy-old.example.com:5683"
        req = Request()
        req.code = defines.Codes.POST.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.content_type = defines.Content_types["application/link-format"]
        req.payload = '</sensors/temp>;ct=41;rt="temperature-c";if="sensor";' \
                      'anchor="coap://spurious.example.com:5683",</sensors/light>;ct=41;rt="light-lux";if="sensor"'

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.BAD_REQUEST.number
        expected.token = None
        expected.content_type = 0
        expected.payload = None

        self.current_mid += 1
        self._test_check([(req, expected)])
Esempio n. 16
0
    def test_uri_discovery(self):
        print("Uri discovery")
        path = ".well-known/core"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.content_type = 0
        req.payload = None

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.content_type = defines.Content_types["application/link-format"]
        expected.payload = '</rd-lookup/res>;rt="core.rd-lookup-res";ct=40,</rd>;rt="core.rd";ct=40,' \
                           '</rd-lookup/ep>;rt="core.rd-lookup-ep";ct=40'

        self.current_mid += 1
        self._test_check([(req, expected)])
    def test_update_expired(self):
        print("Update expired registration resource")
        client = HelperClient(self.server_address)
        path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683&lt=60"
        ct = {'content_type': defines.Content_types["application/link-format"]}
        payload = '</sensors/temp>;ct=41;rt="temperature-c";if="sensor";anchor="coap://spurious.example.com:5683",' \
                  '</sensors/light>;ct=41;rt="light-lux";if="sensor"'
        response = client.post(path, payload, None, None, **ct)
        # After 61 seconds the resource will be expired
        sleep(61)

        loc_path = response.location_path
        client.post(loc_path, None)
        client.stop()

        path = "rd-lookup/res?ep=node1&rt=temperature-c"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.content_type = 0
        req.payload = None

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.content_type = defines.Content_types[
            "application/link-format"]
        expected.payload = '<coap://local-proxy-old.example.com:5683/sensors/temp>;ct=41;rt="temperature-c";' \
                           'if="sensor";anchor="coap://spurious.example.com:5683"'

        self.current_mid += 1
        self._test_check([(req, expected)])
Esempio n. 18
0
    def test_td_coap_block_03(self):
        print("TD_COAP_BLOCK_03")
        path = "/large-update"

        req = Request()
        req.code = defines.Codes.PUT.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.payload = """"Me sabbee plenty"—grunted Queequeg, puffing away at his pipe """
        req.block1 = (0, 1, 64)

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTINUE.number
        expected.token = None
        expected.payload = None
        expected.block1 = (0, 1, 64)

        exchange1 = (req, expected)
        self.current_mid += 1
        self.server_mid += 1

        req = Request()
        req.code = defines.Codes.PUT.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.payload = """and sitting up in bed. "You gettee in," he added, motioning"""
        req.block1 = (1, 0, 64)

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CHANGED.number
        expected.token = None
        expected.payload = None

        exchange2 = (req, expected)
        self.current_mid += 1
        self.server_mid += 1

        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = """"Me sabbee plenty"—grunted Queequeg, puffing away at his pipe and sitting up in bed. "You gettee in," he added, motioning"""

        exchange3 = (req, expected)
        self.current_mid += 1

        self._test_plugtest([exchange1, exchange2, exchange3])
Esempio n. 19
0
    def test_td_coap_core_03(self):
        print("TD_COAP_CORE_03")
        path = "/test"
        req = Request()

        req.code = defines.Codes.PUT.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req.content_type = defines.Content_types["application/xml"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.payload = "<value>test</value>"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CHANGED.number
        expected.token = None
        expected.payload = None

        self.current_mid += 1
        exchange1 = (req, expected)

        req = Request()

        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = "Test Resource"

        self.current_mid += 1
        exchange2 = (req, expected)

        req = Request()

        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.accept = defines.Content_types["application/xml"]

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = "<value>test</value>"
        expected.content_type = defines.Content_types["application/xml"]

        self.current_mid += 1
        exchange3 = (req, expected)
        self._test_with_client([exchange1, exchange2, exchange3])
Esempio n. 20
0
    def test_get_multiple(self):
        print "TEST_GET_MULTIPLE"
        path = "/basic1"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.proxy_uri = "coap://127.0.0.1:5684/basic1"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = "Basic Resource"

        exchange1 = (req, expected)

        self.current_mid += 1

        #PREPARING SECOND EXPECTED RESPONSE (MAX AGE MUST BE CHECKED)
        req2 = Request()
        req2.code = defines.Codes.GET.number
        path = "/basic2"
        req2.uri_path = path
        req2.type = defines.Types["CON"]
        req2._mid = self.current_mid
        req2.destination = self.server_address
        req2.proxy_uri = "coap://127.0.0.1:5684/basic2"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = "Basic Resource"
        expected.max_age = 61

        exchange2 = (req2, expected)
        self.current_mid += 1
        req3 = Request()
        req3.code = defines.Codes.GET.number
        path = "/basic3"
        req3.uri_path = path
        req3.type = defines.Types["CON"]
        req3._mid = self.current_mid
        req3.destination = self.server_address
        req3.proxy_uri = "coap://127.0.0.1:5684/basic3"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = "Basic Resource"
        expected.max_age = 61

        exchange3 = (req3, expected)
        #self._test_with_client_delayed([exchange1,exchange2])
        self._test_with_client_delayed([exchange1, exchange2, exchange3])
Esempio n. 21
0
    def receive_request(self, transaction):
        """
        Handles the Blocks option in a incoming request.

        :type transaction: Transaction
        :param transaction: the transaction that owns the request
        :rtype : Transaction
        :return: the edited transaction
        """
        if transaction.request.block2 is not None:
            host, port = transaction.request.source
            key_token = hash(str(host) + str(port) + str(transaction.request.token))
            num, m, size = transaction.request.block2
            if key_token in self._block2_receive:
                self._block2_receive[key_token].num = num
                self._block2_receive[key_token].size = size
                self._block2_receive[key_token].m = m
                del transaction.request.block2
            else:
                # early negotiation
                byte = 0
                self._block2_receive[key_token] = BlockItem(byte, num, m, size)
                del transaction.request.block2

        elif transaction.request.block1 is not None:
            # POST or PUT
            host, port = transaction.request.source
            key_token = hash(str(host) + str(port) + str(transaction.request.token))
            num, m, size = transaction.request.block1
            if key_token in self._block1_receive:
                content_type = transaction.request.content_type
                if num != self._block1_receive[key_token].num \
                        or content_type != self._block1_receive[key_token].content_type:
                    # Error Incomplete
                    return self.incomplete(transaction)
                self._block1_receive[key_token].payload += transaction.request.payload
            else:
                # first block
                if num != 0:
                    # Error Incomplete
                    return self.incomplete(transaction)
                content_type = transaction.request.content_type
                self._block1_receive[key_token] = BlockItem(size, num, m, size, transaction.request.payload,
                                                            content_type)

            if m == 0:
                transaction.request.payload = self._block1_receive[key_token].payload
                # end of blockwise
                del transaction.request.block1
                transaction.block_transfer = False
                del self._block1_receive[key_token]
                return transaction
            else:
                # Continue
                transaction.block_transfer = True
                transaction.response = Response()
                transaction.response.destination = transaction.request.source
                transaction.response.token = transaction.request.token
                transaction.response.code = defines.Codes.CONTINUE.number
                transaction.response.block1 = (num, m, size)

            num += 1
            byte = size
            self._block1_receive[key_token].byte = byte
            self._block1_receive[key_token].num = num
            self._block1_receive[key_token].size = size
            self._block1_receive[key_token].m = m

        return transaction
Esempio n. 22
0
    def test_get_delete(self):
        print "TEST_GET_DELETE"
        path = "/basic"

        req2 = Request()
        req2.code = defines.Codes.GET.number
        req2.uri_path = path
        req2.type = defines.Types["CON"]
        req2._mid = self.current_mid
        req2.destination = self.server_address
        req2.proxy_uri = "coap://127.0.0.1:5684/storage/new"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.NOT_FOUND.number
        expected.token = None
        expected.payload = None

        exchange0 = (req2, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.POST.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.proxy_uri = "coap://127.0.0.1:5684/storage/new"
        req.payload = "Hello"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CREATED.number
        expected.token = None
        expected.payload = None

        exchange1 = (req, expected)

        self.current_mid += 1

        # PREPARING SECOND EXPECTED RESPONSE
        req2 = Request()
        req2.code = defines.Codes.GET.number
        req2.uri_path = path
        req2.type = defines.Types["CON"]
        req2._mid = self.current_mid
        req2.destination = self.server_address
        req2.proxy_uri = "coap://127.0.0.1:5684/storage/new"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = "Hello"

        exchange2 = (req2, expected)

        self.current_mid += 1

        # PREPARING THIRD EXPECTED RESPONSE
        req3 = Request()
        req3.code = defines.Codes.DELETE.number
        req3.uri_path = path
        req3.type = defines.Types["CON"]
        req3._mid = self.current_mid
        req3.destination = self.server_address
        req3.proxy_uri = "coap://127.0.0.1:5684/storage/new"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.DELETED.number
        expected.token = None
        expected.payload = None

        exchange3 = (req3, expected)

        self.current_mid += 1

        # PREPARING FOURTH EXPECTED RESPONSE
        req4 = Request()
        req4.code = defines.Codes.GET.number
        req4.uri_path = path
        req4.type = defines.Types["CON"]
        req4._mid = self.current_mid
        req4.destination = self.server_address
        req4.proxy_uri = "coap://127.0.0.1:5684/storage/new"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.NOT_FOUND.number
        expected.token = None

        exchange4 = (req4, expected)

        self.current_mid += 1

        self._test_with_client_delayed(
            [exchange0, exchange1, exchange2, exchange3, exchange4])
Esempio n. 23
0
    def test_get_etag(self):
        print "TEST_GET_ETAG"
        path = "/etag"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address
        req.proxy_uri = "coap://127.0.0.1:5684/etag"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = None

        exchange1 = (req, expected)

        self.current_mid += 1

        # PREPARING SECOND EXPECTED RESPONSE
        req2 = Request()
        req2.code = defines.Codes.GET.number
        req2.uri_path = path
        req2.type = defines.Types["CON"]
        req2._mid = self.current_mid
        req2.destination = self.server_address
        req2.proxy_uri = "coap://127.0.0.1:5684/etag"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.etag = 1
        expected.max_age = 1

        exchange2 = (req2, expected)

        self.current_mid += 1

        # PREPARING THIRD EXPECTED RESPONSE
        req3 = Request()
        req3.code = defines.Codes.POST.number
        req3.uri_path = path
        req3.type = defines.Types["CON"]
        req3._mid = self.current_mid
        req3.destination = self.server_address
        req3.proxy_uri = "coap://127.0.0.1:5684/etag"
        req3.payload = "Hello"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CHANGED.number
        expected.token = None
        expected.payload = None
        expected.etag = 2
        expected.location_path = "etag"

        exchange3 = (req3, expected)

        self.current_mid += 1

        # PREPARING FOURTH EXPECTED RESPONSE
        req4 = Request()
        req4.code = defines.Codes.GET.number
        req4.uri_path = path
        req4.type = defines.Types["CON"]
        req4._mid = self.current_mid
        req4.destination = self.server_address
        req4.proxy_uri = "coap://127.0.0.1:5684/etag"

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.token = None
        expected.payload = "Hello"
        expected.etag = 2

        exchange4 = (req4, expected)

        self.current_mid += 1

        self._test_with_client_delayed(
            [exchange1, exchange2, exchange3, exchange4])
Esempio n. 24
0
    def deserialize(datagram, source):
        """
        De-serialize a stream of byte to a message.

        :param datagram: the incoming udp message
        :param source: the source address and port (ip, port)
        :return: the message
        :rtype: Message
        """
        try:
            fmt = "!BBH"
            pos = 4
            length = len(datagram)
            while pos < length:
                fmt += "c"
                pos += 1
            s = struct.Struct(fmt)
            values = s.unpack_from(datagram)
            first = values[0]
            code = values[1]
            mid = values[2]
            version = (first & 0xC0) >> 6
            message_type = (first & 0x30) >> 4
            token_length = (first & 0x0F)
            if Serializer.is_response(code):
                message = Response()
                message.code = code
            elif Serializer.is_request(code):
                message = Request()
                message.code = code
            else:
                message = Message()
            message.source = source
            message.destination = None
            message.version = version
            message.type = message_type
            message.mid = mid
            pos = 3
            if token_length > 0:
                message.token = "".join(values[pos:pos + token_length])
            else:
                message.token = None

            pos += token_length
            current_option = 0
            length_packet = len(values)
            while pos < length_packet:
                next_byte = struct.unpack("B", values[pos])[0]
                pos += 1
                if next_byte != int(defines.PAYLOAD_MARKER):
                    # the first 4 bits of the byte represent the option delta
                    # delta = self._reader.read(4).uint
                    delta = (next_byte & 0xF0) >> 4
                    # the second 4 bits represent the option length
                    # length = self._reader.read(4).uint
                    length = (next_byte & 0x0F)
                    num, pos = Serializer.read_option_value_from_nibble(
                        delta, pos, values)
                    option_length, pos = Serializer.read_option_value_from_nibble(
                        length, pos, values)
                    current_option += num
                    # read option
                    try:
                        option_item = defines.OptionRegistry.LIST[
                            current_option]
                    except KeyError:
                        # log.err("unrecognized option")
                        raise AttributeError
                    if option_length == 0:
                        value = None
                    elif option_item.value_type == defines.INTEGER:
                        tmp = values[pos:pos + option_length]
                        value = 0
                        for b in tmp:
                            value = (value << 8) | struct.unpack("B", b)[0]
                    elif option_item.value_type == defines.OPAQUE:
                        tmp = values[pos:pos + option_length]
                        value = bytearray(tmp)
                    else:
                        tmp = values[pos:pos + option_length]
                        value = ""
                        for b in tmp:
                            value += str(b)

                    pos += option_length
                    option = Option()
                    option.number = current_option
                    option.value = Serializer.convert_to_raw(
                        current_option, value, option_length)

                    message.add_option(option)
                else:

                    if length_packet <= pos:
                        # log.err("Payload Marker with no payload")
                        raise AttributeError
                    message.payload = ""
                    payload = values[pos:]
                    for b in payload:
                        message.payload += str(b)
                        pos += 1
            return message
        except AttributeError:
            return defines.Codes.BAD_REQUEST.number
        except struct.error:
            return defines.Codes.BAD_REQUEST.number
Esempio n. 25
0
    def test_advanced(self):
        print("TEST_ADVANCED")
        path = "/advanced"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.max_age = 20
        expected.token = None

        exchange1 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.POST.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CREATED.number
        expected.payload = "Response changed through POST"
        expected.token = None

        exchange2 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.PUT.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CHANGED.number
        expected.payload = "Response changed through PUT"
        expected.token = None

        exchange3 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.DELETE.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.DELETED.number
        expected.payload = "Response deleted"
        expected.token = None

        exchange4 = (req, expected)

        self.current_mid += 1
        self._test_with_client([exchange1, exchange2, exchange3, exchange4])
Esempio n. 26
0
    def deserialize(datagram, source):
        """
        De-serialize a stream of byte to a message.

        :param datagram: the incoming udp message
        :param source: the source address and port (ip, port)
        :return: the message
        :rtype: Message
        """
        try:
            fmt = "!BBH"
            pos = struct.calcsize(fmt)
            s = struct.Struct(fmt)
            values = s.unpack_from(datagram)
            first = values[0]
            code = values[1]
            mid = values[2]
            version = (first & 0xC0) >> 6
            message_type = (first & 0x30) >> 4
            token_length = (first & 0x0F)
            if Serializer.is_response(code):
                message = Response()
                message.code = code
            elif Serializer.is_request(code):
                message = Request()
                message.code = code
            else:
                message = Message()
            message.source = source
            message.destination = None
            message.version = version
            message.type = message_type
            message.mid = mid
            if token_length > 0:
                fmt = "%ss" % token_length
                s = struct.Struct(fmt)
                token_value = s.unpack_from(datagram[pos:])[0]
                message.token = token_value.decode("utf-8")
            else:
                message.token = None

            pos += token_length
            current_option = 0
            values = datagram[pos:]
            length_packet = len(values)
            pos = 0
            while pos < length_packet:
                next_byte = struct.unpack("B", values[pos].to_bytes(1, "big"))[0]
                pos += 1
                if next_byte != int(defines.PAYLOAD_MARKER):
                    # the first 4 bits of the byte represent the option delta
                    # delta = self._reader.read(4).uint
                    num, option_length, pos = Serializer.read_option_value_len_from_byte(next_byte, pos, values)
                    current_option += num
                    # read option
                    try:
                        option_item = defines.OptionRegistry.LIST[current_option]
                    except KeyError:
                        (opt_critical, _, _) = defines.OptionRegistry.get_option_flags(current_option)
                        if opt_critical:
                            raise AttributeError("Critical option %s unknown" % current_option)
                        else:
                            # If the non-critical option is unknown
                            # (vendor-specific, proprietary) - just skip it
                            #log.err("unrecognized option %d" % current_option)
                            pass
                    else:
                        if option_length == 0:
                            value = None
                        elif option_item.value_type == defines.INTEGER:
                            tmp = values[pos: pos + option_length]
                            value = 0
                            for b in tmp:
                                value = (value << 8) | struct.unpack("B", b.to_bytes(1, "big"))[0]
                        elif option_item.value_type == defines.OPAQUE:
                            tmp = values[pos: pos + option_length]
                            value = tmp
                        else:
                            value = values[pos: pos + option_length]

                        option = Option()
                        option.number = current_option
                        option.value = Serializer.convert_to_raw(current_option, value, option_length)

                        message.add_option(option)
                        if option.number == defines.OptionRegistry.CONTENT_TYPE.number:
                            message.payload_type = option.value
                    finally:
                        pos += option_length
                else:

                    if length_packet <= pos:
                        # log.err("Payload Marker with no payload")
                        raise AttributeError("Packet length %s, pos %s" % (length_packet, pos))
                    message.payload = ""
                    payload = values[pos:]
                    try:
                        if message.payload_type == defines.Content_types["application/octet-stream"]:
                            message.payload = payload
                        else:
                            message.payload = payload.decode("utf-8")
                    except AttributeError:
                        message.payload = payload.decode("utf-8")
                    pos += len(payload)

            return message
        except AttributeError:
            return defines.Codes.BAD_REQUEST.number
        except struct.error:
            return defines.Codes.BAD_REQUEST.number
Esempio n. 27
0
    def test_not_allowed(self):
        print "TEST_NOT_ALLOWED"
        path = "/void"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.METHOD_NOT_ALLOWED.number
        expected.token = None

        exchange1 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.POST.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.METHOD_NOT_ALLOWED.number
        expected.token = None

        exchange2 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.PUT.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.METHOD_NOT_ALLOWED.number
        expected.token = None

        exchange3 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.DELETE.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.METHOD_NOT_ALLOWED.number
        expected.token = None

        exchange4 = (req, expected)

        self.current_mid += 1
        self._test_with_client([exchange1, exchange2, exchange3, exchange4])