[120] | 1 | #Licensed to the Apache Software Foundation (ASF) under one |
---|
| 2 | #or more contributor license agreements. See the NOTICE file |
---|
| 3 | #distributed with this work for additional information |
---|
| 4 | #regarding copyright ownership. The ASF licenses this file |
---|
| 5 | #to you under the Apache License, Version 2.0 (the |
---|
| 6 | #"License"); you may not use this file except in compliance |
---|
| 7 | #with the License. You may obtain a copy of the License at |
---|
| 8 | |
---|
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
---|
| 10 | |
---|
| 11 | #Unless required by applicable law or agreed to in writing, software |
---|
| 12 | #distributed under the License is distributed on an "AS IS" BASIS, |
---|
| 13 | #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
---|
| 14 | #See the License for the specific language governing permissions and |
---|
| 15 | #limitations under the License. |
---|
| 16 | # $Id:tcp.py 6172 2007-05-22 20:26:54Z zim $ |
---|
| 17 | # |
---|
| 18 | #------------------------------------------------------------------------------ |
---|
| 19 | |
---|
| 20 | """ TCP related classes. """ |
---|
| 21 | |
---|
| 22 | import socket, re, string |
---|
| 23 | reAddress = re.compile(":") |
---|
| 24 | reMayBeIp = re.compile("^\d+\.\d+\.\d+\.\d+$") |
---|
| 25 | reValidPort = re.compile("^\d+$") |
---|
| 26 | |
---|
| 27 | class Error(Exception): |
---|
| 28 | def __init__(self, msg=''): |
---|
| 29 | self.message = msg |
---|
| 30 | Exception.__init__(self, msg) |
---|
| 31 | |
---|
| 32 | def __repr__(self): |
---|
| 33 | return self.message |
---|
| 34 | |
---|
| 35 | class tcpError(Error): |
---|
| 36 | def __init__(self, message): |
---|
| 37 | Error.__init__(self, message) |
---|
| 38 | |
---|
| 39 | class tcpSocket: |
---|
| 40 | def __init__(self, address, timeout=30, autoflush=0): |
---|
| 41 | """Constructs a tcpSocket object. |
---|
| 42 | |
---|
| 43 | address - standard tcp address (HOST:PORT) |
---|
| 44 | timeout - socket timeout""" |
---|
| 45 | |
---|
| 46 | self.address = address |
---|
| 47 | self.__autoFlush = autoflush |
---|
| 48 | self.__remoteSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
| 49 | self.__remoteSock.settimeout(timeout) |
---|
| 50 | self.host = None |
---|
| 51 | self.port = None |
---|
| 52 | splitAddress = address |
---|
| 53 | if isinstance(address, (tuple, list)): |
---|
| 54 | self.host = address[0] |
---|
| 55 | self.port = int(address[1]) |
---|
| 56 | else: |
---|
| 57 | splitAddress = get_address_tuple(address) |
---|
| 58 | if not splitAddress[0]: |
---|
| 59 | self.host = 'localhost' |
---|
| 60 | else: |
---|
| 61 | self.host = splitAddress[0] |
---|
| 62 | |
---|
| 63 | self.port = int(splitAddress[1]) |
---|
| 64 | |
---|
| 65 | self.__fileObjectOut = '' |
---|
| 66 | self.__fileObjectIn = '' |
---|
| 67 | |
---|
| 68 | def __repr__(self): |
---|
| 69 | return self.address |
---|
| 70 | |
---|
| 71 | def __iter__(self): |
---|
| 72 | return self |
---|
| 73 | |
---|
| 74 | def next(self): |
---|
| 75 | sockLine = self.read() |
---|
| 76 | if not sockLine: |
---|
| 77 | raise StopIteration |
---|
| 78 | |
---|
| 79 | return sockLine |
---|
| 80 | |
---|
| 81 | def open(self): |
---|
| 82 | """Attempts to open a socket to the specified address.""" |
---|
| 83 | |
---|
| 84 | socketAddress = (self.host, self.port) |
---|
| 85 | |
---|
| 86 | try: |
---|
| 87 | self.__remoteSock.connect(socketAddress) |
---|
| 88 | if self.__autoFlush: |
---|
| 89 | self.__fileObjectOut = self.__remoteSock.makefile('wb', 0) |
---|
| 90 | else: |
---|
| 91 | self.__fileObjectOut = self.__remoteSock.makefile('wb') |
---|
| 92 | |
---|
| 93 | self.__fileObjectIn = self.__remoteSock.makefile('rb', 0) |
---|
| 94 | except: |
---|
| 95 | raise tcpError, "connection failure: %s" % self.address |
---|
| 96 | |
---|
| 97 | def flush(self): |
---|
| 98 | """Flushes write buffer.""" |
---|
| 99 | self.__fileObjectOut.flush() |
---|
| 100 | |
---|
| 101 | def close(self): |
---|
| 102 | """Attempts to close and open socket connection""" |
---|
| 103 | |
---|
| 104 | try: |
---|
| 105 | self.__remoteSock.close() |
---|
| 106 | self.__fileObjectOut.close() |
---|
| 107 | self.__fileObjectIn.close() |
---|
| 108 | except socket.error, exceptionObject: |
---|
| 109 | exceptionMessage = "close failure %s %s" % (self.address, |
---|
| 110 | exceptionObject.__str__()) |
---|
| 111 | raise tcpError, exceptionMessage |
---|
| 112 | |
---|
| 113 | def verify(self): |
---|
| 114 | """Verifies that a given IP address/host and port are valid. This |
---|
| 115 | method will not attempt to open a socket to the specified address. |
---|
| 116 | """ |
---|
| 117 | |
---|
| 118 | isValidAddress = False |
---|
| 119 | if reMayBeIp.match(self.host): |
---|
| 120 | if check_ip_address(self.host): |
---|
| 121 | if reValidPort.match(str(self.port)): |
---|
| 122 | isValidAddress = True |
---|
| 123 | else: |
---|
| 124 | if reValidPort.match(str(self.port)): |
---|
| 125 | isValidAddress = True |
---|
| 126 | |
---|
| 127 | return(isValidAddress) |
---|
| 128 | |
---|
| 129 | def read(self): |
---|
| 130 | """Reads a line off of the active socket.""" |
---|
| 131 | |
---|
| 132 | return self.__fileObjectIn.readline() |
---|
| 133 | |
---|
| 134 | def write(self, string): |
---|
| 135 | """Writes a string to the active socket.""" |
---|
| 136 | |
---|
| 137 | print >> self.__fileObjectOut, string |
---|
| 138 | |
---|
| 139 | def check_net_address(address): |
---|
| 140 | valid = True |
---|
| 141 | pieces = string.split(address, '.') |
---|
| 142 | if len(pieces) != 4: |
---|
| 143 | valid = False |
---|
| 144 | else: |
---|
| 145 | for piece in pieces: |
---|
| 146 | if int(piece) < 0 or int(piece) > 255: |
---|
| 147 | valid = False |
---|
| 148 | |
---|
| 149 | return valid |
---|
| 150 | |
---|
| 151 | def check_ip_address(address): |
---|
| 152 | valid = True |
---|
| 153 | pieces = string.split(address, '.') |
---|
| 154 | if len(pieces) != 4: |
---|
| 155 | valid = False |
---|
| 156 | else: |
---|
| 157 | if int(pieces[0]) < 1 or int(pieces[0]) > 254: |
---|
| 158 | valid = False |
---|
| 159 | for i in range(1,4): |
---|
| 160 | if int(pieces[i]) < 0 or int(pieces[i]) > 255: |
---|
| 161 | valid = False |
---|
| 162 | |
---|
| 163 | return valid |
---|
| 164 | |
---|
| 165 | def get_address_tuple(address): |
---|
| 166 | """ Returns an address tuple for TCP address. |
---|
| 167 | |
---|
| 168 | address - TCP address of the form host:port |
---|
| 169 | |
---|
| 170 | returns address tuple (host, port) |
---|
| 171 | """ |
---|
| 172 | |
---|
| 173 | addressList = reAddress.split(address) |
---|
| 174 | addressTuple = (addressList[0], int(addressList[1])) |
---|
| 175 | |
---|
| 176 | return addressTuple |
---|