Exemplo n.º 1
0
    def sendto(self, message, ip, port):
        if not ip or not port:
            SysMgr.printErr(\
                "Fail to use IP address for client because it is not set")
            return False
        elif not self.socket:
            SysMgr.printErr(\
                "Fail to use socket for client because it is not set")
            return False

        # encode message #
        if UtilMgr.isString(message):
            message = UtilMgr.encodeStr(message)

        try:
            self.socket.sendto(message, (ip, port))
            return True
        except SystemExit:
            sys.exit(0)
        except:
            err = SysMgr.getErrReason()
            SysMgr.printErr(\
                "Fail to send data to %s:%d as client because %s" % \
                (self.ip, self.port, err))
            return False
Exemplo n.º 2
0
    def getData(self):
        try:
            data = b''

            # receive and composite packets #
            while 1:
                output = self.recvfrom(noTimeout=True)

                # handle timeout #
                if not output:
                    continue

                # get only data #
                output = output[0]

                # composite packets #
                data = data + output

                if len(output) == 0:
                    break

                # decode data #
                try:
                    output = output.decode()
                except:
                    pass

                if len(output) < self.recvSize and \
                    output[-1] == '\n':
                    break
        except SystemExit:
            sys.exit(0)
        except:
            err = SysMgr.getErrReason()
            SysMgr.printErr(\
                "Fail to get data from %s:%d as client because %s" % \
                (self.ip, self.port, err))
            return None

        # decode data #
        try:
            retstr = data.decode()
            return retstr
        except:
            return data
Exemplo n.º 3
0
    def recvfrom(self, size=0, noTimeout=False, verbose=True):
        if self.ip is None or self.port is None:
            SysMgr.printErr(\
                "Fail to use IP address for server because it is not set")
            return False
        elif not self.socket:
            SysMgr.printErr(\
                "Fail to use socket for client because it is not set")
            return False

        # get socket object #
        socket = SysMgr.getPkg('socket', False)

        # set recv size #
        if size == 0:
            size = self.recvSize

        while 1:
            try:
                message, address = self.socket.recvfrom(size)
                return (message, address)
            except socket.timeout:
                if noTimeout:
                    continue
                SysMgr.printWarn(\
                    "Fail to receive data from %s:%d as client because %s" % \
                    (self.ip, self.port, 'timeout'))
                return None
            except KeyboardInterrupt:
                sys.exit(0)
            except SystemExit:
                sys.exit(0)
            except:
                if verbose:
                    SysMgr.printWarn(\
                        "Fail to receive data from %s:%d as client because %s" % \
                            (self.ip, self.port, SysMgr.getErrReason()))
                return None
Exemplo n.º 4
0
    def send(self, message, write=False):
        if self.ip is None or self.port is None:
            SysMgr.printErr(\
                "Fail to use IP address for client because it is not set")
            return False
        elif not self.socket:
            SysMgr.printErr(\
                "Fail to use socket for client because it is not set")
            return False

        # encode message #
        if UtilMgr.isString(message):
            message = UtilMgr.encodeStr(message)

        try:
            # check protocol #
            if self.tcp:
                ret = self.socket.send(message)
            elif not write and SysMgr.localServObj:
                ret = SysMgr.localServObj.socket.sendto(\
                    message, (self.ip, self.port))
            else:
                ret = self.socket.sendto(message, (self.ip, self.port))

            if ret < 0:
                raise Exception()

            if self.status != 'ALWAYS':
                self.status = 'SENT'
            return True
        except SystemExit:
            sys.exit(0)
        except:
            err = SysMgr.getErrReason()
            SysMgr.printErr(\
                "Fail to send data to %s:%d as server because %s" % \
                (self.ip, self.port, err))
            return False
Exemplo n.º 5
0
    def recv(self, size=0):
        if self.ip is None or self.port is None:
            SysMgr.printErr(\
                "Fail to use IP address for server because it is not set")
            return False
        elif not self.socket:
            SysMgr.printErr(\
                "Fail to use socket for client because it is not set")
            return False

        # set recv size #
        if size == 0:
            size = self.recvSize

        try:
            return self.socket.recv(size)
        except SystemExit:
            sys.exit(0)
        except:
            err = SysMgr.getErrReason()
            SysMgr.printWarn(\
                "Fail to receive data from %s:%d as client because %s" % \
                (self.ip, self.port, err))
            return False
Exemplo n.º 6
0
    def getServerConn():
        def printErr():
            SysMgr.printErr(\
                "No running server or wrong server address")

        # set server address in local #
        if SysMgr.isLinux and not SysMgr.remoteServObj:
            try:
                addr = SysMgr.getProcAddrs(__module__)
            except:
                addr = None

            if not addr:
                return None

            # classify ip and port #
            service, ip, port = NetworkMgr.parseAddr(addr)
            if service == ip == port == None:
                printErr()
                return None
            else:
                NetworkMgr.setRemoteServer(addr, tcp=True)
        # set server address again #
        elif SysMgr.remoteServObj:
            servObj = SysMgr.remoteServObj
            ip = servObj.ip
            port = servObj.port
            NetworkMgr.setRemoteServer('%s:%s' % (ip, port), tcp=True)

        # check server address #
        if not SysMgr.remoteServObj:
            printErr()
            return None

        # bind local socket for UDP #
        try:
            if not SysMgr.remoteServObj.tcp and \
                SysMgr.localServObj:
                lip = SysMgr.localServObj.ip
                lport = SysMgr.localServObj.port
                SysMgr.remoteServObj.socket.bind((lip, lport))
        except:
            err = SysMgr.getErrReason()
            SysMgr.printErr(\
                "Fail to bind socket to %s:%s for connection because %s" % \
                    (lip, lport, err))

        # do connect to server #
        try:
            connObj = SysMgr.remoteServObj

            connObj.timeout()

            # connect with handling CLOSE_WAIT #
            while 1:
                try:
                    connObj.connect()
                    break
                except:
                    err = SysMgr.getErrReason()
                    SysMgr.printWarn(\
                        "Fail to connect to %s:%s because %s" % \
                            (ip, port, err))
                    if err.startswith('99'):
                        time.sleep(0.1)
                        continue
                    break

            return connObj
        except:
            err = SysMgr.getErrReason()
            SysMgr.printErr(\
                "Fail to set socket for connection because %s" % err)
            return None
Exemplo n.º 7
0
        def onUpload(req):
            # parse path #
            plist = req.split('|', 1)[1]
            path = plist.split(',')

            origPath = path[0].strip()
            targetPath = path[1].strip()
            sender = self
            targetIp = self.ip
            targetPort = self.port
            addr = '%s:%s' % (targetIp, targetPort)

            # check file #
            if not os.path.isfile(origPath):
                SysMgr.printErr(\
                    'Failed to find %s to transfer' % origPath)
                return

            convert = UtilMgr.convertSize2Unit

            try:
                # receive file size #
                stat = os.stat(origPath)
                st_size = '%s' % stat.st_size
                sender.send(st_size)

                # read for ACK #
                while 1:
                    ret = sender.recv(3)
                    if ret is None:
                        continue
                    elif ret is False:
                        sys.exit(0)
                    else:
                        break

                # transfer file #
                curSize = long(0)
                totalSize = long(st_size)
                with open(origPath, 'rb') as fd:
                    buf = fd.read(sender.sendSize)
                    while buf:
                        # print progress #
                        UtilMgr.printProgress(curSize, totalSize)

                        ret = sender.send(buf)
                        if not ret:
                            raise Exception()
                        else:
                            curSize = len(buf)

                        buf = fd.read(sender.sendSize)

                UtilMgr.deleteProgress()

                SysMgr.printInfo(\
                    "%s [%s] is uploaded to %s:%s successfully\n" % \
                        (origPath, convert(os.path.getsize(origPath)), \
                            addr, targetPath))
            except:
                err = SysMgr.getErrReason()
                SysMgr.printErr(\
                    "Fail to upload %s to %s:%s because %s" % \
                        (origPath, addr, targetPath, err))
            finally:
                sender.close()
Exemplo n.º 8
0
        def onDownload(req):
            # parse path #
            plist = req.split('|', 1)[1]
            path = plist.split(',')
            origPath = path[0].strip()
            targetPath = path[1].strip()
            receiver = self
            targetIp = self.ip
            targetPort = self.port

            # get select object #
            selectObj = SysMgr.getPkg('select')

            # receive file #
            try:
                curSize = long(0)
                totalSize = None
                dirPos = targetPath.rfind('/')
                if dirPos >= 0 and \
                    not os.path.isdir(targetPath[:dirPos]):
                    os.makedirs(targetPath[:dirPos])

                # receive file size #
                while 1:
                    size = receiver.recv(receiver.recvSize)
                    if not size:
                        continue
                    else:
                        totalSize = long(size.decode())
                        receiver.send('ACK'.encode())
                        break

                # receive file #
                with open(targetPath, 'wb') as fd:
                    while 1:
                        selectObj.select([receiver.socket], [], [], 3)

                        buf = receiver.recv(receiver.recvSize)
                        if buf:
                            curSize += len(buf)
                            fd.write(buf)
                        else:
                            break

                        # print progress #
                        UtilMgr.printProgress(curSize, totalSize)

                UtilMgr.deleteProgress()

                SysMgr.printInfo(\
                    "%s [%s] is downloaded from %s:%s:%s successfully\n" % \
                    (targetPath, \
                    UtilMgr.convertSize2Unit(os.path.getsize(targetPath)),
                    targetIp, targetPort, origPath))
            except:
                err = SysMgr.getErrReason()
                SysMgr.printErr(\
                    'Fail to download %s from %s:%s:%s because %s' % \
                    (origPath, targetIp, targetPort, targetPath, err))
            finally:
                receiver.close()
Exemplo n.º 9
0
    def __init__(\
        self, mode, ip, port, blocking=True, tcp=False, anyPort=False):
        self.mode = mode
        self.ip = None
        self.port = None
        self.socket = None
        self.request = None
        self.status = None
        self.ignore = long(0)
        self.fileno = -1
        self.time = None
        self.sendSize = 32767
        self.recvSize = 32767
        self.tcp = tcp
        self.connected = False

        # get socket object #
        socket = SysMgr.getPkg('socket')

        try:
            from socket import socket, AF_INET, SOCK_DGRAM, \
                SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR, SO_SNDBUF, SO_RCVBUF, \
                SOL_TCP, TCP_NODELAY, SO_RCVTIMEO, SO_SNDTIMEO
        except:
            return None

        try:
            # set socket type #
            if tcp:
                self.socket = socket(AF_INET, SOCK_STREAM)
            else:
                self.socket = socket(AF_INET, SOCK_DGRAM)

            self.fileno = self.socket.fileno()

            # increate socket buffer size to 1MB #
            self.socket.setsockopt(SOL_SOCKET, SO_SNDBUF, 1 << 20)
            self.socket.setsockopt(SOL_SOCKET, SO_RCVBUF, 1 << 20)

            # get buffer size #
            self.sendSize = self.socket.getsockopt(SOL_SOCKET, SO_SNDBUF)
            self.recvSize = self.socket.getsockopt(SOL_SOCKET, SO_RCVBUF)

            # set REUSEADDR #
            self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

            # set SENDTIMEOUT #
            '''
            sec = 1
            usec = long(0)
            timeval = struct.pack('ll', sec, usec)
            self.socket.setsockopt(SOL_SOCKET, SO_SNDTIMEO, timeval)
            '''

            # set NODELAY #
            '''
            self.socket.setsockopt(SOL_TCP, TCP_NODELAY, 1)
            '''

            # set IP & PORT #
            self.ip = ip
            self.port = port

            if mode == 'server':
                # IP #
                if not ip:
                    self.ip = '0.0.0.0'

                # PORT #
                if anyPort:
                    self.port = long(0)
                elif not port:
                    self.port = SysMgr.defaultPort

                # bind #
                try:
                    self.socket.bind((self.ip, self.port))
                except:
                    self.socket.bind((self.ip, self.port))

                # get bind port #
                self.port = self.socket.getsockname()[1]

            if not blocking:
                self.socket.setblocking(0)
        except:
            err = SysMgr.getErrReason()
            if err.startswith('13') and \
                not SysMgr.isRoot() and \
                port < 1024:
                feedback = ', use port bigger than 1024'
            else:
                feedback = ''

            SysMgr.printErr(\
                "Fail to create socket with %s:%s as server because %s%s" % \
                    (self.ip, self.port, err, feedback))
            '''
            if error "99 Cannot assign requested address" occurs:
                add "net.ipv4.ip_nonlocal_bind = 1" in /etc/sysctl.conf
                execute sysctl -p /etc/sysctl.conf
            '''

            self.ip = None
            self.port = None

            return None