function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {})
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def get_long_running_output(pipeline_response): deserialized = self._deserialize('PublicIPAddress', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list_all( self, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_all.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list( self, resource_group_name: str, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list_virtual_machine_scale_set_public_ip_addresses( self, resource_group_name: str, virtual_machine_scale_set_name: str, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_virtual_machine_scale_set_public_ip_addresses.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualMachineScaleSetName': self._serialize.url("virtual_machine_scale_set_name", virtual_machine_scale_set_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def list_virtual_machine_scale_set_vm_public_ip_addresses( self, resource_group_name: str, virtual_machine_scale_set_name: str, virtualmachine_index: str, network_interface_name: str, ip_configuration_name: str, **kwargs: Any
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_virtual_machine_scale_set_vm_public_ip_addresses.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualMachineScaleSetName': self._serialize.url("virtual_machine_scale_set_name", virtual_machine_scale_set_name, 'str'), 'virtualmachineIndex': self._serialize.url("virtualmachine_index", virtualmachine_index, 'str'), 'networkInterfaceName': self._serialize.url("network_interface_name", network_interface_name, 'str'), 'ipConfigurationName': self._serialize.url("ip_configuration_name", ip_configuration_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request
Azure/azure-sdk-for-python
[ 3526, 2256, 3526, 986, 1335285972 ]
def doWarnings(): import twisted from twisted.python import versions if (twisted.version < versions.Version('twisted', 8, 0, 0)): LOG.warning("You should get Twisted 8 or later. Previous versions " "have some bugs that affect Dtella.") try: import dtella.bridge except ImportError: # Don't warn about GMP for clients, because verifying a signature # is fast enough without it (~1ms on a Core2) pass else: import Crypto.PublicKey try: import Crypto.PublicKey._fastmath except ImportError: LOG.warning("Your version of PyCrypto was compiled without " "GMP (fastmath). Signing messages will be slower.")
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, main): self.main = main self.nickmap = {} # {nick.lower() -> Node}
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def lookupNick(self, nick): # Might raise KeyError return self.nickmap[nick.lower()]
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def addNode(self, n): if not n.nick: return lnick = n.nick.lower() if lnick in self.nickmap: raise NickError("collision") so = self.main.getStateObserver() if so: # Might raise NickError so.event_AddNick(n) so.event_UpdateInfo(n) self.nickmap[lnick] = n
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, main): self.main = main self.remap_ip = None self.choke_time = seconds() - self.CHOKE_PERIOD self.choke_reported = seconds() - 999 # True iff we're shutting down after a socket failure. self.stopping_protocol = False
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def getSocketState(self): # Figure out the state of our UDP socket. if self.stopping_protocol: return 'dying' elif not self.transport: return 'dead' elif hasattr(self.transport, "d"): return 'dying' else: return 'alive'
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def datagramReceived(self, rawdata, addr, altport=False): ad = Ad().setAddrTuple(addr) if not ad.port: return # This will remap a router's internal IP to its external IP, # if the remapping is known. if self.remap_ip and ad.ip == self.remap_ip[0]: ad.orig_ip = ad.ip ad.ip = self.remap_ip[1] # Special handler for search results directly from DC if rawdata[:4] == '$SR ': dch = self.main.getOnlineDCH() if dch and ad.auth('sb', self.main): dch.pushSearchResult(rawdata) return try: try: data = self.main.pk_enc.decrypt(rawdata) except ValueError, e: raise BadPacketError("Decrypt Failed: " + str(e)) if len(data) < 2: raise BadPacketError("Too Short") kind = data[:2] if not kind.isalpha(): raise BadPacketError("Kind not alphabetical") if altport: kind += "_alt" self.main.logPacket("%s <- %s:%d" % (kind, addr[0], addr[1])) # Make sure the sender's IP is permitted, but delay the check if # it's an initialize packet. if kind not in ('IQ', 'EC', 'IR', 'IC_alt'): if not ad.auth('sbx', self.main): raise BadPacketError("Invalid source IP") try: method = getattr(self, 'handlePacket_%s' % kind) except AttributeError: raise BadPacketError("Unknown kind: %s" % kind) # arg1: Address the packet came from # arg2: The unencrypted packet method(ad, data) except (BadPacketError, BadTimingError), e: self.main.logPacket("Bad Packet/Timing: %s" % str(e))
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def decodeString1(self, data, factor=1): try: length, = struct.unpack('!B', data[:1]) except struct.error: raise BadPacketError("Can't decode 1string") length *= factor if len(data) < 1+length: raise BadPacketError("Bad 1string length") return data[1:1+length], data[1+length:]
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def decodeChunkList(self, fmt, data): size = struct.calcsize(fmt) try: return [struct.unpack(fmt, data[i:i+size]) for i in range(0, len(data), size)] except struct.error: raise BadPacketError("Can't decode chunk list")
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def decodeNodeTimeList(self, data): nbs, rest = self.decodeString1(data, 6+4) nbs = [(ipp, age) for (ipp, age) in self.decodeChunkList('!6sI', nbs) if Ad().setRawIPPort(ipp).auth('sx', self.main)] return nbs, rest
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handleBroadcast(self, ad, data, check_cb, bridgey=False): (kind, nb_ipp, hop, flags, src_ipp, rest ) = self.decodePacket('!2s6sBB6s+', data) osm = self.main.osm if not osm: raise BadTimingError("Not ready to route '%s' packet" % kind) # Make sure nb_ipp agrees with the sender's IP self.checkSource(nb_ipp, ad, exempt_ip=True) # Make sure the src_ipp is valid. # Any broadcast which might be from a bridge is 'bridgey' src_ad = Ad().setRawIPPort(src_ipp) if bridgey: kinds = 'sbx' else: kinds = 'sb' if not src_ad.auth(kinds, self.main): raise BadPacketError("Invalid forwarded source IP") # Make sure this came from one of my ping neighbors. # This helps a little to prevent the injection of random broadcast # traffic into the network. try: if not osm.pgm.pnbs[nb_ipp].got_ack: raise KeyError except KeyError: raise BadTimingError("Broadcast packet not from a ping neighbor") ack_flags = 0 # Check if we've seen this message before. ack_key = osm.mrm.generateKey(data) if osm.mrm.pokeMessage(ack_key, nb_ipp): # Ack and skip the rest self.sendAckPacket(nb_ipp, ACK_BROADCAST, ack_flags, ack_key) return # Get the source node object, if any try: src_n = osm.lookup_ipp[src_ipp] except KeyError: src_n = None try: # Filter all non-bridgey broadcasts from bridge nodes. if not bridgey and self.isFromBridgeNode(src_n, src_ipp): raise BadBroadcast("Bridge can't use " + kind) # Callback the check_cb function check_cb(src_n, src_ipp, rest) except BadBroadcast, e: self.main.logPacket("Bad Broadcast: %s" % str(e)) # Mark that we've seen this message, but don't forward it. osm.mrm.newMessage(data, tries=0, nb_ipp=nb_ipp) # Ack and skip the rest self.sendAckPacket(nb_ipp, ACK_BROADCAST, ack_flags, ack_key) return except Reject: # check_cb told us to reject this broadcast if src_ipp == nb_ipp: # If this is from a neighbor, just set the flag. # We'll send the ack later. ack_flags |= ACK_REJECT_BIT elif not (flags & REJECT_BIT): # Not from a neighbor, so send a reject packet immediately. self.sendAckPacket( src_ipp, ACK_BROADCAST, ACK_REJECT_BIT, ack_key) # Set this flag to indicate to forwarded neighbors that we've # rejected the message. flags |= REJECT_BIT if hop > 0: # Start with the broadcast header packet = osm.mrm.broadcastHeader(kind, src_ipp, hop-1, flags) # Keep the rest of the message intact packet.append(rest) # Pass this message to MessageRoutingManager, so it will be # forwarded to all of my neighbors. osm.mrm.newMessage(''.join(packet), tries=2, nb_ipp=nb_ipp) # Ack the neighbor self.sendAckPacket(nb_ipp, ACK_BROADCAST, ack_flags, ack_key) # Update the original sender's age in the peer cache src_ad = Ad().setRawIPPort(src_ipp) self.main.state.refreshPeer(src_ad, 0)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def sendAckPacket(self, ipp, mode, flags, ack_key): packet = ['AK'] packet.append(self.main.osm.me.ipp) packet.append(struct.pack("!BB", mode, flags)) packet.append(ack_key) ad = Ad().setRawIPPort(ipp) self.main.ph.sendPacket(''.join(packet), ad.getAddrTuple())
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def isMyStatus(self, src_ipp, pktnum, sendfull): # This makes corrections to any stray messages on the network that # would have an adverse effect on my current state. osm = self.main.osm # If it's not for me, nothing's wrong. if src_ipp != osm.me.ipp: return False # If it's old, ignore it. if 0 < (osm.me.status_pktnum - pktnum) % 0x100000000 < PKTNUM_BUF: self.main.logPacket("Outdated from-me packet") return True # If it's from my near future, then repair my packet number if 0 < (pktnum - osm.me.status_pktnum) % 0x100000000 < 2 * PKTNUM_BUF: osm.me.status_pktnum = pktnum # If I'm syncd, retransmit my status if osm.syncd: self.main.logPacket("Reacting to an impersonated status") osm.sendMyStatus(sendfull) return True
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_IQ(self, ad, data): # Initialization Request; someone else is trying to get online (kind, myip, port ) = self.decodePacket('!2s4sH', data) if port == 0: raise BadPacketError("Zero Port") # The IPPort which is allegedly mine my_ad = Ad().setRawIP(myip) my_ad.port = self.main.state.udp_port # src_ad is supposed to be the sender node's "true external IPPort" src_ad = Ad() src_ad.port = port if ad.isPrivate() and my_ad.auth('sx', self.main): # If the request came from a private IP address, but was sent # toward a public IP address, then assume the sender node also # has the same public IP address. src_ad.ip = my_ad.ip else: src_ad.ip = ad.ip if not src_ad.auth('sx', self.main): ip_code = CODE_IP_FOREIGN elif not src_ad.auth('b', self.main): ip_code = CODE_IP_BANNED else: ip_code = CODE_IP_OK osm = self.main.osm state = self.main.state # Provide a max of 48 addresses in a normal response, # 8 addresses in a little cache response IR_LEN = 48 IC_LEN = 8 # Lists of stuff node_ipps = [] ir_nodes = [] ir_peercache = [] ic_peercache = [] if ip_code != CODE_IP_OK: # For invalid IPs, send no neighbors, and a small peercache # just so they can try for a second opinion. IR_LEN = IC_LEN elif osm and osm.syncd: # Get a random sample of online nodes (plus me). indices = xrange(len(osm.nodes) + 1) try: indices = random.sample(indices, IR_LEN) except ValueError: pass # Remap the list of indices into a list of ipps. # For the one out-of-bounds index, fill in 'me'. def get_ipp(i): try: return osm.nodes[i].ipp except IndexError: return osm.me.ipp node_ipps = [get_ipp(i) for i in indices] elif osm: # Not syncd yet, don't add any online nodes pass elif (self.main.reconnect_dcall and self.main.accept_IQ_trigger and my_ad.auth('sx', self.main)): # If we've recently failed to connect, then go online # as the sole node on the network. Then report our node ipp # so this other node can try to join us. self.main.addMyIPReport(src_ad, my_ad) self.main.startNodeSync(()) osm = self.main.osm node_ipps = [osm.me.ipp] # Get my own IPP (if I know it) if osm: my_ipp = osm.me.ipp else: my_ipp = None now = time.time() # For each node, add its ip:port, and age. for ipp in node_ipps: if ipp == my_ipp: age = 0 else: try: age = max(now - state.peers[ipp], 0) except KeyError: # If the entry has expired from the cache # (not very likely), then assume 1 hour age = 60*60 ir_nodes.append(struct.pack('!6sI', ipp, int(age))) # Convert node_ipps into a set, for O(1) lookups node_ipps = set(node_ipps) # Grab the youngest peers in our cache. for when,ipp in state.getYoungestPeers(IR_LEN): # Add packet data to the outlist age = max(int(now - when), 0) pc_entry = struct.pack('!6sI', ipp, int(age)) if (len(node_ipps) + len(ir_peercache) < IR_LEN and ipp not in node_ipps): ir_peercache.append(pc_entry) if len(ic_peercache) < IC_LEN: ic_peercache.append(pc_entry) # === IC response packet === packet = ['IC'] # My IPPort packet.append(my_ad.getRawIPPort()) # Add 4-byte sender's IP address packet.append(src_ad.getRawIP()) # Add 1-byte flag: 1 if IP is invalid packet.append(struct.pack('!B', ip_code)) # Add the peercache list packet.append(struct.pack('!B', len(ic_peercache))) packet.extend(ic_peercache) # Send IC packet to alternate port, undo NAT remapping if ad.orig_ip: ad.ip = ad.orig_ip self.sendPacket(''.join(packet), ad.getAddrTuple()) # === IR response packet === packet = ['IR'] # My IPPort packet.append(my_ad.getRawIPPort()) # Add to packet: 4-byte sender's IP address packet.append(src_ad.getRawIP()) # Add 1-byte flag: 1 if IP is invalid packet.append(struct.pack('!B', ip_code)) # Add the node list packet.append(struct.pack('!B', len(ir_nodes))) packet.extend(ir_nodes) # Now add the peercache list packet.append(struct.pack('!B', len(ir_peercache))) packet.extend(ir_peercache) # Send IR packet to dtella port self.sendPacket(''.join(packet), src_ad.getAddrTuple()) # Update the sender in my peer cache (if valid) self.main.state.refreshPeer(src_ad, 0)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_IR(self, ad, data): # Initialization Response (kind, src_ipp, myip, code, rest ) = self.decodePacket('!2s6s4sB+', data) src_ad = Ad().setRawIPPort(src_ipp) if ad.isPrivate(): if not src_ad.auth('sx', self.main): raise BadPacketError("Invalid reported source IP") else: self.checkSource(src_ipp, ad, exempt_ip=True) # Node list, Peer Cache nd, rest = self.decodeNodeTimeList(rest) pc, rest = self.decodeNodeTimeList(rest) if rest: raise BadPacketError("Extra data") if code not in (CODE_IP_OK, CODE_IP_FOREIGN, CODE_IP_BANNED): raise BadPacketError("Bad Response Code") if not self.main.icm: raise BadTimingError("Not in initial connection mode") self.main.icm.receivedInitResponse(src_ipp, myip, code, pc, nd)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def check_cb(src_n, src_ipp, rest): (pktnum, expire, sesid, uptime, flags, rest ) = self.decodePacket('!IH4sIB+', rest) nick, rest = self.decodeString1(rest) info, rest = self.decodeString1(rest) persist = bool(flags & PERSIST_BIT) # 2011-08-21: allow 'rest' to be non-empty, in case we want to add # new fields someday. if len(rest) > 1024: raise BadPacketError("Too much extra data") if not (5 <= expire <= 30*60): raise BadPacketError("Expire time out of range") # Make sure this isn't about me if self.isMyStatus(src_ipp, pktnum, sendfull=True): raise BadBroadcast("Impersonating me") if self.isOutdatedStatus(src_n, pktnum): raise BadBroadcast("Outdated") n = osm.refreshNodeStatus( src_ipp, pktnum, expire, sesid, uptime, persist, nick, info) # They had a nick, now they don't. This indicates a problem. # Stop forwarding and notify the user. if nick and not n.nick: raise Reject
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_NH(self, ad, data): # Broadcast: Node Status Hash (keep-alive) osm = self.main.osm def check_cb(src_n, src_ipp, rest): (pktnum, expire, infohash ) = self.decodePacket('!IH4s', rest) if not (5 <= expire <= 30*60): raise BadPacketError("Expire time out of range") # Make sure this isn't about me if self.isMyStatus(src_ipp, pktnum, sendfull=True): raise BadBroadcast("Impersonating me") if self.isOutdatedStatus(src_n, pktnum): raise BadBroadcast("Outdated") if osm.syncd: if src_n and src_n.infohash == infohash: # We are syncd, and this node matches, so extend the # expire timeout and keep forwarding. src_n.status_pktnum = pktnum osm.scheduleNodeExpire(src_n, expire + NODE_EXPIRE_EXTEND) return else: # Syncd, and we don't recognize it raise Reject else: if not (src_n and src_n.expire_dcall): # Not syncd, don't know enough about this node yet, # so just forward blindly. return elif src_n.infohash == infohash: # We know about this node already, and the infohash # matches, so extend timeout and keep forwarding src_n.status_pktnum = pktnum osm.scheduleNodeExpire(src_n, expire + NODE_EXPIRE_EXTEND) return else: # Not syncd, but we know the infohash is wrong. raise Reject self.handleBroadcast(ad, data, check_cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def check_cb(src_n, src_ipp, rest): (sesid, ) = self.decodePacket('!4s', rest) if osm.syncd: if src_ipp == osm.me.ipp and sesid == osm.me.sesid: # Yikes! Make me a new session id and rebroadcast it. osm.me.sesid = randbytes(4) osm.reorderNodesList() osm.sendMyStatus() osm.pgm.scheduleMakeNewLinks() raise BadBroadcast("Tried to exit me") if not src_n: raise BadBroadcast("Node not online") if sesid != src_n.sesid: raise BadBroadcast("Wrong session ID") elif not src_n: # Not syncd, and haven't seen this node yet. # Forward blindly return # Remove node osm.nodeExited(src_n, "Received NX")
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_NF(self, ad, data): # Broadcast: Node failure osm = self.main.osm def check_cb(src_n, src_ipp, rest): (pktnum, sesid, ) = self.decodePacket('!I4s', rest) # Make sure this isn't about me if self.isMyStatus(src_ipp, pktnum, sendfull=False): raise BadBroadcast("I'm not dead!") if not (src_n and src_n.expire_dcall): raise BadBroadcast("Nonexistent node") if src_n.sesid != sesid: raise BadBroadcast("Wrong session ID") if self.isOutdatedStatus(src_n, pktnum): raise BadBroadcast("Outdated") # Reduce the expiration time. If that node isn't actually # dead, it will rebroadcast a status update to correct it. if (dcall_timeleft(src_n.expire_dcall) > NODE_EXPIRE_EXTEND): osm.scheduleNodeExpire(src_n, NODE_EXPIRE_EXTEND) self.handleBroadcast(ad, data, check_cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_CH(self, ad, data): # Broadcast: Chat message osm = self.main.osm def check_cb(src_n, src_ipp, rest): (pktnum, nhash, flags, rest ) = self.decodePacket('!I4sB+', rest) text, rest = self.decodeString2(rest) if rest: raise BadPacketError("Extra data") if src_ipp == osm.me.ipp: # Possibly a spoofed chat from me if nhash == osm.me.nickHash(): dch = self.main.getOnlineDCH() if dch: dch.pushStatus( "*** Chat spoofing detected: %s" % text) raise BadBroadcast("Spoofed chat") if not osm.syncd: # Not syncd, forward blindly return if osm.isModerated(): # Note: this may desync the sender's chat_pktnum, causing # their next valid message to be delayed by 2 seconds, but # it's better than broadcasting useless traffic. raise BadBroadcast("Chat is moderated") elif src_n and nhash == src_n.nickHash(): osm.cms.addMessage( src_n, pktnum, src_n.nick, text, flags) else: raise Reject self.handleBroadcast(ad, data, check_cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def check_cb(src_n, src_ipp, rest): (pktnum, nhash, rest ) = self.decodePacket('!I4s+', rest) topic, rest = self.decodeString1(rest) if rest: raise BadPacketError("Extra data") if src_ipp == osm.me.ipp: # Possibly a spoofed topic from me if nhash == osm.me.nickHash(): dch = self.main.getOnlineDCH() if dch: dch.pushStatus( "*** Topic spoofing detected: %s" % topic) raise BadBroadcast("Spoofed topic") if not osm.syncd: # Not syncd, forward blindly return None if src_n and nhash == src_n.nickHash(): osm.tm.gotTopic(src_n, topic) else: raise Reject
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_SQ(self, ad, data): # Broadcast: Search Request osm = self.main.osm def check_cb(src_n, src_ipp, rest): (pktnum, rest ) = self.decodePacket("!I+", rest) string, rest = self.decodeString1(rest) if rest: raise BadPacketError("Extra data") if src_ipp == osm.me.ipp: raise BadBroadcast("Spoofed search") if not osm.syncd: # Not syncd, forward blindly return if src_n: # Looks good dch = self.main.getOnlineDCH() if dch: dch.pushSearchRequest(src_ipp, string) else: # From an invalid node raise Reject self.handleBroadcast(ad, data, check_cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_CA(self, ad, data): # Direct: ConnectToMe def cb(dch, n, rest): # SSLHACK: newer Dtella versions have an extra flags byte, to allow # for SSL connection requests. Try to decode both forms. try: flags, port = self.decodePacket('!BH', rest) except BadPacketError: flags = 0 port, = self.decodePacket('!H', rest) if port == 0: raise BadPacketError("Zero port") ad = Ad().setRawIPPort(n.ipp) ad.port = port use_ssl = bool(flags & USE_SSL_BIT) dch.pushConnectToMe(ad, use_ssl) self.handlePrivMsg(ad, data, cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(dch, n, rest): if rest: raise BadPacketError("Extra data") n.openRevConnectWindow() dch.pushRevConnectToMe(n.nick)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_PM(self, ad, data): # Direct: Private Message def cb(dch, n, rest): flags, rest = self.decodePacket('!B+', rest) text, rest = self.decodeString2(rest) if rest: raise BadPacketError("Extra data") notice = bool(flags & NOTICE_BIT) if notice: nick = "*N %s" % n.nick dch.pushChatMessage(nick, text) else: dch.pushPrivMsg(n.nick, text) self.handlePrivMsg(ad, data, cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_YQ(self, ad, data): # Sync Request (kind, nb_ipp, hop, flags, src_ipp, sesid ) = self.decodePacket('!2s6sBB6s4s', data) osm = self.main.osm if not (osm and osm.syncd): raise BadTimingError("Not ready to handle a sync request") # Hidden nodes shouldn't be getting sync requests. if self.main.hide_node: raise BadTimingError("Hidden node can't handle sync requests.") self.checkSource(nb_ipp, ad, exempt_ip=True) src_ad = Ad().setRawIPPort(src_ipp) if not src_ad.auth('sbx', self.main): raise BadPacketError("Invalid source IP") timedout = bool(flags & TIMEDOUT_BIT) if not 0 <= hop <= 2: raise BadPacketError("Bad hop count") elif hop == 2 and src_ipp != nb_ipp: raise BadPacketError("Source ip mismatch") # Decrease hop count, and call handler osm.yqrm.receivedSyncRequest(nb_ipp, src_ipp, sesid, hop, timedout)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def handlePacket_EC(self, ad, data): # Login echo osm = self.main.osm if not osm: raise BadTimingError("Not ready for login echo") (kind, rand ) = self.decodePacket('!2s8s', data) osm.receivedLoginEcho(ad, rand)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, ipp, seen): self.ipp = ipp self.seen = seen self.inheap = True self.timeout_dcall = None self.alt_reply = False self.bad_code = False
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def start(self): CHECK(self.deferred is None) self.deferred = defer.Deferred() self.main.showLoginStatus("Scanning For Online Nodes...", counter=1) # Get the main UDP socket's bind interface (usually empty) bind_ip = self.main.ph.transport.interface # Listen on an arbitrary UDP port try: reactor.listenUDP(0, self, interface=bind_ip) except twisted.internet.error.BindError: self.main.showLoginStatus("Failed to bind alt UDP port!") self.deferred.callback(('no_nodes', None)) else: self.scheduleInitRequest() return self.deferred
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def scheduleInitRequest(self): if not self.deferred: return if self.initrequest_dcall: return def cb(): self.initrequest_dcall = None try: p = heapq.heappop(self.heap) except IndexError: self.checkStatus() return p.inheap = False ad = Ad().setRawIPPort(p.ipp) packet = ['IQ'] packet.append(ad.getRawIP()) packet.append(struct.pack('!H', self.main.state.udp_port)) self.main.logPacket("IQ -> %s:%d" % ad.getAddrTuple()) packet = self.main.pk_enc.encrypt(''.join(packet)) try: # Send from the alternate port self.transport.write(packet, ad.getAddrTuple()) except (AttributeError, socket.error): # Socket got funky, let the timeouts take care of it. pass except RuntimeError: # Workaround for the Twisted infinte recursion bug pass else: self.schedulePeerContactTimeout(p) self.initrequest_dcall = reactor.callLater(0.05, cb) self.initrequest_dcall = reactor.callLater(0, cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): p.timeout_dcall = None self.waitreply.remove(p) if p.alt_reply: self.recordResultType('dead_port') self.checkStatus()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cancelPeerContactTimeout(self, p): try: self.waitreply.remove(p) except KeyError: return False dcall_discard(p, 'timeout_dcall') return True
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def recordResultType(self, kind): self.main.logPacket("Recording result: '%s'" % kind) self.counters[kind] += 1 # Finish init after 5 seconds of inactivity if self.finish_dcall: self.finish_dcall.reset(5.0) return def cb(): self.finish_dcall = None self.checkStatus(finished=True) self.finish_dcall = reactor.callLater(5.0, cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def initCompleted(self, good): self.shutdown() if good: self.deferred.callback(('good', self.node_ipps)) else: # In a tie, prefer 'banned_ip' over 'foreign_ip', etc. rank = [] i = 3 for name in ('banned_ip', 'foreign_ip', 'dead_port'): rank.append( (self.counters[name], i, name) ) i -= 1 # Sort in descending order rank.sort(reverse=True) if rank[0][0] == 0: # Nobody replied self.deferred.callback(('no_nodes', None)) else: # Return the name of the failure which occurred most self.deferred.callback((rank[0][2], None))
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def shutdown(self): # Cancel all dcalls dcall_discard(self, 'initrequest_dcall') dcall_discard(self, 'finish_dcall') for p in self.peers.values(): dcall_discard(p, 'timeout_dcall') # Close socket if self.transport: self.transport.stopListening()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, ipp): # Dtella Tracking stuff self.ipp = ipp # 6-byte IP:Port self.sesid = None # 4-byte session ID self.dist = None # 16-byte md5 "distance" self.expire_dcall = None # dcall for expiring stale nodes self.status_pktnum = None # Pktnum of last status update # ChatMessageSequencer stuff self.chatq = [] self.chatq_base = None self.chatq_dcall = None # ack_key -> timeout DelayedCall self.msgkeys_out = {} self.msgkeys_in = {} # General Info self.nick = '' self.dcinfo = '' self.location = '' self.shared = 0 self.dttag = "" self.infohash = None self.uptime = 0.0 self.persist = False
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def nickHash(self): # Return a 4-byte hash to prevent a transient nick mismapping if self.nick: return md5(self.ipp + self.sesid + self.nick).digest()[:4] else: return None
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def getPMAckKey(self): # Generate random packet ID for messages going TO this node while 1: ack_key = randbytes(8) if ack_key not in self.msgkeys_out: break return ack_key
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): self.msgkeys_in.pop(ack_key)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def setInfo(self, info): old_dcinfo = self.dcinfo self.dcinfo, self.location, self.shared = ( parse_incoming_info(SSLHACK_filter_flags(info))) if self.sesid is None: # Node is uninitialized self.infohash = None else: self.infohash = md5( self.sesid + self.flags() + self.nick + '|' + info ).digest()[:4] return self.dcinfo != old_dcinfo
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def openRevConnectWindow(self): # When get a RevConnect, create a 5-second window during # which errors are suppressed for outgoing connects. if self.rcWindow_dcall: self.rcWindow_dcall.reset(5.0) return def cb(): del self.rcWindow_dcall self.rcWindow_dcall = reactor.callLater(5.0, cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def sendPrivateMessage(self, ph, ack_key, packet, fail_cb): # Send an ACK-able direct message to this node def cb(tries): if tries == 0: del self.msgkeys_out[ack_key] fail_cb("Timeout") return ad = Ad().setRawIPPort(self.ipp) ph.sendPacket(packet, ad.getAddrTuple()) # Set timeout for outbound message # This will be cancelled if we receive an AK in time. dcall = reactor.callLater(1.0, cb, tries-1) dcall.pm_fail_cb = fail_cb self.msgkeys_out[ack_key] = dcall # Send it 3 times, then fail. cb(3)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def event_PrivateMessage(self, main, text, fail_cb): osm = main.osm if len(text) > 1024: text = text[:1024-12] + ' [Truncated]' flags = 0 ack_key = self.getPMAckKey() packet = ['PM'] packet.append(osm.me.ipp) packet.append(ack_key) packet.append(osm.me.nickHash()) packet.append(self.nickHash()) packet.append(struct.pack('!BH', flags, len(text))) packet.append(text) packet = ''.join(packet) self.sendPrivateMessage(main.ph, ack_key, packet, fail_cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def event_RevConnectToMe(self, main, fail_cb): osm = main.osm ack_key = self.getPMAckKey() packet = ['CP'] packet.append(osm.me.ipp) packet.append(ack_key) packet.append(osm.me.nickHash()) packet.append(self.nickHash()) packet = ''.join(packet) self.sendPrivateMessage(main.ph, ack_key, packet, fail_cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def shutdown(self, main): dcall_discard(self, 'expire_dcall') dcall_discard(self, 'rcWindow_dcall') self.nickRemoved(main) if self.bridge_data: self.bridge_data.shutdown()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def event_PrivateMessage(self, main, text, fail_cb): dch = main.getOnlineDCH() if dch: dch.pushPrivMsg(dch.nick, text) else: fail_cb("I'm not online!")
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def event_RevConnectToMe(self, main, fail_cb): fail_cb("can't get files from yourself!")
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, ipp): self.ipp = ipp self.timeout_dcall = None self.fail_limit = 2 # Used for stats self.in_total = False self.in_done = False self.proxy_request = False
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def updateStats(self, s, done, total): # Update the sync statistics for a single node. if done > 0 and not s.in_done: s.in_done = True self.stats_done += 1 elif done < 0 and s.in_done: s.in_done = False self.stats_done -= 1 if total > 0 and not s.in_total: s.in_total = True self.stats_total += 1 elif total < 0 and s.in_total: s.in_total = False self.stats_total -= 1
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): self.showProgress_dcall = None if bar == self.stats_lastbar: return self.stats_lastbar = bar progress = '>'*bar + '_'*(MAX-bar) self.main.showLoginStatus( "[%s] (%d/%d)" % (progress, done, total))
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def advanceQueue(self): # Raise request limit the first time it fills up if self.request_limit < 5 and self.waitcount >= 5: self.request_limit = 5 while self.waitcount < self.request_limit: try: # Grab an arbitrary (semi-pseudorandom) uncontacted node. ipp = self.uncontacted.pop() except KeyError: # Ran out of nodes; see if we're done yet. if self.waitcount == 0: dcall_discard(self, 'showProgress_dcall') self.main.osm.syncComplete() return s = self.info[ipp] osm = self.main.osm ph = self.main.ph hops = 2 flags = (s.fail_limit < 2) and TIMEDOUT_BIT # Send the sync request packet = osm.mrm.broadcastHeader('YQ', osm.me.ipp, hops, flags) packet.append(osm.me.sesid) ad = Ad().setRawIPPort(s.ipp) ph.sendPacket(''.join(packet), ad.getAddrTuple()) self.scheduleSyncTimeout(s)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def receivedSyncReply(self, src_ipp, c_nbs, u_nbs): my_ipp = self.main.osm.me.ipp # Loop through all the nodes that were just contacted by proxy for ipp in c_nbs: if ipp == my_ipp: continue try: s = self.info[ipp] except KeyError: # Haven't seen this one before, set a timeout because # we should be hearing a reply. s = self.info[ipp] = self.SyncInfo(ipp) self.scheduleSyncTimeout(s, proxy=True) self.updateStats(s, 0, +1) else: if ipp in self.uncontacted: # Seen this node, had planned to ping it later. # Pretend like we just pinged it now. self.uncontacted.discard(ipp) self.scheduleSyncTimeout(s, proxy=True) # Loop through all the nodes which weren't contacted by this # host, but that the host is neighbors with. for ipp in u_nbs: if ipp == my_ipp: continue if ipp not in self.info: # If we haven't heard of this node before, create some # info and plan on pinging it later s = self.info[ipp] = self.SyncInfo(ipp) self.uncontacted.add(ipp) self.updateStats(s, 0, +1) self.advanceQueue() # Mark off that we've received a reply. try: s = self.info[src_ipp] except KeyError: s = self.info[src_ipp] = self.SyncInfo(src_ipp) # Keep track of NAT stats if s.proxy_request: s.proxy_request = False if s.fail_limit == 2: self.proxy_success += 1 elif s.fail_limit == 1: self.proxy_failed += 1 if (self.proxy_failed + self.proxy_success >= 10 and self.proxy_failed > self.proxy_success): self.main.needPortForward() return self.uncontacted.discard(src_ipp) self.updateStats(s, +1, +1) self.showProgress() self.cancelSyncTimeout(s)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): s.timeout_dcall = None self.waitcount -= 1 s.fail_limit -= 1 if s.fail_limit > 0: # Try again later self.uncontacted.add(s.ipp) else: self.updateStats(s, 0, -1) self.showProgress() self.advanceQueue()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cancelSyncTimeout(self, s): if not s.timeout_dcall: return dcall_discard(s, 'timeout_dcall') self.waitcount -= 1 self.advanceQueue()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, main, my_ipp, node_ipps, bcm=None, bsm=None): self.main = main self.main.osm = self self.syncd = False # Don't allow myself in the nodes list if node_ipps: node_ipps.discard(my_ipp) # Create a Node for me self.me = MeNode(my_ipp) self.me.sesid = randbytes(4) self.me.uptime = seconds() # NickManager self.nkm = NickManager(main) # MessageRoutingManager self.mrm = MessageRoutingManager(main) # PingManager self.pgm = PingManager(main) # TopicManager self.tm = TopicManager(main) # BanManager self.banm = BanManager(main) # ChatMessageSequencer self.cms = ChatMessageSequencer(main) # BridgeClientManager / BridgeServerManager self.bcm = bcm self.bsm = bsm # SyncManager (init after contacting the first neighbor) self.sm = None # Init all these when sync is established: self.yqrm = None # SyncRequestRoutingManager self.sendStatus_dcall = None # Keep track of outbound status rate limiting self.statusLimit_time = seconds() - 999 self.statusLimit_dcall = None self.sendLoginEcho() # List of online nodes, sorted by random distance. self.nodes = [] # Index of online nodes: ipp -> Node() self.lookup_ipp = {} for ipp in node_ipps: self.addNodeToNodesList(Node(ipp)) # Initially, we'll just connect to random nodes. # This list will be sorted after syncing is finished. random.shuffle(self.nodes) if self.nodes: self.main.showLoginStatus( "Joining The Network.", counter='inc') self.pgm.scheduleMakeNewLinks() else: self.main.showLoginStatus( "Creating a new empty network.", counter='inc') self.syncComplete()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def refreshNodeStatus(self, src_ipp, pktnum, expire, sesid, uptime, persist, nick, info): CHECK(src_ipp != self.me.ipp) try: n = self.lookup_ipp[src_ipp] in_nodes = True except KeyError: n = Node(src_ipp) in_nodes = False self.main.logPacket("Status: %s %d (%s)" % (hexlify(src_ipp), expire, nick)) # Update the last-seen status packet number n.status_pktnum = pktnum # Change uptime to a fixed time when the node went up uptime = seconds() - uptime if self.syncd and in_nodes and n.sesid != sesid: # session ID changed; remove n from sorted nodes list # so that it will be reinserted into the correct place self.removeNodeFromNodesList(n) in_nodes = False # Update info n.sesid = sesid n.uptime = uptime n.persist = persist # Save version info n.dttag = parse_dtella_tag(info) if nick == n.nick: # Nick hasn't changed, just update info self.nkm.setInfoInList(n, info) else: # Nick has changed. # Remove old nick, if it's in there self.nkm.removeNode(n, "No DC client") # Run a sanity check on the new nick if nick and validateNick(nick) != '': # Malformed n.setNoUser() else: # Good nick, update the info n.nick = nick n.setInfo(info) # Try to add the new nick (no-op if the nick is empty) try: self.nkm.addNode(n) except NickError: n.setNoUser() # If n isn't in nodes list, then add it if not in_nodes: self.addNodeToNodesList(n) # Expire this node after the expected retransmit self.scheduleNodeExpire(n, expire + NODE_EXPIRE_EXTEND) # Possibly make this new node an outgoing link self.pgm.scheduleMakeNewLinks() # Return the node return n
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def addNodeToNodesList(self, n): if self.syncd: n.calcDistance(self.me) bisect.insort(self.nodes, n) else: self.nodes.append(n) self.lookup_ipp[n.ipp] = n
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def reorderNodesList(self): # Recalculate and sort all nodes in the nodes list. for n in self.nodes: n.calcDistance(self.me) self.nodes.sort()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): n.expire_dcall = None self.nodeExited(n, "Node Timeout")
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def getStatus(self): status = [] # My Session ID status.append(self.me.sesid) # My Uptime and Flags status.append(struct.pack('!I', int(seconds() - self.me.uptime))) status.append(self.me.flags()) # My Nick status.append(struct.pack('!B', len(self.me.nick))) status.append(self.me.nick) # My Info status.append(struct.pack('!B', len(self.me.info_out))) status.append(self.me.info_out) return status
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def sendMyStatus(self, sendfull=True): # Immediately send my status, and keep sending updates over time. # This should never be called for a bridge. CHECK(not self.bsm) # Skip this stuff for hidden nodes. if self.main.hide_node: return self.checkStatusLimit() def cb(sendfull): # Choose an expiration time so that the network handles # approximately 1 status update per second, but set bounds of # about 1-15 minutes expire = max(60.0, min(900.0, len(self.nodes))) expire *= random.uniform(0.9, 1.1) self.sendStatus_dcall = reactor.callLater(expire, cb, False) pkt_id = struct.pack('!I', self.mrm.getPacketNumber_status()) if sendfull: packet = self.mrm.broadcastHeader('NS', self.me.ipp) packet.append(pkt_id) packet.append(struct.pack('!H', int(expire))) packet.extend(self.getStatus()) else: packet = self.mrm.broadcastHeader('NH', self.me.ipp) packet.append(pkt_id) packet.append(struct.pack('!H', expire)) packet.append(self.me.infohash) self.mrm.newMessage(''.join(packet), tries=8) dcall_discard(self, 'sendStatus_dcall') cb(sendfull)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): self.statusLimit_dcall = None self.main.showLoginStatus("*** YIKES! Too many status updates!") self.main.shutdown(reconnect='max')
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def isModerated(self): if self.bcm: return self.bcm.isModerated() if self.bsm: return self.bsm.isModerated() return False
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): self.loginEcho_dcall = None self.loginEcho_rand = None self.main.logPacket("No EC response")
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def receivedLoginEcho(self, ad, rand): if rand != self.loginEcho_rand: raise BadPacketError("EC Rand mismatch") myad = Ad().setRawIPPort(self.me.ipp) dcall_discard(self, 'loginEcho_dcall') self.loginEcho_rand = None if ad.ip == myad.ip: return if ad.isPrivate(): # This matches an RFC1918 address, so it looks like a router. # Remap this address to my external IP in the future self.main.ph.remap_ip = (ad.ip, myad.ip) self.main.logPacket("EC: Remap %s->%s" % (ad.getTextIP(), myad.getTextIP())) else: self.main.logPacket("EC: Not RFC1918")
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def shutdown(self): # Cancel all the dcalls here dcall_discard(self, 'sendStatus_dcall') dcall_discard(self, 'statusLimit_dcall') # If I'm still syncing, shutdown the SyncManager if self.sm: self.sm.shutdown() # Shut down the MessageRoutingManager (and broadcast NX) if self.mrm: self.mrm.shutdown() # Shut down the BridgeServerManager if self.bsm: self.bsm.shutdown() # Shut down all nodes for n in self.nodes: n.shutdown(self.main) # Shut down the PingManager (and notify outbounds) if self.pgm: self.pgm.shutdown() # Shut down the BanManager (just cancels some dcalls) if self.banm: self.banm.shutdown() # Shut down the BridgeClientManager if self.bcm: self.bcm.shutdown() # Shut down the SyncRequestRoutingManager if self.yqrm: self.yqrm.shutdown()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, ipp): self.ipp = ipp self.outbound = False self.inbound = False self.ping_reqs = {} # {ack_key: time sent} self.sendPing_dcall = None # dcall for sending pings self.deadNb_dcall = None # keep track of node failure self.got_ack = False self.u_got_ack = False self.ping_nbs = None self.avg_ping = None
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def stronglyConnected(self): # return True if both ends are willing to accept broadcast traffic return (self.got_ack and self.u_got_ack)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, main): self.main = main self.chopExcessLinks_dcall = None self.makeNewLinks_dcall = None # All of my ping neighbors: ipp -> PingNeighbor() self.pnbs = {} self.onlineTimeout_dcall = None self.scheduleOnlineTimeout()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def i_req(): if not (pn.outbound or pn.inbound): # Don't request an ack for an unwanted connection return False if not pn.stillAlive(): # Try to revitalize this connection return True if (ping_now and hasattr(pn.sendPing_dcall, 'ping_is_shortable') and dcall_timeleft(pn.sendPing_dcall) <= 1.0 ): # We've got a REQ to send out in a very short time, so # send it out early with this packet we're sending already. return True return False
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def pingWithRetransmit(self, pn, tries, later, ack_key=None): dcall_discard(pn, 'sendPing_dcall') pn.ping_reqs.clear() def cb(tries): pn.sendPing_dcall = None # Send the ping self.sendPing(pn, True) # While tries is positive, use 1 second intervals. # When it hits zero, trigger a timeout. As it goes negative, # pings get progressively more spaced out. if tries > 0: when = 1.0 else: tries = max(tries, -7) when = 2.0 ** -tries # max of 128 sec # Tweak the delay when *= random.uniform(0.9, 1.1) # Schedule retransmit pn.sendPing_dcall = reactor.callLater(when, cb, tries-1) # Just failed now if tries == 0: if self.main.osm.syncd and pn.got_ack: # Note that we had to set sendPing_dcall before this. self.handleNodeFailure(pn.ipp) pn.got_ack = False # If this was an inbound node, forget it. pn.inbound = False if pn.outbound: # An outbound link just failed. Go find another one. self.scheduleMakeNewLinks() else: # Neither side wants this link. Clean up. self.cancelInactiveLink(pn) if later: when = 5.0 else: # Send first ping self.sendPing(pn, True, ack_key) tries -= 1 when = 1.0 # Schedule retransmit(s) when *= random.uniform(0.9, 1.1) pn.sendPing_dcall = reactor.callLater(when, cb, tries) # Leave a flag value in the dcall so we can test whether this # ping can be made a bit sooner if later: pn.sendPing_dcall.ping_is_shortable = True
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def instaKillNeighbor(self, pn): # Unconditionally drop neighbor connection (used for bans) iwant = pn.outbound pn.inbound = False pn.outbound = False self.cancelInactiveLink(pn) if iwant: self.scheduleMakeNewLinks()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): pn.deadNb_dcall = None
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def scheduleMakeNewLinks(self): # Call this whenever a new sync'd node is added # Or when a connected link dies # This never needs to run more than once per reactor loop if self.makeNewLinks_dcall: return def cb(): self.makeNewLinks_dcall = None osm = self.main.osm # Make sure the K closest nonbroken nodes are marked as outbound n_alive = 0 for n in osm.nodes: try: pn = self.pnbs[n.ipp] except KeyError: pn = self.pnbs[n.ipp] = self.PingNeighbor(n.ipp) if not pn.outbound: if not pn.inbound: # Completely new link tries = 2 elif pn.stronglyConnected(): # An active inbound link is being marked as outbound, # so we might want to close some other outbound # link. Note that this won't run until the next # reactor loop. self.scheduleChopExcessLinks() tries = 4 else: # Existing link, not strongly connected yet tries = 2 pn.outbound = True self.pingWithRetransmit(pn, tries=tries, later=False) if pn.outbound and pn.stillAlive(): n_alive += 1 if n_alive >= self.OUTLINK_GOAL: break self.makeNewLinks_dcall = reactor.callLater(0, cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): self.chopExcessLinks_dcall = None osm = self.main.osm # Keep a set of unwanted outbound neighbors. We will remove # wanted neighbors from this set, and kill what remains. unwanted = set(pn.ipp for pn in self.pnbs.itervalues() if pn.outbound) n_alive = 0 for n in osm.nodes: try: pn = self.pnbs[n.ipp] if not pn.outbound: raise KeyError except KeyError: # We ran out of nodes before hitting the target number # of strongly connected nodes. That means stuff's still # connecting, and there's no need to remove anyone. unwanted.clear() break # This neighbor is NOT unwanted. unwanted.remove(pn.ipp) # Stop once we reach the desired number of outbound links. if pn.stronglyConnected(): n_alive += 1 if n_alive == self.OUTLINK_GOAL: break # If any unwanted links remain, remove them. for ipp in unwanted: CHECK(self.removeOutboundLink(ipp))
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def scheduleOnlineTimeout(self): # This will automatically shut down the node if we don't get any # ping acknowledgements for a while if self.onlineTimeout_dcall: self.onlineTimeout_dcall.reset(ONLINE_TIMEOUT) return def cb(): self.onlineTimeout_dcall = None self.main.showLoginStatus("Lost Sync!") self.main.shutdown(reconnect='normal') self.onlineTimeout_dcall = reactor.callLater(ONLINE_TIMEOUT, cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def sendPing(self, pn, i_req, ack_key=None): # Transmit a single ping to the given node osm = self.main.osm # Expire old ack requests if pn.ping_reqs: now = seconds() for req_key, when in pn.ping_reqs.items(): if now - when > 15.0: del pn.ping_reqs[req_key] iwant = pn.outbound # For now, include neighbor list only when requesting an ack. nblist = i_req # Offline bit is set if this neighbor is not recognized. # (this just gets ignored, but it could be useful someday) offline = osm.syncd and (pn.ipp not in osm.lookup_ipp) # Build packet packet = ['PG'] packet.append(osm.me.ipp) flags = ((iwant and IWANT_BIT) | (pn.got_ack and GOTACK_BIT) | (i_req and REQ_BIT) | (bool(ack_key) and ACK_BIT) | (nblist and NBLIST_BIT) | (offline and OFFLINE_BIT) ) packet.append(struct.pack('!B', flags)) if i_req: # I'm requesting that this packet be acknowledged, so generate # a new req_key while True: req_key = randbytes(4) if req_key not in pn.ping_reqs: break pn.ping_reqs[req_key] = seconds() packet.append(req_key) if ack_key: packet.append(ack_key) if nblist: if osm.syncd: # Grab my list of ping neighbors. nbs = [pn_it.ipp for pn_it in self.pnbs.itervalues() if (pn_it.ipp != pn.ipp and pn_it.ipp in osm.lookup_ipp and pn_it.stronglyConnected())] # Don't bother sending more than 8 nbs.sort() del nbs[8:] else: nbs = [] packet.append(struct.pack("!B", len(nbs))) packet.extend(nbs) ad = Ad().setRawIPPort(pn.ipp) self.main.ph.sendPacket(''.join(packet), ad.getAddrTuple())
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, data, tries, sendto, ph): # Message expiration timer. self.expire_dcall = None # If no tries remain, don't try to send anything. if not tries > 0: return # {neighbor ipp -> retry dcall} self.sending = {} create_time = seconds() for nb_ipp in sendto: self.scheduleSend(data, tries, nb_ipp, create_time, ph) self.cleanupIfDoneSending()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(tries): # Ack timeout/retransmit callback send_data = data # Decrease the hop count by the number of seconds the packet # has been buffered. buffered_time = int(seconds() - create_time) if buffered_time > 0: hops = ord(data[8]) - buffered_time if hops >= 0: # Splice in the reduced hop count. send_data = "%s%c%s" % (data[:8], hops, data[9:]) else: # Drop packet. tries = 0 # Make an attempt now if tries > 0: addr = Ad().setRawIPPort(nb_ipp).getAddrTuple() ph.sendPacket(send_data, addr, broadcast=True) # Reschedule another attempt if tries-1 > 0: when = random.uniform(1.0, 2.0) self.sending[nb_ipp] = reactor.callLater(when, cb, tries-1) else: del self.sending[nb_ipp] self.cleanupIfDoneSending()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cancelSendToNeighbor(self, nb_ipp): # This neighbor already has the message, so don't send it. try: self.sending.pop(nb_ipp).cancel() except (AttributeError, KeyError): return self.cleanupIfDoneSending()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def scheduleExpire(self, msgs, ack_key): # Forget about this message, eventually. if self.expire_dcall: self.expire_dcall.reset(180.0) return def cb(): self.expire_dcall = None self.cancelAllSends() del msgs[ack_key] self.expire_dcall = reactor.callLater(180.0, cb)
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, main): self.main = main self.msgs = {} self.rcollide_last_NS = None self.rcollide_ipps = set() r = random.randint(0, 0xFFFFFFFF) self.search_pktnum = r self.chat_pktnum = r self.main.osm.me.status_pktnum = r
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def pokeMessage(self, ack_key, nb_ipp): # If we know about this message, then mark down that this neighbor # has acknowledged it. try: m = self.msgs[ack_key] except KeyError: # Don't know about this message return False # Extend the expiration time. m.scheduleExpire(self.msgs, ack_key) # If not locally-generated, tell the message that this neighbor # acknowledged it. if nb_ipp: m.cancelSendToNeighbor(nb_ipp) # Message is known. return True
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def receivedRejection(self, ack_key, ipp): # Broadcast rejection, sent in response to a previous broadcast if # another node doesn't recognize us on the network. # We attach a status_pktnum to any broadcast which could possibly # be rejected. If this matches my status_pktnum now, then we should # broadcast a new status, which will change status_pktnum and # prevent this same broadcast from triggering another status update. osm = self.main.osm try: m = self.msgs[ack_key] except KeyError: raise BadTimingError("Reject refers to an unknown broadcast") if m is self.rcollide_last_NS: # Remote nick collision might have occurred self.rcollide_ipps.add(ipp) if len(self.rcollide_ipps) > 1: # Multiple nodes have reported a problem, so tell the user. dch = self.main.getOnlineDCH() if dch: dch.remoteNickCollision() # No more reports until next time self.rcollide_last_NS = None self.rcollide_ipps.clear() if osm.me.status_pktnum == m.status_pktnum: # One of my hash-containing broadcasts has been rejected, so # send my full status to refresh everyone. # (Note: m.status_pktnum is None for irrelevant messages.) osm.sendMyStatus()
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def getPacketNumber_chat(self): self.chat_pktnum = (self.chat_pktnum + 1) % 0x100000000 return self.chat_pktnum
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def broadcastHeader(self, kind, src_ipp, hops=32, flags=0): # Build the header used for all broadcast packets packet = [kind] packet.append(self.main.osm.me.ipp) packet.append(struct.pack('!BB', hops, flags)) packet.append(src_ipp) return packet
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self): self.nbs = {} # {ipp: max hop count} self.expire_dcall = None
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def cb(): del msgs[key]
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def __init__(self, main): self.main = main self.msgs = {}
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]
def sendSyncReply(self, src_ipp, cont, uncont): ad = Ad().setRawIPPort(src_ipp) osm = self.main.osm CHECK(osm and osm.syncd) # Build Packet packet = ['YR'] # My IP:Port packet.append(osm.me.ipp) # My last pktnum packet.append(struct.pack('!I', osm.me.status_pktnum)) # If we send a YR which is almost expired, followed closely by # an NH with an extended expire time, then a race condition exists, # because the target could discard the NH before receiving the YR. # So, if we're about to expire, go send a status update NOW so that # we'll have a big expire time to give to the target. expire = dcall_timeleft(osm.sendStatus_dcall) if expire <= 5.0: osm.sendMyStatus(sendfull=False) expire = dcall_timeleft(osm.sendStatus_dcall) # Exact time left before my status expires. # (The receiver will add a few buffer seconds.) packet.append(struct.pack('!H', int(expire))) # Session ID, Uptime, Flags, Nick, Info packet.extend(osm.getStatus()) # If I think I set the topic last, then put it in here. # It's up to the receiving end whether they'll believe me. if osm.tm.topic_node is osm.me: topic = osm.tm.topic else: topic = "" packet.append(struct.pack('!B', len(topic))) packet.append(topic) # Contacted Nodes packet.append(struct.pack('!B', len(cont))) packet.extend(cont) # Uncontacted Nodes packet.append(struct.pack('!B', len(uncont))) packet.extend(uncont) self.main.ph.sendPacket(''.join(packet), ad.getAddrTuple())
pmarks-net/dtella
[ 5, 2, 5, 11, 1426380623 ]