Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 1 | # Wrapper module for _socket, providing some additional facilities |
| 2 | # implemented in Python. |
| 3 | |
| 4 | """\ |
| 5 | This module provides socket operations and some related functions. |
| 6 | On Unix, it supports IP (Internet Protocol) and Unix domain sockets. |
Tim Peters | 495ad3c | 2001-01-15 01:36:40 +0000 | [diff] [blame] | 7 | On other systems, it only supports IP. Functions specific for a |
Martin v. Löwis | af484d5 | 2000-09-30 11:34:30 +0000 | [diff] [blame] | 8 | socket are available as methods of the socket object. |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 9 | |
| 10 | Functions: |
| 11 | |
| 12 | socket() -- create a new socket object |
| 13 | fromfd() -- create a socket object from an open file descriptor [*] |
| 14 | gethostname() -- return the current hostname |
| 15 | gethostbyname() -- map a hostname to its IP number |
| 16 | gethostbyaddr() -- map an IP number or hostname to DNS info |
| 17 | getservbyname() -- map a service name and a protocol name to a port number |
| 18 | getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number |
| 19 | ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order |
| 20 | htons(), htonl() -- convert 16, 32 bit int from host to network byte order |
| 21 | inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format |
| 22 | inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) |
| 23 | ssl() -- secure socket layer support (only available if configured) |
| 24 | |
| 25 | [*] not available on all platforms! |
| 26 | |
| 27 | Special objects: |
| 28 | |
| 29 | SocketType -- type object for socket objects |
| 30 | error -- exception raised for I/O errors |
| 31 | |
| 32 | Integer constants: |
| 33 | |
| 34 | AF_INET, AF_UNIX -- socket domains (first argument to socket() call) |
| 35 | SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) |
| 36 | |
| 37 | Many other constants may be defined; these may be used in calls to |
| 38 | the setsockopt() and getsockopt() methods. |
| 39 | """ |
| 40 | |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 41 | import _socket |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 42 | from _socket import * |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 43 | |
| 44 | SSL_EXISTS = 1 |
Marc-André Lemburg | a5d2b4c | 2002-02-16 18:23:30 +0000 | [diff] [blame] | 45 | try: |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 46 | import _ssl |
Marc-André Lemburg | a5d2b4c | 2002-02-16 18:23:30 +0000 | [diff] [blame] | 47 | from _ssl import * |
| 48 | except ImportError: |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 49 | SSL_EXISTS = 0 |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 50 | |
| 51 | import os, sys |
| 52 | |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 53 | __all__ = ["getfqdn"] |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 54 | __all__.extend(os._get_exports_list(_socket)) |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 55 | # XXX shouldn't there be something similar to the above for _ssl exports? |
Skip Montanaro | 0de6580 | 2001-02-15 22:15:14 +0000 | [diff] [blame] | 56 | |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 57 | if (sys.platform.lower().startswith("win") |
Guido van Rossum | d74fb6b | 2001-03-02 06:43:49 +0000 | [diff] [blame] | 58 | or (hasattr(os, 'uname') and os.uname()[0] == "BeOS") |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 59 | or sys.platform=="riscos"): |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 60 | |
Guido van Rossum | 3f69f21 | 2001-03-22 22:12:17 +0000 | [diff] [blame] | 61 | _realsocketcall = _socket.socket |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 62 | |
| 63 | def socket(family, type, proto=0): |
| 64 | return _socketobject(_realsocketcall(family, type, proto)) |
| 65 | |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 66 | if SSL_EXISTS: |
Marc-André Lemburg | a5d2b4c | 2002-02-16 18:23:30 +0000 | [diff] [blame] | 67 | _realsslcall = _ssl.ssl |
Guido van Rossum | 3f69f21 | 2001-03-22 22:12:17 +0000 | [diff] [blame] | 68 | def ssl(sock, keyfile=None, certfile=None): |
| 69 | if hasattr(sock, "_sock"): |
| 70 | sock = sock._sock |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 71 | return _realsslcall(sock, keyfile, certfile) |
Guido van Rossum | 3f69f21 | 2001-03-22 22:12:17 +0000 | [diff] [blame] | 72 | |
Tim Peters | 18e6778 | 2002-02-17 04:25:24 +0000 | [diff] [blame] | 73 | del _socket |
| 74 | if SSL_EXISTS: |
| 75 | del _ssl |
| 76 | del SSL_EXISTS |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 77 | |
| 78 | # WSA error codes |
| 79 | if sys.platform.lower().startswith("win"): |
| 80 | errorTab = {} |
| 81 | errorTab[10004] = "The operation was interrupted." |
| 82 | errorTab[10009] = "A bad file handle was passed." |
| 83 | errorTab[10013] = "Permission denied." |
| 84 | errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT |
| 85 | errorTab[10022] = "An invalid operation was attempted." |
| 86 | errorTab[10035] = "The socket operation would block" |
| 87 | errorTab[10036] = "A blocking operation is already in progress." |
| 88 | errorTab[10048] = "The network address is in use." |
| 89 | errorTab[10054] = "The connection has been reset." |
| 90 | errorTab[10058] = "The network has been shut down." |
| 91 | errorTab[10060] = "The operation timed out." |
| 92 | errorTab[10061] = "Connection refused." |
| 93 | errorTab[10063] = "The name is too long." |
| 94 | errorTab[10064] = "The host is down." |
| 95 | errorTab[10065] = "The host is unreachable." |
Skip Montanaro | 64de1a4 | 2001-03-18 19:53:21 +0000 | [diff] [blame] | 96 | __all__.append("errorTab") |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 97 | del os, sys |
| 98 | |
| 99 | |
| 100 | def getfqdn(name=''): |
| 101 | """Get fully qualified domain name from name. |
| 102 | |
| 103 | An empty argument is interpreted as meaning the local host. |
| 104 | |
| 105 | First the hostname returned by gethostbyaddr() is checked, then |
| 106 | possibly existing aliases. In case no FQDN is available, hostname |
| 107 | is returned. |
| 108 | """ |
| 109 | name = name.strip() |
Peter Schneider-Kamp | 2d2785a | 2000-08-16 20:30:21 +0000 | [diff] [blame] | 110 | if not name or name == '0.0.0.0': |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 111 | name = gethostname() |
| 112 | try: |
| 113 | hostname, aliases, ipaddrs = gethostbyaddr(name) |
| 114 | except error: |
| 115 | pass |
| 116 | else: |
| 117 | aliases.insert(0, hostname) |
| 118 | for name in aliases: |
| 119 | if '.' in name: |
| 120 | break |
| 121 | else: |
| 122 | name = hostname |
| 123 | return name |
| 124 | |
| 125 | |
| 126 | # |
| 127 | # These classes are used by the socket() defined on Windows and BeOS |
| 128 | # platforms to provide a best-effort implementation of the cleanup |
| 129 | # semantics needed when sockets can't be dup()ed. |
| 130 | # |
| 131 | # These are not actually used on other platforms. |
| 132 | # |
| 133 | |
Guido van Rossum | e5e5059 | 2001-08-18 01:23:20 +0000 | [diff] [blame] | 134 | _socketmethods = ( |
| 135 | 'bind', 'connect', 'connect_ex', 'fileno', 'listen', |
| 136 | 'getpeername', 'getsockname', 'getsockopt', 'setsockopt', |
Guido van Rossum | b2c763f | 2001-10-29 07:13:53 +0000 | [diff] [blame] | 137 | 'recv', 'recvfrom', 'send', 'sendall', 'sendto', 'setblocking', 'shutdown') |
Guido van Rossum | e5e5059 | 2001-08-18 01:23:20 +0000 | [diff] [blame] | 138 | |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 139 | class _socketobject: |
| 140 | |
Guido van Rossum | 99d2fbb | 2001-12-18 22:22:25 +0000 | [diff] [blame] | 141 | class _closedsocket: |
| 142 | def __getattr__(self, name): |
| 143 | raise error(9, 'Bad file descriptor') |
| 144 | |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 145 | def __init__(self, sock): |
| 146 | self._sock = sock |
| 147 | |
| 148 | def close(self): |
Guido van Rossum | 99d2fbb | 2001-12-18 22:22:25 +0000 | [diff] [blame] | 149 | # Avoid referencing globals here |
| 150 | self._sock = self.__class__._closedsocket() |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 151 | |
| 152 | def __del__(self): |
| 153 | self.close() |
| 154 | |
| 155 | def accept(self): |
| 156 | sock, addr = self._sock.accept() |
| 157 | return _socketobject(sock), addr |
| 158 | |
| 159 | def dup(self): |
| 160 | return _socketobject(self._sock) |
| 161 | |
| 162 | def makefile(self, mode='r', bufsize=-1): |
| 163 | return _fileobject(self._sock, mode, bufsize) |
| 164 | |
Guido van Rossum | e5e5059 | 2001-08-18 01:23:20 +0000 | [diff] [blame] | 165 | _s = "def %s(self, *args): return self._sock.%s(*args)\n\n" |
| 166 | for _m in _socketmethods: |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 167 | exec _s % (_m, _m) |
| 168 | |
| 169 | |
| 170 | class _fileobject: |
| 171 | |
| 172 | def __init__(self, sock, mode, bufsize): |
| 173 | self._sock = sock |
| 174 | self._mode = mode |
| 175 | if bufsize < 0: |
| 176 | bufsize = 512 |
| 177 | self._rbufsize = max(1, bufsize) |
| 178 | self._wbufsize = bufsize |
| 179 | self._wbuf = self._rbuf = "" |
| 180 | |
| 181 | def close(self): |
| 182 | try: |
| 183 | if self._sock: |
| 184 | self.flush() |
| 185 | finally: |
| 186 | self._sock = 0 |
| 187 | |
| 188 | def __del__(self): |
| 189 | self.close() |
| 190 | |
| 191 | def flush(self): |
| 192 | if self._wbuf: |
Martin v. Löwis | e12454f | 2002-02-16 23:06:19 +0000 | [diff] [blame] | 193 | self._sock.sendall(self._wbuf) |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 194 | self._wbuf = "" |
| 195 | |
| 196 | def fileno(self): |
| 197 | return self._sock.fileno() |
| 198 | |
| 199 | def write(self, data): |
| 200 | self._wbuf = self._wbuf + data |
| 201 | if self._wbufsize == 1: |
| 202 | if '\n' in data: |
| 203 | self.flush() |
| 204 | else: |
| 205 | if len(self._wbuf) >= self._wbufsize: |
| 206 | self.flush() |
| 207 | |
| 208 | def writelines(self, list): |
Martin v. Löwis | e12454f | 2002-02-16 23:06:19 +0000 | [diff] [blame] | 209 | filter(self._sock.sendall, list) |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 210 | self.flush() |
| 211 | |
| 212 | def read(self, n=-1): |
| 213 | if n >= 0: |
| 214 | k = len(self._rbuf) |
| 215 | if n <= k: |
| 216 | data = self._rbuf[:n] |
| 217 | self._rbuf = self._rbuf[n:] |
| 218 | return data |
| 219 | n = n - k |
| 220 | L = [self._rbuf] |
| 221 | self._rbuf = "" |
| 222 | while n > 0: |
| 223 | new = self._sock.recv(max(n, self._rbufsize)) |
| 224 | if not new: break |
| 225 | k = len(new) |
| 226 | if k > n: |
| 227 | L.append(new[:n]) |
| 228 | self._rbuf = new[n:] |
| 229 | break |
| 230 | L.append(new) |
| 231 | n = n - k |
| 232 | return "".join(L) |
| 233 | k = max(512, self._rbufsize) |
| 234 | L = [self._rbuf] |
| 235 | self._rbuf = "" |
| 236 | while 1: |
| 237 | new = self._sock.recv(k) |
| 238 | if not new: break |
| 239 | L.append(new) |
| 240 | k = min(k*2, 1024**2) |
| 241 | return "".join(L) |
| 242 | |
| 243 | def readline(self, limit=-1): |
| 244 | data = "" |
| 245 | i = self._rbuf.find('\n') |
| 246 | while i < 0 and not (0 < limit <= len(self._rbuf)): |
| 247 | new = self._sock.recv(self._rbufsize) |
| 248 | if not new: break |
| 249 | i = new.find('\n') |
| 250 | if i >= 0: i = i + len(self._rbuf) |
| 251 | self._rbuf = self._rbuf + new |
| 252 | if i < 0: i = len(self._rbuf) |
| 253 | else: i = i+1 |
| 254 | if 0 <= limit < len(self._rbuf): i = limit |
| 255 | data, self._rbuf = self._rbuf[:i], self._rbuf[i:] |
| 256 | return data |
| 257 | |
Martin v. Löwis | 6df27f8 | 2000-09-19 11:25:58 +0000 | [diff] [blame] | 258 | def readlines(self, sizehint = 0): |
| 259 | total = 0 |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 260 | list = [] |
| 261 | while 1: |
| 262 | line = self.readline() |
| 263 | if not line: break |
| 264 | list.append(line) |
Martin v. Löwis | 6df27f8 | 2000-09-19 11:25:58 +0000 | [diff] [blame] | 265 | total += len(line) |
| 266 | if sizehint and total >= sizehint: |
| 267 | break |
Fred Drake | a6070f0 | 2000-08-16 14:14:32 +0000 | [diff] [blame] | 268 | return list |