Debian Codegraph @

pypy/module/_socket/interp_socket.py

raw symbols SCIP
1 import sys, errno
2 from rpython.rlib import rsocket, rweaklist
3 from rpython.rlib.buffer import RawByteBuffer
4 from rpython.rlib.objectmodel import specialize
5 from rpython.rlib.rarithmetic import intmask, widen, r_uint
6 from rpython.rlib.rsocket import (
7 RSocket, AF_INET, SOCK_STREAM, SocketError, SocketErrorWithErrno,
8 RSocketError, SOMAXCONN, HAS_SO_PROTOCOL,
9 )
10 from rpython.rtyper.lltypesystem import lltype, rffi
11
12 from pypy.interpreter import gateway
13 from pypy.interpreter.baseobjspace import W_Root
14 from pypy.interpreter.error import OperationError, oefmt
15 from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
16 from pypy.interpreter.typedef import (
17 GetSetProperty, TypeDef, generic_new_descr, interp_attrproperty,
18 make_weakref_descr)
19
20 _WIN32 = sys.platform.startswith('win')
21
22 # XXX Hack to separate rpython and pypy
23 def addr_as_object(addr, fd, space):
24 from rpython.rlib import _rsocket_rffi as _c
25 if isinstance(addr, rsocket.INETAddress):
26 return space.newtuple2(space.newtext(addr.get_host()),
27 space.newint(addr.get_port()))
28 elif isinstance(addr, rsocket.INET6Address):
29 # For IPv6 remove the scope ID, see issue 3938
30 host = addr.get_host()
31 return space.newtuple([space.newtext(host.split("%")[0]),
32 space.newint(addr.get_port()),
33 space.newint(addr.get_flowinfo()),
34 space.newint(addr.get_scope_id())])
35 elif rsocket.HAS_AF_PACKET and isinstance(addr, rsocket.PacketAddress):
36 return space.newtuple([space.newtext(addr.get_ifname(fd)),
37 space.newint(addr.get_protocol()),
38 space.newint(addr.get_pkttype()),
39 space.newint(addr.get_hatype()),
40 space.newbytes(addr.get_haddr())])
41 elif rsocket.HAS_AF_UNIX and isinstance(addr, rsocket.UNIXAddress):
42 path = addr.get_path()
43 if _c.linux and len(path) > 0 and path[0] == '\x00':
44 # Linux abstract namespace
45 return space.newbytes(path)
46 else:
47 return space.newfilename(path)
48 elif rsocket.HAS_AF_NETLINK and isinstance(addr, rsocket.NETLINKAddress):
49 return space.newtuple2(space.newint(addr.get_pid()),
50 space.newint(addr.get_groups()))
51 # If we don't know the address family, don't raise an
52 # exception -- return it as a tuple.
53 a = addr.lock()
54 family = rffi.cast(lltype.Signed, a.c_sa_family)
55 datalen = addr.addrlen - rsocket.offsetof(_c.sockaddr, 'c_sa_data')
56 rawdata = ''.join([a.c_sa_data[i] for i in range(datalen)])
57 addr.unlock()
58 return space.newtuple2(space.newint(family),
59 space.newtext(rawdata))
60
61 # XXX Hack to seperate rpython and pypy
62 # XXX a bit of code duplication
63 def fill_from_object(addr, space, w_address):
64 from rpython.rlib import _rsocket_rffi as _c
65 if isinstance(addr, rsocket.INETAddress):
66 _, w_port = space.unpackiterable(w_address, 2)
67 port = space.int_w(w_port)
68 port = make_ushort_port(space, port)
69 a = addr.lock(_c.sockaddr_in)
70 rffi.setintfield(a, 'c_sin_port', rsocket.htons(port))
71 addr.unlock()
72 elif isinstance(addr, rsocket.INET6Address):
73 pieces_w = space.unpackiterable(w_address)
74 if not (2 <= len(pieces_w) <= 4):
75 raise RSocketError("AF_INET6 address must be a tuple of length 2 "
76 "to 4, not %d" % len(pieces_w))
77 port = space.int_w(pieces_w[1])
78 port = make_ushort_port(space, port)
79 if len(pieces_w) > 2: flowinfo = space.int_w(pieces_w[2])
80 else: flowinfo = 0
81 if len(pieces_w) > 3: scope_id = space.uint_w(pieces_w[3])
82 else: scope_id = 0
83 flowinfo = make_unsigned_flowinfo(space, flowinfo)
84 a = addr.lock(_c.sockaddr_in6)
85 rffi.setintfield(a, 'c_sin6_port', rsocket.htons(port))
86 rffi.setintfield(a, 'c_sin6_flowinfo', rsocket.htonl(flowinfo))
87 rffi.setintfield(a, 'c_sin6_scope_id', scope_id)
88 addr.unlock()
89 else:
90 raise NotImplementedError
91
92
93 if HAS_SO_PROTOCOL:
94 def get_so_protocol(fd):
95 from rpython.rlib import _rsocket_rffi as _c
96 return rsocket.getsockopt_int(fd, _c.SOL_SOCKET, _c.SO_PROTOCOL)
97 else:
98 def get_so_protocol(fd):
99 return -1
100
101
102 def idna_converter(space, w_host):
103 # Converts w_host to a byte string. Similar to encode_idna()
104 # but accepts more types and refuses NULL bytes.
105 if space.isinstance_w(w_host, space.w_unicode):
106 try:
107 w_s = space.encode_unicode_object(w_host, 'ascii', None)
108 except OperationError as e:
109 if not e.match(space, space.w_UnicodeEncodeError):
110 raise
111 w_s = space.encode_unicode_object(w_host, 'idna', None)
112 s = space.bytes_w(w_s)
113 elif space.isinstance_w(w_host, space.w_bytes):
114 s = space.bytes_w(w_host)
115 elif space.isinstance_w(w_host, space.w_bytearray):
116 s = space.charbuf_w(w_host)
117 else:
118 raise oefmt(space.w_TypeError,
119 "string or unicode text buffer expected, not %T", w_host)
120 if '\x00' in s:
121 raise oefmt(space.w_TypeError,
122 "host name must not contain null character")
123 return s
124
125
126 # XXX Hack to seperate rpython and pypy
127 def addr_from_object(family, fd, space, w_address):
128 family = widen(family)
129 if family == rsocket.AF_INET:
130 w_host, w_port = space.unpackiterable(w_address, 2)
131 host = idna_converter(space, w_host)
132 port = space.int_w(w_port)
133 port = make_ushort_port(space, port)
134 return rsocket.INETAddress(host, port)
135 if family == rsocket.AF_INET6:
136 pieces_w = space.unpackiterable(w_address)
137 if not (2 <= len(pieces_w) <= 4):
138 raise oefmt(space.w_TypeError,
139 "AF_INET6 address must be a tuple of length 2 "
140 "to 4, not %d", len(pieces_w))
141 host = idna_converter(space, pieces_w[0])
142 port = space.int_w(pieces_w[1])
143 port = make_ushort_port(space, port)
144 if len(pieces_w) > 2: flowinfo = space.int_w(pieces_w[2])
145 else: flowinfo = 0
146 if len(pieces_w) > 3: scope_id = space.uint_w(pieces_w[3])
147 else: scope_id = 0
148 flowinfo = make_unsigned_flowinfo(space, flowinfo)
149 return rsocket.INET6Address(host, port, flowinfo, scope_id)
150 if rsocket.HAS_AF_UNIX and family == rsocket.AF_UNIX:
151 # Not using space.fsencode_w since Linux allows embedded NULs.
152 if space.isinstance_w(w_address, space.w_unicode):
153 w_address = space.fsencode(w_address)
154 elif space.isinstance_w(w_address, space.w_bytearray):
155 w_address = space.newbytes(space.charbuf_w(w_address))
156 bytelike = space.bytes_w(w_address) # getarg_w('y*', w_address)
157 return rsocket.UNIXAddress(bytelike)
158 if rsocket.HAS_AF_NETLINK and family == rsocket.AF_NETLINK:
159 w_pid, w_groups = space.unpackiterable(w_address, 2)
160 return rsocket.NETLINKAddress(space.uint_w(w_pid), space.uint_w(w_groups))
161 if rsocket.HAS_AF_PACKET and family == rsocket.AF_PACKET:
162 pieces_w = space.unpackiterable(w_address)
163 if not (2 <= len(pieces_w) <= 5):
164 raise oefmt(space.w_TypeError,
165 "AF_PACKET address must be a tuple of length 2 "
166 "to 5, not %d", len(pieces_w))
167 ifname = space.text_w(pieces_w[0])
168 ifindex = rsocket.PacketAddress.get_ifindex_from_ifname(fd, ifname)
169 protocol = space.int_w(pieces_w[1])
170 if len(pieces_w) > 2: pkttype = space.int_w(pieces_w[2])
171 else: pkttype = 0
172 if len(pieces_w) > 3: hatype = space.int_w(pieces_w[3])
173 else: hatype = 0
174 if len(pieces_w) > 4: haddr = space.bytes_w(pieces_w[4])
175 else: haddr = ""
176 if len(haddr) > 8:
177 raise oefmt(space.w_ValueError,
178 "Hardware address must be 8 bytes or less")
179 if protocol < 0 or protocol > 0xfffff:
180 raise oefmt(space.w_OverflowError, "protoNumber must be 0-65535.")
181 return rsocket.PacketAddress(ifindex, protocol, pkttype, hatype, haddr)
182 raise RSocketError("unknown address family")
183
184 # XXX Hack to seperate rpython and pypy
185 def make_ushort_port(space, port):
186 assert isinstance(port, int)
187 if port < 0 or port > 0xffff:
188 raise oefmt(space.w_OverflowError, "port must be 0-65535.")
189 return port
190
191 def make_unsigned_flowinfo(space, flowinfo):
192 if flowinfo < 0 or flowinfo > 0xfffff:
193 raise oefmt(space.w_OverflowError, "flowinfo must be 0-1048575.")
194 return rffi.cast(lltype.Unsigned, flowinfo)
195
196 # XXX Hack to seperate rpython and pypy
197 def ipaddr_from_object(space, w_sockaddr):
198 host = space.text_w(space.getitem(w_sockaddr, space.newint(0)))
199 addr = rsocket.makeipaddr(host)
200 fill_from_object(addr, space, w_sockaddr)
201 return addr
202
203
204 class W_Socket(W_Root):
205 def __init__(self, space, sock=None):
206 self.space = space
207 if sock is None:
208 self.sock = RSocket.empty_rsocket()
209 else:
210 register_socket(space, sock)
211 self.sock = sock
212 self.register_finalizer(space)
213
214 @unwrap_spec(family=int, type=int, proto=int,
215 w_fileno=WrappedDefault(None))
216 def descr_init(self, space, family=-1, type=-1, proto=-1,
217 w_fileno=None):
218 from rpython.rlib.rsocket import _c
219 if space.is_w(w_fileno, space.w_None):
220 if family == -1:
221 family = AF_INET
222 if type == -1:
223 type = SOCK_STREAM
224 if proto == -1:
225 proto = 0
226 # TODO: figure out a way to not slow down the non-audit case
227 space.audit("socket.__new__",
228 [self, space.newint(family), space.newint(type),
229 space.newint(proto)])
230 try:
231 if not space.is_w(w_fileno, space.w_None):
232 if _WIN32 and space.isinstance_w(w_fileno, space.w_bytes):
233 # it is possible to pass some bytes representing a socket
234 # in the file descriptor object on winodws
235 fdobj = space.bytes_w(w_fileno)
236 if len(fdobj) != rffi.sizeof(_c.WSAPROTOCOL_INFOW):
237 raise oefmt(space.w_ValueError,
238 "socket descriptor string has wrong size, should be %d bytes",
239 rffi.sizeof(_c.WSAPROTOCOL_INFOW))
240 info_charptr = rffi.str2charp(fdobj)
241 try:
242 info_ptr = rffi.cast(lltype.Ptr(_c.WSAPROTOCOL_INFOW), info_charptr)
243 type = info_ptr.c_iSocketType
244 fd = _c.WSASocketW(_c.FROM_PROTOCOL_INFO, _c.FROM_PROTOCOL_INFO,
245 _c.FROM_PROTOCOL_INFO, info_ptr, 0, _c.WSA_FLAG_OVERLAPPED)
246 fd_int = rffi.cast(lltype.Signed, fd)
247 if fd_int == rsocket.INVALID_SOCKET:
248 raise converted_error(space, rsocket.last_error())
249 sock = RSocket(info_ptr.c_iAddressFamily, info_ptr.c_iSocketType, info_ptr.c_iProtocol, fd)
250 finally:
251 lltype.free(info_charptr, flavor='raw')
252 else:
253 if space.isinstance_w(w_fileno, space.w_float):
254 raise oefmt(space.w_TypeError,
255 "integer argument expected, got float")
256 fd = space.int_w(w_fileno)
257 if fd < 0:
258 raise oefmt(space.w_ValueError,
259 "negative file descriptor")
260 if family == -1:
261 family = rsocket.get_socket_family(fd)
262 if type == -1:
263 type = rsocket.getsockopt_int(fd, _c.SOL_SOCKET, _c.SO_TYPE)
264 if proto == -1:
265 proto = get_so_protocol(fd)
266 sock = RSocket(family, type, proto, fd=fd)
267 else:
268 sock = RSocket(family, type, proto, inheritable=False)
269 W_Socket.__init__(self, space, sock)
270 except SocketError as e:
271 raise converted_error(space, e)
272
273 def _finalize_(self):
274 sock = self.sock
275 if widen(sock.fd) != rsocket.INVALID_SOCKET:
276 try:
277 self._dealloc_warn()
278 finally:
279 try:
280 sock.close()
281 except SocketError:
282 pass
283
284 def get_type_w(self, space):
285 return space.newint(self.sock.type)
286
287 def get_proto_w(self, space):
288 return space.newint(self.sock.proto)
289
290 def get_family_w(self, space):
291 return space.newint(self.sock.family)
292
293 def _dealloc_warn(self):
294 space = self.space
295 try:
296 msg = (b"unclosed %s" %
297 space.utf8_w(space.repr(self)))
298 space.warn(space.newtext(msg), space.w_ResourceWarning)
299 except OperationError as e:
300 # Spurious errors can appear at shutdown
301 if e.match(space, space.w_Warning):
302 e.write_unraisable(space, '', self)
303
304 def descr_repr(self, space):
305 fd = widen(self.sock.fd) # Force to signed type even on Windows.
306 family = widen(self.sock.family) # these are too small on win64
307 tp = widen(self.sock.type)
308 proto = widen(self.sock.proto)
309 return space.newtext("<socket object, fd=%d, family=%d,"
310 " type=%d, proto=%d>" %
311 (fd, family, tp, proto))
312
313 def _accept_w(self, space):
314 """_accept() -> (socket object, address info)
315
316 Wait for an incoming connection. Return a new socket file descriptor
317 representing the connection, and the address of the client.
318 For IP sockets, the address info is a pair (hostaddr, port).
319 """
320 while True:
321 try:
322 fd, addr = self.sock.accept(inheritable=False)
323 return space.newtuple2(space.newint(fd),
324 addr_as_object(addr, fd, space))
325 except SocketError as e:
326 converted_error(space, e, eintr_retry=True)
327
328 # convert an Address into an app-level object
329 def addr_as_object(self, space, address):
330 return addr_as_object(address, self.sock.fd, space)
331
332 # convert an app-level object into an Address
333 # based on the current socket's family
334 def addr_from_object(self, space, w_address):
335 fd = widen(self.sock.fd)
336 return addr_from_object(self.sock.family, fd, space, w_address)
337
338 def bind_w(self, space, w_addr):
339 """bind(address)
340
341 Bind the socket to a local address. For IP sockets, the address is a
342 pair (host, port); the host must refer to the local host. For raw packet
343 sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])
344 """
345 space.audit("socket.bind", [self, w_addr])
346 try:
347 self.sock.bind(self.addr_from_object(space, w_addr))
348 except SocketError as e:
349 raise converted_error(space, e)
350
351 def close_w(self, space):
352 """close()
353
354 Close the socket. It cannot be used after this call.
355 """
356 try:
357 self.sock.close()
358 except SocketError as e:
359 raise converted_error(space, e)
360 self.may_unregister_rpython_finalizer(space)
361
362 def connect_w(self, space, w_addr):
363 """connect(address)
364
365 Connect the socket to a remote address. For IP sockets, the address
366 is a pair (host, port).
367 """
368 space.audit("socket.connect", [self, w_addr])
369 while True:
370 try:
371 self.sock.connect(self.addr_from_object(space, w_addr))
372 break
373 except SocketError as e:
374 converted_error(space, e, eintr_retry=True)
375
376 def connect_ex_w(self, space, w_addr):
377 """connect_ex(address) -> errno
378
379 This is like connect(address), but returns an error code (the errno value)
380 instead of raising an exception when an error occurs.
381 """
382 try:
383 addr = self.addr_from_object(space, w_addr)
384 except SocketError as e:
385 raise converted_error(space, e)
386 space.audit("socket.connect", [self, w_addr])
387 while True:
388 error = self.sock.connect_ex(addr)
389 if error != errno.EINTR:
390 break
391 space.getexecutioncontext().checksignals()
392 return space.newint(error)
393
394 def fileno_w(self, space):
395 """fileno() -> integer
396
397 Return the integer file descriptor of the socket.
398 """
399 return space.newint(widen(self.sock.fd))
400
401 def detach_w(self, space):
402 """detach()
403
404 Close the socket object without closing the underlying file descriptor.
405 The object cannot be used after this call, but the file descriptor
406 can be reused for other purposes. The file descriptor is returned."""
407 fd = self.sock.detach()
408 return space.newint(intmask(fd))
409
410 def getpeername_w(self, space):
411 """getpeername() -> address info
412
413 Return the address of the remote endpoint. For IP sockets, the address
414 info is a pair (hostaddr, port).
415 """
416 try:
417 addr = self.sock.getpeername()
418 return addr_as_object(addr, self.sock.fd, space)
419 except SocketError as e:
420 raise converted_error(space, e)
421
422 def getsockname_w(self, space):
423 """getsockname() -> address info
424
425 Return the address of the local endpoint. For IP sockets, the address
426 info is a pair (hostaddr, port).
427 """
428 try:
429 addr = self.sock.getsockname()
430 return addr_as_object(addr, self.sock.fd, space)
431 except SocketError as e:
432 raise converted_error(space, e)
433
434 @unwrap_spec(level=int, optname=int, buflen=int)
435 def getsockopt_w(self, space, level, optname, buflen=0):
436 """getsockopt(level, option[, buffersize]) -> value
437
438 Get a socket option. See the Unix manual for level and option.
439 If a nonzero buffersize argument is given, the return value is a
440 string of that length; otherwise it is an integer.
441 """
442 if buflen == 0:
443 try:
444 return space.newint(self.sock.getsockopt_int(level, optname))
445 except SocketError as e:
446 raise converted_error(space, e)
447 if buflen < 0 or buflen > 1024:
448 raise explicit_socket_error(space, "getsockopt buflen out of range")
449 try:
450 return space.newbytes(self.sock.getsockopt(level, optname, buflen))
451 except SocketError as e:
452 raise converted_error(space, e)
453
454 def gettimeout_w(self, space):
455 """gettimeout() -> timeout
456
457 Returns the timeout in floating seconds associated with socket
458 operations. A timeout of None indicates that timeouts on socket
459 operations are disabled.
460 """
461 timeout = self.sock.gettimeout()
462 if timeout < 0.0:
463 return space.w_None
464 return space.newfloat(timeout)
465
466 def getblocking_w(self, space):
467 """getblocking()
468
469 Returns True if socket is in blocking mode, or False if it
470 is in non-blocking mode.
471 """
472 return space.newbool(self.sock.gettimeout() != 0.0)
473
474 @unwrap_spec(backlog="c_int")
475 def listen_w(self, space, backlog=min(SOMAXCONN, 128)):
476 """listen(backlog)
477
478 Enable a server to accept connections. The backlog argument must be at
479 least 0 (if it is lower, it is set to 0); it specifies the number of
480 unaccepted connection that the system will allow before refusing new
481 connections. If not specified, a default reasonable value is chosen.
482 """
483 if backlog < 0:
484 backlog = 0
485 try:
486 self.sock.listen(backlog)
487 except SocketError as e:
488 raise converted_error(space, e)
489
490 @unwrap_spec(buffersize='nonnegint', flags=int)
491 def recv_w(self, space, buffersize, flags=0):
492 """recv(buffersize[, flags]) -> data
493
494 Receive up to buffersize bytes from the socket. For the optional flags
495 argument, see the Unix manual. When no data is available, block until
496 at least one byte is available or until the remote end is closed. When
497 the remote end is closed and all data is read, return the empty string.
498 """
499 while True:
500 try:
501 data = self.sock.recv(buffersize, flags)
502 break
503 except SocketError as e:
504 converted_error(space, e, eintr_retry=True)
505 return space.newbytes(data)
506
507 @unwrap_spec(buffersize='nonnegint', flags=int)
508 def recvfrom_w(self, space, buffersize, flags=0):
509 """recvfrom(buffersize[, flags]) -> (data, address info)
510
511 Like recv(buffersize, flags) but also return the sender's address info.
512 """
513 while True:
514 try:
515 data, addr = self.sock.recvfrom(buffersize, flags)
516 if addr:
517 w_addr = addr_as_object(addr, self.sock.fd, space)
518 else:
519 w_addr = space.w_None
520 break
521 except SocketError as e:
522 converted_error(space, e, eintr_retry=True)
523 return space.newtuple2(space.newbytes(data), w_addr)
524
525 @unwrap_spec(message_size=int, ancbufsize=int, flags=int)
526 def recvmsg_w(self, space, message_size, ancbufsize=0, flags=0):
527 """
528 recvmsg(message_size[, ancbufsize[, flags]]) -> (message, ancillary, flags, address)
529 Receive normal data (up to bufsize bytes) and ancillary data from the socket.
530 The ancbufsize argument sets the size in bytes of the internal buffer used to receive the ancillary data;
531 it defaults to 0, meaning that no ancillary data will be received.
532 Appropriate buffer sizes for ancillary data can be calculated using CMSG_SPACE() or CMSG_LEN(),
533 and items which do not fit into the buffer might be truncated or discarded.
534 The flags argument defaults to 0 and has the same meaning as for recv().
535 The ancdata item is a list of zero or more tuples (cmsg_level, cmsg_type, cmsg_data):
536 cmsg_level and cmsg_type are integers specifying the protocol level and protocol-specific type respectively,
537 and cmsg_data is a bytes object holding the associated data.
538
539 :param space: Non useable parameter. It represents the object space.
540 :param message_size: Maximum size of the message to be received
541 :param ancbufsize: Maximum size of the ancillary data to be received
542 :param flags: Receive flag. For more details, please check the Unix manual
543 :return: a tuple consisting of the message, the ancillary data, return flag and the address.
544 """
545 if message_size < 0:
546 raise oefmt(space.w_ValueError, "negative buffer size in recvmsg()")
547 if ancbufsize < 0:
548 raise oefmt(space.w_ValueError, "invalid ancillary data buffer length")
549 while True:
550 try:
551 recvtup = self.sock.recvmsg(message_size, ancbufsize, flags)
552 w_message = space.newbytes(recvtup[0])
553 anclist = []
554 for l in recvtup[1]:
555 tup = space.newtuple([space.newint(l[0]), space.newint(l[1]), space.newbytes(l[2])])
556 anclist.append(tup)
557
558 w_anc = space.newlist(anclist)
559
560 w_flag = space.newint(recvtup[2])
561 if (recvtup[3] is not None):
562 w_address = addr_as_object(recvtup[3], self.sock.fd, space)
563 else:
564 w_address = space.w_None
565 rettup = space.newtuple([w_message, w_anc, w_flag, w_address])
566 break
567 except SocketError as e:
568 converted_error(space, e, eintr_retry=True)
569 return rettup
570
571 @unwrap_spec(ancbufsize=int, flags=int)
572 def recvmsg_into_w(self, space, w_buffers, ancbufsize=0, flags=0):
573 """
574 recvmsg_into(buffers[, ancbufsize[, flags]]) -> (nbytes, ancdata, msg_flags, address)
575
576 Receive normal data and ancillary data from the socket, scattering the
577 non-ancillary data into a series of buffers. The buffers argument
578 must be an iterable of objects that export writable buffers
579 (e.g. bytearray objects); these will be filled with successive chunks
580 of the non-ancillary data until it has all been written or there are
581 no more buffers. The ancbufsize argument sets the size in bytes of
582 the internal buffer used to receive the ancillary data; it defaults to
583 0, meaning that no ancillary data will be received. Appropriate
584 buffer sizes for ancillary data can be calculated using CMSG_SPACE()
585 or CMSG_LEN(), and items which do not fit into the buffer might be
586 truncated or discarded. The flags argument defaults to 0 and has the
587 same meaning as for recv().
588
589 The return value is a 4-tuple: (nbytes, ancdata, msg_flags, address).
590 The nbytes item is the total number of bytes of non-ancillary data
591 written into the buffers. The ancdata item is a list of zero or more
592 tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary
593 data (control messages) received: cmsg_level and cmsg_type are
594 integers specifying the protocol level and protocol-specific type
595 respectively, and cmsg_data is a bytes object holding the associated
596 data. The msg_flags item is the bitwise OR of various flags
597 indicating conditions on the received message; see your system
598 documentation for details. If the receiving socket is unconnected,
599 address is the address of the sending socket, if available; otherwise,
600 its value is unspecified.
601
602 If recvmsg_into() raises an exception after the system call returns,
603 it will first attempt to close any file descriptors received via the
604 SCM_RIGHTS mechanism.
605 """
606 if ancbufsize < 0:
607 raise oefmt(space.w_ValueError, "invalid ancillary data buffer length")
608 buffers_w = space.unpackiterable(w_buffers)
609 buffers = [space.writebuf_w(w_buffer) for w_buffer in buffers_w]
610 rawbufs = [None] * len(buffers)
611 for i in range(len(buffers)):
612 try:
613 buffers[i].get_raw_address()
614 except ValueError:
615 rawbufs[i] = RawByteBuffer(buffers[i].getlength())
616 else:
617 rawbufs[i] = buffers[i]
618
619 while True:
620 try:
621 recvtup = self.sock.recvmsg_into(rawbufs, ancbufsize, flags)
622 nbytes, ancdata, retflag, address = recvtup
623 w_nbytes = space.newint(nbytes)
624 anclist = []
625 for level, type, anc in ancdata:
626 w_tup = space.newtuple([
627 space.newint(level), space.newint(type),
628 space.newbytes(anc)])
629 anclist.append(w_tup)
630
631 w_anc = space.newlist(anclist)
632
633 w_flag = space.newint(retflag)
634 if (address is not None):
635 w_address = addr_as_object(recvtup[3], self.sock.fd, space)
636 else:
637 w_address = space.w_None
638 rettup = space.newtuple([w_nbytes, w_anc, w_flag, w_address])
639 break
640 except SocketError as e:
641 converted_error(space, e, eintr_retry=True)
642
643 n_remaining = nbytes
644 for i in range(len(buffers)):
645 lgt = rawbufs[i].getlength()
646 n_read = min(lgt, n_remaining)
647 n_remaining -= n_read
648 if rawbufs[i] is not buffers[i]:
649 buffers[i].setslice(0, rawbufs[i].getslice(0, 1, n_read))
650 if n_remaining == 0:
651 break
652 return rettup
653
654 @unwrap_spec(data='bufferstr', flags=int)
655 def send_w(self, space, data, flags=0):
656 """send(data[, flags]) -> count
657
658 Send a data string to the socket. For the optional flags
659 argument, see the Unix manual. Return the number of bytes
660 sent; this may be less than len(data) if the network is busy.
661 """
662 while True:
663 try:
664 count = self.sock.send(data, flags)
665 break
666 except SocketError as e:
667 converted_error(space, e, eintr_retry=True)
668 return space.newint(count)
669
670 @unwrap_spec(data='bufferstr', flags=int)
671 def sendall_w(self, space, data, flags=0):
672 """sendall(data[, flags])
673
674 Send a data string to the socket. For the optional flags
675 argument, see the Unix manual. This calls send() repeatedly
676 until all data is sent. If an error occurs, it's impossible
677 to tell how much data has been sent.
678 """
679 try:
680 self.sock.sendall(
681 data, flags, space.getexecutioncontext().checksignals)
682 except SocketError as e:
683 raise converted_error(space, e)
684
685 def sendto_w(self, space, w_data, w_param2, w_param3=None):
686 """sendto(data[, flags], address) -> count
687
688 Like send(data, flags) but allows specifying the destination address.
689 For IP sockets, the address is a pair (hostaddr, port).
690 """
691 data = space.charbuf_w(w_data)
692 if w_param3 is None:
693 # 2 args version
694 flags = 0
695 w_addr = w_param2
696 else:
697 # 3 args version
698 flags = space.int_w(w_param2)
699 w_addr = w_param3
700 space.audit("socket.sendto", [self, w_addr])
701 while True:
702 try:
703 addr = self.addr_from_object(space, w_addr)
704 count = self.sock.sendto(data, len(data), flags, addr)
705 break
706 except SocketError as e:
707 converted_error(space, e, eintr_retry=True)
708 return space.newint(count)
709
710 @unwrap_spec(flags=int)
711 def sendmsg_w(self, space, w_data, w_ancillary=None, flags=0 ,w_address=None):
712 """
713 sendmsg(data[,ancillary[,flags[,address]]]) -> bytes_sent
714 Send normal and ancillary data to the socket, gathering the non-ancillary data
715 from a series of buffers and concatenating it into a single message.
716 The ancdata argument specifies the ancillary data (control messages) as an iterable of zero or more tuples
717 (cmsg_level, cmsg_type, cmsg_data), where cmsg_level and cmsg_type are integers specifying the protocol level
718 and protocol-specific type respectively, and cmsg_data is a bytes-like object holding the associated data.
719 :param space: Represents the object space.
720 :param w_data: The message(s). needs to be a bytes like object
721 :param w_ancillary: needs to be a sequence object Can remain unspecified.
722 :param w_flags: needs to be an integer. Can remain unspecified.
723 :param w_address: needs to be a bytes-like object Can remain unspecified.
724 :return: Bytes sent from the message
725 """
726 if not space.is_none(w_address):
727 space.audit("socket.sendmsg", [self, w_address])
728 else:
729 space.audit("socket.sendmsg", [self, space.w_None])
730 # Get the flag and address from the object space
731 while True:
732 try:
733 address = None
734 if not space.is_none(w_address):
735 address = self.addr_from_object(space, w_address)
736
737 # find data's type in the ObjectSpace and get a list of string out of it.
738 data = []
739 data_iter = space.unpackiterable(w_data)
740 for i in data_iter:
741 data.append(space.readbuf_w(i).as_str())
742
743 # find the ancillary's type in the ObjectSpace and get a list of tuples out of it.
744 ancillary = []
745 if w_ancillary is not None:
746 anc_iter = space.unpackiterable(w_ancillary)
747 for w_i in anc_iter:
748 if not space.isinstance_w(w_i, space.w_tuple):
749 raise oefmt(space.w_TypeError, "[sendmsg() ancillary data items]() argument must be sequence")
750 if space.len_w(w_i) == 3:
751 intemtup = space.unpackiterable(w_i)
752 level = space.int_w(intemtup[0])
753 type = space.int_w(intemtup[1])
754 cont = space.readbuf_w(intemtup[2]).as_str()
755 tup = (level, type, cont)
756 ancillary.append(tup)
757 else:
758 raise oefmt(space.w_TypeError,
759 "[sendmsg() ancillary data items]() argument must be sequence of length 3")
760
761 count = self.sock.sendmsg(data, ancillary, flags, address)
762 if count < 0:
763 if (count == -1000):
764 raise oefmt(space.w_OSError, "sending multiple control messages not supported")
765 if (count == -1001):
766 raise oefmt(space.w_OSError, "ancillary data item too large")
767 if (count == -1002):
768 raise oefmt(space.w_OSError, "too much ancillary data")
769 break
770 except SocketError as e:
771 converted_error(space, e, eintr_retry=True)
772
773 return space.newint(count)
774
775 @unwrap_spec(flag=int)
776 def setblocking_w(self, space, flag):
777 """setblocking(flag)
778
779 Set the socket to blocking (flag is true) or non-blocking (false).
780 setblocking(True) is equivalent to settimeout(None);
781 setblocking(False) is equivalent to settimeout(0.0).
782 """
783 try:
784 self.sock.setblocking(bool(flag))
785 except SocketError as e:
786 raise converted_error(space, e)
787
788 @unwrap_spec(level=int, optname=int)
789 def setsockopt_w(self, space, level, optname, w_optval):
790 """setsockopt(level, option, value)
791
792 Set a socket option. See the Unix manual for level and option.
793 The value argument can either be an integer or a string.
794 """
795 try:
796 optval = space.c_int_w(w_optval)
797 except OperationError as e:
798 if e.async(space):
799 raise
800 optval = space.charbuf_w(w_optval)
801 try:
802 self.sock.setsockopt(level, optname, optval)
803 except SocketError as e:
804 raise converted_error(space, e)
805 return
806 try:
807 self.sock.setsockopt_int(level, optname, optval)
808 except SocketError as e:
809 raise converted_error(space, e)
810
811 def settimeout_w(self, space, w_timeout):
812 """settimeout(timeout)
813
814 Set a timeout on socket operations. 'timeout' can be a float,
815 giving in seconds, or None. Setting a timeout of None disables
816 the timeout feature and is equivalent to setblocking(1).
817 Setting a timeout of zero is the same as setblocking(0).
818 """
819 if space.is_w(w_timeout, space.w_None):
820 timeout = -1.0
821 else:
822 timeout = space.float_w(w_timeout)
823 if timeout < 0.0:
824 raise oefmt(space.w_ValueError, "Timeout value out of range")
825 try:
826 self.sock.settimeout(timeout)
827 except SocketError as e:
828 raise converted_error(space, e)
829
830 @unwrap_spec(nbytes=int, flags=int)
831 def recv_into_w(self, space, w_buffer, nbytes=0, flags=0):
832 """recv_into(buffer, [nbytes[, flags]]) -> nbytes_read
833
834 A version of recv() that stores its data into a buffer rather than creating
835 a new string. Receive up to buffersize bytes from the socket. If buffersize
836 is not specified (or 0), receive up to the size available in the given buffer.
837
838 See recv() for documentation about the flags.
839 """
840 rwbuffer = space.writebuf_w(w_buffer)
841 lgt = rwbuffer.getlength()
842 if nbytes < 0:
843 raise oefmt(space.w_ValueError, "negative buffersize in recv_into")
844 if nbytes == 0:
845 nbytes = lgt
846 if lgt < nbytes:
847 raise oefmt(space.w_ValueError, "buffer too small for requested bytes")
848 try:
849 rwbuffer.get_raw_address()
850 except ValueError:
851 rawbuf = RawByteBuffer(nbytes)
852 else:
853 rawbuf = rwbuffer
854
855 while True:
856 try:
857 nbytes_read = self.sock.recvinto(rawbuf, nbytes, flags)
858 break
859 except SocketError as e:
860 converted_error(space, e, eintr_retry=True)
861 if rawbuf is not rwbuffer:
862 rwbuffer.setslice(0, rawbuf.getslice(0, 1, nbytes_read))
863 return space.newint(nbytes_read)
864
865 @unwrap_spec(nbytes=int, flags=int)
866 def recvfrom_into_w(self, space, w_buffer, nbytes=0, flags=0):
867 """recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)
868
869 Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.
870 """
871 rwbuffer = space.writebuf_w(w_buffer)
872 lgt = rwbuffer.getlength()
873 if nbytes == 0:
874 nbytes = lgt
875 elif nbytes > lgt:
876 raise oefmt(space.w_ValueError,
877 "nbytes is greater than the length of the buffer")
878 try:
879 rwbuffer.get_raw_address()
880 except ValueError:
881 rawbuf = RawByteBuffer(nbytes)
882 else:
883 rawbuf = rwbuffer
884 while True:
885 try:
886 readlgt, addr = self.sock.recvfrom_into(rawbuf, nbytes, flags)
887 break
888 except SocketError as e:
889 converted_error(space, e, eintr_retry=True)
890 if rawbuf is not rwbuffer:
891 rwbuffer.setslice(0, rawbuf.getslice(0, 1, readlgt))
892 if addr:
893 try:
894 w_addr = addr_as_object(addr, self.sock.fd, space)
895 except SocketError as e:
896 raise converted_error(space, e)
897 else:
898 w_addr = space.w_None
899 return space.newtuple2(space.newint(readlgt), w_addr)
900
901 @unwrap_spec(cmd=int)
902 def ioctl_w(self, space, cmd, w_option):
903 from rpython.rtyper.lltypesystem import rffi, lltype
904 from rpython.rlib import rwin32
905 from rpython.rlib.rsocket import _c
906
907 recv_ptr = lltype.malloc(rwin32.LPDWORD.TO, 1, flavor='raw')
908 try:
909 if cmd == _c.SIO_RCVALL:
910 value_size = rffi.sizeof(rffi.INTP)
911 elif cmd == _c.SIO_KEEPALIVE_VALS:
912 value_size = rffi.sizeof(_c.tcp_keepalive)
913 else:
914 raise oefmt(space.w_ValueError,
915 "invalid ioctl command %d", cmd)
916
917 value_ptr = lltype.malloc(rffi.VOIDP.TO, value_size, flavor='raw')
918 try:
919 if cmd == _c.SIO_RCVALL:
920 option_ptr = rffi.cast(rffi.INTP, value_ptr)
921 option_ptr[0] = rffi.cast(rffi.INT, space.int_w(w_option))
922 elif cmd == _c.SIO_KEEPALIVE_VALS:
923 w_onoff, w_time, w_interval = space.unpackiterable(w_option, 3)
924 option_ptr = rffi.cast(lltype.Ptr(_c.tcp_keepalive), value_ptr)
925 option_ptr.c_onoff = rffi.cast(rffi.UINT, space.uint_w(w_onoff))
926 option_ptr.c_keepalivetime = rffi.cast(rffi.UINT, space.uint_w(w_time))
927 option_ptr.c_keepaliveinterval = rffi.cast(rffi.UINT, space.uint_w(w_interval))
928
929 res = _c.WSAIoctl(
930 self.sock.fd, cmd, value_ptr, value_size,
931 rffi.NULL, 0, recv_ptr, rffi.NULL, rffi.NULL)
932 if res < 0:
933 raise converted_error(space, rsocket.last_error())
934 finally:
935 if value_ptr:
936 lltype.free(value_ptr, flavor='raw')
937
938 return space.newint(recv_ptr[0])
939 finally:
940 lltype.free(recv_ptr, flavor='raw')
941
942 @unwrap_spec(processid=int)
943 def share_w(self, space, processid):
944 from rpython.rtyper.lltypesystem import rffi, lltype
945 from rpython.rlib import rwin32
946 from rpython.rlib.rsocket import _c
947 info_ptr = lltype.malloc(_c.WSAPROTOCOL_INFOW, flavor='raw')
948 try:
949 winprocessid = rffi.cast(rwin32.DWORD, processid)
950 res = _c.WSADuplicateSocketW(
951 self.sock.fd, winprocessid, info_ptr)
952
953 if res < 0:
954 raise converted_error(space, rsocket.last_error())
955
956 bytes_ptr = rffi.cast(rffi.CCHARP, info_ptr)
957 w_bytes = space.newbytes(rffi.charpsize2str(bytes_ptr, rffi.sizeof(_c.WSAPROTOCOL_INFOW)))
958 finally:
959 lltype.free(info_ptr, flavor='raw')
960 return w_bytes
961
962 @unwrap_spec(how="c_int")
963 def shutdown_w(self, space, how):
964 """shutdown(flag)
965
966 Shut down the reading side of the socket (flag == SHUT_RD), the
967 writing side of the socket (flag == SHUT_WR), or both ends
968 (flag == SHUT_RDWR).
969 """
970 try:
971 self.sock.shutdown(how)
972 except SocketError as e:
973 raise converted_error(space, e)
974
975 #------------------------------------------------------------
976 # Support functions for socket._socketobject
977 usecount = 1
978 def _reuse_w(self):
979 """_resue()
980
981 Increase the usecount of the socketobject.
982 Intended only to be used by socket._socketobject
983 """
984 self.usecount += 1
985
986 def _drop_w(self, space):
987 """_drop()
988
989 Decrease the usecount of the socketobject. If the
990 usecount reaches 0 close the socket.
991 Intended only to be used by socket._socketobject
992 """
993 self.usecount -= 1
994 if self.usecount > 0:
995 return
996 self.close_w(space)
997
998
999 # ____________________________________________________________
1000 # Automatic shutdown()/close()
1001
1002 # On some systems, the C library does not guarantee that when the program
1003 # finishes, all data sent so far is really sent even if the socket is not
1004 # explicitly closed. This behavior has been observed on Windows but not
1005 # on Linux, so far.
1006 NEED_EXPLICIT_CLOSE = (sys.platform == 'win32')
1007
1008 class OpenRSockets(rweaklist.RWeakListMixin):
1009 pass
1010 class OpenRSocketsState:
1011 def __init__(self, space):
1012 self.openrsockets = OpenRSockets()
1013 self.openrsockets.initialize()
1014
1015 def getopenrsockets(space):
1016 if NEED_EXPLICIT_CLOSE and space.config.translation.rweakref:
1017 return space.fromcache(OpenRSocketsState).openrsockets
1018 else:
1019 return None
1020
1021 def register_socket(space, socket):
1022 openrsockets = getopenrsockets(space)
1023 if openrsockets is not None:
1024 openrsockets.add_handle(socket)
1025
1026 def close_all_sockets(space):
1027 openrsockets = getopenrsockets(space)
1028 if openrsockets is not None:
1029 for sock_wref in openrsockets.get_all_handles():
1030 sock = sock_wref()
1031 if sock is not None:
1032 try:
1033 sock.close()
1034 except SocketError:
1035 pass
1036
1037
1038 # ____________________________________________________________
1039 # Error handling
1040
1041 class SocketAPI:
1042 def __init__(self, space):
1043 self.w_error = space.w_OSError
1044 self.w_herror = space.new_exception_class(
1045 "_socket.herror", self.w_error)
1046 self.w_gaierror = space.new_exception_class(
1047 "_socket.gaierror", self.w_error)
1048 self.w_timeout = space.new_exception_class(
1049 "_socket.timeout", self.w_error)
1050
1051 self.errors_w = {'error': self.w_error,
1052 'herror': self.w_herror,
1053 'gaierror': self.w_gaierror,
1054 'timeout': self.w_timeout,
1055 }
1056
1057 def get_exception(self, applevelerrcls):
1058 return self.errors_w[applevelerrcls]
1059
1060 def get_error(space, name):
1061 if name == "timeout":
1062 return space.w_TimeoutError
1063 return space.fromcache(SocketAPI).get_exception(name)
1064
1065 @specialize.arg(2)
1066 def converted_error(space, e, eintr_retry=False):
1067 message, lgt = e.get_msg_utf8()
1068 w_exception_class = get_error(space, e.applevelerrcls)
1069 if isinstance(e, SocketErrorWithErrno):
1070 if e.errno == errno.EINTR:
1071 space.getexecutioncontext().checksignals()
1072 if eintr_retry:
1073 return # only return None if eintr_retry==True
1074 w_exception = space.call_function(w_exception_class, space.newint(e.errno),
1075 space.newtext(message, lgt))
1076 else:
1077 w_exception = space.call_function(w_exception_class,
1078 space.newtext(message, lgt))
1079 raise OperationError(w_exception_class, w_exception)
1080
1081 def explicit_socket_error(space, msg):
1082 w_exception_class = space.fromcache(SocketAPI).w_error
1083 w_exception = space.call_function(w_exception_class, space.newtext(msg))
1084 return OperationError(w_exception_class, w_exception)
1085
1086
1087 # ____________________________________________________________
1088
1089 socketmethodnames = """
1090 _accept bind close connect connect_ex fileno detach
1091 getpeername getsockname getsockopt gettimeout listen
1092 recv recvfrom send sendall sendto setblocking
1093 setsockopt settimeout shutdown _reuse _drop
1094 recv_into recvfrom_into
1095 getblocking
1096 """.split()
1097 if hasattr(rsocket._c, 'WSAIoctl'):
1098 socketmethodnames.append('ioctl')
1099 socketmethodnames.append('share')
1100 if rsocket._c.HAVE_SENDMSG:
1101 socketmethodnames.append('sendmsg')
1102 socketmethodnames.append('recvmsg')
1103 socketmethodnames.append('recvmsg_into')
1104
1105 socketmethods = {}
1106 for methodname in socketmethodnames:
1107 method = getattr(W_Socket, methodname + '_w')
1108 socketmethods[methodname] = interp2app(method)
1109
1110 W_Socket.typedef = TypeDef("_socket.socket",
1111 __doc__ = """\
1112 socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None) -> socket object
1113
1114 Open a socket of the given type. The family argument specifies the
1115 address family; it defaults to AF_INET. The type argument specifies
1116 whether this is a stream (SOCK_STREAM, this is the default)
1117 or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,
1118 specifying the default protocol. Keyword arguments are accepted.
1119 The socket is created as non-inheritable.
1120
1121 A socket object represents one endpoint of a network connection.
1122
1123 Methods of socket objects (keyword arguments not allowed):
1124
1125 _accept() -- accept connection, returning new socket fd and client address
1126 bind(addr) -- bind the socket to a local address
1127 close() -- close the socket
1128 connect(addr) -- connect the socket to a remote address
1129 connect_ex(addr) -- connect, return an error code instead of an exception
1130 dup() -- return a new socket fd duplicated from fileno()
1131 fileno() -- return underlying file descriptor
1132 getpeername() -- return remote address [*]
1133 getsockname() -- return local address
1134 getsockopt(level, optname[, buflen]) -- get socket options
1135 gettimeout() -- return timeout or None
1136 listen([n]) -- start listening for incoming connections
1137 recv(buflen[, flags]) -- receive data
1138 recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)
1139 recvfrom(buflen[, flags]) -- receive data and sender\'s address
1140 recvfrom_into(buffer[, nbytes, [, flags])
1141 -- receive data and sender\'s address (into a buffer)
1142 sendall(data[, flags]) -- send all data
1143 send(data[, flags]) -- send data, may not send all of it
1144 sendto(data[, flags], addr) -- send data to a given address
1145 setblocking(0 | 1) -- set or clear the blocking I/O flag
1146 setsockopt(level, optname, value[, optlen]) -- set socket options
1147 settimeout(None | float) -- set or clear the timeout
1148 shutdown(how) -- shut down traffic in one or both directions
1149 if_nameindex() -- return all network interface indices and names
1150 if_nametoindex(name) -- return the corresponding interface index
1151 if_indextoname(index) -- return the corresponding interface name
1152
1153 [*] not available on all platforms!""",
1154 __new__ = generic_new_descr(W_Socket),
1155 __init__ = interp2app(W_Socket.descr_init),
1156 __repr__ = interp2app(W_Socket.descr_repr),
1157 type = GetSetProperty(W_Socket.get_type_w),
1158 proto = GetSetProperty(W_Socket.get_proto_w),
1159 family = GetSetProperty(W_Socket.get_family_w),
1160 timeout = GetSetProperty(W_Socket.gettimeout_w),
1161 **socketmethods
1162 )
1163
1164 @unwrap_spec(fd=int)
1165 def close(space, fd):
1166 from rpython.rlib import _rsocket_rffi as _c
1167 res = _c.socketclose(fd)
1168 if res:
1169 converted_error(space, rsocket.last_error())
1170
1171
1172 def if_nameindex(space):
1173 """Returns a list of network interface information (index, name) tuples.
1174 """
1175 return space.newlist([space.newtuple([space.newint(i), space.newtext(n)])
1176 for i,n in rsocket.if_nameindex()])
1177
1178 @unwrap_spec(index=int)
1179 def if_indextoname(space, index):
1180 if index < 0:
1181 raise oefmt(space.w_OverflowError, "can't convert negative value to unsigned int")
1182 interfaces = rsocket.if_nameindex()
1183 for indx, name in interfaces:
1184 indx = widen(indx)
1185 if indx == index:
1186 return space.newtext(name)
1187 raise oefmt(space.w_OSError, "No such device or address")
1188
1189 @unwrap_spec(name='text')
1190 def if_nametoindex(space, name):
1191 interfaces = rsocket.if_nameindex()
1192 for indx, nam in interfaces:
1193 if nam == name:
1194 return space.newint(indx)
1195 raise oefmt(space.w_OSError, "No such device or address")