PageRenderTime 74ms CodeModel.GetById 30ms app.highlight 28ms RepoModel.GetById 12ms app.codeStats 0ms

/pypy/module/_socket/interp_func.py

https://bitbucket.org/pypy/pypy/
Python | 316 lines | 306 code | 4 blank | 6 comment | 0 complexity | 99d8cc841837e5500c67e7806f2ca148 MD5 | raw file
  1from rpython.rlib import rsocket
  2from rpython.rlib.rsocket import SocketError, INVALID_SOCKET
  3from rpython.rlib.rarithmetic import intmask
  4
  5from pypy.interpreter.error import OperationError, oefmt
  6from pypy.interpreter.gateway import unwrap_spec, WrappedDefault
  7from pypy.module._socket.interp_socket import (
  8    converted_error, W_Socket, addr_as_object, ipaddr_from_object
  9)
 10
 11
 12def gethostname(space):
 13    """gethostname() -> string
 14
 15    Return the current host name.
 16    """
 17    try:
 18        res = rsocket.gethostname()
 19    except SocketError as e:
 20        raise converted_error(space, e)
 21    return space.wrap(res)
 22
 23@unwrap_spec(host=str)
 24def gethostbyname(space, host):
 25    """gethostbyname(host) -> address
 26
 27    Return the IP address (a string of the form '255.255.255.255') for a host.
 28    """
 29    try:
 30        addr = rsocket.gethostbyname(host)
 31        ip = addr.get_host()
 32    except SocketError as e:
 33        raise converted_error(space, e)
 34    return space.wrap(ip)
 35
 36def common_wrapgethost(space, (name, aliases, address_list)):
 37    aliases = [space.wrap(alias) for alias in aliases]
 38    address_list = [space.wrap(addr.get_host()) for addr in address_list]
 39    return space.newtuple([space.wrap(name),
 40                           space.newlist(aliases),
 41                           space.newlist(address_list)])
 42
 43@unwrap_spec(host=str)
 44def gethostbyname_ex(space, host):
 45    """gethostbyname_ex(host) -> (name, aliaslist, addresslist)
 46
 47    Return the true host name, a list of aliases, and a list of IP addresses,
 48    for a host.  The host argument is a string giving a host name or IP number.
 49    """
 50    try:
 51        res = rsocket.gethostbyname_ex(host)
 52    except SocketError as e:
 53        raise converted_error(space, e)
 54    return common_wrapgethost(space, res)
 55
 56@unwrap_spec(host=str)
 57def gethostbyaddr(space, host):
 58    """gethostbyaddr(host) -> (name, aliaslist, addresslist)
 59
 60    Return the true host name, a list of aliases, and a list of IP addresses,
 61    for a host.  The host argument is a string giving a host name or IP number.
 62    """
 63    try:
 64        res = rsocket.gethostbyaddr(host)
 65    except SocketError as e:
 66        raise converted_error(space, e)
 67    return common_wrapgethost(space, res)
 68
 69@unwrap_spec(name=str, w_proto = WrappedDefault(None))
 70def getservbyname(space, name, w_proto):
 71    """getservbyname(servicename[, protocolname]) -> integer
 72
 73    Return a port number from a service name and protocol name.
 74    The optional protocol name, if given, should be 'tcp' or 'udp',
 75    otherwise any protocol will match.
 76    """
 77    if space.is_w(w_proto, space.w_None):
 78        proto = None
 79    else:
 80        proto = space.str_w(w_proto)
 81    try:
 82        port = rsocket.getservbyname(name, proto)
 83    except SocketError as e:
 84        raise converted_error(space, e)
 85    return space.wrap(port)
 86
 87@unwrap_spec(port=int, w_proto = WrappedDefault(None))
 88def getservbyport(space, port, w_proto):
 89    """getservbyport(port[, protocolname]) -> string
 90
 91    Return the service name from a port number and protocol name.
 92    The optional protocol name, if given, should be 'tcp' or 'udp',
 93    otherwise any protocol will match.
 94    """
 95    if space.is_w(w_proto, space.w_None):
 96        proto = None
 97    else:
 98        proto = space.str_w(w_proto)
 99
100    if port < 0 or port > 0xffff:
101        raise oefmt(space.w_ValueError, "getservbyport: port must be 0-65535.")
102
103    try:
104        service = rsocket.getservbyport(port, proto)
105    except SocketError as e:
106        raise converted_error(space, e)
107    return space.wrap(service)
108
109@unwrap_spec(name=str)
110def getprotobyname(space, name):
111    """getprotobyname(name) -> integer
112
113    Return the protocol number for the named protocol.  (Rarely used.)
114    """
115    try:
116        proto = rsocket.getprotobyname(name)
117    except SocketError as e:
118        raise converted_error(space, e)
119    return space.wrap(proto)
120
121@unwrap_spec(flags=int)
122def getnameinfo(space, w_sockaddr, flags):
123    """getnameinfo(sockaddr, flags) --> (host, port)
124
125    Get host and port for a sockaddr."""
126    try:
127        addr = ipaddr_from_object(space, w_sockaddr)
128        host, servport = rsocket.getnameinfo(addr, flags)
129    except SocketError as e:
130        raise converted_error(space, e)
131    return space.newtuple([space.wrap(host), space.wrap(servport)])
132
133@unwrap_spec(fd=int, family=int, type=int, proto=int)
134def fromfd(space, fd, family, type, proto=0):
135    """fromfd(fd, family, type[, proto]) -> socket object
136
137    Create a socket object from the given file descriptor.
138    The remaining arguments are the same as for socket().
139    """
140    try:
141        sock = rsocket.fromfd(fd, family, type, proto)
142    except SocketError as e:
143        raise converted_error(space, e)
144    return space.wrap(W_Socket(space, sock))
145
146@unwrap_spec(family=int, type=int, proto=int)
147def socketpair(space, family=rsocket.socketpair_default_family,
148                      type  =rsocket.SOCK_STREAM,
149                      proto =0):
150    """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
151
152    Create a pair of socket objects from the sockets returned by the platform
153    socketpair() function.
154    The arguments are the same as for socket() except the default family is
155    AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
156    """
157    try:
158        sock1, sock2 = rsocket.socketpair(family, type, proto)
159    except SocketError as e:
160        raise converted_error(space, e)
161    return space.newtuple([
162        space.wrap(W_Socket(space, sock1)),
163        space.wrap(W_Socket(space, sock2))
164    ])
165
166# The following 4 functions refuse all negative numbers, like CPython 2.6.
167# They could also check that the argument is not too large, but CPython 2.6
168# is not doing that consistently.
169@unwrap_spec(x="c_uint")
170def ntohs(space, x):
171    """ntohs(integer) -> integer
172
173    Convert a 16-bit integer from network to host byte order.
174    """
175    return space.wrap(rsocket.ntohs(intmask(x)))
176
177@unwrap_spec(x="c_uint")
178def ntohl(space, x):
179    """ntohl(integer) -> integer
180
181    Convert a 32-bit integer from network to host byte order.
182    """
183    return space.wrap(rsocket.ntohl(x))
184
185@unwrap_spec(x="c_uint")
186def htons(space, x):
187    """htons(integer) -> integer
188
189    Convert a 16-bit integer from host to network byte order.
190    """
191    return space.wrap(rsocket.htons(intmask(x)))
192
193@unwrap_spec(x="c_uint")
194def htonl(space, x):
195    """htonl(integer) -> integer
196
197    Convert a 32-bit integer from host to network byte order.
198    """
199    return space.wrap(rsocket.htonl(x))
200
201@unwrap_spec(ip=str)
202def inet_aton(space, ip):
203    """inet_aton(string) -> packed 32-bit IP representation
204
205    Convert an IP address in string format (123.45.67.89) to the 32-bit packed
206    binary format used in low-level network functions.
207    """
208    try:
209        buf = rsocket.inet_aton(ip)
210    except SocketError as e:
211        raise converted_error(space, e)
212    return space.newbytes(buf)
213
214@unwrap_spec(packed=str)
215def inet_ntoa(space, packed):
216    """inet_ntoa(packed_ip) -> ip_address_string
217
218    Convert an IP address from 32-bit packed binary format to string format
219    """
220    try:
221        ip = rsocket.inet_ntoa(packed)
222    except SocketError as e:
223        raise converted_error(space, e)
224    return space.wrap(ip)
225
226@unwrap_spec(family=int, ip=str)
227def inet_pton(space, family, ip):
228    """inet_pton(family, ip) -> packed IP address string
229
230    Convert an IP address from string format to a packed string suitable
231    for use with low-level network functions.
232    """
233    try:
234        buf = rsocket.inet_pton(family, ip)
235    except SocketError as e:
236        raise converted_error(space, e)
237    return space.newbytes(buf)
238
239@unwrap_spec(family=int, packed=str)
240def inet_ntop(space, family, packed):
241    """inet_ntop(family, packed_ip) -> string formatted IP address
242
243    Convert a packed IP address of the given family to string format.
244    """
245    try:
246        ip = rsocket.inet_ntop(family, packed)
247    except SocketError as e:
248        raise converted_error(space, e)
249    except ValueError:
250        raise oefmt(space.w_ValueError,
251                    "invalid length of packed IP address string")
252    return space.wrap(ip)
253
254@unwrap_spec(family=int, socktype=int, proto=int, flags=int)
255def getaddrinfo(space, w_host, w_port,
256                family=rsocket.AF_UNSPEC, socktype=0, proto=0, flags=0):
257    """getaddrinfo(host, port [, family, socktype, proto, flags])
258        -> list of (family, socktype, proto, canonname, sockaddr)
259
260    Resolve host and port into addrinfo struct.
261    """
262    # host can be None, string or unicode
263    if space.is_w(w_host, space.w_None):
264        host = None
265    elif space.isinstance_w(w_host, space.w_str):
266        host = space.bytes_w(w_host)
267    elif space.isinstance_w(w_host, space.w_unicode):
268        w_shost = space.call_method(w_host, "encode", space.wrap("idna"))
269        host = space.bytes_w(w_shost)
270    else:
271        raise oefmt(space.w_TypeError,
272                    "getaddrinfo() argument 1 must be string or None")
273
274    # port can be None, int or string
275    if space.is_w(w_port, space.w_None):
276        port = None
277    elif space.isinstance_w(w_port, space.w_int) or space.isinstance_w(w_port, space.w_long):
278        port = str(space.int_w(w_port))
279    elif space.isinstance_w(w_port, space.w_str):
280        port = space.bytes_w(w_port)
281    else:
282        raise oefmt(space.w_TypeError,
283                    "getaddrinfo() argument 2 must be integer or string")
284    try:
285        lst = rsocket.getaddrinfo(host, port, family, socktype,
286                                  proto, flags)
287    except SocketError as e:
288        raise converted_error(space, e)
289    lst1 = [space.newtuple([space.wrap(family),
290                            space.wrap(socktype),
291                            space.wrap(protocol),
292                            space.wrap(canonname),
293                            addr_as_object(addr, INVALID_SOCKET, space)]) # -1 as per cpython
294            for (family, socktype, protocol, canonname, addr) in lst]
295    return space.newlist(lst1)
296
297def getdefaulttimeout(space):
298    """getdefaulttimeout() -> timeout
299
300    Returns the default timeout in floating seconds for new socket objects.
301    A value of None indicates that new socket objects have no timeout.
302    When the socket module is first imported, the default is None.
303    """
304    timeout = rsocket.getdefaulttimeout()
305    if timeout < 0.0:
306        return space.w_None
307    return space.wrap(timeout)
308
309def setdefaulttimeout(space, w_timeout):
310    if space.is_w(w_timeout, space.w_None):
311        timeout = -1.0
312    else:
313        timeout = space.float_w(w_timeout)
314        if timeout < 0.0:
315            raise oefmt(space.w_ValueError, "Timeout value out of range")
316    rsocket.setdefaulttimeout(timeout)