def test_get_separate(self): print "\nGET /separate\n" args = ("/separate",) kwargs = {} path = args[0] req = Request() for key in kwargs: o = Option() o.number = defines.inv_options[key] o.value = kwargs[key] req.add_option(o) req.code = defines.inv_codes['GET'] req.uri_path = path req.type = defines.inv_types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.inv_types["CON"] expected.code = defines.responses["CONTENT"] expected.token = None expected.payload = "Separate" self.current_mid += 1 self._test_separate(req, expected)
def handle_get(self, request): """ Handles a GET request. :param request: the request :return: the response """ path = request.uri_path response = Response() response.destination = request.source if path == defines.DISCOVERY_URL: response = self._parent.discover(request, response) else: path = path.strip("/") node = self._parent.root.find_complete(path) if node is not None: resource = node.value else: resource = None if resource is None: # Not Found response = self._parent.send_error(request, response, 'NOT_FOUND') else: response = self._parent.get_resource(request, response, resource) return response
def prepare_notification_deletion(self, t): """ Create the notification message for deleted resource. :type t: (resource, request, old_response) :param t: the arguments of the notification message :return: the notification message """ resource, request, old_response = t response = Response() response.destination = old_response.destination response.token = old_response.token response.code = defines.responses['NOT_FOUND'] response.payload = None # Blockwise response, resource = self._parent.blockwise_response(request, response, resource) host, port = request.source key = hash(str(host) + str(port) + str(request.token)) if key in self._parent.blockwise: del self._parent.blockwise[key] # Reliability request.acknowledged = True response = self._parent.message_layer.reliability_response(request, response) # Matcher response = self._parent.message_layer.matcher_response(response) return resource, request, response
def map(self, request): path = request.uri_path if request.uri_path == defines.DISCOVERY_URL: response = Response() response.destination = request.source response = self._resource_layer.discover(request, response) self.result_forward(response, request) server = self.root.find_complete(path) if server is not None: new_request = Request() segments = server.find_path().split("/") path = segments[2:] path = "/".join(path) segments = segments[1].split(":") host = segments[0] port = int(segments[1]) # new_request.destination = (host, port) new_request.source = request.source new_request.type = request.type new_request._mid = (self._currentMID + 1) % (1 << 16) new_request.code = request.code new_request.proxy_uri = "coap://" + str(host) + ":" + str(port) + "/" + path new_request.payload = request.payload for option in request.options: if option.name == defines.inv_options["Uri-Path"]: continue if option.name == defines.inv_options["Uri-Query"]: continue if option.name == defines.inv_options["Uri-Host"]: continue new_request.add_option(option) return new_request return None
def handle_delete(self, request): """ Handles a DELETE request. :param request: the request :return: the response """ path = request.uri_path path = path.strip("/") node = self._parent.root.find_complete(path) if node is not None: resource = node.value else: resource = None response = Response() response.destination = request.source if resource is None: # Create request response = self._parent.send_error(request, response, 'NOT_FOUND') log.msg("Resource Not Found") return response else: # Delete response = self._parent.delete_resource(request, response, node) return response
def handle_post(self, request): """ Handles a POST request. :param request: the request :return: the response """ path = str("/" + request.uri_path) response = Response() response.destination = request.source # Create request response = self._parent.resource_layer.create_resource(path, request, response) return response
def test_delete(self): print("Delete") client = HelperClient(self.server_address) path = "rd?ep=endpoint1<=500&con=coap://local-proxy-old.example.com:5683&et=oic.d.sensor" 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_path = response.location_path client.stop() path = loc_path 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.DELETED.number expected.token = None expected.content_type = 0 expected.payload = None self.current_mid += 1 self._test_check([(req, expected)])
def test_lookup_expired_ep(self): print("Expired endpoint lookup") client = HelperClient(self.server_address) path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683<=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"' client.post(path, payload, None, None, **ct) client.stop() path = "rd-lookup/ep?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 = None self.current_mid += 1 # After 61 seconds the resource will be expired self._test_check([(req, expected)], 61)
def test_wrong_ep(self): print("Endpoint name already exists") client = HelperClient(self.server_address) path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683<=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"' client.post(path, payload, None, None, **ct) client.stop() path = "rd?ep=node1&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.SERVICE_UNAVAILABLE.number expected.token = None expected.content_type = 0 expected.payload = None self.current_mid += 1 self._test_check([(req, expected)])
def test_td_coap_core_06(self): print "TD_COAP_CORE_06" path = "/test_post" req = Request() req.code = defines.inv_codes['POST'] req.uri_path = path req.type = defines.inv_types["NON"] o = Option() o.number = defines.inv_options["Content-Type"] o.value = defines.inv_content_types["application/xml"] req.add_option(o) req._mid = self.current_mid req.destination = self.server_address req.payload = "<value>test</value>" expected = Response() expected.type = defines.inv_types["NON"] expected._mid = None expected.code = defines.responses["CREATED"] expected.token = None expected.payload = None option = Option() option.number = defines.inv_options["Location-Path"] option.value = "/test_post" expected.add_option(option) self.current_mid += 1 self._test_plugtest(req, expected)
def datagramReceived(self, data, addr): """ Handler for received UDP datagram. :param data: the UDP datagram :param host: source host :param port: source port """ try: host, port = addr except ValueError: host, port, tmp1, tmp2 = addr log.msg("Datagram received from " + str(host) + ":" + str(port)) serializer = Serializer() message = serializer.deserialize(data, host, port) print "Message received from " + host + ":" + str(port) print "----------------------------------------" print message print "----------------------------------------" if isinstance(message, Request): log.msg("Received request") ret = self.request_layer.handle_request(message) if isinstance(ret, Request): response = self.request_layer.process(ret) else: response = ret self.schedule_retrasmission(message, response, None) log.msg("Send Response") self.send(response, host, port) elif isinstance(message, Response): log.err("Received response") rst = Message.new_rst(message) rst = self.message_layer.matcher_response(rst) log.msg("Send RST") self.send(rst, host, port) elif isinstance(message, tuple): message, error = message response = Response() response.destination = (host, port) response.code = defines.responses[error] response = self.reliability_response(message, response) response = self.message_layer.matcher_response(response) log.msg("Send Error") self.send(response, host, port) elif message is not None: # ACK or RST log.msg("Received ACK or RST") self.message_layer.handle_message(message)
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: transaction.response.code = defines.Codes.NOT_FOUND.number else: transaction.resource = resource # Update request transaction = self._server.resourceLayer.update_resource( transaction) return transaction
def incomplete(transaction): transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token transaction.response.code = defines.Codes.REQUEST_ENTITY_INCOMPLETE.number return transaction
def _handle_delete(self, transaction): """ Handle DELETE 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 try: resource = self._server.root[path] except KeyError: resource = None if resource is None: transaction.response.code = defines.Codes.NOT_FOUND.number else: # Delete transaction.resource = resource transaction = self._server.resourceLayer.delete_resource( transaction, path) return transaction
def _handle_get(self, transaction): """ Handle GET requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ 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 transaction.response.token_length = transaction.request.token_length print(" RequestLayer _handle_get ", transaction.request.token) print(" RequestLayer _handle_get path: ", path) if path == defines.DISCOVERY_URL and not wkc_resource_is_defined: print(" discovery...") transaction = self._server.resourceLayer.discover(transaction) else: 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._server.resourceLayer.get_resource( transaction) return transaction
def _handle_delete(self, transaction): """ Handle DELETE 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 print("Notifying resource:",resource,"\n") observers = self._server._observeLayer.notify(resource) print("Observers",observers) for transaction_ in observers: with transaction_: transaction_.response.code = defines.Codes.NOT_FOUND.number transaction_.response.observe = transaction_.resource.observe_count+1 transaction_.response.type = defines.Types["NON"] if transaction_.response is not None: self._server.send_datagram(transaction_.response) if resource is None: transaction.response.code = defines.Codes.NOT_FOUND.number else: # Delete transaction.resource = resource transaction = self._server.resourceLayer.delete_resource(transaction, path) return transaction
def _handle_get(self, transaction): """ Handle GET 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 if path == defines.DISCOVERY_URL: transaction = self._server.resourceLayer.discover(transaction) else: 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._server.resourceLayer.get_resource( transaction) return transaction
def _handle_get(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 if path == defines.DISCOVERY_URL: transaction = self._server.resourceLayer.discover(transaction) else: 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._server.resourceLayer.get_resource( transaction) return transaction
def receive_request_reverse(self, transaction): 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: 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 finish_request(self, args): """ Handler for received UDP datagram. :param args: (data, (client_ip, client_port) """ data, client_address = args host = client_address[0] port = client_address[1] # logging.log(logging.INFO, "Datagram received from " + str(host) + ":" + str(port)) serializer = Serializer() message = serializer.deserialize(data, host, port) # print "Message received from " + host + ":" + str(port) # print "----------------------------------------" # print message # print "----------------------------------------" if isinstance(message, Request): # log.msg("Received request") ret = self.request_layer.handle_request(message) if isinstance(ret, Request): response = self.request_layer.process(ret) else: response = ret self.schedule_retrasmission(message, response, None) # log.msg("Send Response") return response, host, port elif isinstance(message, Response): # log.err("Received response") rst = Message.new_rst(message) rst = self.message_layer.matcher_response(rst) # log.msg("Send RST") return rst, host, port elif isinstance(message, tuple): message, error = message response = Response() response.destination = (host, port) response.code = defines.responses[error] response = self.message_layer.reliability_response(message, response) response = self.message_layer.matcher_response(response) # log.msg("Send Error") return response, host, port elif message is not None: # ACK or RST # log.msg("Received ACK or RST") self.message_layer.handle_message(message) return None
def error(transaction, code): # pragma: no cover transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.type = defines.Types["RST"] transaction.response.token = transaction.request.token transaction.response.code = code return transaction
def _handle_get(self, transaction): """ Handle GET 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.METHOD_NOT_ALLOWED.number return transaction elif path == defines.DISCOVERY_URL: return self._server.resourceLayer.discover(transaction) else: try: resource = self._server.root[path] except KeyError: resource = None if resource is None: # Not Found transaction.response.code = defines.Codes.NOT_FOUND.number #transaction.response.payload = path+ " NOT FOUND" transaction.response.payload = "NOT FOUND" return transaction transaction.resource = resource #perform a discovery with path and query specified in the uri if (transaction.request.uri_query is not None and transaction.request.uri_query != ""): return self._server.resourceLayer.discover_subtopics( transaction) transaction = self._server.resourceLayer.get_resource(transaction) """ BLOCKING READ HERE """ if self._server._blocking_read: if ( transaction.response.payload is None or transaction.response.payload == "" ) and transaction.response.code == defines.Codes.CONTENT.number: transaction.response.code = defines.Codes.NO_CONTENT.number [host, port] = transaction.request.source key = hash(str(host) + str(port)) if key in self._server._observeLayer._readers[ resource.path]: allowed = True else: allowed = False self._server._observeLayer._readers[ resource.path][key] = ObserveItem( time.time(), 0, allowed, transaction) return transaction return transaction
def test_lookup_expired_ep(self): print("Expired endpoint lookup") client = HelperClient(self.server_address) path = "rd?ep=node1&con=coap://local-proxy-old.example.com:5683<=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"' client.post(path, payload, None, None, **ct) client.stop() path = "rd-lookup/ep?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 = None self.current_mid += 1 # After 61 seconds the resource will be expired self._test_check([(req, expected)], 61)
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)])
def handle_put(self, request): """ Handles a PUT request :param request: the request :return: the response """ response = Response() response.destination = request.source path = request.uri_path path = path.strip("/") node = self._parent.root.find_complete(path) if node is None: response = self._parent.send_error(request, response, 'NOT_FOUND') return response # Update request response = self._parent.update_resource(request, response, node) return response
def test_td_coap_core_12(self): print "TD_COAP_CORE_12" path = "/seg1/seg2/seg3" 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.payload = "Test Resource" self.current_mid += 1 self._test_with_client([(req, expected)])
def test_td_coap_core_12(self): print "TD_COAP_CORE_12" path = "/seg1/seg2/seg3" req = Request() req.code = defines.inv_codes['GET'] req.uri_path = path req.type = defines.inv_types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.inv_types["ACK"] expected._mid = self.current_mid expected.code = defines.responses["CONTENT"] expected.payload = "Test Resource" self.current_mid += 1 self._test_plugtest(req, expected)
def handle_put(self, request): """ Handles a PUT request :param request: the request :return: the response """ response = Response() response.destination = request.source path = str("/" + request.uri_path) try: resource = self._parent.root[path] except KeyError: resource = None if resource is None: response = self._parent.send_error(request, response, 'NOT_FOUND') return response # Update request response = self._parent.resource_layer.update_resource(request, response, resource) return response
def test_td_coap_block_01_client(self): print("TD_COAP_BLOCK_01") path = "/large" req = Request() req.code = defines.Codes.GET.number req.uri_path = path req.type = defines.Types["CON"] req._mid = None req.destination = self.server_address req.block2 = (0, 0, 1024) expected = Response() expected.type = defines.Types["ACK"] expected._mid = None 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 to me with his tomahawk, and throwing the clothes to one side. He really did this in not only a civil but a really kind and charitable way. I stood looking at him a moment. For all his tattooings he was on the whole a clean, comely looking cannibal. What's all this fuss I have been making about, thought I to myself—the man's a human being just as I am: he has just as much reason to fear me, as I have to be afraid of him. Better sleep with a sober cannibal than a drunken Christian. "Landlord," said I, "tell him to stash his tomahawk there, or pipe, or whatever you call it; tell him to stop smoking, in short, and I will turn in with him. But I don't fancy having a man smoking in bed with me. It's dangerous. Besides, I ain't insured." This being told to Queequeg, he at once complied, and again politely motioned me to get into bed—rolling over to one side as much as to say—"I won't touch a leg of ye." "Good night, landlord," said I, "you may go." I turned in, and never slept better in my life. Upon waking next morning about daylight, I found Queequeg's arm thrown over me in the most loving and affectionate manner. You had almost thought I had been his wife. The counterpane was of patchwork, full of odd little parti-coloured squares and triangles; and this arm of his tattooed all over with an interminable Cretan labyrinth of a figure, no two parts of which were of one precise shade—owing I suppose to his keeping his arm at sea unmethodically in sun and shade, his shirt sleeves irregularly rolled up at various times—this same arm of his, I say, looked for all the world like a strip of that same patchwork quilt. Indeed, partly lying on it as the arm did when I first awoke, I could hardly tell it from the quilt, they so blended their hues together; and it was only by the sense of weight and pressure that I could tell that Queequeg was hugging""" expected.block2 = (1, 0, 1024) expected.size2 = 1990 exchange1 = (req, expected) self.current_mid += 1 self.server_mid += 1 self._test_with_client([exchange1])
def error(self, mid, host, port): """ Handler of errors. Send an error message to the client. :param mid: the mid of the response that generates the error. :param host: the host of the server. :param port: the port of the server. """ key = hash(str(host) + str(port) + str(mid)) request = self._forward_mid.get(key) if request is not None: response = Response() host, port = request.source response.destination = request.source response.token = request.token response._mid = self._currentMID response.type = defines.inv_types["NON"] response.code = defines.responses["GATEWAY_TIMEOUT"] key = hash(str(host) + str(port) + str(response.token)) del self._forward[key] key = hash(str(host) + str(port) + str(mid)) try: del self._forward_mid[key] except KeyError: # log.err("MID has not been deleted") pass self.send(response, host, port)
def test_get_not_found(self): print "\nGET /not_found\n" args = ("/not_found",) kwargs = {} path = args[0] req = Request() for key in kwargs: o = Option() o.number = defines.inv_options[key] o.value = kwargs[key] req.add_option(o) req.code = defines.inv_codes['GET'] req.uri_path = path req.type = defines.inv_types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.inv_types["ACK"] expected._mid = self.current_mid expected.code = defines.responses["NOT_FOUND"] expected.token = None expected.payload = None self.current_mid += 1 self._test(req, expected)
def prepare_notification(self, t): """ Create the notification message. :type t: (resource, request, old_response) :param t: the arguments of the notification message :return: the notification message """ resource, request, old_response = t assert(isinstance(resource, Resource)) response = Response() response.destination = old_response.destination response.token = old_response.token option = Option() option.number = defines.inv_options['Observe'] option.value = resource.observe_count response.add_option(option) method = getattr(resource, 'render_GET', None) if hasattr(method, '__call__'): # Render_GET response.code = defines.responses['CONTENT'] resource = method(request) response.payload = resource.payload # Blockwise response, resource = self._parent.blockwise_response(request, response, resource) host, port = request.source key = hash(str(host) + str(port) + str(request.token)) if key in self._parent.blockwise: del self._parent.blockwise[key] # Reliability request.acknowledged = True response = self._parent.message_layer.reliability_response(request, response) # Matcher response = self._parent.message_layer.matcher_response(response) return resource, request, response else: response.code = defines.responses['METHOD_NOT_ALLOWED'] # Blockwise response, resource = self._parent.blockwise_response(request, response, resource) host, port = request.source key = hash(str(host) + str(port) + str(request.token)) if key in self._parent.blockwise: del self._parent.blockwise[key] # Reliability request.acknowledged = True response = self._parent.message_layer.reliability_response(request, response) # Matcher response = self._parent.message_layer.matcher_response(response) return resource, request, response
def handle_get(self, request): """ Handles a GET request. :param request: the request :return: the response """ path = str("/" + request.uri_path) response = Response() response.destination = request.source if path == defines.DISCOVERY_URL: response = self._parent.resource_layer.discover(request, response) else: try: resource = self._parent.root[path] except KeyError: resource = None if resource is None: # Not Found response = self._parent.send_error(request, response, 'NOT_FOUND') else: response = self._parent.resource_layer.get_resource(request, response, resource) return response
def finish_request(self, request, client_address): host = client_address[0] port = client_address[1] data = request[0] self.socket = request[1] # log.msg("Datagram received from " + str(host) + ":" + str(port)) serializer = Serializer() message = serializer.deserialize(data, host, port) # print "Message received from " + host + ":" + str(port) # print "----------------------------------------" # print message # print "----------------------------------------" if isinstance(message, Request): # log.msg("Received request") ret = self.request_layer.handle_request(message) if isinstance(ret, Request): self.forward_request(ret) elif isinstance(message, Response): # log.err("Received response") rst = Message.new_rst(message) rst = self.message_layer.matcher_response(rst) # log.msg("Send RST") self.send(rst, host, port) elif isinstance(message, tuple): message, error = message response = Response() response.destination = (host, port) response.code = defines.responses[error] response = self.message_layer.reliability_response(message, response) response = self.message_layer.matcher_response(response) # log.msg("Send Error") self.send(response, host, port) elif message is not None: # ACK or RST # log.msg("Received ACK or RST") self.message_layer.handle_message(message)
def handle_delete(self, request): """ Handles a DELETE request. :param request: the request :return: the response """ path = str("/" + request.uri_path) try: resource = self._parent.root[path] except KeyError: resource = None response = Response() response.destination = request.source if resource is None: # Create request response = self._parent.send_error(request, response, 'NOT_FOUND') return response else: # Delete response = self._parent.resource_layer.delete_resource(request, response, path) return response
def receive_request(self, transaction): """ :type transaction: Transaction :param transaction: :rtype : Transaction """ uri = transaction.request.proxy_uri host, port, path = parse_uri(uri) path = str("/" + path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token return self._forward_request(transaction, (host, port), path)
def test_duplicate_not_completed(self): print "TEST_DUPLICATE_NOT_COMPLETED" path = "/long" 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 = None expected.token = None expected2 = Response() expected2.type = defines.Types["CON"] expected2._mid = None expected2.code = defines.Codes.CONTENT.number expected2.token = None self.current_mid += 1 self._test_plugtest([(req, None), (req, expected), (None, expected2)])
def incomplete(transaction): """ Notifies incomplete blockwise exchange. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction """ transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token transaction.response.code = defines.Codes.REQUEST_ENTITY_INCOMPLETE.number return transaction
def receive_request(self, transaction): """ Setup the transaction for forwarding purposes on Forward Proxies. :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction """ uri = transaction.request.proxy_uri if uri is None: transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token transaction.response.type = defines.Types["RST"] transaction.response.code = defines.Codes.BAD_REQUEST.number return transaction host, port, path = parse_uri(uri) path = str("/" + path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token return self._forward_request(transaction, (host, port), path)
def test_no_response(self): print "TEST_NO_RESPONSE" path = "/long" 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 = None expected.token = None expected2 = Response() expected2.type = defines.Types["CON"] expected2._mid = None expected2.code = defines.Codes.CONTENT.number expected2.token = None self.current_mid += 1 self._test_plugtest([(req, expected), (None, expected2), (None, expected2), (None, expected2)])
def error(transaction, code): # pragma: no cover """ Notifies generic error on blockwise exchange. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction """ transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.type = defines.Types["RST"] transaction.response.token = transaction.request.token transaction.response.code = code return transaction
def _handle_post(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 # Create request transaction = self._server.resourceLayer.create_resource( path, transaction) return transaction
def receive_request(self, transaction): """ Setup the transaction for forwarding purposes on Forward Proxies. :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction """ uri = transaction.request.proxy_uri host, port, path = parse_uri(uri) path = str("/" + path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token return self._forward_request(transaction, (host, port), path)
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 # Create request transaction = self._server.resourceLayer.create_resource(path, transaction) return transaction
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 if path == "/": transaction.response.code = defines.Codes.FORBIDDEN.number return transaction return self._server.resourceLayer.update_resource(transaction)
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 = """</large>;</large-update>;</long>;</obs>;obs,</query>;rt="Type1";sz="13",</seg1>;rt="Type1";sz="13",</seg1/seg2>;rt="Type1";sz="13",</seg1/seg2/seg3>;rt="Type1";sz="13",</separate>;ct=0;if="separate",</test>;rt="Type1";sz="13",""" self.current_mid += 1 self._test_with_client([(req, expected)])
def test_td_coap_block_01_client(self): print "TD_COAP_BLOCK_01" path = "/large" req = Request() req.code = defines.Codes.GET.number req.uri_path = path req.type = defines.Types["CON"] req._mid = None req.destination = self.server_address req.block2 = (0, 0, 1024) expected = Response() expected.type = defines.Types["ACK"] expected._mid = None 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 to me with his tomahawk, and throwing the clothes to one side. He really did this in not only a civil but a really kind and charitable way. I stood looking at him a moment. For all his tattooings he was on the whole a clean, comely looking cannibal. What's all this fuss I have been making about, thought I to myself—the man's a human being just as I am: he has just as much reason to fear me, as I have to be afraid of him. Better sleep with a sober cannibal than a drunken Christian. "Landlord," said I, "tell him to stash his tomahawk there, or pipe, or whatever you call it; tell him to stop smoking, in short, and I will turn in with him. But I don't fancy having a man smoking in bed with me. It's dangerous. Besides, I ain't insured." This being told to Queequeg, he at once complied, and again politely motioned me to get into bed—rolling over to one side as much as to say—"I won't touch a leg of ye." "Good night, landlord," said I, "you may go." I turned in, and never slept better in my life. Upon waking next morning about daylight, I found Queequeg's arm thrown over me in the most loving and affectionate manner. You had almost thought I had been his wife. The counterpane was of patchwork, full of odd little parti-coloured squares and triangles; and this arm of his tattooed all over with an interminable Cretan labyrinth of a figure, no two parts of which were of one precise shade—owing I suppose to his keeping his arm at sea unmethodically in sun and shade, his shirt sleeves irregularly rolled up at various times—this same arm of his, I say, looked for all the world like a strip of that same patchwork quilt. Indeed, partly lying on it as the arm did when I first awoke, I could hardly tell it from the quilt, they so blended their hues together; and it was only by the sense of weight and pressure that I could tell that Queequeg was hugging""" expected.block2 = (1, 0, 1024) exchange1 = (req, expected) self.current_mid += 1 self.server_mid += 1 self._test_with_client([exchange1])
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)])
def test_td_coap_core_10(self): print("TD_COAP_CORE_10") 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 req.token = "ciao" 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" expected.token = "ciao" self.current_mid += 1 self._test_with_client([(req, expected)])
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_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)])
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
def test_td_coap_core_06(self): print("TD_COAP_CORE_06") path = "/test_post" req = Request() req.code = defines.Codes.POST.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.CREATED.number expected.token = None expected.payload = None expected.location_path = "/test_post" self.current_mid += 1 self._test_with_client([(req, expected)])
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)])
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>;</large-update>;</seg1/seg2/seg3>;rt="Type1",</large>;</seg1/seg2>;rt="Type1",</test>;rt="Type1",</obs>;</long>;</seg1>;rt="Type1",</query>;rt="Type1",""" self.current_mid += 1 self._test_with_client([(req, expected)])
def test_td_coap_link_02(self): print "TD_COAP_LINK_02" path = "/.well-known/core" req = Request() req.code = defines.inv_codes['GET'] req.uri_path = path req.type = defines.inv_types["CON"] req._mid = self.current_mid req.destination = self.server_address req.add_query("rt=Type1") expected = Response() expected.type = defines.inv_types["ACK"] expected._mid = self.current_mid expected.code = defines.responses["CONTENT"] expected.token = None option = Option() option.number = defines.inv_options["Content-Type"] option.value = defines.inv_content_types["application/link-format"] expected.add_option(option) expected.payload = """</seg1/seg2/seg3>;rt="Type1",</seg1/seg2>;rt="Type1",</test>;rt="Type1",</seg1>;rt="Type1",</query>;rt="Type1",""" self.current_mid += 1 self._test_plugtest([(req, expected)])
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.CREATED.number expected.token = None expected.payload = None expected.location_path = "/obs" self.current_mid += 1 self._test_with_client([(req, expected)])