j f{J@sdZddlZddlTddlZddlZddlZddlmZyddlZWnek rzdZYnXe eddZ e eddZ e ed dZ d d d d dgZ e jejeejd eddejdeddddZeZejjjdriZdedd?d Z"e#Z$e$dd@d Z%dddddAdBZ&dS)Ca0This module provides socket operations and some related functions. On Unix, it supports IP (Internet Protocol) and Unix domain sockets. On other systems, it only supports IP. Functions specific for a socket are available as methods of the socket object. Functions: socket() -- create a new socket object socketpair() -- create a pair of new socket objects [*] fromfd() -- create a socket object from an open file descriptor [*] fromshare() -- create a socket object from data received from socket.share() [*] gethostname() -- return the current hostname gethostbyname() -- map a hostname to its IP number gethostbyaddr() -- map an IP number or hostname to DNS info getservbyname() -- map a service name and a protocol name to a port number getprotobyname() -- map a protocol name (e.g. 'tcp') to a number ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order htons(), htonl() -- convert 16, 32 bit int from host to network byte order inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89) socket.getdefaulttimeout() -- get the default timeout value socket.setdefaulttimeout() -- set the default timeout value create_connection() -- connects to an address, with an optional timeout and optional source address. [*] not available on all platforms! Special objects: SocketType -- type object for socket objects error -- exception raised for I/O errors has_ipv6 -- boolean value indicating if IPv6 is supported IntEnum constants: AF_INET, AF_UNIX -- socket domains (first argument to socket() call) SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument) Integer constants: Many other constants may be defined; these may be used in calls to the setsockopt() and getsockopt() methods. N)*)IntEnumEBADF EAGAIN EWOULDBLOCKfromfdgetfqdncreate_connection AddressFamily SocketKindcCs|jo|jdS)NZAF_)isupper startswith)Cr+/opt/alt/python34/lib64/python3.4/socket.pyKsrcCs|jo|jdS)NZSOCK_)rr)rrrrrPsc Cs+y||SWntk r&|SYnXdS)z{Convert a numeric family value to an IntEnum member. If it's not a known member, return the numeric value itself. N) ValueError)valueZ enum_klassrrr_intenum_converterRs rwinzThe operation was interrupted.i'zA bad file handle was passed.i'zPermission denied.i'z!A fault occurred on the network??i'z#An invalid operation was attempted.i&'z The socket operation would blocki3'z,A blocking operation is already in progress.i4'zThe network address is in use.i@'zThe connection has been reset.iF'zThe network has been shut down.iJ'zThe operation timed out.iL'zConnection refused.iM'zThe name is too long.iO'zThe host is down.iP'zThe host is unreachable.iQ'errorTabc sieZdZdZdddgZeeddddZd d Zd d Z d dZ ddZ ddZ ddZ ddddddddddZddZejddZdd Zfd!d"Zefd#d$Zefd%d&Zejd'kr;d(d)Zd*d+Znd,d)Zd-d+Zd.e_d/e_S)0socketz:A subclass of _socket.socket adding the makefile() method. __weakref___io_refs_closedrNcCs2tjj|||||d|_d|_dS)NrF)_socketr__init__rr)selffamilytypeprotofilenorrrrys zsocket.__init__cCs|S)Nr)rrrr __enter__szsocket.__enter__cGs|js|jndS)N)rclose)rargsrrr__exit__s zsocket.__exit__cCst|dd}d|jj|jj|r3dnd|j|j|j|jf}|sy-|j}|r|dt |7}nWnt k rYnXy-|j }|r|dt |7}nWqt k rYqXn|d7}|S) zVWrap __repr__() to reveal the real class name and socket address(es). rFz,<%s.%s%s fd=%i, family=%s, type=%s, proto=%iz [closed]z , laddr=%sz , raddr=%s>) getattr __class__ __module____name__r#r r!r"Z getsocknamestrerrorZ getpeername)rclosedsZladdrZraddrrrr__repr__s0         zsocket.__repr__cCstddS)NzCannot serialize socket object) TypeError)rrrr __getstate__szsocket.__getstate__cCsMt|j}|j|j|j|jd|}|j|j|S)zdup() -> socket object Duplicate the socket. Return a new socket object connected to the same system resource. The new socket is non-inheritable. r#)dupr#r+r r!r" settimeout gettimeout)rfdsockrrrr5s$z socket.dupcCs|j\}}|jtjdd@}t|j||jd|}tdkrx|jrx|j dn||fS)zaccept() -> (socket object, address info) Wait for an incoming connection. Return a new socket representing the connection, and the address of the client. For IP sockets, the address info is a pair (hostaddr, port). Z SOCK_NONBLOCKrr#NT) Z_acceptr!globalsgetrr r"Zgetdefaulttimeoutr7Z setblocking)rr8Zaddrr!r9rrraccepts z socket.acceptrencodingerrorsnewlinec Cst|dddhks1td|fnd|k}d|kpM| }|sb|sbtd|k}d} |r| d7} n|r| d7} nt|| } |jd7_|dkrd }n|dkrtj}n|dkr |std n| S|r.|r.tj| | |} n9|rItj| |} n|sUttj | |} |rq| Stj | |||} || _ | S) a makefile(...) -> an I/O stream connected to the socket The arguments are as for io.open() after the filename, except the only mode characters supported are 'r', 'w' and 'b'. The semantics are similar too. (XXX refactor to share code?) r=wbz&invalid mode %r (only r, w, b allowed)r(Nrz!unbuffered streams must be binary) setrAssertionErrorSocketIOrioDEFAULT_BUFFER_SIZEBufferedRWPairBufferedReaderBufferedWriter TextIOWrappermode) rrN bufferingr>r?r@ZwritingZreadingZbinaryZrawmoderawbuffertextrrrmakefiles@            zsocket.makefilecCs;|jdkr!|jd8_n|jr7|jndS)NrrC)rrr%)rrrr_decref_socketioss zsocket._decref_socketioscCs|j|dS)N)r%)rZ_ssrrr _real_closeszsocket._real_closecCs)d|_|jdkr%|jndS)NTr)rrrU)rrrrr%s z socket.closecsd|_tjS)a detach() -> file descriptor Close the socket object without closing the underlying file descriptor. The object cannot be used after this call, but the file descriptor can be reused for other purposes. The file descriptor is returned. T)rsuperdetach)r)r+rrrWs z socket.detachcsttjtS)z@Read-only access to the address family for this socket. )rrVr r )r)r+rrr sz socket.familycsttjtS)z-Read-only access to the socket type. )rrVr!r )r)r+rrr!sz socket.typentcCstj|jS)N)osZget_handle_inheritabler#)rrrrget_inheritableszsocket.get_inheritablecCstj|j|dS)N)rYZset_handle_inheritabler#)r inheritablerrrset_inheritableszsocket.set_inheritablecCstj|jS)N)rYrZr#)rrrrrZscCstj|j|dS)N)rYr\r#)rr[rrrr\ sz&Get the inheritable flag of the socketz&Set the inheritable flag of the socket)r-r, __qualname____doc__ __slots__AF_INET SOCK_STREAMrr$r'r2r4r5r<rSrTrrrUr%rWpropertyr r!rYnamerZr\rr)r+rrss0       )       rcCst|}t||||S)z fromfd(fd, family, type[, proto]) -> socket object Create a socket object from a duplicate of the given file descriptor. The remaining arguments are the same as for socket(). )r5r)r8r r!r"Znfdrrrr %s ZsharecCstddd|S)z fromshare(info) -> socket object Create a socket object from the bytes object returned by socket.share(pid). r)r)inforrr fromshare/sre socketpairc Cs|dkr4y t}Wq4tk r0t}Yq4Xntj|||\}}t||||j}t||||j}||fS)aasocketpair([family[, type[, proto]]]) -> (socket object, socket object) Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET. N)ZAF_UNIX NameErrorr`rrfrrW)r r!r"arBrrrrf:s   cseZdZdZddZddZddZdd Zd d Zfd d Z ddZ e ddZ e ddZ ddZS)rGzRaw I/O implementation for stream sockets. This class supports the makefile() method on sockets. It provides the raw I/O interface on top of a socket object. cCs|d krtd|ntjj|||_d|krQ|d7}n||_d|k|_d|k|_d |_dS) Nr=rArwrbwbrwbzinvalid mode: %rrBF)r=rArizrbzwbrl) rrH RawIOBaser_sock_mode_reading_writing_timeout_occurred)rr9rNrrrr`s     zSocketIO.__init__cCs|j|j|jr,tdnxy|jj|SWq/tk rcd|_Yq/tk rww/Yq/tk r}z|j dt krdSWYdd}~Xq/Xq/WdS)a3Read up to len(b) bytes into the writable buffer *b* and return the number of bytes read. If the socket is non-blocking and no bytes are available, None is returned. If *b* is non-empty, a 0 return value indicates that the connection was shutdown at the other end. z!cannot read from timed out objectTrN) _checkClosed_checkReadablerrOSErrorrnZ recv_intotimeoutInterruptedErrorr/r&_blocking_errnos)rrBerrrreadintols       zSocketIO.readintocCsn|j|jy|jj|SWn?tk ri}z|jdtkrTdSWYdd}~XnXdS)aWrite the given bytes or bytearray object *b* to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned. rN)rs_checkWritablernsendr/r&rx)rrBryrrrwrites  zSocketIO.writecCs|jrtdn|jS)z2True if the SocketIO is open for reading. zI/O operation on closed socket.)r0rrp)rrrrreadables zSocketIO.readablecCs|jrtdn|jS)z2True if the SocketIO is open for writing. zI/O operation on closed socket.)r0rrq)rrrrwritables zSocketIO.writablecs%|jrtdntjS)z2True if the SocketIO is open for seeking. zI/O operation on closed socket.)r0rrVseekable)r)r+rrrs zSocketIO.seekablecCs|j|jjS)z=Return the file descriptor of the underlying socket. )rsrnr#)rrrrr#s zSocketIO.filenocCs|js|jSdSdS)NrCrD)r0r#)rrrrrcs  z SocketIO.namecCs|jS)N)ro)rrrrrNsz SocketIO.modecCs7|jr dStjj||jjd|_dS)zClose the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. N)r0rHrmr%rnrT)rrrrr%s   zSocketIO.close)r-r,r]r^rrzr}r~rrr#rbrcrNr%rr)r+rrGOs      rGr(c Cs|j}| s|dkr+t}nyt|\}}}Wntk rXYn8X|jd|x$|D]}d|krpPqpqpW|}|S)aGet fully qualified domain name from name. An empty argument is interpreted as meaning the local host. First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned. z0.0.0.0r.)stripZ gethostnameZ gethostbyaddrr/insert)rcZhostnamealiasesZipaddrsrrrr s     cCs|\}}d}xt||dtD]}|\}}} } } d} yYt||| } |tk rz| j|n|r| j|n| j| | SWq(tk r} z$| }| dk r| jnWYdd} ~ Xq(Xq(W|dk r|n tddS)adConnect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. Nrz!getaddrinfo returns an empty list) getaddrinforar_GLOBAL_DEFAULT_TIMEOUTr6ZbindZconnectr/r%)ZaddressrvZsource_addresshostporterrresafsocktyper" canonnamesar9_rrrr s(    $  c Csvg}xitj||||||D]I}|\}} }} } |jt|tt| t|| | fq%W|S)aResolve host and port into list of address info entries. Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. host is a domain name, a string representation of an IPv4/v6 address or None. port is a string service name such as 'http', a numeric port number or None. By passing None as the value of host and port, you can pass NULL to the underlying C API. The family, type and proto arguments can be optionally specified in order to narrow the list of addresses returned. Passing zero as a value for each of these arguments selects the full range of results. )rrappendrr r ) rrr r!r"flagsZaddrlistrrrrrrrrrs% r)'r^rrYsysrHZenumrerrno ImportErrorr*rrr__all__extend_get_exports_listZ_convertr-rrZ _realsocketplatformlowerrrrr hasattrrerarfrxrmrGr objectrr rrrrr/sp  $                         w %