idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
21,800 | def _retransmit ( self , transaction , message , future_time , retransmit_count ) : with transaction : while retransmit_count < defines . MAX_RETRANSMIT and ( not message . acknowledged and not message . rejected ) and not self . stopped . isSet ( ) : transaction . retransmit_stop . wait ( timeout = future_time ) if not message . acknowledged and not message . rejected and not self . stopped . isSet ( ) : retransmit_count += 1 future_time *= 2 self . send_datagram ( message ) if message . acknowledged or message . rejected : message . timeouted = False else : logger . warning ( "Give up on message {message}" . format ( message = message . line_print ) ) message . timeouted = True if message . observe is not None : self . _observeLayer . remove_subscriber ( message ) try : self . to_be_stopped . remove ( transaction . retransmit_stop ) except ValueError : pass transaction . retransmit_stop = None transaction . retransmit_thread = None | Thread function to retransmit the message in the future |
21,801 | def _start_separate_timer ( self , transaction ) : t = threading . Timer ( defines . ACK_TIMEOUT , self . _send_ack , ( transaction , ) ) t . start ( ) return t | Start a thread to handle separate mode . |
21,802 | def parse_config ( self ) : tree = ElementTree . parse ( self . file_xml ) root = tree . getroot ( ) for server in root . findall ( 'server' ) : destination = server . text name = server . get ( "name" ) self . discover_remote ( destination , name ) | Parse the xml file with remote servers and discover resources on each found server . |
21,803 | def discover_remote ( self , destination , name ) : assert ( isinstance ( destination , str ) ) if destination . startswith ( "[" ) : split = destination . split ( "]" , 1 ) host = split [ 0 ] [ 1 : ] port = int ( split [ 1 ] [ 1 : ] ) else : split = destination . split ( ":" , 1 ) host = split [ 0 ] port = int ( split [ 1 ] ) server = ( host , port ) client = HelperClient ( server ) response = client . discover ( ) client . stop ( ) self . discover_remote_results ( response , name ) | Discover resources on remote servers . |
21,804 | def discover_remote_results ( self , response , name ) : host , port = response . source if response . code == defines . Codes . CONTENT . number : resource = Resource ( 'server' , self , visible = True , observable = False , allow_children = True ) self . add_resource ( name , resource ) self . _mapping [ name ] = ( host , port ) self . parse_core_link_format ( response . payload , name , ( host , port ) ) else : logger . error ( "Server: " + response . source + " isn't valid." ) | Create a new remote server resource for each valid discover response . |
21,805 | def parse_core_link_format ( self , link_format , base_path , remote_server ) : while len ( link_format ) > 0 : pattern = "<([^>]*)>;" result = re . match ( pattern , link_format ) path = result . group ( 1 ) path = path . split ( "/" ) path = path [ 1 : ] [ 0 ] link_format = link_format [ result . end ( 1 ) + 2 : ] pattern = "([^<,])*" result = re . match ( pattern , link_format ) attributes = result . group ( 0 ) dict_att = { } if len ( attributes ) > 0 : attributes = attributes . split ( ";" ) for att in attributes : a = att . split ( "=" ) if len ( a ) > 1 : dict_att [ a [ 0 ] ] = a [ 1 ] else : dict_att [ a [ 0 ] ] = a [ 0 ] link_format = link_format [ result . end ( 0 ) + 1 : ] resource = RemoteResource ( 'server' , remote_server , path , coap_server = self , visible = True , observable = False , allow_children = True ) resource . attributes = dict_att self . add_resource ( base_path + "/" + path , resource ) logger . info ( self . root . dump ( ) ) | Parse discovery results . |
21,806 | def receive_datagram ( self , args ) : data , client_address = args serializer = Serializer ( ) message = serializer . deserialize ( data , client_address ) if isinstance ( message , int ) : logger . error ( "receive_datagram - BAD REQUEST" ) rst = Message ( ) rst . destination = client_address rst . type = defines . Types [ "RST" ] rst . code = message self . send_datagram ( rst ) return logger . debug ( "receive_datagram - " + str ( message ) ) if isinstance ( message , Request ) : transaction = self . _messageLayer . receive_request ( message ) if transaction . request . duplicated and transaction . completed : logger . debug ( "message duplicated,transaction completed" ) transaction = self . _observeLayer . send_response ( transaction ) transaction = self . _blockLayer . send_response ( transaction ) transaction = self . _messageLayer . send_response ( transaction ) self . send_datagram ( transaction . response ) return elif transaction . request . duplicated and not transaction . completed : logger . debug ( "message duplicated,transaction NOT completed" ) self . _send_ack ( transaction ) return transaction . separate_timer = self . _start_separate_timer ( transaction ) transaction = self . _blockLayer . receive_request ( transaction ) if transaction . block_transfer : self . _stop_separate_timer ( transaction . separate_timer ) transaction = self . _messageLayer . send_response ( transaction ) self . send_datagram ( transaction . response ) return transaction = self . _observeLayer . receive_request ( transaction ) if self . _cacheLayer is not None : transaction = self . _cacheLayer . receive_request ( transaction ) if transaction . cacheHit is False : logger . debug ( transaction . request ) transaction = self . _forwardLayer . receive_request_reverse ( transaction ) logger . debug ( transaction . response ) transaction = self . _observeLayer . send_response ( transaction ) transaction = self . _blockLayer . send_response ( transaction ) transaction = self . _cacheLayer . send_response ( transaction ) else : transaction = self . _forwardLayer . receive_request_reverse ( transaction ) transaction = self . _observeLayer . send_response ( transaction ) transaction = self . _blockLayer . send_response ( transaction ) self . _stop_separate_timer ( transaction . separate_timer ) transaction = self . _messageLayer . send_response ( transaction ) if transaction . response is not None : if transaction . response . type == defines . Types [ "CON" ] : self . _start_retrasmission ( transaction , transaction . response ) self . send_datagram ( transaction . response ) elif isinstance ( message , Message ) : transaction = self . _messageLayer . receive_empty ( message ) if transaction is not None : transaction = self . _blockLayer . receive_empty ( message , transaction ) self . _observeLayer . receive_empty ( message , transaction ) else : logger . error ( "Received response from %s" , message . source ) | Handle messages coming from the udp socket . |
21,807 | def _wait_response ( self , message ) : if message is None or message . code != defines . Codes . CONTINUE . number : self . queue . put ( message ) | Private function to get responses from the server . |
21,808 | def _thread_body ( self , request , callback ) : self . protocol . send_message ( request ) while not self . protocol . stopped . isSet ( ) : response = self . queue . get ( block = True ) callback ( response ) | Private function . Send a request wait for response and call the callback function . |
21,809 | def cancel_observing ( self , response , send_rst ) : if send_rst : message = Message ( ) message . destination = self . server message . code = defines . Codes . EMPTY . number message . type = defines . Types [ "RST" ] message . token = response . token message . mid = response . mid self . protocol . send_message ( message ) self . stop ( ) | Delete observing on the remote server . |
21,810 | def observe ( self , path , callback , timeout = None , ** kwargs ) : request = self . mk_request ( defines . Codes . GET , path ) request . observe = 0 for k , v in kwargs . items ( ) : if hasattr ( request , k ) : setattr ( request , k , v ) return self . send_request ( request , callback , timeout ) | Perform a GET with observe on a certain path . |
21,811 | def delete ( self , path , callback = None , timeout = None , ** kwargs ) : request = self . mk_request ( defines . Codes . DELETE , path ) for k , v in kwargs . items ( ) : if hasattr ( request , k ) : setattr ( request , k , v ) return self . send_request ( request , callback , timeout ) | Perform a DELETE on a certain path . |
21,812 | def post ( self , path , payload , callback = None , timeout = None , no_response = False , ** kwargs ) : request = self . mk_request ( defines . Codes . POST , path ) request . token = generate_random_token ( 2 ) request . payload = payload if no_response : request . add_no_response ( ) request . type = defines . Types [ "NON" ] for k , v in kwargs . items ( ) : if hasattr ( request , k ) : setattr ( request , k , v ) return self . send_request ( request , callback , timeout , no_response = no_response ) | Perform a POST on a certain path . |
21,813 | def discover ( self , callback = None , timeout = None , ** kwargs ) : request = self . mk_request ( defines . Codes . GET , defines . DISCOVERY_URL ) for k , v in kwargs . items ( ) : if hasattr ( request , k ) : setattr ( request , k , v ) return self . send_request ( request , callback , timeout ) | Perform a Discover request on the server . |
21,814 | def send_request ( self , request , callback = None , timeout = None , no_response = False ) : if callback is not None : thread = threading . Thread ( target = self . _thread_body , args = ( request , callback ) ) thread . start ( ) else : self . protocol . send_message ( request ) if no_response : return try : response = self . queue . get ( block = True , timeout = timeout ) except Empty : response = None return response | Send a request to the remote server . |
21,815 | def run ( self ) : server_address = ( self . ip , self . hc_port ) hc_proxy = HTTPServer ( server_address , HCProxyHandler ) logger . info ( 'Starting HTTP-CoAP Proxy...' ) hc_proxy . serve_forever ( ) | Start the proxy . |
21,816 | def get_formatted_path ( path ) : if path [ 0 ] != '/' : path = '/' + path if path [ - 1 ] != '/' : path = '{0}/' . format ( path ) return path | Uniform the path string |
21,817 | def get_payload ( self ) : temp = self . get_uri_as_list ( ) query_string = temp [ 4 ] if query_string == "" : return None query_string_as_list = str . split ( query_string , "=" ) return query_string_as_list [ 1 ] | Return the query string of the uri . |
21,818 | def do_initial_operations ( self ) : if not self . request_hc_path_corresponds ( ) : return self . set_coap_uri ( ) self . client = HelperClient ( server = ( self . coap_uri . host , self . coap_uri . port ) ) | Setup the client for interact with remote server |
21,819 | def do_GET ( self ) : self . do_initial_operations ( ) coap_response = self . client . get ( self . coap_uri . path ) self . client . stop ( ) logger . info ( "Server response: %s" , coap_response . pretty_print ( ) ) self . set_http_response ( coap_response ) | Perform a GET request |
21,820 | def do_HEAD ( self ) : self . do_initial_operations ( ) coap_response = self . client . get ( self . coap_uri . path ) self . client . stop ( ) logger . info ( "Server response: %s" , coap_response . pretty_print ( ) ) self . set_http_header ( coap_response ) | Perform a HEAD request |
21,821 | def do_POST ( self ) : self . do_initial_operations ( ) payload = self . coap_uri . get_payload ( ) if payload is None : logger . error ( "BAD POST REQUEST" ) self . send_error ( BAD_REQUEST ) return coap_response = self . client . post ( self . coap_uri . path , payload ) self . client . stop ( ) logger . info ( "Server response: %s" , coap_response . pretty_print ( ) ) self . set_http_response ( coap_response ) | Perform a POST request |
21,822 | def do_PUT ( self ) : self . do_initial_operations ( ) payload = self . coap_uri . get_payload ( ) if payload is None : logger . error ( "BAD PUT REQUEST" ) self . send_error ( BAD_REQUEST ) return logger . debug ( payload ) coap_response = self . client . put ( self . coap_uri . path , payload ) self . client . stop ( ) logger . debug ( "Server response: %s" , coap_response . pretty_print ( ) ) self . set_http_response ( coap_response ) | Perform a PUT request |
21,823 | def do_DELETE ( self ) : self . do_initial_operations ( ) coap_response = self . client . delete ( self . coap_uri . path ) self . client . stop ( ) logger . debug ( "Server response: %s" , coap_response . pretty_print ( ) ) self . set_http_response ( coap_response ) | Perform a DELETE request |
21,824 | def request_hc_path_corresponds ( self ) : uri_path = self . path . split ( COAP_PREFACE ) request_hc_path = uri_path [ 0 ] logger . debug ( "HCPATH: %s" , hc_path ) logger . debug ( "URI: %s" , request_hc_path ) if hc_path != request_hc_path : return False else : return True | Tells if the hc path of the request corresponds to that specified by the admin |
21,825 | def set_http_header ( self , coap_response ) : logger . debug ( ( "Server: %s\n" "codice risposta: %s\n" "PROXED: %s\n" "payload risposta: %s" ) , coap_response . source , coap_response . code , CoAP_HTTP [ Codes . LIST [ coap_response . code ] . name ] , coap_response . payload ) self . send_response ( int ( CoAP_HTTP [ Codes . LIST [ coap_response . code ] . name ] ) ) self . send_header ( 'Content-type' , 'text/html' ) self . end_headers ( ) | Sets http headers . |
21,826 | def set_http_body ( self , coap_response ) : if coap_response . payload is not None : body = "<html><body><h1>" , coap_response . payload , "</h1></body></html>" self . wfile . write ( "" . join ( body ) ) else : self . wfile . write ( "<html><body><h1>None</h1></body></html>" ) | Set http body . |
21,827 | def parse_blockwise ( value ) : length = byte_len ( value ) if length == 1 : num = value & 0xF0 num >>= 4 m = value & 0x08 m >>= 3 size = value & 0x07 elif length == 2 : num = value & 0xFFF0 num >>= 4 m = value & 0x0008 m >>= 3 size = value & 0x0007 else : num = value & 0xFFFFF0 num >>= 4 m = value & 0x000008 m >>= 3 size = value & 0x000007 return num , int ( m ) , pow ( 2 , ( size + 4 ) ) | Parse Blockwise option . |
21,828 | def byte_len ( int_type ) : length = 0 while int_type : int_type >>= 1 length += 1 if length > 0 : if length % 8 != 0 : length = int ( length / 8 ) + 1 else : length = int ( length / 8 ) return length | Get the number of byte needed to encode the int passed . |
21,829 | def value ( self ) : if type ( self . _value ) is None : self . _value = bytearray ( ) opt_type = defines . OptionRegistry . LIST [ self . _number ] . value_type if opt_type == defines . INTEGER : if byte_len ( self . _value ) > 0 : return int ( self . _value ) else : return defines . OptionRegistry . LIST [ self . _number ] . default return self . _value | Return the option value . |
21,830 | def value ( self , value ) : opt_type = defines . OptionRegistry . LIST [ self . _number ] . value_type if opt_type == defines . INTEGER : if type ( value ) is not int : value = int ( value ) if byte_len ( value ) == 0 : value = 0 elif opt_type == defines . STRING : if type ( value ) is not str : value = str ( value ) elif opt_type == defines . OPAQUE : if type ( value ) is bytes : pass else : if value is not None : value = bytes ( value , "utf-8" ) self . _value = value | Set the value of the option . |
21,831 | def length ( self ) : if isinstance ( self . _value , int ) : return byte_len ( self . _value ) if self . _value is None : return 0 return len ( self . _value ) | Return the value length |
21,832 | def is_safe ( self ) : if self . _number == defines . OptionRegistry . URI_HOST . number or self . _number == defines . OptionRegistry . URI_PORT . number or self . _number == defines . OptionRegistry . URI_PATH . number or self . _number == defines . OptionRegistry . MAX_AGE . number or self . _number == defines . OptionRegistry . URI_QUERY . number or self . _number == defines . OptionRegistry . PROXY_URI . number or self . _number == defines . OptionRegistry . PROXY_SCHEME . number : return False return True | Check if the option is safe . |
21,833 | def get_option_flags ( option_num ) : opt_bytes = array . array ( 'B' , '\0\0' ) if option_num < 256 : s = struct . Struct ( "!B" ) s . pack_into ( opt_bytes , 0 , option_num ) else : s = struct . Struct ( "H" ) s . pack_into ( opt_bytes , 0 , option_num ) critical = ( opt_bytes [ 0 ] & 0x01 ) > 0 unsafe = ( opt_bytes [ 0 ] & 0x02 ) > 0 nocache = ( ( opt_bytes [ 0 ] & 0x1e ) == 0x1c ) return ( critical , unsafe , nocache ) | Get Critical UnSafe NoCacheKey flags from the option number as per RFC 7252 section 5 . 4 . 6 |
21,834 | def read_option_value_from_nibble ( nibble , pos , values ) : if nibble <= 12 : return nibble , pos elif nibble == 13 : tmp = struct . unpack ( "!B" , values [ pos ] . to_bytes ( 1 , "big" ) ) [ 0 ] + 13 pos += 1 return tmp , pos elif nibble == 14 : s = struct . Struct ( "!H" ) tmp = s . unpack_from ( values [ pos : ] . to_bytes ( 2 , "big" ) ) [ 0 ] + 269 pos += 2 return tmp , pos else : raise AttributeError ( "Unsupported option nibble " + str ( nibble ) ) | Calculates the value used in the extended option fields . |
21,835 | def read_option_value_len_from_byte ( byte , pos , values ) : h_nibble = ( byte & 0xF0 ) >> 4 l_nibble = byte & 0x0F value = 0 length = 0 if h_nibble <= 12 : value = h_nibble elif h_nibble == 13 : value = struct . unpack ( "!B" , values [ pos ] . to_bytes ( 1 , "big" ) ) [ 0 ] + 13 pos += 1 elif h_nibble == 14 : s = struct . Struct ( "!H" ) value = s . unpack_from ( values [ pos : ] . to_bytes ( 2 , "big" ) ) [ 0 ] + 269 pos += 2 else : raise AttributeError ( "Unsupported option number nibble " + str ( h_nibble ) ) if l_nibble <= 12 : length = l_nibble elif l_nibble == 13 : length = struct . unpack ( "!B" , values [ pos ] . to_bytes ( 1 , "big" ) ) [ 0 ] + 13 pos += 1 elif l_nibble == 14 : length = s . unpack_from ( values [ pos : ] . to_bytes ( 2 , "big" ) ) [ 0 ] + 269 pos += 2 else : raise AttributeError ( "Unsupported option length nibble " + str ( l_nibble ) ) return value , length , pos | Calculates the value and length used in the extended option fields . |
21,836 | def convert_to_raw ( number , value , length ) : opt_type = defines . OptionRegistry . LIST [ number ] . value_type if length == 0 and opt_type != defines . INTEGER : return bytes ( ) elif length == 0 and opt_type == defines . INTEGER : return 0 elif opt_type == defines . STRING : if isinstance ( value , bytes ) : return value . decode ( "utf-8" ) elif opt_type == defines . OPAQUE : if isinstance ( value , bytes ) : return value else : return bytes ( value , "utf-8" ) if isinstance ( value , tuple ) : value = value [ 0 ] if isinstance ( value , str ) : value = str ( value ) if isinstance ( value , str ) : return bytearray ( value , "utf-8" ) elif isinstance ( value , int ) : return value else : return bytearray ( value ) | Get the value of an option as a ByteArray . |
21,837 | def as_sorted_list ( options ) : if len ( options ) > 0 : options = sorted ( options , key = lambda o : o . number ) return options | Returns all options in a list sorted according to their option numbers . |
21,838 | def int_to_words ( int_val , num_words = 4 , word_size = 32 ) : max_int = 2 ** ( word_size * num_words ) - 1 max_word_size = 2 ** word_size - 1 if not 0 <= int_val <= max_int : raise AttributeError ( 'integer %r is out of bounds!' % hex ( int_val ) ) words = [ ] for _ in range ( num_words ) : word = int_val & max_word_size words . append ( int ( word ) ) int_val >>= word_size words . reverse ( ) return words | Convert a int value to bytes . |
21,839 | def str_append_hash ( * args ) : ret_hash = "" for i in args : ret_hash += str ( i ) . lower ( ) return hash ( ret_hash ) | Convert each argument to a lower case string appended then hash |
21,840 | def fetch_mid ( self ) : current_mid = self . _current_mid self . _current_mid += 1 self . _current_mid %= 65535 return current_mid | Gets the next valid MID . |
21,841 | def receive_request ( self , request ) : logger . debug ( "receive_request - " + str ( request ) ) try : host , port = request . source except AttributeError : return key_mid = str_append_hash ( host , port , request . mid ) key_token = str_append_hash ( host , port , request . token ) if key_mid in list ( self . _transactions . keys ( ) ) : self . _transactions [ key_mid ] . request . duplicated = True transaction = self . _transactions [ key_mid ] else : request . timestamp = time . time ( ) transaction = Transaction ( request = request , timestamp = request . timestamp ) with transaction : self . _transactions [ key_mid ] = transaction self . _transactions_token [ key_token ] = transaction return transaction | Handle duplicates and store received messages . |
21,842 | def receive_response ( self , response ) : logger . debug ( "receive_response - " + str ( response ) ) try : host , port = response . source except AttributeError : return key_mid = str_append_hash ( host , port , response . mid ) key_mid_multicast = str_append_hash ( defines . ALL_COAP_NODES , port , response . mid ) key_token = str_append_hash ( host , port , response . token ) key_token_multicast = str_append_hash ( defines . ALL_COAP_NODES , port , response . token ) if key_mid in list ( self . _transactions . keys ( ) ) : transaction = self . _transactions [ key_mid ] if response . token != transaction . request . token : logger . warning ( "Tokens does not match - response message " + str ( host ) + ":" + str ( port ) ) return None , False elif key_token in self . _transactions_token : transaction = self . _transactions_token [ key_token ] elif key_mid_multicast in list ( self . _transactions . keys ( ) ) : transaction = self . _transactions [ key_mid_multicast ] elif key_token_multicast in self . _transactions_token : transaction = self . _transactions_token [ key_token_multicast ] if response . token != transaction . request . token : logger . warning ( "Tokens does not match - response message " + str ( host ) + ":" + str ( port ) ) return None , False else : logger . warning ( "Un-Matched incoming response message " + str ( host ) + ":" + str ( port ) ) return None , False send_ack = False if response . type == defines . Types [ "CON" ] : send_ack = True transaction . request . acknowledged = True transaction . completed = True transaction . response = response if transaction . retransmit_stop is not None : transaction . retransmit_stop . set ( ) return transaction , send_ack | Pair responses with requests . |
21,843 | def receive_empty ( self , message ) : logger . debug ( "receive_empty - " + str ( message ) ) try : host , port = message . source except AttributeError : return key_mid = str_append_hash ( host , port , message . mid ) key_mid_multicast = str_append_hash ( defines . ALL_COAP_NODES , port , message . mid ) key_token = str_append_hash ( host , port , message . token ) key_token_multicast = str_append_hash ( defines . ALL_COAP_NODES , port , message . token ) if key_mid in list ( self . _transactions . keys ( ) ) : transaction = self . _transactions [ key_mid ] elif key_token in self . _transactions_token : transaction = self . _transactions_token [ key_token ] elif key_mid_multicast in list ( self . _transactions . keys ( ) ) : transaction = self . _transactions [ key_mid_multicast ] elif key_token_multicast in self . _transactions_token : transaction = self . _transactions_token [ key_token_multicast ] else : logger . warning ( "Un-Matched incoming empty message " + str ( host ) + ":" + str ( port ) ) return None if message . type == defines . Types [ "ACK" ] : if not transaction . request . acknowledged : transaction . request . acknowledged = True elif ( transaction . response is not None ) and ( not transaction . response . acknowledged ) : transaction . response . acknowledged = True elif message . type == defines . Types [ "RST" ] : if not transaction . request . acknowledged : transaction . request . rejected = True elif not transaction . response . acknowledged : transaction . response . rejected = True elif message . type == defines . Types [ "CON" ] : logger . debug ( "Implicit ACK on received CON for waiting transaction" ) transaction . request . acknowledged = True else : logger . warning ( "Unhandled message type..." ) if transaction . retransmit_stop is not None : transaction . retransmit_stop . set ( ) return transaction | Pair ACKs with requests . |
21,844 | def send_request ( self , request ) : logger . debug ( "send_request - " + str ( request ) ) assert isinstance ( request , Request ) try : host , port = request . destination except AttributeError : return request . timestamp = time . time ( ) transaction = Transaction ( request = request , timestamp = request . timestamp ) if transaction . request . type is None : transaction . request . type = defines . Types [ "CON" ] if transaction . request . mid is None : transaction . request . mid = self . fetch_mid ( ) key_mid = str_append_hash ( host , port , request . mid ) self . _transactions [ key_mid ] = transaction key_token = str_append_hash ( host , port , request . token ) self . _transactions_token [ key_token ] = transaction return self . _transactions [ key_mid ] | Create the transaction and fill it with the outgoing request . |
21,845 | def send_response ( self , transaction ) : logger . debug ( "send_response - " + str ( transaction . response ) ) if transaction . response . type is None : if transaction . request . type == defines . Types [ "CON" ] and not transaction . request . acknowledged : transaction . response . type = defines . Types [ "ACK" ] transaction . response . mid = transaction . request . mid transaction . response . acknowledged = True transaction . completed = True elif transaction . request . type == defines . Types [ "NON" ] : transaction . response . type = defines . Types [ "NON" ] else : transaction . response . type = defines . Types [ "CON" ] transaction . response . token = transaction . request . token if transaction . response . mid is None : transaction . response . mid = self . fetch_mid ( ) try : host , port = transaction . response . destination except AttributeError : return key_mid = str_append_hash ( host , port , transaction . response . mid ) self . _transactions [ key_mid ] = transaction transaction . request . acknowledged = True return transaction | Set the type the token and eventually the MID for the outgoing response |
21,846 | def send_empty ( self , transaction , related , message ) : logger . debug ( "send_empty - " + str ( message ) ) if transaction is None : try : host , port = message . destination except AttributeError : return key_mid = str_append_hash ( host , port , message . mid ) key_token = str_append_hash ( host , port , message . token ) if key_mid in self . _transactions : transaction = self . _transactions [ key_mid ] related = transaction . response elif key_token in self . _transactions_token : transaction = self . _transactions_token [ key_token ] related = transaction . response else : return message if message . type == defines . Types [ "ACK" ] : if transaction . request == related : transaction . request . acknowledged = True transaction . completed = True message . mid = transaction . request . mid message . code = 0 message . destination = transaction . request . source elif transaction . response == related : transaction . response . acknowledged = True transaction . completed = True message . mid = transaction . response . mid message . code = 0 message . token = transaction . response . token message . destination = transaction . response . source elif message . type == defines . Types [ "RST" ] : if transaction . request == related : transaction . request . rejected = True message . _mid = transaction . request . mid if message . mid is None : message . mid = self . fetch_mid ( ) message . code = 0 message . token = transaction . request . token message . destination = transaction . request . source elif transaction . response == related : transaction . response . rejected = True transaction . completed = True message . _mid = transaction . response . mid if message . mid is None : message . mid = self . fetch_mid ( ) message . code = 0 message . token = transaction . response . token message . destination = transaction . response . source return message | Manage ACK or RST related to a transaction . Sets if the transaction has been acknowledged or rejected . |
21,847 | def location_path ( self ) : value = [ ] for option in self . options : if option . number == defines . OptionRegistry . LOCATION_PATH . number : value . append ( str ( option . value ) ) return "/" . join ( value ) | Return the Location - Path of the response . |
21,848 | def location_path ( self , path ) : path = path . strip ( "/" ) tmp = path . split ( "?" ) path = tmp [ 0 ] paths = path . split ( "/" ) for p in paths : option = Option ( ) option . number = defines . OptionRegistry . LOCATION_PATH . number option . value = p self . add_option ( option ) | Set the Location - Path of the response . |
21,849 | def location_query ( self ) : value = [ ] for option in self . options : if option . number == defines . OptionRegistry . LOCATION_QUERY . number : value . append ( option . value ) return value | Return the Location - Query of the response . |
21,850 | def location_query ( self , value ) : del self . location_query queries = value . split ( "&" ) for q in queries : option = Option ( ) option . number = defines . OptionRegistry . LOCATION_QUERY . number option . value = str ( q ) self . add_option ( option ) | Set the Location - Query of the response . |
21,851 | def max_age ( self ) : value = defines . OptionRegistry . MAX_AGE . default for option in self . options : if option . number == defines . OptionRegistry . MAX_AGE . number : value = int ( option . value ) return value | Return the MaxAge of the response . |
21,852 | def max_age ( self , value ) : option = Option ( ) option . number = defines . OptionRegistry . MAX_AGE . number option . value = int ( value ) self . del_option_by_number ( defines . OptionRegistry . MAX_AGE . number ) self . add_option ( option ) | Set the MaxAge of the response . |
21,853 | def receive_request ( self , transaction ) : with transaction : transaction . separate_timer = self . _start_separate_timer ( transaction ) self . _blockLayer . receive_request ( transaction ) if transaction . block_transfer : self . _stop_separate_timer ( transaction . separate_timer ) self . _messageLayer . send_response ( transaction ) self . send_datagram ( transaction . response ) return self . _observeLayer . receive_request ( transaction ) self . _requestLayer . receive_request ( transaction ) if transaction . resource is not None and transaction . resource . changed : self . notify ( transaction . resource ) transaction . resource . changed = False elif transaction . resource is not None and transaction . resource . deleted : self . notify ( transaction . resource ) transaction . resource . deleted = False self . _observeLayer . send_response ( transaction ) self . _blockLayer . send_response ( transaction ) self . _stop_separate_timer ( transaction . separate_timer ) self . _messageLayer . send_response ( transaction ) if transaction . response is not None : if transaction . response . type == defines . Types [ "CON" ] : self . _start_retransmission ( transaction , transaction . response ) self . send_datagram ( transaction . response ) | Handle requests coming from the udp socket . |
21,854 | def add_resource ( self , path , resource ) : assert isinstance ( resource , Resource ) path = path . strip ( "/" ) paths = path . split ( "/" ) actual_path = "" i = 0 for p in paths : i += 1 actual_path += "/" + p try : res = self . root [ actual_path ] except KeyError : res = None if res is None : resource . path = actual_path self . root [ actual_path ] = resource return True | Helper function to add resources to the resource directory during server initialization . |
21,855 | def remove_resource ( self , path ) : path = path . strip ( "/" ) paths = path . split ( "/" ) actual_path = "" i = 0 for p in paths : i += 1 actual_path += "/" + p try : res = self . root [ actual_path ] except KeyError : res = None if res is not None : del ( self . root [ actual_path ] ) return res | Helper function to remove resources . |
21,856 | def _send_ack ( self , transaction ) : ack = Message ( ) ack . type = defines . Types [ 'ACK' ] if not transaction . request . acknowledged and transaction . request . type == defines . Types [ "CON" ] : ack = self . _messageLayer . send_empty ( transaction , transaction . request , ack ) self . send_datagram ( ack ) | Sends an ACK message for the request . |
21,857 | def notify ( self , resource ) : observers = self . _observeLayer . notify ( resource ) logger . debug ( "Notify" ) for transaction in observers : with transaction : transaction . response = None transaction = self . _requestLayer . receive_request ( transaction ) transaction = self . _observeLayer . send_response ( transaction ) transaction = self . _blockLayer . send_response ( transaction ) transaction = self . _messageLayer . send_response ( transaction ) if transaction . response is not None : if transaction . response . type == defines . Types [ "CON" ] : self . _start_retransmission ( transaction , transaction . response ) self . send_datagram ( transaction . response ) | Notifies the observers of a certain resource . |
21,858 | def create_resource ( self , path , transaction ) : t = self . _parent . root . with_prefix ( path ) max_len = 0 imax = None for i in t : if i == path : return self . edit_resource ( transaction , path ) elif len ( i ) > max_len : imax = i max_len = len ( i ) lp = path parent_resource = self . _parent . root [ imax ] if parent_resource . allow_children : return self . add_resource ( transaction , parent_resource , lp ) else : transaction . response . code = defines . Codes . METHOD_NOT_ALLOWED . number return transaction | Render a POST request . |
21,859 | def delete_resource ( self , transaction , path ) : resource = transaction . resource method = getattr ( resource , 'render_DELETE' , None ) try : ret = method ( request = transaction . request ) except NotImplementedError : try : method = getattr ( transaction . resource , "render_DELETE_advanced" , None ) ret = method ( request = transaction . request , response = transaction . response ) if isinstance ( ret , tuple ) and len ( ret ) == 2 and isinstance ( ret [ 1 ] , Response ) and isinstance ( ret [ 0 ] , bool ) : delete , response = ret if delete : del self . _parent . root [ path ] transaction . response = response if transaction . response . code is None : transaction . response . code = defines . Codes . DELETED . number return transaction elif isinstance ( ret , tuple ) and len ( ret ) == 3 and isinstance ( ret [ 1 ] , Response ) and isinstance ( ret [ 0 ] , Resource ) : resource , response , callback = ret ret = self . _handle_separate_advanced ( transaction , callback ) if not isinstance ( ret , tuple ) or not ( isinstance ( ret [ 0 ] , bool ) and isinstance ( ret [ 1 ] , Response ) ) : transaction . response . code = defines . Codes . INTERNAL_SERVER_ERROR . number return transaction delete , response = ret if delete : del self . _parent . root [ path ] transaction . response = response if transaction . response . code is None : transaction . response . code = defines . Codes . DELETED . number return transaction else : raise NotImplementedError except NotImplementedError : transaction . response . code = defines . Codes . METHOD_NOT_ALLOWED . number return transaction if isinstance ( ret , bool ) : pass elif isinstance ( ret , tuple ) and len ( ret ) == 2 : resource , callback = ret ret = self . _handle_separate ( transaction , callback ) if not isinstance ( ret , bool ) : transaction . response . code = defines . Codes . INTERNAL_SERVER_ERROR . number return transaction else : transaction . response . code = defines . Codes . INTERNAL_SERVER_ERROR . number return transaction if ret : del self . _parent . root [ path ] transaction . response . code = defines . Codes . DELETED . number transaction . response . payload = None transaction . resource . deleted = True else : transaction . response . code = defines . Codes . INTERNAL_SERVER_ERROR . number return transaction | Render a DELETE request . |
21,860 | def corelinkformat ( resource ) : msg = "<" + resource . path + ">;" assert ( isinstance ( resource , Resource ) ) keys = sorted ( list ( resource . attributes . keys ( ) ) ) for k in keys : method = getattr ( resource , defines . corelinkformat [ k ] , None ) if method is not None and method != "" : v = method msg = msg [ : - 1 ] + ";" + str ( v ) + "," else : v = resource . attributes [ k ] if v is not None : msg = msg [ : - 1 ] + ";" + k + "=" + v + "," return msg | Return a formatted string representation of the corelinkformat in the tree . |
21,861 | def receive_request ( self , transaction ) : method = transaction . request . code if method == defines . Codes . GET . number : transaction = self . _handle_get ( transaction ) elif method == defines . Codes . POST . number : transaction = self . _handle_post ( transaction ) elif method == defines . Codes . PUT . number : transaction = self . _handle_put ( transaction ) elif method == defines . Codes . DELETE . number : transaction = self . _handle_delete ( transaction ) else : transaction . response = None return transaction | Handle request and execute the requested method |
21,862 | def _handle_delete ( self , 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 transaction = self . _server . resourceLayer . delete_resource ( transaction , path ) return transaction | Handle DELETE requests |
21,863 | def uri_path ( self ) : value = [ ] for option in self . options : if option . number == defines . OptionRegistry . URI_PATH . number : value . append ( str ( option . value ) + '/' ) value = "" . join ( value ) value = value [ : - 1 ] return value | Return the Uri - Path of a request |
21,864 | def uri_path ( self , path ) : path = path . strip ( "/" ) tmp = path . split ( "?" ) path = tmp [ 0 ] paths = path . split ( "/" ) for p in paths : option = Option ( ) option . number = defines . OptionRegistry . URI_PATH . number option . value = p self . add_option ( option ) if len ( tmp ) > 1 : query = tmp [ 1 ] self . uri_query = query | Set the Uri - Path of a request . |
21,865 | def uri_query ( self ) : value = [ ] for option in self . options : if option . number == defines . OptionRegistry . URI_QUERY . number : value . append ( str ( option . value ) ) return "&" . join ( value ) | Get the Uri - Query of a request . |
21,866 | def uri_query ( self , value ) : del self . uri_query queries = value . split ( "&" ) for q in queries : option = Option ( ) option . number = defines . OptionRegistry . URI_QUERY . number option . value = str ( q ) self . add_option ( option ) | Adds a query . |
21,867 | def accept ( self ) : for option in self . options : if option . number == defines . OptionRegistry . ACCEPT . number : return option . value return None | Get the Accept option of a request . |
21,868 | def accept ( self , value ) : if value in list ( defines . Content_types . values ( ) ) : option = Option ( ) option . number = defines . OptionRegistry . ACCEPT . number option . value = value self . add_option ( option ) | Add an Accept option to a request . |
21,869 | def if_match ( self ) : value = [ ] for option in self . options : if option . number == defines . OptionRegistry . IF_MATCH . number : value . append ( option . value ) return value | Get the If - Match option of a request . |
21,870 | def if_match ( self , values ) : assert isinstance ( values , list ) for v in values : option = Option ( ) option . number = defines . OptionRegistry . IF_MATCH . number option . value = v self . add_option ( option ) | Set the If - Match option of a request . |
21,871 | def if_none_match ( self ) : for option in self . options : if option . number == defines . OptionRegistry . IF_NONE_MATCH . number : return True return False | Get the if - none - match option of a request . |
21,872 | def add_if_none_match ( self ) : option = Option ( ) option . number = defines . OptionRegistry . IF_NONE_MATCH . number option . value = None self . add_option ( option ) | Add the if - none - match option to the request . |
21,873 | def proxy_uri ( self ) : for option in self . options : if option . number == defines . OptionRegistry . PROXY_URI . number : return option . value return None | Get the Proxy - Uri option of a request . |
21,874 | def proxy_uri ( self , value ) : option = Option ( ) option . number = defines . OptionRegistry . PROXY_URI . number option . value = str ( value ) self . add_option ( option ) | Set the Proxy - Uri option of a request . |
21,875 | def proxy_schema ( self ) : for option in self . options : if option . number == defines . OptionRegistry . PROXY_SCHEME . number : return option . value return None | Get the Proxy - Schema option of a request . |
21,876 | def proxy_schema ( self , value ) : option = Option ( ) option . number = defines . OptionRegistry . PROXY_SCHEME . number option . value = str ( value ) self . add_option ( option ) | Set the Proxy - Schema option of a request . |
21,877 | def cache_add ( self , request , response ) : logger . debug ( "adding response to the cache" ) code = response . code try : utils . check_code ( code ) except utils . InvalidResponseCode : logger . error ( "Invalid response code" ) return if response . max_age == 0 : return if self . mode == defines . FORWARD_PROXY : new_key = CacheKey ( request ) else : new_key = ReverseCacheKey ( request ) logger . debug ( "MaxAge = {maxage}" . format ( maxage = response . max_age ) ) new_element = CacheElement ( new_key , response , request , response . max_age ) self . cache . update ( new_key , new_element ) logger . debug ( "Cache Size = {size}" . format ( size = self . cache . debug_print ( ) ) ) | checks for full cache and valid code before updating the cache |
21,878 | def search_related ( self , request ) : logger . debug ( "Cache Search Request" ) if self . cache . is_empty ( ) is True : logger . debug ( "Empty Cache" ) return None result = [ ] items = list ( self . cache . cache . items ( ) ) for key , item in items : element = self . cache . get ( item . key ) logger . debug ( "Element : {elm}" . format ( elm = str ( element ) ) ) if request . proxy_uri == element . uri : result . append ( item ) return result | extracting everything from the cache |
21,879 | def search_response ( self , request ) : logger . debug ( "Cache Search Response" ) if self . cache . is_empty ( ) is True : logger . debug ( "Empty Cache" ) return None if self . mode == defines . FORWARD_PROXY : search_key = CacheKey ( request ) else : search_key = ReverseCacheKey ( request ) response = self . cache . get ( search_key ) return response | creates a key from the request and searches the cache with it |
21,880 | def validate ( self , request , response ) : element = self . search_response ( request ) if element is not None : element . cached_response . options = response . options element . freshness = True element . max_age = response . max_age element . creation_time = time . time ( ) element . uri = request . proxy_uri | refreshes a resource when a validation response is received |
21,881 | def _forward_request ( transaction , destination , path ) : client = HelperClient ( destination ) request = Request ( ) request . options = copy . deepcopy ( transaction . request . options ) del request . block2 del request . block1 del request . uri_path del request . proxy_uri del request . proxy_schema del request . observe request . uri_path = path request . destination = destination request . payload = transaction . request . payload request . code = transaction . request . code response = client . send_request ( request ) client . stop ( ) if response is not None : transaction . response . payload = response . payload transaction . response . code = response . code transaction . response . options = response . options else : transaction . response . code = defines . Codes . SERVICE_UNAVAILABLE . number return transaction | Forward requests . |
21,882 | def close ( self ) : self . stopped . set ( ) for event in self . to_be_stopped : event . set ( ) if self . _receiver_thread is not None : self . _receiver_thread . join ( ) self . _socket . close ( ) | Stop the client . |
21,883 | def send_message ( self , message ) : if isinstance ( message , Request ) : request = self . _requestLayer . send_request ( message ) request = self . _observeLayer . send_request ( request ) request = self . _blockLayer . send_request ( request ) transaction = self . _messageLayer . send_request ( request ) self . send_datagram ( transaction . request ) if transaction . request . type == defines . Types [ "CON" ] : self . _start_retransmission ( transaction , transaction . request ) elif isinstance ( message , Message ) : message = self . _observeLayer . send_empty ( message ) message = self . _messageLayer . send_empty ( None , None , message ) self . send_datagram ( message ) | Prepare a message to send on the UDP socket . Eventually set retransmissions . |
21,884 | def _wait_for_retransmit_thread ( transaction ) : if hasattr ( transaction , 'retransmit_thread' ) : while transaction . retransmit_thread is not None : logger . debug ( "Waiting for retransmit thread to finish ..." ) time . sleep ( 0.01 ) continue | Only one retransmit thread at a time wait for other to finish |
21,885 | def send_datagram ( self , message ) : host , port = message . destination logger . debug ( "send_datagram - " + str ( message ) ) serializer = Serializer ( ) raw_message = serializer . serialize ( message ) try : self . _socket . sendto ( raw_message , ( host , port ) ) except Exception as e : if self . _cb_ignore_write_exception is not None and isinstance ( self . _cb_ignore_write_exception , collections . Callable ) : if not self . _cb_ignore_write_exception ( e , self ) : raise for opt in message . options : if opt . number == defines . OptionRegistry . NO_RESPONSE . number : if opt . value == 26 : return if self . _receiver_thread is None or not self . _receiver_thread . isAlive ( ) : self . _receiver_thread = threading . Thread ( target = self . receive_datagram ) self . _receiver_thread . daemon = True self . _receiver_thread . start ( ) | Send a message over the UDP socket . |
21,886 | def _start_retransmission ( self , transaction , message ) : with transaction : if message . type == defines . Types [ 'CON' ] : future_time = random . uniform ( defines . ACK_TIMEOUT , ( defines . ACK_TIMEOUT * defines . ACK_RANDOM_FACTOR ) ) transaction . retransmit_stop = threading . Event ( ) self . to_be_stopped . append ( transaction . retransmit_stop ) transaction . retransmit_thread = threading . Thread ( target = self . _retransmit , name = str ( '%s-Retry-%d' % ( threading . current_thread ( ) . name , message . mid ) ) , args = ( transaction , message , future_time , 0 ) ) transaction . retransmit_thread . start ( ) | Start the retransmission task . |
21,887 | def receive_datagram ( self ) : logger . debug ( "Start receiver Thread" ) while not self . stopped . isSet ( ) : self . _socket . settimeout ( 0.1 ) try : datagram , addr = self . _socket . recvfrom ( 1152 ) except socket . timeout : continue except Exception as e : if self . _cb_ignore_read_exception is not None and isinstance ( self . _cb_ignore_read_exception , collections . Callable ) : if self . _cb_ignore_read_exception ( e , self ) : continue return else : if len ( datagram ) == 0 : logger . debug ( "Exiting receiver Thread due to orderly shutdown on server end" ) return serializer = Serializer ( ) try : host , port = addr except ValueError : host , port , tmp1 , tmp2 = addr source = ( host , port ) message = serializer . deserialize ( datagram , source ) if isinstance ( message , Response ) : logger . debug ( "receive_datagram - " + str ( message ) ) transaction , send_ack = self . _messageLayer . receive_response ( message ) if transaction is None : continue self . _wait_for_retransmit_thread ( transaction ) if send_ack : self . _send_ack ( transaction ) self . _blockLayer . receive_response ( transaction ) if transaction . block_transfer : self . _send_block_request ( transaction ) continue elif transaction is None : self . _send_rst ( transaction ) return self . _observeLayer . receive_response ( transaction ) if transaction . notification : ack = Message ( ) ack . type = defines . Types [ 'ACK' ] ack = self . _messageLayer . send_empty ( transaction , transaction . response , ack ) self . send_datagram ( ack ) self . _callback ( transaction . response ) else : self . _callback ( transaction . response ) elif isinstance ( message , Message ) : self . _messageLayer . receive_empty ( message ) logger . debug ( "Exiting receiver Thread due to request" ) | Receive datagram from the UDP socket and invoke the callback function . |
21,888 | def _send_rst ( self , transaction ) : rst = Message ( ) rst . type = defines . Types [ 'RST' ] if not transaction . response . acknowledged : rst = self . _messageLayer . send_empty ( transaction , transaction . response , rst ) self . send_datagram ( rst ) | Sends an RST message for the response . |
21,889 | def receive_request ( self , transaction ) : transaction . cached_element = self . cache . search_response ( transaction . request ) if transaction . cached_element is None : transaction . cacheHit = False else : transaction . response = transaction . cached_element . cached_response transaction . response . mid = transaction . request . mid transaction . cacheHit = True age = transaction . cached_element . creation_time + transaction . cached_element . max_age - time . time ( ) if transaction . cached_element . freshness is True : if age <= 0 : logger . debug ( "resource not fresh" ) transaction . cached_element . freshness = False transaction . cacheHit = False logger . debug ( "requesting etag %s" , transaction . response . etag ) transaction . request . etag = transaction . response . etag else : transaction . response . max_age = age else : transaction . cacheHit = False return transaction | checks the cache for a response to the request |
21,890 | def send_response ( self , transaction ) : if transaction . cacheHit is False : logger . debug ( "handling response" ) self . _handle_response ( transaction ) return transaction | updates the cache with the response if there was a cache miss |
21,891 | def _handle_response ( self , transaction ) : code = transaction . response . code utils . check_code ( code ) if code == Codes . VALID . number : logger . debug ( "received VALID" ) self . cache . validate ( transaction . request , transaction . response ) if transaction . request . etag != transaction . response . etag : element = self . cache . search_response ( transaction . request ) transaction . response = element . cached_response return transaction if code == Codes . CHANGED . number or code == Codes . CREATED . number or code == Codes . DELETED . number : target = self . cache . search_related ( transaction . request ) if target is not None : for element in target : self . cache . mark ( element ) return transaction self . cache . cache_add ( transaction . request , transaction . response ) return transaction | handles responses based on their type |
21,892 | def version ( self , v ) : if not isinstance ( v , int ) or v != 1 : raise AttributeError self . _version = v | Sets the CoAP version |
21,893 | def type ( self , value ) : if value not in list ( defines . Types . values ( ) ) : raise AttributeError self . _type = value | Sets the type of the message . |
21,894 | def mid ( self , value ) : if not isinstance ( value , int ) or value > 65536 : raise AttributeError self . _mid = value | Sets the MID of the message . |
21,895 | def token ( self , value ) : if value is None : self . _token = value return if not isinstance ( value , str ) : value = str ( value ) if len ( value ) > 256 : raise AttributeError self . _token = value | Set the Token of the message . |
21,896 | def options ( self , value ) : if value is None : value = [ ] assert isinstance ( value , list ) self . _options = value | Set the options of the CoAP message . |
21,897 | def payload ( self , value ) : if isinstance ( value , tuple ) : content_type , payload = value self . content_type = content_type self . _payload = payload else : self . _payload = value | Sets the payload of the message and eventually the Content - Type |
21,898 | def destination ( self , value ) : if value is not None and ( not isinstance ( value , tuple ) or len ( value ) ) != 2 : raise AttributeError self . _destination = value | Set the destination of the message . |
21,899 | def source ( self , value ) : if not isinstance ( value , tuple ) or len ( value ) != 2 : raise AttributeError self . _source = value | Set the source of the message . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.