Debian Codegraph @

pypy/module/_socket/interp_func.py

raw symbols SCIP
1 import sys
2 from rpython.rlib import rsocket
3 from rpython.rlib.rsocket import SocketError, INVALID_SOCKET
4 from rpython.rlib.rarithmetic import intmask, r_longlong, r_uint32
5
6 from pypy.interpreter.error import oefmt
7 from pypy.interpreter.gateway import unwrap_spec, WrappedDefault
8 from pypy.module._socket.interp_socket import (
9 converted_error, W_Socket, addr_as_object, fill_from_object, get_error,
10 ipaddr_from_object
11 )
12
13
14 def gethostname(space):
15 """gethostname() -> string
16
17 Return the current host name.
18 """
19 space.audit("socket.gethostname", [])
20 try:
21 res = rsocket.gethostname()
22 except SocketError as e:
23 raise converted_error(space, e)
24 return space.fsdecode(space.newbytes(res))
25
26 def encode_idna(space, w_host):
27 # call unicode.encode(host, 'idna'), and not host.encode('idna') in case
28 # type(host) is not unicode. See also interp_socket.idna_converter()
29 return space.bytes_w(space.call_method(space.w_unicode, 'encode',
30 w_host, space.newtext('idna')))
31
32 def gethostbyname(space, w_host):
33 """gethostbyname(host) -> address
34
35 Return the IP address (a string of the form '255.255.255.255') for a host.
36 """
37 host = encode_idna(space, w_host)
38 space.audit('socket.gethostbyname', [w_host])
39 try:
40 addr = rsocket.gethostbyname(host)
41 ip = addr.get_host()
42 except SocketError as e:
43 raise converted_error(space, e)
44 return space.newtext(ip)
45
46 def common_wrapgethost(space, (name, aliases, address_list)):
47 aliases = [space.newtext(alias) for alias in aliases]
48 address_list = [space.newtext(addr.get_host()) for addr in address_list]
49 return space.newtuple([space.newtext(name),
50 space.newlist(aliases),
51 space.newlist(address_list)])
52
53 def gethostbyname_ex(space, w_host):
54 """gethostbyname_ex(host) -> (name, aliaslist, addresslist)
55
56 Return the true host name, a list of aliases, and a list of IP addresses,
57 for a host. The host argument is a string giving a host name or IP number.
58 """
59 host = encode_idna(space, w_host)
60 space.audit('socket.gethostbyname', [w_host])
61 try:
62 res = rsocket.gethostbyname_ex(host)
63 except SocketError as e:
64 raise converted_error(space, e)
65 return common_wrapgethost(space, res)
66
67 def gethostbyaddr(space, w_host):
68 """gethostbyaddr(host) -> (name, aliaslist, addresslist)
69
70 Return the true host name, a list of aliases, and a list of IP addresses,
71 for a host. The host argument is a string giving a host name or IP number.
72 """
73 host = encode_idna(space, w_host)
74 space.audit('socket.gethostbyname', [w_host])
75 try:
76 res = rsocket.gethostbyaddr(host)
77 except SocketError as e:
78 raise converted_error(space, e)
79 return common_wrapgethost(space, res)
80
81 @unwrap_spec(name='text', w_proto = WrappedDefault(None))
82 def getservbyname(space, name, w_proto):
83 """getservbyname(servicename[, protocolname]) -> integer
84
85 Return a port number from a service name and protocol name.
86 The optional protocol name, if given, should be 'tcp' or 'udp',
87 otherwise any protocol will match.
88 """
89 if space.is_w(w_proto, space.w_None):
90 proto = None
91 else:
92 proto = space.text_w(w_proto)
93 space.audit('socket.getservbyname', [space.newtext(name), w_proto])
94 try:
95 port = rsocket.getservbyname(name, proto)
96 except SocketError as e:
97 raise converted_error(space, e)
98 return space.newint(port)
99
100 @unwrap_spec(port=int, w_proto = WrappedDefault(None))
101 def getservbyport(space, port, w_proto):
102 """getservbyport(port[, protocolname]) -> string
103
104 Return the service name from a port number and protocol name.
105 The optional protocol name, if given, should be 'tcp' or 'udp',
106 otherwise any protocol will match.
107 """
108 if space.is_w(w_proto, space.w_None):
109 proto = None
110 else:
111 proto = space.text_w(w_proto)
112
113 if port < 0 or port > 0xffff:
114 raise oefmt(space.w_OverflowError,
115 "getservbyport: port must be 0-65535.")
116
117 space.audit('socket.getservbyport', [space.newint(port), w_proto])
118 try:
119 service = rsocket.getservbyport(port, proto)
120 except SocketError as e:
121 raise converted_error(space, e)
122 return space.newtext(service)
123
124 @unwrap_spec(name='text')
125 def getprotobyname(space, name):
126 """getprotobyname(name) -> integer
127
128 Return the protocol number for the named protocol. (Rarely used.)
129 """
130 try:
131 proto = rsocket.getprotobyname(name)
132 except SocketError as e:
133 raise converted_error(space, e)
134 return space.newint(proto)
135
136 @unwrap_spec(flags=int)
137 def getnameinfo(space, w_sockaddr, flags):
138 """getnameinfo(sockaddr, flags) --> (host, port)
139
140 Get host and port for a sockaddr."""
141 space.audit('socket.getnameinfo', [w_sockaddr])
142 try:
143 host = space.text_w((space.getitem(w_sockaddr, space.newint(0))))
144 port = str(space.int_w(space.getitem(w_sockaddr, space.newint(1))))
145 lst = rsocket.getaddrinfo(host, port, rsocket.AF_UNSPEC,
146 rsocket.SOCK_DGRAM, 0,
147 rsocket.AI_NUMERICHOST)
148 if len(lst) > 1:
149 raise oefmt(get_error(space, 'error'),
150 "sockaddr resolved to multiple addresses")
151 addr = lst[0][4]
152 fill_from_object(addr, space, w_sockaddr)
153 host, servport = rsocket.getnameinfo(addr, flags)
154 except SocketError as e:
155 raise converted_error(space, e)
156 return space.newtuple2(space.newtext(host), space.newtext(servport))
157
158 @unwrap_spec(fd=int)
159 def dup(space, fd):
160 try:
161 newfd = rsocket.dup(fd, inheritable=False)
162 except SocketError as e:
163 raise converted_error(space, e)
164 return space.newint(newfd)
165
166 @unwrap_spec(family=int, type=int, proto=int)
167 def socketpair(space, family=rsocket.socketpair_default_family,
168 type =rsocket.SOCK_STREAM,
169 proto =0):
170 """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
171
172 Create a pair of socket objects from the sockets returned by the platform
173 socketpair() function.
174 The arguments are the same as for socket() except the default family is
175 AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
176 """
177 try:
178 sock1, sock2 = rsocket.socketpair(family, type, proto,
179 inheritable=False)
180 except SocketError as e:
181 raise converted_error(space, e)
182 return space.newtuple2(
183 W_Socket(space, sock1),
184 W_Socket(space, sock2)
185 )
186
187 # The following 4 functions refuse all negative numbers.
188 # They also check that the argument is not too large, but note that
189 # CPython 2.7 is not doing that consistently (CPython 3.x does).
190 LONGLONG_UINT32_MAX = r_longlong(2**32-1)
191
192 @unwrap_spec(x="c_int")
193 def ntohs(space, x):
194 """ntohs(integer) -> integer
195
196 Convert a 16-bit integer from network to host byte order.
197 """
198 if x < 0:
199 raise oefmt(space.w_OverflowError,
200 "can't convert negative number to unsigned long")
201 return space.newint(rsocket.ntohs(intmask(x)))
202
203 @unwrap_spec(x=r_longlong)
204 def ntohl(space, x):
205 """ntohl(integer) -> integer
206
207 Convert a 32-bit integer from network to host byte order.
208 """
209 if x < r_longlong(0):
210 raise oefmt(space.w_OverflowError,
211 "can't convert negative number to unsigned long")
212 if x > LONGLONG_UINT32_MAX:
213 raise oefmt(space.w_OverflowError, "long int larger than 32 bits")
214 return space.newint(rsocket.ntohl(r_uint32(x)))
215
216 @unwrap_spec(x="c_int")
217 def htons(space, x):
218 """htons(integer) -> integer
219
220 Convert a 16-bit integer from host to network byte order.
221 """
222 if x < 0:
223 raise oefmt(space.w_OverflowError,
224 "can't convert negative number to unsigned long")
225 return space.newint(rsocket.htons(x))
226
227 @unwrap_spec(x=r_longlong)
228 def htonl(space, x):
229 """htonl(integer) -> integer
230
231 Convert a 32-bit integer from host to network byte order.
232 """
233 if x < r_longlong(0):
234 raise oefmt(space.w_OverflowError,
235 "can't convert negative number to unsigned long")
236 if x > LONGLONG_UINT32_MAX:
237 raise oefmt(space.w_OverflowError, "long int larger than 32 bits")
238 return space.newint(rsocket.htonl(r_uint32(x)))
239
240 @unwrap_spec(ip='text')
241 def inet_aton(space, ip):
242 """inet_aton(string) -> packed 32-bit IP representation
243
244 Convert an IP address in string format (123.45.67.89) to the 32-bit packed
245 binary format used in low-level network functions.
246 """
247 try:
248 buf = rsocket.inet_aton(ip)
249 except SocketError as e:
250 raise converted_error(space, e)
251 return space.newbytes(buf)
252
253 @unwrap_spec(packed="bufferstr")
254 def inet_ntoa(space, packed):
255 """inet_ntoa(packed_ip) -> ip_address_string
256
257 Convert an IP address from 32-bit packed binary format to string format
258 """
259 try:
260 ip = rsocket.inet_ntoa(packed)
261 except SocketError as e:
262 raise converted_error(space, e)
263 return space.newtext(ip)
264
265 @unwrap_spec(family=int, ip='text')
266 def inet_pton(space, family, ip):
267 """inet_pton(family, ip) -> packed IP address string
268
269 Convert an IP address from string format to a packed string suitable
270 for use with low-level network functions.
271 """
272 try:
273 buf = rsocket.inet_pton(family, ip)
274 except SocketError as e:
275 raise converted_error(space, e)
276 return space.newbytes(buf)
277
278 @unwrap_spec(family=int, packed='bufferstr')
279 def inet_ntop(space, family, packed):
280 """inet_ntop(family, packed_ip) -> string formatted IP address
281
282 Convert a packed IP address of the given family to string format.
283 """
284 try:
285 ip = rsocket.inet_ntop(family, packed)
286 except SocketError as e:
287 raise converted_error(space, e)
288 except ValueError:
289 raise oefmt(space.w_ValueError,
290 "invalid length of packed IP address string")
291 return space.newtext(ip)
292
293 @unwrap_spec(family=int, type=int, proto=int, flags=int)
294 def getaddrinfo(space, w_host, w_port,
295 family=rsocket.AF_UNSPEC, type=0, proto=0, flags=0):
296 """getaddrinfo(host, port [, family, type, proto, flags])
297 -> list of (family, type, proto, canonname, sockaddr)
298
299 Resolve host and port into addrinfo struct.
300 """
301 socktype = type
302 # host can be None, string or unicode
303 if space.is_w(w_host, space.w_None):
304 host = None
305 elif space.isinstance_w(w_host, space.w_bytes):
306 host = space.bytes_w(w_host)
307 elif space.isinstance_w(w_host, space.w_unicode):
308 host = encode_idna(space, w_host)
309 else:
310 raise oefmt(space.w_TypeError,
311 "getaddrinfo() argument 1 must be string or None")
312
313 # port can be None, int or string
314 if space.is_w(w_port, space.w_None):
315 port = None
316 elif space.isinstance_w(w_port, space.w_int):
317 port = str(space.int_w(w_port))
318 elif space.isinstance_w(w_port, space.w_bytes):
319 port = space.bytes_w(w_port)
320 elif space.isinstance_w(w_port, space.w_unicode):
321 port = space.bytes_w(space.encode_unicode_object(w_port, 'utf-8', 'strict'))
322 else:
323 raise oefmt(space.w_TypeError,
324 "getaddrinfo() argument 2 must be integer or string")
325 space.audit('socket.getaddrinfo',
326 [w_host, w_port, space.newint(family),
327 space.newint(socktype), space.newint(proto)])
328 try:
329 lst = rsocket.getaddrinfo(host, port, family, socktype,
330 proto, flags)
331 except SocketError as e:
332 raise converted_error(space, e)
333 lst1 = [space.newtuple([space.newint(family),
334 space.newint(socktype),
335 space.newint(proto),
336 space.newtext(canonname),
337 addr_as_object(addr, INVALID_SOCKET, space)]) # -1 as per cpython
338 for (family, socktype, proto, canonname, addr) in lst]
339 return space.newlist(lst1)
340
341 if sys.platform != 'win32':
342 @unwrap_spec(size=int)
343 def CMSG_SPACE(space, size):
344 """
345 Socket method to determine the optimal byte size of the ancillary.
346 Recommended to be used when computing the ancillary size for recvmsg.
347 :param space:
348 :param size: an integer with the minimum size required.
349 :return: an integer with the minimum memory needed for the required size. The value is memory aligned
350 """
351 if size < 0:
352 raise oefmt(space.w_OverflowError,
353 "CMSG_SPACE() argument out of range")
354 retval = rsocket.CMSG_SPACE(size)
355 if retval == 0:
356 raise oefmt(space.w_OverflowError,
357 "CMSG_SPACE() argument out of range")
358 return space.newint(retval)
359
360 @unwrap_spec(len=int)
361 def CMSG_LEN(space, len):
362 """
363 Socket method to determine the optimal byte size of the ancillary.
364 Recommended to be used when computing the ancillary size for recvmsg.
365 :param space:
366 :param len: an integer with the minimum size required.
367 :return: an integer with the minimum memory needed for the required size. The value is not mem aligned.
368 """
369 if len < 0:
370 raise oefmt(space.w_OverflowError,
371 "CMSG_LEN() argument out of range")
372 retval = rsocket.CMSG_LEN(len)
373 if retval == 0:
374 raise oefmt(space.w_OverflowError,
375 "CMSG_LEN() argument out of range")
376 return space.newint(retval)
377
378 def getdefaulttimeout(space):
379 """getdefaulttimeout() -> timeout
380
381 Returns the default timeout in floating seconds for new socket objects.
382 A value of None indicates that new socket objects have no timeout.
383 When the socket module is first imported, the default is None.
384 """
385 timeout = rsocket.getdefaulttimeout()
386 if timeout < 0.0:
387 return space.w_None
388 return space.newfloat(timeout)
389
390 def setdefaulttimeout(space, w_timeout):
391 if space.is_w(w_timeout, space.w_None):
392 timeout = -1.0
393 else:
394 timeout = space.float_w(w_timeout)
395 if timeout < 0.0:
396 raise oefmt(space.w_ValueError, "Timeout value out of range")
397 rsocket.setdefaulttimeout(timeout)
398
399 if hasattr(rsocket, 'sethostname'):
400 def sethostname(space, w_hostname):
401 """sethostname(hostname)
402
403 Set the host name.
404 """
405 if space.isinstance_w(w_hostname, space.w_bytes):
406 hostname = space.bytes_w(w_hostname)
407 elif space.isinstance_w(w_hostname, space.w_unicode):
408 hostname = space.fsencode_w(w_hostname)
409 else:
410 raise oefmt(space.w_TypeError,
411 "sethostname() argument 1 must be str or bytes")
412 space.audit("socket.sethostname", [w_hostname])
413 try:
414 res = rsocket.sethostname(hostname)
415 except SocketError as e:
416 raise converted_error(space, e)