def parser(self):
        """
        Get a function for parsing a datagram read from a I{tun} device.

        @return: A function which accepts a datagram exactly as might be read
            from a I{tun} device.  The datagram is expected to ultimately carry
            a UDP datagram.  When called, it returns a L{list} of L{tuple}s.
            Each tuple has the UDP application data as the first element and
            the sender address as the second element.
        """
        datagrams = []
        receiver = DatagramProtocol()

        def capture(*args):
            datagrams.append(args)

        receiver.datagramReceived = capture

        udp = RawUDPProtocol()
        udp.addProto(12345, receiver)

        ip = IPProtocol()
        ip.addProto(17, udp)

        def parse(data):
            # TUN devices omit the ethernet framing so we can start parsing
            # right at the IP layer.
            ip.datagramReceived(data, False, None, None, None)
            return datagrams

        return parse
Exemple #2
0
	def doStop(self):
		'''Make sure we send out the byebye notifications.'''

		for st in self.known.keys():
			self.doByebye(st)
			del self.known[st]

		DatagramProtocol.doStop(self)
Exemple #3
0
    def startProtocol(self):
        log("Starting stat_server")
        self.summarize = None
        self.statHolder = Stats()
        DatagramProtocol.startProtocol(self)

        # start stat dump collector task
        self.summarize = task.LoopingCall(self.statHolder.dump)
        self.summarize.start(30, now=False)
Exemple #4
0
 def stopProtocol(self):
     # clean shutdown has to happen like:
     #  - stop accepting new packets
     #  - stop our loop to dump stats
     #  - manually dump any remaining stats
     log("Stopping stat_server:")
     DatagramProtocol.stopProtocol(self)
     log("\tStopping summary loop")
     self.summarize.stop()
     log("\tDumping accumulated stats")
     self.statHolder.dump()
     log("Stopped stat_server")
Exemple #5
0
    def recv(self, nbytes):
        """
        Receive a datagram sent to this port using the L{MemoryIOSystem} which
        created this object.

        This behaves like L{socket.socket.recv} but the data being I{sent} and
        I{received} only passes through various memory buffers managed by this
        object and L{MemoryIOSystem}.

        @see: L{socket.socket.recv}
        """
        data = self._system._openFiles[self._fileno].writeBuffer.popleft()

        datagrams = []
        receiver = DatagramProtocol()

        def capture(datagram, address):
            datagrams.append(datagram)

        receiver.datagramReceived = capture

        udp = RawUDPProtocol()
        udp.addProto(12345, receiver)

        ip = IPProtocol()
        ip.addProto(17, udp)

        mode = self._system._openFiles[self._fileno].tunnelMode
        if (mode & TunnelFlags.IFF_TAP.value):
            ether = EthernetProtocol()
            ether.addProto(0x800, ip)
            datagramReceived = ether.datagramReceived
        else:
            datagramReceived = lambda data: ip.datagramReceived(
                data, None, None, None, None)

        dataHasPI = not (mode & TunnelFlags.IFF_NO_PI.value)

        if dataHasPI:
            # datagramReceived can't handle the PI, get rid of it.
            data = data[_PI_SIZE:]

        datagramReceived(data)
        return datagrams[0][:nbytes]
Exemple #6
0
 def test_getHostIPv6(self):
     """
     L{IListeningPort.getHost} returns an L{IPv6Address} when listening on
     an IPv6 interface.
     """
     reactor = self.buildReactor()
     port = self.getListeningPort(reactor,
                                  DatagramProtocol(),
                                  interface='::1')
     addr = port.getHost()
     self.assertEqual(addr.host, "::1")
     self.assertIsInstance(addr, IPv6Address)
Exemple #7
0
 def test_getHost(self):
     """
     L{IListeningPort.getHost} returns an L{IPv4Address} giving a
     dotted-quad of the IPv4 address the port is listening on as well as
     the port number.
     """
     host, portNumber = findFreePort(type=SOCK_DGRAM)
     reactor = self.buildReactor()
     port = reactor.listenUDP(portNumber,
                              DatagramProtocol(),
                              interface=host)
     self.assertEqual(port.getHost(), IPv4Address('UDP', host, portNumber))
    def parser(self):
        """
        Get a function for parsing a datagram read from a I{tap} device.

        @return: A function which accepts a datagram exactly as might be read
            from a I{tap} device.  The datagram is expected to ultimately carry
            a UDP datagram.  When called, it returns a L{list} of L{tuple}s.
            Each tuple has the UDP application data as the first element and
            the sender address as the second element.
        """
        datagrams = []
        receiver = DatagramProtocol()

        def capture(*args):
            datagrams.append(args)

        receiver.datagramReceived = capture

        udp = RawUDPProtocol()
        udp.addProto(12345, receiver)

        ip = IPProtocol()
        ip.addProto(17, udp)

        ether = EthernetProtocol()
        ether.addProto(0x800, ip)

        def parser(datagram):
            # TAP devices might include a PI header.  Strip that off if we
            # expect it to be there.
            if self.pi:
                datagram = datagram[_PI_SIZE:]

            # TAP devices include ethernet framing so start parsing at the
            # ethernet layer.
            ether.datagramReceived(datagram)
            return datagrams

        return parser
Exemple #9
0
 def test_invalidInterface(self):
     """
     An L{InvalidAddressError} is raised when trying to listen on an address
     that isn't a valid IPv4 or IPv6 address.
     """
     reactor = self.buildReactor()
     self.assertRaises(
         error.InvalidAddressError,
         reactor.listenUDP,
         DatagramProtocol(),
         0,
         interface="example.com",
     )
Exemple #10
0
    def parser(self):
        """
        Get a function for parsing a datagram read from a I{tap} device.

        @return: A function which accepts a datagram exactly as might be read
            from a I{tap} device.  The datagram is expected to ultimately carry
            a UDP datagram.  When called, it returns a L{list} of L{tuple}s.
            Each tuple has the UDP application data as the first element and
            the sender address as the second element.
        """
        datagrams = []
        receiver = DatagramProtocol()

        def capture(*args):
            datagrams.append(args)

        receiver.datagramReceived = capture

        udp = RawUDPProtocol()
        udp.addProto(12345, receiver)

        ip = IPProtocol()
        ip.addProto(17, udp)

        ether = EthernetProtocol()
        ether.addProto(0x800, ip)

        def parser(datagram):
            # TAP devices might include a PI header.  Strip that off if we
            # expect it to be there.
            if self.pi:
                datagram = datagram[_PI_SIZE:]

            # TAP devices include ethernet framing so start parsing at the
            # ethernet layer.
            ether.datagramReceived(datagram)
            return datagrams

        return parser
Exemple #11
0
    def check(self, first=False):
        try:
            import subprocess, os, sys, time

            R = reactor.listenUDP(self._port.protocol.port, DatagramProtocol())
            R.stopListening()

            log.info('Starting repeater')
            subprocess.Popen([sys.executable, "-m", "cac.repeater"],
                             close_fds=True)

            reactor.callLater(0.5, self._port.protocol.sendReg)
        except CannotListenError:
            if first:
                self._port.protocol.sendReg()
Exemple #12
0
    def test_invalidAddressFamily(self):
        """
        An implementation of L{IReactorSocket.adoptDatagramPort} raises
        L{UnsupportedAddressFamily} if passed an address family it does not
        support.
        """
        reactor = self.buildReactor()

        port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.addCleanup(port.close)

        arbitrary = 2**16 + 7

        self.assertRaises(UnsupportedAddressFamily, reactor.adoptDatagramPort,
                          port.fileno(), arbitrary, DatagramProtocol())
Exemple #13
0
    def test_invalidDescriptor(self):
        """
        An implementation of L{IReactorSocket.adoptDatagramPort} raises
        L{socket.error} if passed an integer which is not associated with a
        socket.
        """
        reactor = self.buildReactor()

        probe = socket.socket()
        fileno = probe.fileno()
        probe.close()

        exc = self.assertRaises(socket.error, reactor.adoptDatagramPort,
                                fileno, socket.AF_INET, DatagramProtocol())
        self.assertEqual(exc.args[0], errno.EBADF)
Exemple #14
0
def _getLocalIPAddressViaConnectedUDP(ip):
    from twisted.internet import reactor
    from twisted.internet.protocol import DatagramProtocol
    if _Debug: print "connecting UDP socket to", ip
    prot = DatagramProtocol()
    p = reactor.listenUDP(0, prot)
    res = prot.transport.connect(ip, 7)
    locip = prot.transport.getHost().host
    p.stopListening()
    del prot, p

    if _Debug: print "connected UDP socket says", locip
    if isBogusAddress(locip):
        # #$#*(&??!@#$!!!
        if _Debug: print "connected UDP socket gives crack, trying mcast instead"
        return _getLocalIPAddressViaMulticast()
    else:
        return locip
Exemple #15
0
def _get_via_connected_udp(ipaddr):
    """
	Init a UDP socket ip discovery. We do a dns query, and retreive our
	ip address from the connected udp socket.
	
	@param ipaddr: The ip address of a dns server
	@type ipaddr: a string "x.x.x.x"
	@raise RuntimeError: When the ip is a bogus ip (0.0.0.0 or alike)
	"""
    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 addres returned"
    else:
        return (is_rfc1918_ip(localip), localip)
Exemple #16
0
def get_local_ip_for(target):
    """Find out what our IP address is for use by a given target.

    @return: the IP address as a dotted-quad native string which could be used
              to connect to us. It might work for them, it might not. If
              there is no suitable address (perhaps we don't currently have an
              externally-visible interface), this will return None.
    """

    try:
        target_ipaddr = socket.gethostbyname(target)
    except socket.gaierror:
        # DNS isn't running, or somehow we encountered an error

        # note: if an interface is configured and up, but nothing is
        # connected to it, gethostbyname("A.ROOT-SERVERS.NET") will take 20
        # seconds to raise socket.gaierror . This is synchronous and occurs
        # for each node being started, so users of
        # test.common.SystemTestMixin (like test_system) will see something
        # like 120s of delay, which may be enough to hit the default trial
        # timeouts. For that reason, get_local_addresses_async() was changed
        # to default to the numerical ip address for A.ROOT-SERVERS.NET, to
        # avoid this DNS lookup. This also makes node startup fractionally
        # faster.
        return None

    try:
        udpprot = DatagramProtocol()
        port = reactor.listenUDP(0, udpprot)
        try:
            # connect() will fail if we're offline (e.g. running tests on a
            # disconnected laptop), which is fine (localip=None), but we must
            # still do port.stopListening() or we'll get a DirtyReactorError
            udpprot.transport.connect(target_ipaddr, 7)
            localip = udpprot.transport.getHost().host
            return localip
        finally:
            d = port.stopListening()
            d.addErrback(log.err)
    except (socket.error, CannotListenError):
        # no route to that host
        localip = None
    return native_str(localip)
Exemple #17
0
    def test_connectionLostLogMessage(self):
        """
        When a connection is lost a message is logged containing an
        address identifying the port and the fact that it was closed.
        """
        loggedMessages = self.observe()
        reactor = self.buildReactor()
        p = self.getListeningPort(reactor, DatagramProtocol())
        expectedMessage = "(UDP Port %s Closed)" % (p.getHost().port, )

        def stopReactor(ignored):
            reactor.stop()

        def doStopListening():
            del loggedMessages[:]
            maybeDeferred(p.stopListening).addCallback(stopReactor)

        reactor.callWhenRunning(doStopListening)
        self.runReactor(reactor)

        self.assertEqual((expectedMessage, ), loggedMessages[0]['message'])
Exemple #18
0
    def test_connectionLostLogMessage(self):
        """
        When a connection is lost, an informative message should be logged (see
        L{getExpectedConnectionLostLogMessage}): an address identifying the port
        and the fact that it was closed.
        """
        loggedMessages = self.observe()
        reactor = self.buildReactor()
        p = self.getListeningPort(reactor, DatagramProtocol())
        expectedMessage = self.getExpectedConnectionLostLogMessage(p)

        def stopReactor(ignored):
            reactor.stop()

        def doStopListening():
            del loggedMessages[:]
            maybeDeferred(p.stopListening).addCallback(stopReactor)

        reactor.callWhenRunning(doStopListening)
        self.runReactor(reactor)

        self.assertEqual((expectedMessage, ), loggedMessages[0]['message'])
Exemple #19
0
def can_listen_udp(port, interface=''):
    """Attempts to create a udp listener on a port/interface combo
    Args:
        port (int): Listening port
        interface (str): Hostname to bind to. If not specified binds to all
    Returns:
        ListenResult: the result of the test
    """
    protocol = DatagramProtocol()

    try:
        listener = reactor.listenUDP(
            port=port,
            protocol=protocol,
            interface=interface,
        )
        yield listener.stopListening()
        result = ListenResult(True, port, interface)
    except CannotListenError as e:
        result = _reason_port_is_used(port, interface, e, 'udp')

    defer.returnValue(result)
    def test_stopOnlyCloses(self):
        """
        When the L{IListeningPort} returned by
        L{IReactorSocket.adoptDatagramPort} is stopped using
        C{stopListening}, the underlying socket is closed but not
        shutdown.  This allows another process which still has a
        reference to it to continue reading and writing to it.
        """
        reactor = self.buildReactor()

        portSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.addCleanup(portSocket.close)

        portSocket.bind(("127.0.0.1", 0))
        portSocket.setblocking(False)

        # The file descriptor is duplicated by adoptDatagramPort
        port = reactor.adoptDatagramPort(
            portSocket.fileno(), portSocket.family, DatagramProtocol()
        )
        d = port.stopListening()

        def stopped(ignored):
            # Should still be possible to recv on portSocket.  If
            # it was shutdown, the exception would be EINVAL instead.
            exc = self.assertRaises(socket.error, portSocket.recvfrom, 1)
            if platform.isWindows():
                self.assertEqual(exc.args[0], errno.WSAEWOULDBLOCK)
            else:
                self.assertEqual(exc.args[0], errno.EAGAIN)

        d.addCallback(stopped)
        d.addErrback(err, "Failed to read on original port.")

        needsRunningReactor(
            reactor, lambda: d.addCallback(lambda ignored: reactor.stop())
        )

        reactor.run()
 def connectionRefused(self):
     # we don't use these at all for udp, so skip the CallbackConnection
     DatagramProtocol.connectionRefused(self)
Exemple #22
0
def main():
    global config
    parser = argparse.ArgumentParser(
        description='mitm6 - pwning IPv4 via IPv6')
    parser.add_argument(
        "-d",
        "--domain",
        action='append',
        metavar='DOMAIN',
        help=
        "Interal domain name to filter DNS queries on (Whitelist principle, multiple can be specified. Note that the first will be used as DNS search domain)"
    )
    parser.add_argument("-i",
                        "--interface",
                        type=str,
                        metavar='INTERFACE',
                        help="Interface to use (default: autodetect)")
    parser.add_argument(
        "-4",
        "--ipv4",
        type=str,
        metavar='ADDRESS',
        help="IPv4 address to send packets from (default: autodetect)")
    parser.add_argument(
        "-6",
        "--ipv6",
        type=str,
        metavar='ADDRESS',
        help=
        "IPv6 link-local address to send packets from (default: autodetect)")
    parser.add_argument(
        "-m",
        "--mac",
        type=str,
        metavar='ADDRESS',
        help=
        "Custom mac address - probably breaks stuff (default: mac of selected interface)"
    )
    parser.add_argument(
        "-a",
        "--no-ra",
        action='store_true',
        help=
        "Do not advertise ourselves (useful for networks which detect rogue Router Advertisements)"
    )
    parser.add_argument("-v",
                        "--verbose",
                        action='store_true',
                        help="Show verbose information")
    parser.add_argument("--debug",
                        action='store_true',
                        help="Show debug information")

    args = parser.parse_args()
    config = Config(args)
    print('Starting mitm6 using the following configuration:')
    print('Primary adapter: %s [%s]' % (config.default_if, config.selfmac))
    print('IPv4 address: %s' % config.selfipv4)
    print('IPv6 address: %s' % config.selfaddr)
    if config.dnsdomain is None:
        print(
            'Warning: Not filtering on any domain, mitm6 will reply to all DNS queries.\nUnless this is what you want, specify a domain with -d'
        )
        config.dnsdomain = []
    else:
        print('DNS domains: %s' % ', '.join(config.dnsdomain))

    #Main packet capture thread
    d = threads.deferToThread(
        sniff,
        filter="ip6 proto \\udp or arp or udp port 53",
        prn=lambda x: reactor.callFromThread(parsepacket, x, config),
        stop_filter=should_stop)
    d.addErrback(print_err)

    #RA loop
    if not args.no_ra:
        loop = task.LoopingCall(send_ra)
        d = loop.start(30.0)
        d.addErrback(print_err)

    # Set up DNS
    dnssock = setupFakeDns()
    reactor.adoptDatagramPort(dnssock.fileno(), socket.AF_INET6,
                              DatagramProtocol())

    reactor.addSystemEventTrigger('before', 'shutdown', shutdownnotice)
    reactor.run()
Exemple #23
0
def main():
    global config
    parser = argparse.ArgumentParser(
        description=
        'mitm6 - pwning IPv4 via IPv6\nFor help or reporting issues, visit https://github.com/fox-it/mitm6',
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("-i",
                        "--interface",
                        type=str,
                        metavar='INTERFACE',
                        help="Interface to use (default: autodetect)")
    parser.add_argument(
        "-l",
        "--localdomain",
        type=str,
        metavar='LOCALDOMAIN',
        help=
        "Domain name to use as DNS search domain (default: use first DNS domain)"
    )
    parser.add_argument(
        "-4",
        "--ipv4",
        type=str,
        metavar='ADDRESS',
        help="IPv4 address to send packets from (default: autodetect)")
    parser.add_argument(
        "-6",
        "--ipv6",
        type=str,
        metavar='ADDRESS',
        help=
        "IPv6 link-local address to send packets from (default: autodetect)")
    parser.add_argument(
        "-m",
        "--mac",
        type=str,
        metavar='ADDRESS',
        help=
        "Custom mac address - probably breaks stuff (default: mac of selected interface)"
    )
    parser.add_argument(
        "-a",
        "--no-ra",
        action='store_true',
        help=
        "Do not advertise ourselves (useful for networks which detect rogue Router Advertisements)"
    )
    parser.add_argument("-v",
                        "--verbose",
                        action='store_true',
                        help="Show verbose information")
    parser.add_argument("--debug",
                        action='store_true',
                        help="Show debug information")

    filtergroup = parser.add_argument_group("Filtering options")
    filtergroup.add_argument(
        "-d",
        "--domain",
        action='append',
        default=[],
        metavar='DOMAIN',
        help=
        "Domain name to filter DNS queries on (Whitelist principle, multiple can be specified.)"
    )
    filtergroup.add_argument(
        "-b",
        "--blacklist",
        action='append',
        default=[],
        metavar='DOMAIN',
        help=
        "Domain name to filter DNS queries on (Blacklist principle, multiple can be specified.)"
    )
    filtergroup.add_argument(
        "-hw",
        "--host-whitelist",
        action='append',
        default=[],
        metavar='DOMAIN',
        help=
        "Hostname (FQDN) to filter DHCPv6 queries on (Whitelist principle, multiple can be specified.)"
    )
    filtergroup.add_argument(
        "-hb",
        "--host-blacklist",
        action='append',
        default=[],
        metavar='DOMAIN',
        help=
        "Hostname (FQDN) to filter DHCPv6 queries on (Blacklist principle, multiple can be specified.)"
    )
    filtergroup.add_argument(
        "--ignore-nofqdn",
        action='store_true',
        help=
        "Ignore DHCPv6 queries that do not contain the Fully Qualified Domain Name (FQDN) option."
    )

    args = parser.parse_args()
    config = Config(args)

    print('Starting mitm6 using the following configuration:')
    print('Primary adapter: %s [%s]' % (config.default_if, config.selfmac))
    print('IPv4 address: %s' % config.selfipv4)
    print('IPv6 address: %s' % config.selfaddr)
    if config.localdomain is not None:
        print('DNS local search domain: %s' % config.localdomain)
    if not config.dns_whitelist and not config.dns_blacklist:
        print(
            'Warning: Not filtering on any domain, mitm6 will reply to all DNS queries.\nUnless this is what you want, specify at least one domain with -d'
        )
    else:
        if not config.dns_whitelist:
            print('DNS whitelist: *')
        else:
            print('DNS whitelist: %s' % ', '.join(config.dns_whitelist))
        if config.dns_blacklist:
            print('DNS blacklist: %s' % ', '.join(config.dns_blacklist))
    if config.host_whitelist:
        print('Hostname whitelist: %s' % ', '.join(config.host_whitelist))
    if config.host_blacklist:
        print('Hostname blacklist: %s' % ', '.join(config.host_blacklist))

    #Main packet capture thread
    d = threads.deferToThread(
        sniff,
        iface=config.default_if,
        filter="ip6 proto \\udp or arp or udp port 53",
        prn=lambda x: reactor.callFromThread(parsepacket, x),
        stop_filter=should_stop)
    d.addErrback(print_err)

    #RA loop
    if not args.no_ra:
        loop = task.LoopingCall(send_ra)
        d = loop.start(30.0)
        d.addErrback(print_err)

    # Set up DNS
    dnssock = setupFakeDns()
    reactor.adoptDatagramPort(dnssock.fileno(), socket.AF_INET6,
                              DatagramProtocol())

    reactor.addSystemEventTrigger('before', 'shutdown', shutdownnotice)
    reactor.run()
Exemple #24
0
 def stopProtocol(self):
     DatagramProtocol.stopProtocol(self)
Exemple #25
0
 def __init__(self, service, key, weight=10.0, *args, **kwargs):
     DatagramProtocol.__init__(self, *args, **kwargs)
     Client.__init__(self, service, key, None, weight)
 def startProtocol(self):
     self.can_timeout = 0
     self.attachTransport(self.transport, self.connection, ())
     DatagramProtocol.startProtocol(self)
 def connectionRefused(self):
     # we don't use these at all for udp, so skip the CallbackConnection
     DatagramProtocol.connectionRefused(self)
Exemple #28
0
 def connectionRefused(self):
     return DatagramProtocol.connectionRefused(self)
Exemple #29
0
 def startProtocol(self):
     self.transport.socket.setsockopt(SOL_SOCKET, SO_BROADCAST,True)
     return DatagramProtocol.startProtocol(self)
Exemple #30
0
 def _gotRequestLoggerHost(self, host, port):
     self.requestLogger = DatagramProtocol()
     self.reactor.listenUDP(0, self.requestLogger)
     self.requestLogger.transport.connect(host, port)
 def stopProtocol(self):
     self.timeout_watchdog.cancel()
     return DatagramProtocol.stopProtocol(self)
Exemple #32
0
 def makeConnection(self, transport):
     DatagramProtocol.makeConnection(self, transport)
     if not self.common_protocol is None:
         self.common_protocol.makeConnection(transport)
     self.connected_factory.doStart()
     return
 def stopProtocol(self):
     DatagramProtocol.stopProtocol(self)
Exemple #34
0
 def startProtocol(self):
     self.transport.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, True)
     return DatagramProtocol.startProtocol(self)
Exemple #35
0
 def getConnection(self):
     if self.proto is None:
         self.proto = DatagramProtocol()
         reactor.listenUDP(0, self.proto)
 def __init__(self, aUDPSIPTransport):
     # cannot user super - old style class.  Grrr...
     # TODO:  Working on this - What is init protocol for DatagramProtocol?  Look at docs when we get to Internet.
     DatagramProtocol.__init__(self)
     self.sipTransport = aUDPSIPTransport
 def startProtocol(self):
     self.can_timeout = False
     self.attachTransport(self.transport, self.connection)
     return DatagramProtocol.startProtocol(self)
Exemple #38
0
 def stopProtocol(self):
     self.timeout_watchdog.cancel()
     return DatagramProtocol.stopProtocol(self)
Exemple #39
0
 def __init__ (self, service, key, weight = 10.0, *args, **kwargs):
     DatagramProtocol.__init__(self, *args, **kwargs)
     Client.__init__(self, service, key, None, weight)
Exemple #40
0
 def __init__(self, *args, **kwargs):
     try:
         DatagramProtocol.__init__(self, *args, **kwargs)
     except AttributeError:
         pass
     self.__attempts = _TIMEOUT_JOINERROR
 def startProtocol(self):
     self.can_timeout = 0
     self.attachTransport(self.transport, self.connection, ())
     DatagramProtocol.startProtocol(self)
Exemple #42
0
	def doStart(self):
		DatagramProtocol.doStart(self)  # super lol
		self.port = self.transport.getHost().port
		self.getMasterPeerlist()
Exemple #43
0
 def test_listenMode(self):
     """
     The UNIX socket created by L{IReactorUNIXDatagram.listenUNIXDatagram}
     is created with the mode specified.
     """
     self._modeTest('listenUNIXDatagram', self.mktemp(), DatagramProtocol())
Exemple #44
0
 def startProtocol(self):
     self.can_timeout = False
     self.attachTransport(self.transport, self.connection)
     return DatagramProtocol.startProtocol(self)
    def addPlayer(self, player):
        playerblob = PlayerBlob(player)
        self.players.append(playerblob)


class TrackRecv(LineReceiver):
    def connectionMade(self):
        print "connected"
        self.fooie = random.randint(1, 100)

    def lineReceived(self, line):
        point = cPickle.loads(line)
        #print point
        # TODO: Uniquify
        point['id'] = point['id'] << 8 + self.fooie
        tm.process(point)


tm = TrackMaster()
tracker_factory = protocol.ClientFactory()
tracker_factory.protocol = TrackRecv

# SETUP
reactor.connectTCP("192.168.1.101", 1025, tracker_factory)
reactor.connectTCP("192.168.1.102", 1025, tracker_factory)
#reactor.connectTCP("127.0.0.1", 1025, tracker_factory)

p = reactor.listenUDP(0, DatagramProtocol())
LoopingCall(lambda: p.write("FlatlandARG!!!", ("224.0.0.1", 8000))).start(1)
reactor.run()
Exemple #46
0
 def stopProtocol(self):
     self.task.stopListening()
     DatagramProtocol.stopProtocol(self)