def add_setCrashDetectGen(self): self.app.status.append('Crash detection Initiated') self.state = self.SETTING_CRASH_DETECT if not self._setCrashGen: self._setCrashGen = self._setCrashDetect() multitask.add(self._setCrashGen) return self
def clientlistener(self, client): '''Client listener (generator). It receives a command and invokes client handler, or receives a new stream and invokes streamlistener.''' try: while True: msg, arg = (yield client.recv()) # receive new message from client if not msg: # if the client disconnected, if _debug: print 'connection closed from client' break # come out of listening loop. if msg == 'command': # handle a new command multitask.add(self.clienthandler(client, arg)) elif msg == 'stream': # a new stream is created, handle the stream. arg.client = client multitask.add(self.streamlistener(arg)) except StopIteration: raise except: if _debug: print 'clientlistener exception', (sys and sys.exc_info() or None) traceback.print_exc() # client is disconnected, clear our state for application instance. if _debug: print 'cleaning up client', client.path inst = None if client.path in self.clients: inst = self.clients[client.path][0] self.clients[client.path].remove(client) for stream in client.streams.values(): # for all streams of this client self.closehandler(stream) client.streams.clear() # and clear the collection of streams if client.path in self.clients and len(self.clients[client.path]) == 1: # no more clients left, delete the instance. if _debug: print 'removing the application instance' inst = self.clients[client.path][0] inst._clients = None del self.clients[client.path] if inst is not None: inst.onDisconnect(client)
def onConnect(self, client, *args): result = rtmp.App.onConnect(self, client, *args) self.clientId += 1 client.clientId = self.clientId def invokeAdded( self, client ): # invoke the added and published callbacks on this client, and added on other clients. for other in filter(lambda x: x != client, self.clients): yield client.call('added', str(other.clientId)) yield other.call('added', str(client.clientId)) for stream in filter(lambda x: x.client != client, self.publishers.values()): yield client.call('published', str(stream.client.clientId), stream.name) yield multitask.add( invokeAdded(self, client) ) # need to invoke later so that connection is established before callback # if _debug: # def printBW(client, interval=5): # while True: # yield multitask.sleep(interval) # print 'client bandwidth up=', int(client.stream.bytesRead*8/interval*0.001),'down=', int(client.stream.bytesWritten*8/interval*0.001) # client.stream.bytesRead = client.stream.bytesWritten = 0 # self._bwthread = printBW(client) # multitask.add(self._bwthread) return result
def __init__(self, options): ''' Inits App with options and calls mainController()''' logger.info("ntsga: init app") self.options = options self.status = [] self.user = None multitask.add(self.mainController())
def __init__(self, options): ''' Inits App with options and calls mainController()''' logger.info("ntsga: init app") self.options = options self.status = [] self.user = None multitask.add(self.mainController())
def start(self, delay=None): import multitask if self.running: self.stop() # stop previous one first. if delay is not None: self.delay = delay # set the new delay self.running = True self.gen = self.run() multitask.add(self.gen)
def add_setCrashDetectGen(self): self.app.status.append('Crash detection Initiated') self.state = self.SETTING_CRASH_DETECT if not self._setCrashGen: self._setCrashGen = self._setCrashDetect() multitask.add(self._setCrashGen) return self
def _sipreceiver(self, stack, maxsize=16386): '''Handle the messages or connections on the given SIP stack's socket, and pass it to the stack so that stack can invoke appropriate callback on this object such as receivedRequest.''' sock = stack.sock def tcpreceiver(sock, remote): # handle the messages on the given TCP connection. while True: data = yield multitask.recv(sock, maxsize) if _debug: print '%r=>%r on type=%r\n%s' % ( remote, sock.getsockname(), sock.type, data) if data: stack.received(data, remote) while True: if sock.type == socket.SOCK_DGRAM: data, remote = yield multitask.recvfrom(sock, maxsize) if _debug: print '%r=>%r on type=%r\n%s' % ( remote, sock.getsockname(), sock.type, data) if data: stack.received(data, remote) elif sock.type == socket.SOCK_STREAM: conn, remote = yield multitask.accept(sock) if conn: self.conn[remote] = conn multitask.add(tcpreceiver(conn, remote)) else: raise ValueError, 'invalid socket type'
def start(self, net=None, servers=None): """Start the p2p node as ordinary node. Create a network object if none.""" if self.net is None: self.net = net or Network(Ks=crypto.generateRSA()[0], cert=None, port=self.port) self.net.start() # convert from serevrs ip:port list to Node list if servers: servers = [ Node(ip=ip, port=port, type=socket.SOCK_DGRAM, guid=H(ip + ":" + str(port))) for ip, port in servers ] if _debug: print "using servers=", servers self.client = Client(self.net, server=self.server).start(servers) if self.server: if self.router is None: self.router = dht.Router(self.net).start() if self.storage is None: self.storage = dht.Storage(self.net, self.router).start() if not self.router.initialized: self.router.initialized = True if not self._gens: for gen in [self.handler()]: multitask.add(gen) self._gens.append(gen) return self
def clienthandler(self): """Receive requests from client and send to the router module, and viceversa.""" net = self.net def requesthandler(msg): p = msg.payload response = None if self.server: # only if a server if p.name == "Put:Request": result = yield dht.put(net, p.dest, p.value, p.nonce, p.expires, p.Ks, p.put) response = Message(name="Put:Response", seq=p.seq, result=result) elif p.name == "Get:Request": result = yield dht.get(net, p.dest, p.maxvalues, p.Kp) response = Message(name="Get:Response", seq=p.seq, guid=p.guid, vals=result) if response: yield self.net.send( Message(name="Proxy:Response", src=net.node, payload=response), node=msg.src, timeout=5 ) def responsehandler(msg): if not self.server: # only if a client yield net.put(msg.payload, timeout=5) while True: msg = yield self.net.get(lambda x: x.name == "Proxy:Request" or x.name == "Proxy:Response") if msg: multitask.add(requesthandler(msg) if msg.name == "Proxy:Request" else responsehandler(msg))
def start(self, delay=None): import multitask if self.running: self.stop() # stop previous one first. if delay is not None: self.delay = delay # set the new delay self.running = True self.gen = self.run() multitask.add(self.gen)
def send(self, data, remote, stack): '''Send a given data to remote for the SIP stack.''' def _send(self, data, remote, stack): # a generator function that does the sending logger.debug('%r=>%r on type=%r\n%s', stack.sock.getsockname(), remote, stack.transport.type, data) try: if stack.sock.type == socket.SOCK_STREAM: # for TCP send only if a connection exists to the remote. if stack.transport.type in ('ws', 'wss'): if len(data) < 126: init = struct.pack('>BB', 0x81, len(data)) elif len(data) < 65536: init = struct.pack('>BBH', 0x81, 126, len(data)) else: raise ValueError, 'cannot send long message' data = init + data if remote in self.conn: yield multitask.send( self.conn[remote], data) # and send using that connected TCP socket. else: logger.warning( 'ignoring message to %r as no existing connection', remote) else: # for UDP send using the stack's UDP socket. yield multitask.sendto(stack.sock, data, remote) except StopIteration: pass except: logger.exception('sending') multitask.add(_send(self, data, remote, stack))
def start(self, net=None, servers=None): '''Start the p2p node as ordinary node. Create a network object if none.''' if self.net is None: self.net = net or Network( Ks=crypto.generateRSA()[0], cert=None, port=self.port) self.net.start() # convert from serevrs ip:port list to Node list if servers: servers = [ Node(ip=ip, port=port, type=socket.SOCK_DGRAM, guid=H(ip + ':' + str(port))) for ip, port in servers ] if _debug: print 'using servers=', servers self.client = Client(self.net, server=self.server).start(servers) if self.server: if self.router is None: self.router = dht.Router(self.net).start() if self.storage is None: self.storage = dht.Storage(self.net, self.router).start() if not self.router.initialized: self.router.initialized = True if not self._gens: for gen in [self.handler()]: multitask.add(gen) self._gens.append(gen) return self
def onConnect(self, client, *args): result = rtmp.App.onConnect(self, client, *args) self.clientId += 1 client.clientId = self.clientId def invokeAdded( self, client ): # invoke the added and published callbacks on this client, and added on other clients. for other in filter(lambda x: x != client, self.clients): client.call("added", str(other.clientId)) other.call("added", str(client.clientId)) for stream in filter(lambda x: x.client != client, self.publishers.values()): client.call("published", str(stream.client.clientId), stream.name) yield multitask.add( invokeAdded(self, client) ) # need to invoke later so that connection is established before callback # if _debug: # def printBW(client, interval=5): # while True: # yield multitask.sleep(interval) # print 'client bandwidth up=', int(client.stream.bytesRead*8/interval*0.001),'down=', int(client.stream.bytesWritten*8/interval*0.001) # client.stream.bytesRead = client.stream.bytesWritten = 0 # self._bwthread = printBW(client) # multitask.add(self._bwthread) return result
def test1(publishers, players): duration = 30 for i in xrange(publishers): url, stream = 'rtmp://localhost/live%d'%(i,), 'live' multitask.add(rtmpclient.connect(url, publishFile='file1.flv', publishStream=stream, playStream=None, duration=duration, params=[])) for j in xrange(players): multitask.add(rtmpclient.connect(url, playStream=stream, duration=duration, params=[]))
def handshake(self): # Implement the client side of the handshake. Must be invoked by caller after TCP connection completes. yield self.stream.write('\x03' + '\x00'*(Protocol.PING_SIZE)) # send first handshake data = (yield self.stream.read(Protocol.PING_SIZE + 1)) yield self.stream.write(data[1:]) # send second handshake data = (yield self.stream.read(Protocol.PING_SIZE)) multitask.add(self.parse()); multitask.add(self.write()) # launch the reader and writer tasks raise StopIteration, self
def start(self): '''Start the listening tasks in this agent. It returns self for cascaded method calls.''' for s in self.stack.values(): gen = self._sipreceiver(s) self._gens.append(gen) multitask.add(gen) return self
def receivedRequest(self, ua, request, stack): '''Callback when received an incoming request.''' def _receivedRequest(self, ua, request): # a generator version logger.debug('receivedRequest method=', request.method, 'ua=', ua, ' for ua', (ua.queue is not None and 'with queue' or 'without queue') ) if hasattr(ua, 'queue') and ua.queue is not None: yield ua.queue.put(request) elif request.method == 'INVITE': # a new invitation if self._queue is not None: if not request['Conf-ID']: # regular call invitation yield self._queue.put(('connect', (str(request.From.value), ua))) else: # conference invitation if request['Invited-By']: yield self._queue.put(('confconnect', (str(request.From.value), ua))) else: yield self._queue.put(('confinvite', (str(request.From.value), ua))) else: ua.sendResponse(405, 'Method not allowed') elif request.method == 'SUBSCRIBE': # a new watch request if self._queue: yield self._queue.put(('watch', (str(request.From.value), ua))) else: ua.sendResponse(405, 'Method not allowed') elif request.method == 'MESSAGE': # a paging-mode instant message if request.body and self._queue: ua.sendResponse(200, 'OK') # blindly accept the message yield self._queue.put(('send', (str(request.From.value), request.body))) else: ua.sendResponse(405, 'Method not allowed') elif request.method == 'CANCEL': # TODO: non-dialog CANCEL comes here. need to fix rfc3261_IPv6 so that it goes to cancelled() callback. if ua.request.method == 'INVITE': # only INVITE is allowed to be cancelled. yield self._queue.put(('close', (str(request.From.value), ua))) else: ua.sendResponse(405, 'Method not allowed') multitask.add(_receivedRequest(self, ua, request))
def _sipreceiver(self, stack, maxsize=16386): '''Handle the messages or connections on the given SIP stack's socket, and pass it to the stack so that stack can invoke appropriate callback on this object such as receivedRequest.''' sock = stack.sock while True: if sock.type == socket.SOCK_DGRAM: data, remote = yield multitask.recvfrom(sock, maxsize) logger.debug('%r=>%r on type=%r\n%s', remote, sock.getsockname(), stack.transport.type, data) if data: try: stack.received(data, remote) except: logger.exception('received') elif sock.type == socket.SOCK_STREAM: conn, remote = yield multitask.accept(sock) if conn: logger.debug('%r=>%r connection type %r', remote, conn.getsockname(), stack.transport.type) if stack.transport.type in ('ws', 'wss'): multitask.add( self._wsreceiver(stack, conn, remote, maxsize)) else: multitask.add( self._tcpreceiver(stack, conn, remote, maxsize)) else: raise ValueError, 'invalid socket type'
def allocateRequest(sock, m, remote): # serve the allocate request of TURN fivetuple = (sock.type, getlocaladdr(sock), remote) lifetime = timeout if Attribute.LIFETIME in m: lt = struct.unpack('!L', m[Attribute.LIFETIME].value) if lt < lifetime: lifetime = lt if fivetuple in binding: # already found newsock = binding[fivetuple] if lifetime == 0: # terminate the binding del binding[fivetuple] del binding[newsock] else: if lifetime > 0: # allocate, otherwise it is already missing. newsock = socket.socket(sock.family, sock.type) newsock.bind(('0.0.0.0', 0)) # bind to any binding[newsock] = fivetuple binding[fivetuple] = newsock res = Message() res.method, res.type, res.tid = m.method, Message.RESPONSE, m.tid mapped = Attribute(Attribute.MAPPED_ADDRESS) # mapped-address attribute mapped.address = (newsock.family, (external, newsock and newsock.getsockname()[1] or 0)) res.attrs.append(mapped) res.attrs.append(Attribute(Attribute.LIFETIME, struct.pack('!L', lifetime))) if lifetime == 0 and newsock: # close any previous listening function newsock.close() # this should trigger close of functions else: if sock.type == socket.SOCK_STREAM: multitask.add(relayaccepter(newsock, fivetuple)) else: multitask.add(relayreceiver(newsock, fivetuple)) yield respond(sock, str(res), remote)
def send(self, data, addr, stack): '''Send data to the remote addr.''' def _send(self, data, addr): # generator version try: logger.debug('sending[%d] to %s\n%s'%(len(data), addr, data)) if self.sock: if self.sock.type == socket.SOCK_STREAM: try: remote = self.sock.getpeername() if remote != addr: logger.debug('connected to wrong addr', remote, 'but sending to', addr) except socket.error: # not connected, try connecting try: self.sock.connect(addr) except socket.error: logger.debug('failed to connect to', addr) try: yield self.sock.send(data) except socket.error: logger.debug('socket error in send') elif self.sock.type == socket.SOCK_DGRAM: try: yield self.sock.sendto(data, addr) except socket.error: logger.debug('socket error in sendto' ) else: logger.debug('invalid socket type', self.sock.type) except AttributeError: pass multitask.add(_send(self, data, addr))
def send(self, data, addr, stack): '''Send data to the remote addr.''' def _send(self, data, addr): # generator version try: logger.debug('sending[%d] to %s\n%s' % (len(data), addr, data)) if self.sock: if self.sock.type == socket.SOCK_STREAM: try: remote = self.sock.getpeername() if remote != addr: logger.debug('connected to wrong addr', remote, 'but sending to', addr) except socket.error: # not connected, try connecting try: self.sock.connect(addr) except socket.error: logger.debug('failed to connect to', addr) try: yield self.sock.send(data) except socket.error: logger.debug('socket error in send') elif self.sock.type == socket.SOCK_DGRAM: try: yield self.sock.sendto(data, addr) except socket.error: logger.debug('socket error in sendto') else: logger.debug('invalid socket type', self.sock.type) except AttributeError: pass multitask.add(_send(self, data, addr))
def _sipreceiver(self, stack, maxsize=16386): '''Handle the messages or connections on the given SIP stack's socket, and pass it to the stack so that stack can invoke appropriate callback on this object such as receivedRequest.''' sock = stack.sock def tcpreceiver( sock, remote): # handle the messages on the given TCP connection. while True: data = yield multitask.recv(sock, maxsize) if _debug: print '%r=>%r on type=%r\n%s' % ( remote, sock.getsockname(), sock.type, data) if data: stack.received(data, remote) while True: if sock.type == socket.SOCK_DGRAM: data, remote = yield multitask.recvfrom(sock, maxsize) if _debug: print '%r=>%r on type=%r\n%s' % ( remote, sock.getsockname(), sock.type, data) if data: stack.received(data, remote) elif sock.type == socket.SOCK_STREAM: conn, remote = yield multitask.accept(sock) if conn: self.conn[remote] = conn multitask.add(tcpreceiver(conn, remote)) else: raise ValueError, 'invalid socket type'
def _registerUA(self): ''' Creates the requests to Register the use, Authenticates if neccesary and returns success/failed.''' if self.reg_state == None: self.app.status.append('Register Generator Initiated') try: if self.reg_refresh and self._ua.gen: yield multitask.sleep( self.register_interval - min(self.register_interval * 0.05, 5)) # refresh about 5 seconds before expiry self._ua.sendRequest(self._createRegister()) while True: response = (yield self._ua.queue.get()) if response.CSeq.method == 'REGISTER': if response.is2xx: # success if self.reg_refresh: if response.Expires: self.register_interval = int( response.Expires.value) if self.register_interval > 0: self._ua.gen = self._register( ) # generator for refresh multitask.add(self._ua.gen) raise StopIteration(('success', None)) elif response.isfinal: # failed raise StopIteration(('failed', str(response.response) + ' ' + response.responsetext)) except GeneratorExit: raise StopIteration(('failed', 'Generator closed'))
def close(self): '''Ends registration (Reg_Interval=0) and closes the User agent.''' self.register_interval = 0 multitask.add(self._register()) if self._ua.gen: self._ua.gen.close() self._ua.gen = None
def __init__(self, app, **kwargs): '''Initialize the network.''' self.app = app self.src = kwargs.get('src', ('0.0.0.0', 0)) self.dest = kwargs.get('dest', None) self.srcRTCP = kwargs.get( 'srcRTCP', (self.src[0], self.src[1] and self.src[1] + 1 or 0)) self.destRTCP = kwargs.get('destRTCP', None) self.maxsize = kwargs.get('maxsize', 1500) self.rtp = self.rtcp = None if self.src[1] != 0: # specified port try: s1 = socket.socket(type=socket.SOCK_DGRAM) s2 = socket.socket(type=socket.SOCK_DGRAM) if _debug: print 'created RTP/RTCP sockets', s1, s2 s1.bind(self.src) s2.bind(self.srcRTCP) except: if _debug: print 'failed to bind. closing', s1, s2 s1.close() s2.close() s1 = s2 = None else: retry = kwargs.get('retry', 20) # number of retries to do low = kwargs.get( 'low', 10000) # the range low-high for picking port number high = kwargs.get('high', 65535) even = kwargs.get('even', True) # means by default use even port for RTP while retry > 0: s1 = socket.socket(type=socket.SOCK_DGRAM) s2 = socket.socket(type=socket.SOCK_DGRAM) if _debug: print 'created RTP/RTCP sockets(2)', s1, s2 # don't bind to any (port=0) to avoid collision in RTCP, where some OS will allocate same port for RTP for retries if even: port = random.randint( low, high) & 0x0fffe # should not use high+1? else: port = random.randint(low, high) | 0x00001 try: s1.bind((self.src[0], port)) s2.bind((self.src[0], port + 1)) self.src, self.srcRTCP = s1.getsockname(), s2.getsockname() break except: if _debug: print 'failed to bind. closing(2)', s1, s2 s1.close() s2.close() s1 = s2 = None retry = retry - 1 if s1 and s2: self.rtp, self.rtcp = s1, s2 self._rtpgen = self.receiveRTP(self.rtp) self._rtcpgen = self.receiveRTCP(self.rtcp) multitask.add(self._rtpgen) multitask.add(self._rtcpgen) else: raise ValueError, 'cannot allocate sockets'
def cancelled(self, ua, request, stack): '''Callback when given original request has been cancelled by remote.''' def _cancelled(self, ua, request): # a generator version if hasattr(ua, 'queue') and ua.queue is not None: yield ua.queue.put(request) elif self._queue is not None and ua.request.method == 'INVITE': # only INVITE is allowed to be cancelled. yield self._queue.put(('close', (str(request.From.value), ua))) multitask.add(_cancelled(self, ua, request))
def open(self, url): if _debug: print 'FLVReader.open', url self.url, u = url, urlparse.urlparse(url, 'file') self.fp = FLV().open(u.path) if self.fp: self._gen = self.fp.reader(self); multitask.add(self._gen) raise StopIteration, self else: raise StopIteration, None
def p2preceiver(self, p2p): '''Receive packets or connections from p2p socket server.''' def p2phandler(self, sock): # Handle the messages on the given P2P connection. while True: data = yield sock.recv() while True: sock = yield p2p.accept() if hasattr(self, 'identity') and self.identity: multitask.add(p2phandler(sock))
def _testServer(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) sock.bind(('0.0.0.0', 0)) # should use any port for testing multitask.add(server(sock)) sockaddr = getlocaladdr(sock) multitask.add(_testDiscoverBehavior([sockaddr, defaultServers[0]])) yield multitask.sleep(5) sock.close()
def process(self, data): # process incoming message if not isinstance(data, Message): data = Message(str(data)) self.append(data) def add(self, data): if self._queue is not None: yield self._queue.put(data) multitask.add(add(self, data))
def connect(url, params=None, timeout=10, duration=60, publishStream='publish', playStream='play', publishFile=None, enableAudio=True, enableVideo=True): '''Connect to the RTMP url with supplied parameters in NetConnection.connect. Once connected it publishes and plays the supplied streams, and if publish file is supplied uses that to publish to the stream. The connection is kept up for the duration seconds. Any attempt to connect, open streams or file is with supplied timeout. It returns an error string on failure or None on success. Example to publish audio-only with three parameters from 'file1.flv': result = yield connect("rtmp://server/app", ['str-param', None, 20], publish_file='file1.flv', enableVideo=False) ''' if _debug: print 'connect url=%r params=%r timeout=%r duration=%r publishStream=%r playStream=%r publishFile=%r enableAudio=%r enableVideo=%r' % ( url, params, timeout, duration, publishStream, playStream, publishFile, enableAudio, enableVideo) nc = NetConnection() result = yield nc.connect(url, timeout, *params) if not result: raise StopIteration, 'Failed to connect %r' % (url, ) if publishStream: ns1 = yield NetStream().create(nc, timeout=timeout) if not ns1: raise StopIteration, 'Failed to create publish stream' result = yield ns1.publish(publishStream, timeout=timeout) if not result: yield nc.close() raise StopIteration, 'Failed to create publish stream %r' % ( publishStream, ) if playStream: ns2 = yield NetStream().create(nc, timeout=timeout) if not ns2: raise StopIteration, 'Failed to create play stream' result = yield ns2.play(playStream, timeout=timeout) if not result: yield nc.close() raise StopIteration, 'Failed to create play stream %r' % ( playStream, ) if publishFile and publishStream: # copy from file to stream gen = _copy_loop(publishFile, ns1, enableAudio, enableVideo) multitask.add(gen) try: # if the remote side terminates before duration, print 'timeout=', duration yield nc.client.close_queue.get(timeout=duration) if _debug: print 'received connection close' if publishFile and publishStream: gen.close() except (multitask.Timeout, GeneratorExit): # else wait until duration print 'timedout' if _debug: print 'duration completed, connect closing' if publishFile and publishStream: gen.close() yield nc.close() raise StopIteration(None)
def _testAlgorithm(): def testInternal(): #global _debug #_debug = dht._debug = True nodes = [ServerSocket(True).start()] for x in xrange(10): nodes.append(ServerSocket().start()) yield multitask.add(testInternal())
def _testClient(): def internalTest(): n1 = Network(crypto.PrivateKey(), '').start() n2 = Network(crypto.PrivateKey(), '').start() c1 = Client(n1, server=True).start() c2 = Client(n2).start() msg = yield n2.get(lambda x: x.name=='Discover:Indication', timeout=8) assert msg is not None and msg.neighbors[0] == n1.node multitask.add(internalTest()) # need to use a generator for test
def cancelled(self, ua, request, stack): '''Callback when given original request has been cancelled by remote.''' def _cancelled(self, ua, request): # a generator version if hasattr(ua, 'queue') and ua.queue is not None: yield ua.queue.put(request) elif self._queue is not None and ua.request.method == 'INVITE': # only INVITE is allowed to be cancelled. yield self._queue.put(('close', (str(request.From.value), ua))) multitask.add(_cancelled(self, ua, request))
def _spoofing(self): # Msg to spoof generator --------- def _createSpoofMessage(): if self.spoof_msg_file: with open (self.spoof_msg_file, "r") as file_txt: file_txt=file_txt.read() m = rfc3261_IPv6.Message() try: m = m._parse(file_txt.rstrip()+'\r\n\r\n\r\n') except ValueError, E: pass # TODO: send 400 response to non-ACK request else: m = self._ua.createRequest(self.spoof_method) if self.spoof_srcURI: m.From.value.uri = self.spoof_srcURI if m.method == "INVITE": if self.app.options.registrar_ip != self.app.options.to.uri.host: SourceFakeAddr = self.app.options.registrar_ip else: SourceFakeAddr = str(self.app.options.to.uri.host).split('.') SourceFakeAddr[3] = str(random.randint(0,254)) SourceFakeAddr = ".".join(SourceFakeAddr) if not self.spoof_srcURI: m.From.value.uri.user = m.From.value.displayName = str(random.randint(0,999)) m.From.value.uri.host = SourceFakeAddr m.Contact = rfc3261_IPv6.Header(str(self._stack.uri), 'Contact') m.Contact.value.uri.user = self.localParty.uri.user m.Expires = rfc3261_IPv6.Header(str(self.app.options.register_interval), 'Expires') return m # Stop listener if not necessary in spoof mode if self.listenerOff: self._listenerGen.close() try: spoof_message = self.spoofMsg(_createSpoofMessage()) if not self.listenerOff: self._ua.sendRequest(spoof_message) while True: response = (yield self._ua.queue.get()) if response.CSeq.method == 'REGISTER': if response.is2xx: # success if self.reg_refresh: if response.Expires: self.register_interval = int(response.Expires.value) if self.register_interval > 0: self._ua.gen = self._register() # generator for refresh multitask.add(self._ua.gen) raise StopIteration(('success', None)) elif response.isfinal: # failed raise StopIteration(('failed', str(response.response) + ' ' + response.responsetext)) else: self.send(str(spoof_message),self.remoteParty.uri.hostPort,None) yield multitask.sleep(1) self.app.stop() yield raise StopIteration() except GeneratorExit: raise StopIteration(('failed', 'Generator closed')) self.app.stop() yield raise StopIteration()
def onDisconnect(self, client): rtmp.App.onDisconnect(self, client) if hasattr(self, '_bwthread'): self._bwthread.close() def invokeRemoved(self, client): # invoke the removed callbacks on other clients for other in filter(lambda x: x != client, self.clients): other.call('removed', str(client.clientId)) yield if filter(lambda x: x != client, self.clients): multitask.add(invokeRemoved(self, client)) else: webscript.delete(path=client.path.partition('/')[2])
def send(self, msg): def sendInternal(self, msg): yield self.queue.put(msg) if msg.type in (Message.RPC, Message.RPC3): cmd = Command.fromMessage(msg) if cmd.name == 'onStatus' and len(cmd.args) > 0 and hasattr(cmd.args[0], 'code') and cmd.args[ 0].code == 'NetStream.Play.Stop': msg = False # indicates end of file multitask.add(sendInternal(self, msg))
def fset(self, value): self._presence = value if self.connection is not None and value is not None: def sendPresence(value): if self.connection is not None: yield self.connection.put(msg=value) multitask.add(sendPresence(value))
def onClose(self, client, stream): rtmp.App.onClose(self, client, stream) def closeInternal(self, client, stream): for other in filter(lambda x: x != client, self.clients): yield other.call('unpublished', str(client.clientId), stream.name) multitask.add(closeInternal(self, client, stream))
def onDisconnect(self, client): rtmp.App.onDisconnect(self, client) if hasattr(self, '_bwthread'): self._bwthread.close() def invokeRemoved(self, client): # invoke the removed callbacks on other clients for other in filter(lambda x: x != client, self.clients): yield other.call('removed', str(client.clientId)) yield if filter(lambda x: x != client, self.clients): multitask.add(invokeRemoved(self, client)) else: webscript.delete(path=client.path.partition('/')[2])
def echo_server(hostname, port): addrinfo = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM) (family, socktype, proto, canonname, sockaddr) = addrinfo[0] with closing(socket.socket(family, socktype, proto)) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(sockaddr) sock.listen(5) while True: multitask.add(client_handler((yield multitask.accept(sock))[0]))
def start(self, host='0.0.0.0', port=1935): '''This should be used to start listening for RTMP connections on the given port, which defaults to 1935.''' if not self.server: sock = self.sock = socket.socket(type=socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) if _debug: print 'listening on ', sock.getsockname() sock.listen(5) server = self.server = Server(sock) # start rtmp server on that socket multitask.add(self.serverlistener())
def nodebind(sock, identity): yield sock.bind(identity=identity) def sockaccept(sock): sock2 = yield sock.accept() print 'accept sock=%r'%(sock2) def sockrecv(sock): remote, data = yield sock.recvfrom() print 'recvfrom remote=%r, data=%r'%(remote, data) multitask.add(sockaccept(sock)) multitask.add(sockrecv(sock))
def send(self, data, remote, stack): '''Send a given data to remote for the SIP stack.''' def _send(self, data, remote, stack): # a generator function that does the sending if _debug: print '%r=>%r on type=%r\n%s'%(stack.sock.getsockname(), remote, stack.sock.type, data) if stack.sock.type == socket.SOCK_STREAM: # for TCP send only if a connection exists to the remote. if remote in self.conn: yield multitask.send(self.conn[remote], data) # and send using that connected TCP socket. else: # for UDP send using the stack's UDP socket. yield multitask.sendto(stack.sock, data, remote) multitask.add(_send(self, data, remote, stack))
def receivedResponse(self, ua, response, stack): '''Callback when received an incoming response.''' def _receivedResponse(self, ua, response): # a generator version logger.debug('receivedResponse response='+str(response.response)+' for ua'+str(ua.queue is not None and 'with queue' or 'without queue') ) if hasattr(ua, 'queue') and ua.queue is not None: # enqueue it to the ua's queue yield ua.queue.put(response) logger.debug('response put in the ua queue') else: logger.debug('ignoring response', response.response) multitask.add(_receivedResponse(self, ua, response))
def add_spooferGen(self): self.state = self.SPOOFING if not self._spooferGen: if self.spoof_auto: self._spooferGen = self._auto_spoofing() multitask.add(self._spooferGen) else: self._spooferGen = self._spoofing() multitask.add(self._spooferGen) return self
def echo_server(hostname, port): addrinfo = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM) (family, socktype, proto, canonname, sockaddr) = addrinfo[0] with closing(socket.socket(family, socktype, proto)) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(sockaddr) sock.listen(5) while True: multitask.add(client_handler((yield multitask.accept(sock))[0]))
def _testAlgorithm(): def testInternal(): #global _debug #_debug = dht._debug = True nodes = [ServerSocket(True).start()] for x in xrange(10): nodes.append(ServerSocket().start()) yield multitask.add(testInternal())
def send(self, data, remote, stack): '''Send a given data to remote for the SIP stack.''' def _send(self, data, remote, stack): # a generator function that does the sending if _debug: print '%r=>%r on type=%r\n%s'%(stack.sock.getsockname(), remote, stack.sock.type, data) if stack.sock.type == socket.SOCK_STREAM: # for TCP send only if a connection exists to the remote. if remote in self.conn: yield multitask.send(self.conn[remote], data) # and send using that connected TCP socket. else: # for UDP send using the stack's UDP socket. yield multitask.sendto(stack.sock, data, remote) multitask.add(_send(self, data, remote, stack))
def relayreceiver(sock, fivetuple): while True: # start the main listening loop of the udp server try: data, remote = (yield multitask.recvfrom(sock, maxsize)) # receive a packet if data: if _debug: print 'server().recvfrom() from', remote multitask.add(datahandler(sock1, data, remote)) except: # some other socket error, probably sock1 is closed. break if _debug: print 'server() exiting'
def register(username, password, media=None): sock = socket.socket(type=socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('0.0.0.0', 0)) user = User(sock, nat=False).start() #user = User(sock, nat=True).start() result, reason = yield user.bind('<sip:' + username + '>', username=username, password=password, interval = 3600, refresh=True) log.info('user.bind() returned %s %s : %s', result, reason, username) multitask.add(autoAnswer(user, media))