Example #1
0
    def _create_remote_socket(self, ip, port):
        if self._remote_udp:
            addrs_v6 = socket.getaddrinfo("::", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
            addrs = socket.getaddrinfo("0.0.0.0", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
        else:
            addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM, socket.SOL_TCP)
        if len(addrs) == 0:
            raise Exception("getaddrinfo failed for %s:%d" % (ip, port))
        af, socktype, proto, canonname, sa = addrs[0]
        if self._forbidden_iplist:
            if common.to_str(sa[0]) in self._forbidden_iplist:
                raise Exception('IP %s is in forbidden list, reject' %
                                common.to_str(sa[0]))
        remote_sock = socket.socket(af, socktype, proto)
        self._remote_sock = remote_sock
        self._fd_to_handlers[remote_sock.fileno()] = self

        if self._remote_udp:
            af, socktype, proto, canonname, sa = addrs_v6[0]
            remote_sock_v6 = socket.socket(af, socktype, proto)
            self._remote_sock_v6 = remote_sock_v6
            self._fd_to_handlers[remote_sock_v6.fileno()] = self
            remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32)
            remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32)
            remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32)
            remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32)

        remote_sock.setblocking(False)
        if self._remote_udp:
            pass
        else:
            remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        return remote_sock
Example #2
0
def handle(client_socket, address):
    global totalnewconns
    global mysql_stats
    totalnewconns += 1
    mysql_sockets = []
    # First connection is always master, it gets all modifications
    mysql_socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    
    state = "alive"
    try:
        # TODO: add a timer here to wait 10s if a server is dead before
        #       trying to reconnect again
        mysql_socket1.connect(('192.168.127.3', 3306))
        mysql_stats[0]["globalstate"] = "alive"
        state = "alive"
    except socket.error as err:
        mysql_stats[0]["globalstate"] = "dead"
        state = "dead"
    mysql_sockets.append({"conn": mysql_socket1, "state":state, "stats":mysql_stats[0]})
    mysql_socket2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    
    state = "alive"
    try:
        # TODO: add a timer here to wait 10s if a server is dead before
        #       trying to reconnect again
        mysql_socket2.connect(('192.168.127.4', 3306))
        mysql_stats[1]["globalstate"] = "alive"
        state = "alive"
    except socket.error as err:
        mysql_stats[1]["globalstate"] = "dead"
        state = "dead"
    mysql_sockets.append({"conn": mysql_socket2, "state":state, "stats":mysql_stats[1]})
    do_handshake(client_socket, mysql_sockets)
    do_commands(client_socket, mysql_sockets)
Example #3
0
 def send_to_client(self, sctag, msg): #msg is json in str
   msg_ = check_smsg('send', sctag, msg)
   if msg_ == None:
     logging.error('msg is not proto-good')
     return
   cp_info = self.commpair_info_dict[sctag]
   proto = cp_info['proto']
   #sock = cp_info['sock']
   sock = None
   c_addr = cp_info['c_addr']
   #
   response = None
   if proto == 'tcp':
     try:
       sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
       sock.connect(c_addr)
       sock.sendall(msg)
       response = sock.recv(1024)
     except IOError as e:
       if e.errno == errno.EPIPE:
         #due to insuffient recv_buffer at the other end
         logging.error('broken pipe err, check recv_buffer')
     finally:
       sock.close()
   elif proto == 'udp':
     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     sock.sendto(msg, c_addr)
     response = sock.recv(1024)
   #
   logging.info('sent to %s_client=%s, datasize=%sBs', proto,c_addr,sys.getsizeof(msg))
   logging.info('response=%s', response)
Example #4
0
    def on_ONLINE_mouseClick(self, event):
        global ONline
        Switch = self.components.ONLINE.checked
        if Switch == True:
            UDP_IP = self.components.UDP_IP.text
            UDP_PORT = self.components.UDP_PORT.text
            UDP_PORT = int(UDP_PORT)
            time.sleep(1)
            ONline = 1
            self.components.ONLINE.label = "Go Offline"
            #easygui.msgbox("Server>> Online!")
            time.sleep(2)
            sock = socket.socket(socket.AF_INET, # Internet
            socket.SOCK_DGRAM) # UDP
            sock.sendto("Server>> Online!", (UDP_IP, UDP_PORT))

        if Switch == False:
            UDP_IP = self.components.UDP_IP.text
            UDP_PORT = self.components.UDP_PORT.text
            UDP_PORT = int(UDP_PORT)
            time.sleep(1)
            ONline = 0
            self.components.ONLINE.label = "Go Online"
            #easygui.msgbox("Server>> Offline!")
            time.sleep(2)
            sock = socket.socket(socket.AF_INET, # Internet
            socket.SOCK_DGRAM) # UDP
            sock.sendto("Server>> Offline!", (UDP_IP, UDP_PORT))
Example #5
0
    def getFreeAddresses(self):
        import socket
        s = socket.socket()
        s.bind(('',0))
        port0 = s.getsockname()[1]
        
        s1 = socket.socket()
        s1.bind(('',0))
        port1 = s1.getsockname()[1]
        s.close()
        s1.close()
        
        if port0 <= 0 or port1 <= 0:
            #This happens in Jython...
            from java.net import ServerSocket
            s0 = ServerSocket(0)
            port0 = s0.getLocalPort()
            
            s1 = ServerSocket(0)
            port1 = s1.getLocalPort()
            
            s0.close()
            s1.close()

        assert port0 != port1
        assert port0 > 0
        assert port1 > 0
            
        return port0, port1
    def reuse_socket_address(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        old_state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
        print "Old socket state: ", old_state

        # 激活套接字重用
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        new_state = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
        print "New socket state: ", new_state


        local_port = 8282
        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        srv.bind(('', local_port))
        srv.listen(1)
        print "Listen On Port: ", local_port
        while True:
            try:
                connection, addr = srv.accept()
                print "Connect by %s:%s"%(addr[0],addr[1])
            except KeyboardInterrupt:
                break
            except socket.error, msg:
                print '%s' % msg
Example #7
0
	def run(self):
			while True:
				snap_shot()
				#time.sleep(.05)

				#HOST = 'u1204vm.local'
				#CPORT = 9091
				#MPORT = 9090
				#FILE = sys.argv[1]
				print "sending image"
				cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				cs.connect((self.host, self.cport))
				cs.send("SEND " + self.filetosend)
				cs.close()

				time.sleep(0.05)

				ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				ms.connect((self.host, self.mport))

				f = open(self.filetosend, "rb")
				data = f.read()
				f.close()

				ms.send(data)
				ms.close()
				print "waiting one second before sending another image"
Example #8
0
def portscan(target,ports,tcp,udp,verbose):
    #target=IPaddr,ports=list of ports,tcp=true/false,udp=true/false,verbose=true/false
    printmsg(("Now scanning %s" % (target)))
    tcpports=[]
    udpports=[]
    if tcp:
        for portnum in ports:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(0.01)
                s.connect((target, portnum))
            except Exception:
                failvar = 0
                if verbose: print "%d/tcp \tclosed" % (portnum)
            else:
                print "%d/tcp \topen"% (portnum)
                tcpports.append(portnum)
            s.close()
    if udp:
        for portnum in ports:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.settimeout(0.1)
                s.sendto("--TEST LINE--", (target, portnum))
                recv, svr = s.recvfrom(255)
            except Exception, e:
                try: errno, errtxt = e
                except ValueError:
                    print "%d/udp \topen"% (portnum)
                    udpports.append(portnum)
                else:
                    if verbose: print "%d/udp \tclosed" % (portnum)
            s.close()
Example #9
0
    def testDefaultTimeout(self):
        # Testing default timeout
        # The default timeout should initially be None
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Set the default timeout to 10, and see if it propagates
        socket.setdefaulttimeout(10)
        self.assertEqual(socket.getdefaulttimeout(), 10)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), 10)
        s.close()

        # Reset the default timeout to None, and see if it propagates
        socket.setdefaulttimeout(None)
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Check that setting it to an invalid value raises ValueError
        self.assertRaises(ValueError, socket.setdefaulttimeout, -1)

        # Check that setting it to an invalid type raises TypeError
        self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
Example #10
0
def minecraft(phenny, input):
    if input.sender.startswith('#'): return phenny.reply("This command only available in private message.")
    # Set up
    s = socket.socket()
    t = socket.socket()
    u = socket.socket()
    v = socket.socket()
    gamerx = cprossu = packethumper = bitviper = "UP"
    
    # Attempt connections
    try:
        s.connect(('gamerxreviews.net', 25565))
    except:
        gamerx = "DOWN"
    try:
        t.connect(('72.222.196.252',25565))
    except:
        cprossu = "DOWN"
    try:
        u.connect(('minecraft.nerderosity.com',25565))
    except:
        packethumper = "DOWN"
    try:
        v.connect(('minecraft.bitviper.org',25565))
    except:
        bitviper = "DOWN"
    
    # output
    phenny.reply( "GuardianZozo's minecraft server: gamerxreviews.net:25565. Server Status: {}".format(gamerx) )
    phenny.reply( "Cprossu's minecraft server: 72.222.196.252:25565. Server Status: {}".format(cprossu) )
    phenny.reply( "PacketHumper's minecraft server: minecraft.nerderosity.com:25565. Server Status: {}".format(packethumper) )
    phenny.reply( "BitViper's minecraft server: minecraft.bitviper.org:25565. Server Status: {}".format(bitviper) )
Example #11
0
def create_persistent(address):

    """
    Create a new process, returning a persistent communications channel between
    the creating process and the created process. This channel can be
    disconnected from the creating process and connected to another process, and
    thus can be used to collect results from daemon processes.

    In order to be able to reconnect to created processes, the 'address' of the
    communications endpoint for the created process needs to be provided. This
    should be a filename.
    """

    parent = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    child = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    child.bind(address)

    for s in [parent, child]:
        s.setblocking(1)

    pid = os.fork()
    if pid == 0:
        parent.close()
        return PersistentChannel(pid, child, address)
    else:
        child.close()
        #parent.connect(address)
        return Channel(pid, parent.makefile("r", 0), parent.makefile("w", 0))
Example #12
0
def pick_random_port():
    """Bind to an ephemeral port, force it into the TIME_WAIT state, and
    unbind it.

    This means that further ephemeral port alloctions won't pick this
    "reserved" port, but subprocesses can still bind to it explicitly, given
    that they use SO_REUSEADDR.

    By default on linux you have a grace period of 60 seconds to reuse this
    port.

    To check your own particular value:
    $ cat /proc/sys/net/ipv4/tcp_fin_timeout
    60
    """
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('127.0.0.1', 0))
    s.listen(0)

    sockname = s.getsockname()

    # these three are necessary just to get the port into a TIME_WAIT state
    s2 = socket.socket()
    s2.connect(sockname)
    s.accept()

    return sockname[1]
Example #13
0
 def createSockByType(self, sockType):
     if sockType == socktypes.UDP_CLIENT_LOCAL:
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     elif sockType == socktypes.TCP_CLIENT_LOCAL:
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     else:
         logger.error("***** ERROR SOCKTYPE *****")
Example #14
0
File: util.py Project: foxi/miro
def make_dummy_socket_pair():
    """Create a pair of sockets connected to each other on the local
    interface.  Used to implement SocketHandler.wakeup().

    On Unixish systems, port 0 will pick the next available port.
    But that appears to have problems on Windows possibly with
    firewall software.  So if we hit a socketerror with port 0, we
    try ports between 50000 and 65500.
    """
    attempts = 0
    port = 0
    family, addr = localhost_family_and_addr()
    while 1:
        attempts += 1
        try:
            dummy_server = socket.socket(family, socket.SOCK_STREAM)
            dummy_server.bind((addr, port))
            dummy_server.listen(1)
            server_address = dummy_server.getsockname()
            first = socket.socket(dummy_server.family, socket.SOCK_STREAM)
            first.connect(server_address)
            second, address = dummy_server.accept()
            dummy_server.close()
            return first, second
        except socket.error:
            # if we hit this, then it's hopeless--give up
            if port > 65500:
                sys.stderr.write(("Tried %s bind attempts and failed on " "addr %s port %d\n") % (attempts, addr, port))
                raise
            # bump us into ephemeral ports if we need to try a bunch
            if port == 0:
                port = 50000
            else:
                port += 10
Example #15
0
 def test_get_conns(self):
     sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock1.bind(('127.0.0.1', 0))
     sock1.listen(1)
     sock1ipport = '%s:%s' % sock1.getsockname()
     sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock2.bind(('127.0.0.1', 0))
     sock2.listen(1)
     orig_port = memcached.DEFAULT_MEMCACHED_PORT
     try:
         sock2ip, memcached.DEFAULT_MEMCACHED_PORT = sock2.getsockname()
         sock2ipport = '%s:%s' % (sock2ip, memcached.DEFAULT_MEMCACHED_PORT)
         # We're deliberately using sock2ip (no port) here to test that the
         # default port is used.
         memcache_client = memcached.MemcacheRing([sock1ipport, sock2ip])
         one = two = True
         while one or two:  # Run until we match hosts one and two
             key = uuid4().hex
             for conn in memcache_client._get_conns(key):
                 peeripport = '%s:%s' % conn[2].getpeername()
                 self.assert_(peeripport in (sock1ipport, sock2ipport))
                 if peeripport == sock1ipport:
                     one = False
                 if peeripport == sock2ipport:
                     two = False
     finally:
         memcached.DEFAULT_MEMCACHED_PORT = orig_port
Example #16
0
    def connect(self, server, port, channel):
        self.server = server
        self.port = port
        self.channel = channel

        if self.ssl:
            self.socket = ssl.wrap_socket(
                socket.socket(socket.AF_INET, socket.SOCK_STREAM))
        else:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.socket.connect((self.server, self.port))

        # Send user's info
        if self.password:
            self.send('PASS %s' % self.password)
        self.send('NICK %s' % self.nick)
        self.send(
            'USER %s %s %s %s' % (self.nick, self.nick, self.nick, self.nick))

        # Wait for commands
        while True:
            self.send('PING %s' % self.server)
            data = recv_timeout(self.socket)
            try:
                self.parse_data(data)
            except Exception:
                pass
Example #17
0
def init():
    # socket setting
    global receiver
    global sender
    receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    receiver.bind(("", RECEIVE_PORT))
    sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sender.bind(("", SEND_PORT))

    # arduino setting
    global arduino
    try:
        arduino = serial.Serial(SERIAL_PORT, 9600)
    except:
        arduino = serial.Serial(SERIAL_PORT2, 9600)
    arduino.flushInput()

    # thread setting
    global receiver_thread
    global sender_thread
    global gps_thread
    receiver_thread = threading.Thread(target=receive_thread)
    sender_thread = threading.Thread(target=send_thread)
    gps_thread = gps_drive_class()

    # GPS setting
    global gpsd
    gpsd = gps.gps("127.0.0.1", "2947")
    gpsd.stream(gps.WATCH_ENABLE|gps.WATCH_NEWSTYLE)
Example #18
0
 def __init__(self, name):
     ThreadManagement.ThreadManagement(name)
     socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.__target = None
     self.__listen_type = HyperSocket.__LOCAL
     self.__connect_type = None
     self.accept_queue = Queue.Queue(maxsize = 0)
Example #19
0
    def __init__(self, listeners=None, send=False):
        self.sendSocket    = None
        self.receiveSocket = None
        self.sendSeq = 0
        self.receiveSeq = None
        self.listeners = listeners if listeners is not None else []
        for L in self.listeners:
            assert isinstance(L, Listener)

        if send:
            self.sendSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            self.sendSocket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        else:
            ## similar to sending, but need to do the group membership setup
            self.receiveSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            self.receiveSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.receiveSocket.bind(('', Feed.MCAST_PORT))
            mreq = struct.pack("4sl", socket.inet_aton(Feed.MCAST_GRP), socket.INADDR_ANY)
            self.receiveSocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
            self.receiveSocket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 256*1024) ## see /proc/sys/net/core/rmem_*
            ##print "receiveBuf = ", self.receiveSocket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)

            ## start the thread to handle any listeners through the callback mechanism
            if len(self.listeners):
                self.thread = threading.Thread(target=self.run, name="Feed")
                self.thread.daemon = True
                self.thread.start()
Example #20
0
def send_option(option):
	if option==4:
		s=socket.socket()
		s.connect((hosta, porta))
		s.send(str(option))
		op=int(s.recv(1024))
		if option==op:
		    print "option sent"
		s.close()
	else:
		s=socket.socket()
		s.connect((hosta, porta))
		s.send(str(option))
		op=int(s.recv(1024))
		if option==op:
		    print "option sent"
		s.close()
		s=socket.socket()
		if (option!=op and option==2) or option!=2:
			s.connect((hostb, portb))
			s.send(str(option))
			op=int(s.recv(1024))
			if option==op:
				print "option sent"
			s.close()
			tryb=True
Example #21
0
def checkInbox(threadName, delay, counter):
    while True:
        if ONline == True:
            #test = str(raw_input("test: "))
            #if test == "break":
            #    break
            sock = socket.socket(socket.AF_INET, # Internet
                                 socket.SOCK_DGRAM) # UDP
            sock.bind((S_IP, int(S_PORT)))
            data, addr = sock.recvfrom(int(S_BUFFERSIZE)) #buffer size in bytes
            now = datetime.datetime.now()
            if data != "CC":
                print "Server>> ", now, " ", str(addr) + data
                easygui.msgbox(str(addr) + data, now)
                #self.components.chathistory.text = self.components.chathistory.text + "\n\n" + str(now) + " " + UDP_SENDERIP + ": " +  data
                
            if data == "CC":
                print data, str(addr)
                #send "heartbeat" to connected client
                sock = socket.socket(socket.AF_INET, # Internet
                socket.SOCK_DGRAM) # UDP
                sock.sendto(S_IP+" You have Succesfully connected to: "+ S_IP, (addr))

        elif ONline == False:
            print "Server>> OFFLINE!"
            time.sleep(1)
Example #22
0
    def scanfiles(self):
        for root, dirs, files in os.walk("files"):
            for file_ in files:
                check = root+"/"+file_
                if check not in self.files:
                    try:
                        self.files[check] = hash(open(check).read()) 
                        sock = socket.socket()
                        sock.connect((self.host, self.port))
                        upload.upload(sock, check, self.username, self.password)
                        print "{0} Outgoing file transfer {1}".format(datetime.datetime.now(), check)
                    except Exception, e:
                        #print e
                        del self.files[check]
                    
                    time.sleep(0.5)

                else:
                    with open(check, 'rb') as file:
                        hashc = hash(file.read())
                        if hashc != self.files[check]:
                            try:
                                sock = socket.socket()
                                sock.connect((self.host, self.port))
                                upload.upload(sock, check, self.username, self.password)
                                print "{0} Outgoing file transfer {1}".format(datetime.datetime.now(), check)
                                self.files[check] = hash(open(check).read()) 
                            except Exception, e:
                                pass 
                            time.sleep(0.5)
Example #23
0
def send_cmd_info():
    global SERVER_IP,SERVER_PORT,DETECT_TIME
    sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sec=86400
    res,hostname=commands.getstatusoutput('hostname')
    while True:
        begin,end,script,log=parse_history_log_file('/tmp/.history_cmd.log')
        try:
            sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	    sk.connect((SERVER_IP,SERVER_PORT))
            for i in range(begin,end):
	        cmd=script+' '+str(i)+' '+log
	        res,info=commands.getstatusoutput(cmd)
		if info:
		    str_list=info.split('@_@')
		    dicts={'type':'cmd'}
		    dicts['time']=str_list[0].rstrip(' ')
		    dicts['user']=str_list[1]
		    dicts['ip']=str_list[2]
		    dicts['cmd']=str_list[3]
		    dicts['host']=hostname
		    json=simplejson.dumps(dicts)
		    if dicts['ip'] == '' or dicts['user'] == '':
			continue
	            sk.sendall(json)
        except Exception as e:
	    print e
        finally:
	    sk.close()
	time.sleep(DETECT_TIME)
Example #24
0
    def connect (self,fname):

        '''Connect to the server.  Return True if the connection was established.'''

        trace = False and not g.unitTesting

        if trace: g.trace(fname,socket)

        if hasattr(socket,'AF_UNIX'):
            try:
                # pylint: disable=E1101
                # E1101:LProtoClient.connect: Module 'socket' has no 'AF_UNIX' member
                self.socket = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
                self.socket.connect(fname)
                return True
            except Exception:
                g.es_print('lproto.py: failed to connect!',fname)
                g.es_exception(full=False,c=None)
                return False
        else:
            try:
                host = '172.16.0.0' # host is a local address.
                port = 1
                self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                self.socket.connect((host,port),)
                self.socket.connect(fname)
                return True
            except Exception:
                g.es_print('lproto.py: failed to connect! host: %s, port: %s' % (
                    host,port))
                g.es_exception(full=False,c=None)
                return False
 def create_socket(self):
     if self.protocol == 'TCP':
         self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     elif self.protocol == 'UDP':
         self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     else:
         self.socket = socket.socket()
Example #26
0
def create_sock_pair(port=0):
    '''Create socket pair. Works also on windows by using an ephemeral TCP port.'''
    if hasattr(socket, 'socketpair'):
        client_sock, srv_sock = socket.socketpair()
        return client_sock, srv_sock

    # Create a non-blocking temporary server socket
    temp_srv_sock = socket.socket()
    temp_srv_sock.setblocking(False)
    temp_srv_sock.bind(('localhost', port))
    port = temp_srv_sock.getsockname()[1]
    temp_srv_sock.listen(1)
    with closing(temp_srv_sock):
        # Create non-blocking client socket
        client_sock = socket.socket()
        client_sock.setblocking(False)
        while True:
            try:
                client_sock.connect(('localhost', port))
            except socket.error as err:
                # EWOULDBLOCK is not an error, as the socket is non-blocking
                if err.errno not in socket_errors_nonblocking:
                    raise

        # Use select to wait for connect() to succeed.
        timeout = 1
        readable = select.select([temp_srv_sock], [], [], timeout)[0]
        if temp_srv_sock not in readable:
            raise Exception('Client socket not connected in {} second(s)'.format(timeout))
        srv_sock = temp_srv_sock.accept()[0]
        client_sock.setblocking(True)

    return client_sock, srv_sock
Example #27
0
 def connect(self):
     assert self.server_hostname
     assert self.server_port
     assert self.nickname
     self.username = self.username or self.nickname
     self.realname = self.realname or self.nickname
     if self.ipv4:
         self._socket = socket.socket()
     else:
         self._socket = socket.socket(socket.AF_INET6)
     if self.bindhost:
         self._socket.bind((self.bindhost, 0))
     try:
         self._socket.connect((self.server_hostname, self.server_port))
     except Exception as e:
         raise e
     if self.ssl:
         try:
             self._socket = self.ssl_wrap(self._socket)
         except ssl.SSLError:
             self.ssl_verify = False
             if self.connect():
                 self.connected = True
             return False
     if self._socket:
         self.send_pass(self.password)
         self.send_user(self.username, self.realname)
         self.send_nick(self.nickname)
         self.connected = True
         self._socket.setblocking(False)
         return True
     return False
Example #28
0
    def test_F_port_forwarding(self):
        """
        verify that a client can forward new connections from a locally-
        forwarded port.
        """
        self.setup_test_server()
        chan = self.tc.open_session()
        chan.exec_command('yes')
        schan = self.ts.accept(1.0)
        
        # open a port on the "server" that the client will ask to forward to.
        greeting_server = socket.socket()
        greeting_server.bind(('127.0.0.1', 0))
        greeting_server.listen(1)
        greeting_port = greeting_server.getsockname()[1]

        cs = self.tc.open_channel(b'direct-tcpip', ('127.0.0.1', greeting_port), ('', 9000))
        sch = self.ts.accept(1.0)
        cch = socket.socket()
        cch.connect(self.server._tcpip_dest)
        
        ss, _ = greeting_server.accept()
        ss.send(b'Hello!\n')
        ss.close()
        sch.send(cch.recv(8192))
        sch.close()
        
        self.assertEquals(b'Hello!\n', cs.recv(7))
        cs.close()
Example #29
0
	def downloadFile(self, listadapter, *args):
		try:
			self.interface.log("ABOUT TO DOWNLOAD FROM " + listadapter.selection[0].text)
			s = listadapter.selection[0].text
			i = self.app.context["peers_addr"].index(s)
			print("INSIDE DOWNLOAD ")
			key = str(i)+"_"+str(s)
			if(self.app.context["downloads_available"][str(key)]):
				peer = self.app.context["downloads_available"][str(key)]
				print(peer)
				##possiamo far partire il download del file
				destination = (s , int(peer["porta"]))
				print(destination)
				print(peer["md5"])
				self.connection_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
				self.connection_socket.connect(destination)
				message = "RETR"+str(peer["md5"])
				self.connection_socket.send(message)
				message_type = self.connection_socket.recv(4)
				num_chunks = self.connection_socket.recv(6)
				f = open('shared/'+peer["nome"].strip(" "), "wb")
				if int(num_chunks) > 0 :
					print("num chunks " + str(num_chunks))
					self.interface.progress.max = int(num_chunks)
					for i in range(int(num_chunks)):
						len_chunk = self.connection_socket.recv(5)
						if (int(len_chunk) > 0):
							self.interface.progress.value = self.interface.progress.value + 1
							chunk = self.connection_socket.recv(int(len_chunk))
							#f.write(chunk)
							#print("downloading chunk " + str(len_chunk))
							while len(chunk) < int(len_chunk):
								new_data = self.connection_socket.recv(int(len_chunk)-len(chunk))
								#f.write(new_data)
								chunk = chunk + new_data
							f.write(chunk)
					f.close()

				self.connection_socket.close()
				self.interface.progress.value = 0

				## scriviamo alla directory che abbiamo finito il download
				self.connection_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
				self.connection_socket.connect(self.directory)

				message = "DREG" + self.app.context["sessionid"] + peer["md5"]
				self.connection_socket.send(message)

				ack = self.connection_socket.recv(4)
				n_down = self.connection_socket.recv(5)
				self.interface.log("RECEIVED "+ str(ack))
				self.interface.log("#DOWNLOAD " + str(n_down))
				self.connection_socket.close()
			else:
				print("NOT AVAILABLE")
		except:
			print("exception!!")
			print(sys.exc_info()[0])
			print(sys.exc_info()[1])
			print(sys.exc_info()[2])
	def read_chat(self):
		#wait for connection from spatulabot
		bot_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		bot_s.bind(('', 9000))
		bot_s.listen(10)
		conn, addr = bot_s.accept()
		print 'Connected with ' + addr[0] + ':' + str(addr[1])
		#connect to twitch
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((cfg.HOST, cfg.PORT))
		s.send("PASS {}\r\n".format(cfg.PASS).encode("utf-8"))
		s.send("NICK {}\r\n".format(cfg.NICK).encode("utf-8"))
		s.send("JOIN {}\r\n".format(cfg.CHAN).encode("utf-8"))
		done_wait = datetime.datetime.now()
		while self.running:
			response = s.recv(1024).decode("utf-8")
			if datetime.datetime.now() < done_wait:
				continue
			for r in response.split('\r\n'):
				if r == "PING :tmi.twitch.tv\r\n":
				    s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
				elif len(r) > 0 and CHAT_MSG.match(r):
					username = re.search(r"\w+", r).group(0) # return the entire match
					message = CHAT_MSG.sub("", r)
					self.add_line(username, message)
					#check if matches a command
					for c in CHAT_COMMANDS:
						if message in c[0]:
							bot_s.send(c[1]+'\r\n')
							#timeout
							done_wait = datetime.datetime.now() + datetime.timedelta(seconds=12)
		s.close()
		bot_s.close()