def resolveHost(self, host): address = self.dnsCache.getCachedAddress(host) if address != None: mitmf_logger.debug("[ClientRequest] Host cached: {} {}".format( host, address)) return defer.succeed(address) else: mitmf_logger.debug("[ClientRequest] Host not cached.") if self.resolver == 'dnschef': try: mitmf_logger.debug( "[ClientRequest] Resolving with DNSChef") address = str(self.customResolver.query(host)[0].address) return defer.succeed(address) except Exception: mitmf_logger.debug( "[ClientRequest] Exception occured, falling back to reactor.resolve()" ) return reactor.resolve(host) elif self.resolver == 'twisted': return reactor.resolve(host)
def main(): parser = argparse.ArgumentParser() parser.add_argument('dir', nargs='?', default='.', help="the directory to serve") parser.add_argument('-p', '--port', type=int, default=8000, help="the port to listen on") parser.add_argument('-r', '--raw', type=str, nargs='?', const=None, default=argparse.SUPPRESS, help="the port to listen on") args = parser.parse_args() if 'raw' not in args: resource = DirPage(args.dir) dir = args.dir else: if args.raw is None: args.raw = sys.stdin.read() resource = TextPage(args.raw) dir = None factory = server.Site(resource) endpoint = endpoints.TCP4ServerEndpoint(reactor, args.port) endpoint.listen(factory) reactor.resolve(socket.getfqdn()).addCallback(printStatus(dir, args.port)) reactor.run()
def main(argv): FORMAT = "%(levelname)-8s %(module)s: %(message)s" try: opts, args = getopt.getopt(argv, 'hoa:t:id',['help','target=']) except getopt.GetoptError as err: print str(err) sys.exit(2) remote_host = 'ml605' debug = False port = 3000 for opt,arg in opts: if opt in ('-h', '--help'): print '<file_name>.py -t <target> [-i]' sys.exit() elif opt in ('-t', '--target'): remote_host = arg elif opt in ('-d', '--debug'): debug = True if debug: logging.basicConfig(level=logging.DEBUG, format=FORMAT) else: logging.basicConfig(level=logging.INFO, format=FORMAT) #reactor.resolve(remote_host).addCallback(start_io, port, argv) reactor.resolve(remote_host).addCallback(start_io, port) reactor.run()
def __init__(self, host, port): self.begin_host = host self.begin_port = port self.query = DHTQuery() self.tp = TorrentProcess() cmd = [ 'd:\\python27\\python.exe', 'E:\\Projects\\TSpider\\DHT\\torrent.py' ] reactor.spawnProcess(self.tp, cmd[0], cmd) #generate 100 random id , {port : id} self.id_list = {} now_port = 6881 for a in range(0, 0x64): id = struct.pack('B', a) + ''.join( random.choice(string.printable) for x in xrange(19)) self.id_list[now_port] = id now_port += 1 print len(self.id_list) for k, v in self.id_list.iteritems(): logging.info('generate id:[%d][%r]' % (k, v)) reactor.resolve(self.begin_host).addCallback(self.gotIP)
def startAudio(self, sdp): md = sdp.getMediaDescription('audio') addr = md.ipaddr or sdp.ipaddr def go(ipaddr): remoteAddr = (ipaddr, md.port) return RTPStart(cookie=self.cookie, targethost=remoteAddr[0], targetport=remoteAddr[1]).do(self.rtp) reactor.resolve(addr).addCallback(go)
def startProtocol(self): print "1. Start protocol" # Come prima cosa risolvo il nome # TODO: devo unserire una cache nella risoluzione reactor.resolve(self.server_address).addCallbacks(self.got_ip, self.no_ip) self.start_tout(CtrlUnitDatagramProtocol.ERR_NO_DNS_RESOLUTION, "IP resolution")
def __init__(self, host): self.clientFactory = SnarlNetworkProtocolClientFactory() self.serverFactory = SnarlNetworkProtocolServerFactory() if host.enable_outgoing.value: reactor.resolve(host.address.value).addCallback(self.gotIP).addErrback(self.noIP) if host.enable_incoming.value: self.serverPort = reactor.listenTCP(SNP_TCP_PORT, self.serverFactory) self.pending += 1
def main(argv): parser = OptionParser() parser.add_option("-t", dest="target", default='192.168.21.81', help="target host/IP") parser.add_option("-p", dest="port", default=3000, help="UDP port") (opts, args) = parser.parse_args() reactor.resolve(opts.target).addCallback(start_io, opts.port) reactor.run()
def startProtocol(self): #============================== def _start_protocol(ip): """This is called once the host is resolved.""" self.host = ip self.transport.connect(self.host, self.port) self.authenticate() reactor.resolve(self.host).addCallback(_start_protocol)
def add_device(self, device): """ Add a single device to the list of devices that we have """ def really_add_device(addr): device.host = addr reactor.connectTCP(device.host, device.port, self.client_factory) self.devices[device.name] = device self.addr_mapping[(device.host, device.port)] = device device.add_proxy(self) reactor.resolve(device.host).addCallback(really_add_device)
def clientEnter(self): self.clientWait.onEnter() Game.network = TFTProtocol() def onResolve(ip, self=self): if self.state == self.STATE_CONNECT: Game.network.address = (ip, Game.ServerPort) Game.port = reactor.listenUDP(0, Game.network) def onFail(err, self=self): if self.state == self.STATE_CONNECT: Game.failure = err.getErrorMessage() self.changeState(self.STATE_FAILURE) reactor.resolve(Game.ServerIP).addCallback(onResolve).addErrback(onFail)
def resolve(parsedPath): arguments = urlparse.parse_qs(parsedPath.query) hostname = arguments["hostname"][0] try: ip = yield reactor.resolve(hostname) except Exception, e: message = str(e)
def get_local_ip(): """ Returns a deferred which will be called with a 2-uple (lan_flag, ip_address) : - lan_flag: - True if it's a local network (RFC1918) - False if it's a WAN address - ip_address is the actual ip address @return: A deferred called with the above defined tuple @rtype: L{twisted.internet.defer.Deferred} """ # first we try a connected udp socket, then via multicast logging.debug("Resolving dns to get udp ip") try: ipaddr = yield reactor.resolve('A.ROOT-SERVERS.NET') except: pass else: udpprot = DatagramProtocol() port = reactor.listenUDP(0, udpprot) udpprot.transport.connect(ipaddr, 7) localip = udpprot.transport.getHost().host port.stopListening() if is_bogus_ip(localip): raise RuntimeError("Invalid IP address returned") else: defer.returnValue((is_rfc1918_ip(localip), localip)) logging.debug("Multicast ping to retrieve local IP") ipaddr = yield _discover_multicast() defer.returnValue((is_rfc1918_ip(ipaddr), ipaddr))
def initialize(self): self.clean() def resolveCb(result): self.mangle.createChain(chain="cattivo") entry = self._createAuthenticatorEntry(result) self.mangle.appendEntry(entry, chain="cattivo") entry = self._createLocalTrafficEntry() self.mangle.appendEntry(entry, chain="cattivo") entry = self._createDefaultTproxyEntry() self.mangle.appendEntry(entry, chain="cattivo") self.mangle.commit() entry = self._createJumpInCattivoEntry() self.mangle.appendEntry(entry, chain="PREROUTING") self.mangle.commit() authenticator = cattivo.config.get("authenticator", "host") url = URLPath.fromString(authenticator) address = url.netloc dfr = reactor.resolve(address) dfr.addCallback(resolveCb) return dfr
def _reflect_stream(lbry_file, reflector_server): reflector_address, reflector_port = reflector_server[0], reflector_server[ 1] factory = ClientFactory(lbry_file) ip = yield reactor.resolve(reflector_address) yield reactor.connectTCP(ip, reflector_port, factory) yield factory.finished_deferred
def _reflect_blobs(blob_manager, blob_hashes, reflector_server): reflector_address, reflector_port = reflector_server[0], reflector_server[ 1] factory = BlobClientFactory(blob_manager, blob_hashes) ip = yield reactor.resolve(reflector_address) yield reactor.connectTCP(ip, reflector_port, factory) yield factory.finished_deferred
def create(host, port, connect_callback=None, disconnect_callback=None, resolver_errback=None): """Create an instance that resolves the host to an IP asynchronously. Will queue all messages while the host is not yet resolved. Build a connection that reports to the endpoint (on C{host} and C{port}) using UDP. @param host: The StatsD server host. @param port: The StatsD server port. @param resolver_errback: The errback to invoke should issues occur resolving the supplied C{host}. @param connect_callback: The callback to invoke on connection. @param disconnect_callback: The callback to invoke on disconnection.""" from twisted.internet import reactor instance = TwistedStatsDClient(host=host, port=port, connect_callback=connect_callback, disconnect_callback=disconnect_callback) if resolver_errback is None: resolver_errback = log.err instance.resolve_later = reactor.resolve(host) instance.resolve_later.addCallbacks(instance.host_resolved, resolver_errback) return instance
def __init__(self, torrent, url, verbose=None): self._torrent = torrent self._verbose = verbose self.status = "Connecting..." self._connection_id = None self._msngr = None self.seeders = -1 #negative means not connected yet self.leechers = -1 if not url.startswith('udp://'): raise ValueError("URL should be udp") else: u, p = url.split('/')[2].split(':') if self._verbose > 10: print("Trying to resolve ip for %s" % u) self._url = url self._port = int(p) reactor.resolve(u).addCallbacks(self._ip_resolved, self._ip_failed)
def get(self): host = self.config.get('destination', self.hostname) try: ip = yield reactor.resolve(host) except: ip = None if ip: try: loss, latency = yield icmp.ping(ip, 5) except: loss, latency = 100, None event = [self.createEvent('ok', '%s%% loss to %s' % (loss,host), loss, prefix="loss")] if latency: event.append(self.createEvent('ok', 'Latency to %s' % host, latency, prefix="latency")) else: event = [self.createEvent('critical', 'Unable to resolve %s' % host, 100, prefix="loss")] defer.returnValue(event)
def announce(self, torrent): self.torrent = torrent host = yield reactor.resolve(self.host, timeout=(1, 3)) self.host = host reactor.listenUDP(self.factory.track_port, self) peers = yield self.deferred defer.returnValue(peers)
def get_deferred_host_ip(): global _host_ip global _host_ip_callbacks global _host_ip_cachetime assert reactor.ident == thread.get_ident() if _host_ip is not "unknown" and _host_ip_cachetime + CACHE_TIME > bttime(): return defer.succeed(_host_ip) df = defer.Deferred() if not _host_ip_callbacks: def connect(ip): factory = RecorderFactory() factory.protocol = RecorderProtocol if hasattr(reactor, "limiter"): reactor.connectTCP(ip, 80, factory, urgent=True) else: reactor.connectTCP(ip, 80, factory) rdf = reactor.resolve("ip.bittorrent.com") rdf.addCallback(connect) rdf.addErrback(lambda e: _got_result(None)) _host_ip_callbacks.append(df) return df
def __init__(self, torrent, url, verbose=None): self._torrent = torrent self._verbose = verbose self.status = "Connecting..." self._connection_id = None self._msngr = None self.seeders = -1 #negative means not connected yet self.leechers = -1 if not url.startswith('udp://'): raise ValueError("URL should be udp") else: u, p = url.split('/')[2].split(':') if self._verbose > 10: print("Trying to resolve ip for %s"%u) self._url = url self._port = int(p) reactor.resolve(u).addCallbacks(self._ip_resolved, self._ip_failed)
def sendto(self, data, destination): self.last_incoming = time.time() if self.check_num_packets(destination, False): if DataChecker.is_allowed(data): def on_error(failure): self.logger.error( "Can't resolve ip address for hostname %s. Failure: %s", destination[0], failure) def on_ip_address(ip_address): self.logger.debug("Resolved hostname %s to ip_address %s", destination[0], ip_address) try: self.transport.write(data, (ip_address, destination[1])) self.overlay.increase_bytes_sent(self, len(data)) except (AttributeError, MessageLengthError, socket.error) as exception: self.logger.error( "Failed to write data to transport: %s. Destination: %r error was: %r", exception, destination, exception) resolve_ip_address_deferred = reactor.resolve(destination[0]) resolve_ip_address_deferred.addCallbacks( on_ip_address, on_error) self.register_task("resolving_%r" % destination[0], resolve_ip_address_deferred) else: self.logger.error( "dropping forbidden packets from exit socket with circuit_id %d", self.circuit_id)
def get(self): host = self.config.get('destination', self.hostname) try: ip = yield reactor.resolve(host) except: ip = None if ip: try: loss, latency = yield icmp.ping(ip, 5) except: loss, latency = 100, None event = [self.createEvent('ok', '%s%% loss to %s' % (loss, host), loss, prefix="loss")] if latency: event.append(self.createEvent('ok', 'Latency to %s' % host, latency, prefix="latency")) else: event = [self.createEvent('critical', 'Unable to resolve %s' % host, 100, prefix="loss")] defer.returnValue(event)
def create(host, port, connect_callback=None, disconnect_callback=None, resolver_errback=None): """Create an instance that resolves the host to an IP asynchronously. Will queue all messages while the host is not yet resolved. Build a connection that reports to the endpoint (on C{host} and C{port}) using UDP. @param host: The StatsD server host. @param port: The StatsD server port. @param resolver_errback: The errback to invoke should issues occur resolving the supplied C{host}. @param connect_callback: The callback to invoke on connection. @param disconnect_callback: The callback to invoke on disconnection.""" from twisted.internet import reactor instance = TwistedStatsDClient( host=host, port=port, connect_callback=connect_callback, disconnect_callback=disconnect_callback) if resolver_errback is None: resolver_errback = log.err instance.resolve_later = reactor.resolve(host) instance.resolve_later.addCallbacks(instance.host_resolved, resolver_errback) return instance
def resolveAddress(self): host, port = self.addr if isIPAddress(host): return self.addr else: from twisted.internet import reactor return reactor.resolve(host).addCallback(self._filterRealAddress)
def _resolveStunServers(self, localAddress): self.localAddress = localAddress # reactor.resolve the hosts! for host, port in self.servers: d = reactor.resolve(host) #添加向stun server发送消息的函数 d.addCallback(lambda x,p=port: self.initialStunRequest((x, p)))
def get_local_ip(): """ Returns a deferred which will be called with a 2-uple (lan_flag, ip_address) : - lan_flag: - True if it's a local network (RFC1918) - False if it's a WAN address - ip_address is the actual ip address @return: A deferred called with the above defined tuple @rtype: L{twisted.internet.defer.Deferred} """ # first we try a connected udp socket, then via multicast logging.debug("Resolving dns to get udp ip") try: ipaddr = yield reactor.resolve('A.ROOT-SERVERS.NET') except: pass else: udpprot = DatagramProtocol() port = reactor.listenUDP(0, udpprot) udpprot.transport.connect(ipaddr, 7) localip = udpprot.transport.getHost().host port.stopListening() if is_bogus_ip(localip): raise RuntimeError, "Invalid IP address returned" else: defer.returnValue((is_rfc1918_ip(localip), localip)) logging.debug("Multicast ping to retrieve local IP") ipaddr = yield _discover_multicast() defer.returnValue((is_rfc1918_ip(ipaddr), ipaddr))
def resolve(self): """ Resolve all unresolved trackers asynchronously. """ if self.all_resolved: self.cancel_pending_task(u'task_resolving_bootstrap_address') self._logger.debug("Resolved all bootstrap addresses") return succeed(None) else: self._logger.info("Resolving bootstrap addresses") addresses = [address for address, candidate in self._candidates.items() if not candidate] shuffle(addresses) def add_candidate(ip, host, port): self._logger.info("Resolved %s into %s:%d", host, ip, port) self._candidates[(host, port)] = Candidate((str(ip), port), False) def no_candidate(host, port): self._logger.warning("Could not resolve bootstrap candidate: %s:%s", host, port) deferreds = [] for host, port in addresses: if isIPAddress(host): add_candidate(host, host, port) else: deferred = reactor.resolve(host) self.register_task("resolve_%s_%s" % (host, port), deferred) deferred.addCallback(lambda ip, host=host, port=port: add_candidate(ip, host, port)) deferred.addErrback(lambda _, host=host, port=port: no_candidate(host, port)) deferreds.append(deferred) return gatherResults(deferreds)
def join_dht(self, cb=None): from twisted.internet import reactor def join_resolved_addresses(result): addresses = [] for success, value in result: if success is True: addresses.append(value) return addresses @defer.inlineCallbacks def join_network(knownNodes): log.debug("join DHT using known nodes: " + str(knownNodes)) result = yield self.dht_node.joinNetwork(knownNodes) defer.returnValue(result) ds = [] for host, port in self.known_dht_nodes: d = reactor.resolve(host) d.addCallback(lambda h: (h, port)) # match host to port ds.append(d) dl = defer.DeferredList(ds) dl.addCallback(join_resolved_addresses) dl.addCallback(join_network) if cb: dl.addCallback(cb) return dl
def callRemote(self, path): if pipeline_debug: print 'callRemote to %s : %s' % (self.host, path) query = Query(path, self.host, self.user, self.password) self.factory.addQuery(query) if pipeline_debug: print 'factory started: %s' % self.factory.started if not self.factory.started: self.factory.started = True def connect(host): if self.secure: if pipeline_debug: print 'connecting to %s' % str( (host, self.port or 443)) from twisted.internet import ssl reactor.connectSSL(host, self.port or 443, self.factory, ssl.ClientContextFactory(), timeout=60) else: if pipeline_debug: print 'connecting to %s' % str((host, self.port or 80)) reactor.connectTCP(host, self.port or 80, self.factory, timeout=60) df = reactor.resolve(self.host) df.addCallback(connect) df.addErrback(query.deferred.errback) return query.deferred
def dns_resolve(addr): ip, port = addr if re.match(r'^(\d+\.){3}\d+$', ip): defer.returnValue(addr) else: ip = yield reactor.resolve(ip) addr = ip, port defer.returnValue(addr)
def resolveHost(self, host): address = self.dnsCache.getCachedAddress(host) if address != None: mitmf_logger.debug("[Ferret-NG] [ClientRequest] Host cached: {} {}".format(host, address)) return defer.succeed(address) else: return reactor.resolve(host)
def resolve(self): """ Resolve the host IP address to avoid to many DNS queries """ d = reactor.resolve(self.host) d.addCallback(lambda r: setattr(self, 'host_address', r)) d.addCallback(lambda _: setattr(self, 'resolved', True)) d.addCallback(lambda _: self.connect()) return d
def resolveHost(self, host): address = self.dnsCache.getCachedAddress(host) if address != None: log.debug("[ClientRequest] Host cached: {} {}".format(host, address)) return defer.succeed(address) else: return reactor.resolve(host)
def resolve(self, hostname): """Asynchronously resolve a hostname, with caching.""" ip = self.dns_cache.get(hostname, None) if ip is None: ip = yield reactor.resolve(hostname) self.dns_cache[hostname] = ip defer.returnValue(ip)
def _check_if_reflector_has_stream(lbry_file, reflector_server): reflector_address, reflector_port = reflector_server[0], reflector_server[ 1] factory = BlobClientFactory(lbry_file.blob_manager, [lbry_file.sd_hash]) d = reactor.resolve(reflector_address) d.addCallback(lambda ip: reactor.connectTCP(ip, reflector_port, factory)) d.addCallback(lambda _: factory.finished_deferred) d.addCallback(lambda _: not factory.sent_blobs) return d
def resolve_host(self, host): address = self.dns_cache.get(host) if address != None: logging.debug('Host was cached') return defer.succeed(address) else: logging.debug('Host not cached') return reactor.resolve(host)
def on_server(self, data, addr): host, port = addr if data.ip is not None: d = reactor.resolve(data.ip) d.addCallback(self.on_resolve, host, data.ip, data) d.addErrback(self.on_resolve_error, host, data) return data.ip = host self.add_server(data, host)
def resolveHost(self, host): address = self.dnsCache.getCachedAddress(host) if address != None: logging.debug("Host cached.") return defer.succeed(address) else: logging.debug("Host not cached.") return reactor.resolve(host)
def resolve_hosts(nodes_list): result_defer = Deferred() result_list = [] for node_tuple in nodes_list: d = reactor.resolve(node_tuple[0]) d.addCallback(on_host_resoled, node_tuple[1], node_tuple[0], result_list, len(nodes_list), result_defer) d.addErrback(on_host_failed, node_tuple[0], result_list, len(nodes_list), result_defer) # d.addErrback(on_host_resoled, None, node_tuple[0], result_list, len(nodes_list), result_defer) return result_defer
def _resolveStunServers(self, localAddress): self.localAddress = localAddress # reactor.resolve the hosts! self.not_resolved_servers = 0 for host, port in self.servers: # print '_resolveStunServers', host, port d = reactor.resolve(host) d.addCallback(lambda x, p=port: self.initialStunRequest((x, p))) d.addErrback(self._hostNotResolved, (host, port))
def resolveHost(self, host): address = self.dnsCache.getCachedAddress(host) if address != None: logging.debug("[ClientRequest] Host cached: %s %s" % (host, str(address))) return defer.succeed(address) else: logging.debug("[ClientRequest] Host not cached.") return reactor.resolve(host)
def join(self, deferred = None): """See L{apt_p2p.interfaces.IDHT}. @param deferred: the deferred to callback when the join is complete (optional, defaults to creating a new deferred and returning it) """ # Check for multiple simultaneous joins if self.joining: if deferred: deferred.errback(DHTError("a join is already in progress")) return else: raise DHTError, "a join is already in progress" if deferred: self.joining = deferred else: self.joining = defer.Deferred() if self.config is None: self.joining.errback(DHTError("configuration not loaded")) return self.joining # Create the new khashmir instance if not self.khashmir: self.khashmir = Khashmir(self.config, self.cache_dir) self.outstandingJoins = 0 for node in self.bootstrap: host, port = node.rsplit(':', 1) port = int(port) self.outstandingJoins += 1 # Translate host names into IP addresses if isIPAddress(host): self._join_gotIP(host, port) else: reactor.resolve(host).addCallbacks(self._join_gotIP, self._join_resolveFailed, callbackArgs = (port, ), errbackArgs = (host, port)) return self.joining
def discoverAddress(self): """ Sniff out external address. Returns a deferred with the external address as a 2-tuple (ip, port) """ self.installStun() self.deferred = defer.Deferred() for host, port in self.servers[:3]: d = reactor.resolve(host) d.addCallback(lambda x, p=port: self.initialStunRequest((x, p))) return self.deferred
def setup_worker(self): self.format_string = self.config.get( 'format_string', self.DEFAULT_FORMAT_STRING) self.timestamp_format = self.config.get( 'timestamp_format', self.DEFAULT_TIMESTAMP_FORMAT) self.metrics_ip = yield reactor.resolve(self.config['metrics_host']) self.metrics_port = int(self.config['metrics_port']) self.metrics_protocol = UDPMetricsProtocol( self.metrics_ip, self.metrics_port) self.listener = yield reactor.listenUDP(0, self.metrics_protocol)
def info(self): if not hasattr(self, '_info'): hostname = socket.getfqdn() """@warning: C{socket.getfqdn} may block""" address = self.address.to_moduleaddress() ip_address = yield reactor.resolve(socket.gethostname()) self._info = GeneralModuleInfo(address, ip_address, hostname) defer.returnValue(self._info)
def _check_if_reflector_has_stream(lbry_file, reflector_server): reflector_address, reflector_port = reflector_server[0], reflector_server[1] factory = BlobClientFactory( lbry_file.blob_manager, [lbry_file.sd_hash] ) d = reactor.resolve(reflector_address) d.addCallback(lambda ip: reactor.connectTCP(ip, reflector_port, factory)) d.addCallback(lambda _: factory.finished_deferred) d.addCallback(lambda _: not factory.sent_blobs) return d
def fetch(self, remfile, fp=None): if fp is not None: self.fp = fp else: self.fp = StringIO.StringIO() remhost, rempath = remfile.split(':',1) resdef = reactor.resolve(remhost) self.retdef = defer.Deferred() resdef.addCallbacks(lambda x: self._sendRRQ(x,rempath), self.retdef.errback) return self.retdef