PageRenderTime 62ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/rlib/rsocket.py

https://bitbucket.org/nbtaylor/pypy
Python | 1434 lines | 1409 code | 13 blank | 12 comment | 9 complexity | 5761a91535b5d802c36b3db8fd265e56 MD5 | raw file
  1. from __future__ import with_statement
  2. """
  3. An RPython implementation of sockets based on rffi.
  4. Note that the interface has to be slightly different - this is not
  5. a drop-in replacement for the 'socket' module.
  6. """
  7. # Known missing features:
  8. #
  9. # - address families other than AF_INET, AF_INET6, AF_UNIX, AF_PACKET
  10. # - AF_PACKET is only supported on Linux
  11. # - methods makefile(),
  12. # - SSL
  13. #
  14. # It's unclear if makefile() and SSL support belong here or only as
  15. # app-level code for PyPy.
  16. from pypy.rlib.objectmodel import instantiate, keepalive_until_here
  17. from pypy.rlib import _rsocket_rffi as _c
  18. from pypy.rlib.rarithmetic import intmask, r_uint
  19. from pypy.rpython.lltypesystem import lltype, rffi
  20. from pypy.rpython.lltypesystem.rffi import sizeof, offsetof
  21. INVALID_SOCKET = _c.INVALID_SOCKET
  22. def mallocbuf(buffersize):
  23. return lltype.malloc(rffi.CCHARP.TO, buffersize, flavor='raw')
  24. constants = _c.constants
  25. locals().update(constants) # Define constants from _c
  26. if _c.WIN32:
  27. from pypy.rlib import rwin32
  28. def rsocket_startup():
  29. wsadata = lltype.malloc(_c.WSAData, flavor='raw', zero=True)
  30. res = _c.WSAStartup(1, wsadata)
  31. lltype.free(wsadata, flavor='raw')
  32. assert res == 0
  33. else:
  34. def rsocket_startup():
  35. pass
  36. def ntohs(x):
  37. return rffi.cast(lltype.Signed, _c.ntohs(x))
  38. def ntohl(x):
  39. # accepts and returns an Unsigned
  40. return rffi.cast(lltype.Unsigned, _c.ntohl(x))
  41. def htons(x):
  42. return rffi.cast(lltype.Signed, _c.htons(x))
  43. def htonl(x):
  44. # accepts and returns an Unsigned
  45. return rffi.cast(lltype.Unsigned, _c.htonl(x))
  46. _FAMILIES = {}
  47. class Address(object):
  48. """The base class for RPython-level objects representing addresses.
  49. Fields: addr - a _c.sockaddr_ptr (memory owned by the Address instance)
  50. addrlen - size used within 'addr'
  51. """
  52. class __metaclass__(type):
  53. def __new__(cls, name, bases, dict):
  54. family = dict.get('family')
  55. A = type.__new__(cls, name, bases, dict)
  56. if family is not None:
  57. _FAMILIES[family] = A
  58. return A
  59. # default uninitialized value: NULL ptr
  60. addr_p = lltype.nullptr(_c.sockaddr_ptr.TO)
  61. def __init__(self, addr, addrlen):
  62. self.addr_p = addr
  63. self.addrlen = addrlen
  64. def __del__(self):
  65. if self.addr_p:
  66. lltype.free(self.addr_p, flavor='raw')
  67. def setdata(self, addr, addrlen):
  68. # initialize self.addr and self.addrlen. 'addr' can be a different
  69. # pointer type than exactly sockaddr_ptr, and we cast it for you.
  70. assert not self.addr_p
  71. self.addr_p = rffi.cast(_c.sockaddr_ptr, addr)
  72. self.addrlen = addrlen
  73. setdata._annspecialcase_ = 'specialize:ll'
  74. # the following slightly strange interface is needed to manipulate
  75. # what self.addr_p points to in a safe way. The problem is that
  76. # after inlining we might end up with operations that looks like:
  77. # addr = self.addr_p
  78. # <self is freed here, and its __del__ calls lltype.free()>
  79. # read from addr
  80. # To prevent this we have to insert a keepalive after the last
  81. # use of 'addr'. The interface to do that is called lock()/unlock()
  82. # because it strongly reminds callers not to forget unlock().
  83. #
  84. def lock(self, TYPE=_c.sockaddr):
  85. """Return self.addr_p, cast as a pointer to TYPE. Must call unlock()!
  86. """
  87. return rffi.cast(lltype.Ptr(TYPE), self.addr_p)
  88. lock._annspecialcase_ = 'specialize:ll'
  89. def unlock(self):
  90. """To call after we're done with the pointer returned by lock().
  91. Note that locking and unlocking costs nothing at run-time.
  92. """
  93. keepalive_until_here(self)
  94. def as_object(self, fd, space):
  95. """Convert the address to an app-level object."""
  96. # If we don't know the address family, don't raise an
  97. # exception -- return it as a tuple.
  98. addr = self.lock()
  99. family = rffi.cast(lltype.Signed, addr.c_sa_family)
  100. datalen = self.addrlen - offsetof(_c.sockaddr, 'c_sa_data')
  101. rawdata = ''.join([addr.c_sa_data[i] for i in range(datalen)])
  102. self.unlock()
  103. return space.newtuple([space.wrap(family),
  104. space.wrap(rawdata)])
  105. def from_object(space, w_address):
  106. """Convert an app-level object to an Address."""
  107. # It's a static method but it's overridden and must be called
  108. # on the correct subclass.
  109. raise RSocketError("unknown address family")
  110. from_object = staticmethod(from_object)
  111. @staticmethod
  112. def make_ushort_port(space, port):
  113. from pypy.interpreter.error import OperationError
  114. if port < 0 or port > 0xffff:
  115. raise OperationError(space.w_ValueError, space.wrap(
  116. "port must be 0-65535."))
  117. return rffi.cast(rffi.USHORT, port)
  118. def fill_from_object(self, space, w_address):
  119. """ Purely abstract
  120. """
  121. raise NotImplementedError
  122. # ____________________________________________________________
  123. def makeipaddr(name, result=None):
  124. # Convert a string specifying a host name or one of a few symbolic
  125. # names to an IPAddress instance. This usually calls getaddrinfo()
  126. # to do the work; the names "" and "<broadcast>" are special.
  127. # If 'result' is specified it must be a prebuilt INETAddress or
  128. # INET6Address that is filled; otherwise a new INETXAddress is returned.
  129. if result is None:
  130. family = AF_UNSPEC
  131. else:
  132. family = result.family
  133. if len(name) == 0:
  134. info = getaddrinfo(None, "0",
  135. family=family,
  136. socktype=SOCK_DGRAM, # dummy
  137. flags=AI_PASSIVE,
  138. address_to_fill=result)
  139. if len(info) > 1:
  140. raise RSocketError("wildcard resolved to multiple addresses")
  141. return info[0][4]
  142. # IPv4 also supports the special name "<broadcast>".
  143. if name == '<broadcast>':
  144. return makeipv4addr(r_uint(INADDR_BROADCAST), result)
  145. # "dd.dd.dd.dd" format.
  146. digits = name.split('.')
  147. if len(digits) == 4:
  148. try:
  149. d0 = int(digits[0])
  150. d1 = int(digits[1])
  151. d2 = int(digits[2])
  152. d3 = int(digits[3])
  153. except ValueError:
  154. pass
  155. else:
  156. if (0 <= d0 <= 255 and
  157. 0 <= d1 <= 255 and
  158. 0 <= d2 <= 255 and
  159. 0 <= d3 <= 255):
  160. addr = intmask(d0 << 24) | (d1 << 16) | (d2 << 8) | (d3 << 0)
  161. addr = rffi.cast(rffi.UINT, addr)
  162. addr = htonl(addr)
  163. return makeipv4addr(addr, result)
  164. # generic host name to IP conversion
  165. info = getaddrinfo(name, None, family=family, address_to_fill=result)
  166. return info[0][4]
  167. class IPAddress(Address):
  168. """AF_INET and AF_INET6 addresses"""
  169. def get_host(self):
  170. # Create a string object representing an IP address.
  171. # For IPv4 this is always a string of the form 'dd.dd.dd.dd'
  172. # (with variable size numbers).
  173. host, serv = getnameinfo(self, NI_NUMERICHOST | NI_NUMERICSERV)
  174. return host
  175. def lock_in_addr(self):
  176. """ Purely abstract
  177. """
  178. raise NotImplementedError
  179. # ____________________________________________________________
  180. if 'AF_PACKET' in constants:
  181. class PacketAddress(Address):
  182. family = AF_PACKET
  183. struct = _c.sockaddr_ll
  184. maxlen = minlen = sizeof(struct)
  185. def get_ifname(self, fd):
  186. a = self.lock(_c.sockaddr_ll)
  187. p = lltype.malloc(_c.ifreq, flavor='raw')
  188. rffi.setintfield(p, 'c_ifr_ifindex',
  189. rffi.getintfield(a, 'c_sll_ifindex'))
  190. if (_c.ioctl(fd, _c.SIOCGIFNAME, p) == 0):
  191. # eh, the iface name is a constant length array
  192. i = 0
  193. d = []
  194. while p.c_ifr_name[i] != '\x00' and i < len(p.c_ifr_name):
  195. d.append(p.c_ifr_name[i])
  196. i += 1
  197. ifname = ''.join(d)
  198. else:
  199. ifname = ""
  200. lltype.free(p, flavor='raw')
  201. self.unlock()
  202. return ifname
  203. def get_protocol(self):
  204. a = self.lock(_c.sockaddr_ll)
  205. proto = rffi.getintfield(a, 'c_sll_protocol')
  206. proto = rffi.cast(rffi.USHORT, proto)
  207. res = ntohs(proto)
  208. self.unlock()
  209. return res
  210. def get_pkttype(self):
  211. a = self.lock(_c.sockaddr_ll)
  212. res = rffi.getintfield(a, 'c_sll_pkttype')
  213. self.unlock()
  214. return res
  215. def get_hatype(self):
  216. a = self.lock(_c.sockaddr_ll)
  217. res = bool(rffi.getintfield(a, 'c_sll_hatype'))
  218. self.unlock()
  219. return res
  220. def get_addr(self):
  221. a = self.lock(_c.sockaddr_ll)
  222. lgt = rffi.getintfield(a, 'c_sll_halen')
  223. d = []
  224. for i in range(lgt):
  225. d.append(a.c_sll_addr[i])
  226. res = "".join(d)
  227. self.unlock()
  228. return res
  229. def as_object(self, fd, space):
  230. return space.newtuple([space.wrap(self.get_ifname(fd)),
  231. space.wrap(self.get_protocol()),
  232. space.wrap(self.get_pkttype()),
  233. space.wrap(self.get_hatype()),
  234. space.wrap(self.get_addr())])
  235. class INETAddress(IPAddress):
  236. family = AF_INET
  237. struct = _c.sockaddr_in
  238. maxlen = minlen = sizeof(struct)
  239. def __init__(self, host, port):
  240. makeipaddr(host, self)
  241. a = self.lock(_c.sockaddr_in)
  242. port = rffi.cast(rffi.USHORT, port)
  243. rffi.setintfield(a, 'c_sin_port', htons(port))
  244. self.unlock()
  245. def __repr__(self):
  246. try:
  247. return '<INETAddress %s:%d>' % (self.get_host(), self.get_port())
  248. except SocketError:
  249. return '<INETAddress ?>'
  250. def get_port(self):
  251. a = self.lock(_c.sockaddr_in)
  252. port = ntohs(a.c_sin_port)
  253. self.unlock()
  254. return port
  255. def eq(self, other): # __eq__() is not called by RPython :-/
  256. return (isinstance(other, INETAddress) and
  257. self.get_host() == other.get_host() and
  258. self.get_port() == other.get_port())
  259. def as_object(self, fd, space):
  260. return space.newtuple([space.wrap(self.get_host()),
  261. space.wrap(self.get_port())])
  262. def from_object(space, w_address):
  263. # Parse an app-level object representing an AF_INET address
  264. w_host, w_port = space.unpackiterable(w_address, 2)
  265. host = space.str_w(w_host)
  266. port = space.int_w(w_port)
  267. port = Address.make_ushort_port(space, port)
  268. return INETAddress(host, port)
  269. from_object = staticmethod(from_object)
  270. def fill_from_object(self, space, w_address):
  271. # XXX a bit of code duplication
  272. from pypy.interpreter.error import OperationError
  273. _, w_port = space.unpackiterable(w_address, 2)
  274. port = space.int_w(w_port)
  275. port = self.make_ushort_port(space, port)
  276. a = self.lock(_c.sockaddr_in)
  277. rffi.setintfield(a, 'c_sin_port', htons(port))
  278. self.unlock()
  279. def from_in_addr(in_addr):
  280. result = instantiate(INETAddress)
  281. # store the malloc'ed data into 'result' as soon as possible
  282. # to avoid leaks if an exception occurs inbetween
  283. sin = lltype.malloc(_c.sockaddr_in, flavor='raw', zero=True)
  284. result.setdata(sin, sizeof(_c.sockaddr_in))
  285. # PLAT sin_len
  286. rffi.setintfield(sin, 'c_sin_family', AF_INET)
  287. rffi.structcopy(sin.c_sin_addr, in_addr)
  288. return result
  289. from_in_addr = staticmethod(from_in_addr)
  290. def lock_in_addr(self):
  291. a = self.lock(_c.sockaddr_in)
  292. p = rffi.cast(rffi.VOIDP, a.c_sin_addr)
  293. return p, sizeof(_c.in_addr)
  294. # ____________________________________________________________
  295. class INET6Address(IPAddress):
  296. family = AF_INET6
  297. struct = _c.sockaddr_in6
  298. maxlen = minlen = sizeof(struct)
  299. def __init__(self, host, port, flowinfo=0, scope_id=0):
  300. makeipaddr(host, self)
  301. a = self.lock(_c.sockaddr_in6)
  302. rffi.setintfield(a, 'c_sin6_port', htons(port))
  303. rffi.setintfield(a, 'c_sin6_flowinfo', htonl(flowinfo))
  304. rffi.setintfield(a, 'c_sin6_scope_id', scope_id)
  305. self.unlock()
  306. def __repr__(self):
  307. try:
  308. return '<INET6Address %s:%d %d %d>' % (self.get_host(),
  309. self.get_port(),
  310. self.get_flowinfo(),
  311. self.get_scope_id())
  312. except SocketError:
  313. return '<INET6Address ?>'
  314. def get_port(self):
  315. a = self.lock(_c.sockaddr_in6)
  316. port = ntohs(a.c_sin6_port)
  317. self.unlock()
  318. return port
  319. def get_flowinfo(self):
  320. a = self.lock(_c.sockaddr_in6)
  321. flowinfo = ntohl(a.c_sin6_flowinfo)
  322. self.unlock()
  323. return rffi.cast(lltype.Unsigned, flowinfo)
  324. def get_scope_id(self):
  325. a = self.lock(_c.sockaddr_in6)
  326. scope_id = a.c_sin6_scope_id
  327. self.unlock()
  328. return rffi.cast(lltype.Unsigned, scope_id)
  329. def eq(self, other): # __eq__() is not called by RPython :-/
  330. return (isinstance(other, INET6Address) and
  331. self.get_host() == other.get_host() and
  332. self.get_port() == other.get_port() and
  333. self.get_flowinfo() == other.get_flowinfo() and
  334. self.get_scope_id() == other.get_scope_id())
  335. def as_object(self, fd, space):
  336. return space.newtuple([space.wrap(self.get_host()),
  337. space.wrap(self.get_port()),
  338. space.wrap(self.get_flowinfo()),
  339. space.wrap(self.get_scope_id())])
  340. def from_object(space, w_address):
  341. from pypy.interpreter.error import OperationError
  342. pieces_w = space.unpackiterable(w_address)
  343. if not (2 <= len(pieces_w) <= 4):
  344. raise TypeError("AF_INET6 address must be a tuple of length 2 "
  345. "to 4, not %d" % len(pieces_w))
  346. host = space.str_w(pieces_w[0])
  347. port = space.int_w(pieces_w[1])
  348. port = Address.make_ushort_port(space, port)
  349. if len(pieces_w) > 2: flowinfo = space.int_w(pieces_w[2])
  350. else: flowinfo = 0
  351. if len(pieces_w) > 3: scope_id = space.uint_w(pieces_w[3])
  352. else: scope_id = 0
  353. if flowinfo < 0 or flowinfo > 0xfffff:
  354. raise OperationError(space.w_OverflowError, space.wrap(
  355. "flowinfo must be 0-1048575."))
  356. flowinfo = rffi.cast(lltype.Unsigned, flowinfo)
  357. return INET6Address(host, port, flowinfo, scope_id)
  358. from_object = staticmethod(from_object)
  359. def fill_from_object(self, space, w_address):
  360. # XXX a bit of code duplication
  361. from pypy.interpreter.error import OperationError
  362. pieces_w = space.unpackiterable(w_address)
  363. if not (2 <= len(pieces_w) <= 4):
  364. raise RSocketError("AF_INET6 address must be a tuple of length 2 "
  365. "to 4, not %d" % len(pieces_w))
  366. port = space.int_w(pieces_w[1])
  367. port = self.make_ushort_port(space, port)
  368. if len(pieces_w) > 2: flowinfo = space.int_w(pieces_w[2])
  369. else: flowinfo = 0
  370. if len(pieces_w) > 3: scope_id = space.uint_w(pieces_w[3])
  371. else: scope_id = 0
  372. if flowinfo < 0 or flowinfo > 0xfffff:
  373. raise OperationError(space.w_OverflowError, space.wrap(
  374. "flowinfo must be 0-1048575."))
  375. flowinfo = rffi.cast(lltype.Unsigned, flowinfo)
  376. a = self.lock(_c.sockaddr_in6)
  377. rffi.setintfield(a, 'c_sin6_port', htons(port))
  378. rffi.setintfield(a, 'c_sin6_flowinfo', htonl(flowinfo))
  379. rffi.setintfield(a, 'c_sin6_scope_id', scope_id)
  380. self.unlock()
  381. def from_in6_addr(in6_addr):
  382. result = instantiate(INET6Address)
  383. # store the malloc'ed data into 'result' as soon as possible
  384. # to avoid leaks if an exception occurs inbetween
  385. sin = lltype.malloc(_c.sockaddr_in6, flavor='raw', zero=True)
  386. result.setdata(sin, sizeof(_c.sockaddr_in6))
  387. rffi.setintfield(sin, 'c_sin6_family', AF_INET)
  388. rffi.structcopy(sin.c_sin6_addr, in6_addr)
  389. return result
  390. from_in6_addr = staticmethod(from_in6_addr)
  391. def lock_in_addr(self):
  392. a = self.lock(_c.sockaddr_in6)
  393. p = rffi.cast(rffi.VOIDP, a.c_sin6_addr)
  394. return p, sizeof(_c.in6_addr)
  395. # ____________________________________________________________
  396. if 'AF_UNIX' in constants:
  397. class UNIXAddress(Address):
  398. family = AF_UNIX
  399. struct = _c.sockaddr_un
  400. minlen = offsetof(_c.sockaddr_un, 'c_sun_path')
  401. maxlen = sizeof(struct)
  402. def __init__(self, path):
  403. sun = lltype.malloc(_c.sockaddr_un, flavor='raw', zero=True)
  404. baseofs = offsetof(_c.sockaddr_un, 'c_sun_path')
  405. self.setdata(sun, baseofs + len(path))
  406. rffi.setintfield(sun, 'c_sun_family', AF_UNIX)
  407. if _c.linux and path.startswith('\x00'):
  408. # Linux abstract namespace extension
  409. if len(path) > sizeof(_c.sockaddr_un.c_sun_path):
  410. raise RSocketError("AF_UNIX path too long")
  411. else:
  412. # regular NULL-terminated string
  413. if len(path) >= sizeof(_c.sockaddr_un.c_sun_path):
  414. raise RSocketError("AF_UNIX path too long")
  415. sun.c_sun_path[len(path)] = '\x00'
  416. for i in range(len(path)):
  417. sun.c_sun_path[i] = path[i]
  418. def __repr__(self):
  419. try:
  420. return '<UNIXAddress %r>' % (self.get_path(),)
  421. except SocketError:
  422. return '<UNIXAddress ?>'
  423. def get_path(self):
  424. a = self.lock(_c.sockaddr_un)
  425. maxlength = self.addrlen - offsetof(_c.sockaddr_un, 'c_sun_path')
  426. if _c.linux and maxlength > 0 and a.c_sun_path[0] == '\x00':
  427. # Linux abstract namespace
  428. length = maxlength
  429. else:
  430. # regular NULL-terminated string
  431. length = 0
  432. while length < maxlength and a.c_sun_path[length] != '\x00':
  433. length += 1
  434. result = ''.join([a.c_sun_path[i] for i in range(length)])
  435. self.unlock()
  436. return result
  437. def eq(self, other): # __eq__() is not called by RPython :-/
  438. return (isinstance(other, UNIXAddress) and
  439. self.get_path() == other.get_path())
  440. def as_object(self, fd, space):
  441. return space.wrap(self.get_path())
  442. def from_object(space, w_address):
  443. return UNIXAddress(space.str_w(w_address))
  444. from_object = staticmethod(from_object)
  445. if 'AF_NETLINK' in constants:
  446. class NETLINKAddress(Address):
  447. family = AF_NETLINK
  448. struct = _c.sockaddr_nl
  449. maxlen = minlen = sizeof(struct)
  450. def __init__(self, pid, groups):
  451. addr = lltype.malloc(_c.sockaddr_nl, flavor='raw', zero=True)
  452. self.setdata(addr, NETLINKAddress.maxlen)
  453. rffi.setintfield(addr, 'c_nl_family', AF_NETLINK)
  454. rffi.setintfield(addr, 'c_nl_pid', pid)
  455. rffi.setintfield(addr, 'c_nl_groups', groups)
  456. def get_pid(self):
  457. a = self.lock(_c.sockaddr_nl)
  458. pid = a.c_nl_pid
  459. self.unlock()
  460. return rffi.cast(lltype.Unsigned, pid)
  461. def get_groups(self):
  462. a = self.lock(_c.sockaddr_nl)
  463. groups = a.c_nl_groups
  464. self.unlock()
  465. return rffi.cast(lltype.Unsigned, groups)
  466. def __repr__(self):
  467. return '<NETLINKAddress %r>' % (self.get_pid(), self.get_groups())
  468. def as_object(self, fd, space):
  469. return space.newtuple([space.wrap(self.get_pid()),
  470. space.wrap(self.get_groups())])
  471. def from_object(space, w_address):
  472. w_pid, w_groups = space.unpackiterable(w_address, 2)
  473. return NETLINKAddress(space.uint_w(w_pid), space.uint_w(w_groups))
  474. from_object = staticmethod(from_object)
  475. # ____________________________________________________________
  476. def familyclass(family):
  477. return _FAMILIES.get(family, Address)
  478. af_get = familyclass
  479. def make_address(addrptr, addrlen, result=None):
  480. family = rffi.cast(lltype.Signed, addrptr.c_sa_family)
  481. if result is None:
  482. result = instantiate(familyclass(family))
  483. elif result.family != family:
  484. raise RSocketError("address family mismatched")
  485. # copy into a new buffer the address that 'addrptr' points to
  486. addrlen = rffi.cast(lltype.Signed, addrlen)
  487. buf = lltype.malloc(rffi.CCHARP.TO, addrlen, flavor='raw')
  488. src = rffi.cast(rffi.CCHARP, addrptr)
  489. for i in range(addrlen):
  490. buf[i] = src[i]
  491. result.setdata(buf, addrlen)
  492. return result
  493. def makeipv4addr(s_addr, result=None):
  494. if result is None:
  495. result = instantiate(INETAddress)
  496. elif result.family != AF_INET:
  497. raise RSocketError("address family mismatched")
  498. sin = lltype.malloc(_c.sockaddr_in, flavor='raw', zero=True)
  499. result.setdata(sin, sizeof(_c.sockaddr_in))
  500. rffi.setintfield(sin, 'c_sin_family', AF_INET) # PLAT sin_len
  501. rffi.setintfield(sin.c_sin_addr, 'c_s_addr', s_addr)
  502. return result
  503. def make_null_address(family):
  504. klass = familyclass(family)
  505. result = instantiate(klass)
  506. buf = lltype.malloc(rffi.CCHARP.TO, klass.maxlen, flavor='raw', zero=True)
  507. # Initialize the family to the correct value. Avoids surprizes on
  508. # Windows when calling a function that unexpectedly does not set
  509. # the output address (e.g. recvfrom() on a connected IPv4 socket).
  510. rffi.setintfield(rffi.cast(_c.sockaddr_ptr, buf), 'c_sa_family', family)
  511. result.setdata(buf, 0)
  512. return result, klass.maxlen
  513. def ipaddr_from_object(space, w_sockaddr):
  514. host = space.str_w(space.getitem(w_sockaddr, space.wrap(0)))
  515. addr = makeipaddr(host)
  516. addr.fill_from_object(space, w_sockaddr)
  517. return addr
  518. # ____________________________________________________________
  519. class RSocket(object):
  520. """RPython-level socket object.
  521. """
  522. _mixin_ = True # for interp_socket.py
  523. fd = _c.INVALID_SOCKET
  524. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0,
  525. fd=_c.INVALID_SOCKET):
  526. """Create a new socket."""
  527. if _c.invalid_socket(fd):
  528. fd = _c.socket(family, type, proto)
  529. if _c.invalid_socket(fd):
  530. raise self.error_handler()
  531. # PLAT RISCOS
  532. self.fd = fd
  533. self.family = family
  534. self.type = type
  535. self.proto = proto
  536. self.timeout = defaults.timeout
  537. def __del__(self):
  538. fd = self.fd
  539. if fd != _c.INVALID_SOCKET:
  540. self.fd = _c.INVALID_SOCKET
  541. _c.socketclose(fd)
  542. if hasattr(_c, 'fcntl'):
  543. def _setblocking(self, block):
  544. delay_flag = intmask(_c.fcntl(self.fd, _c.F_GETFL, 0))
  545. if block:
  546. delay_flag &= ~_c.O_NONBLOCK
  547. else:
  548. delay_flag |= _c.O_NONBLOCK
  549. _c.fcntl(self.fd, _c.F_SETFL, delay_flag)
  550. elif hasattr(_c, 'ioctlsocket'):
  551. def _setblocking(self, block):
  552. flag = lltype.malloc(rffi.ULONGP.TO, 1, flavor='raw')
  553. flag[0] = rffi.cast(rffi.ULONG, not block)
  554. _c.ioctlsocket(self.fd, _c.FIONBIO, flag)
  555. lltype.free(flag, flavor='raw')
  556. if hasattr(_c, 'poll') and not _c.poll_may_be_broken:
  557. def _select(self, for_writing):
  558. """Returns 0 when reading/writing is possible,
  559. 1 when timing out and -1 on error."""
  560. if self.timeout <= 0.0 or self.fd == _c.INVALID_SOCKET:
  561. # blocking I/O or no socket.
  562. return 0
  563. pollfd = rffi.make(_c.pollfd)
  564. try:
  565. rffi.setintfield(pollfd, 'c_fd', self.fd)
  566. if for_writing:
  567. rffi.setintfield(pollfd, 'c_events', _c.POLLOUT)
  568. else:
  569. rffi.setintfield(pollfd, 'c_events', _c.POLLIN)
  570. timeout = int(self.timeout * 1000.0 + 0.5)
  571. n = _c.poll(rffi.cast(lltype.Ptr(_c.pollfdarray), pollfd),
  572. 1, timeout)
  573. finally:
  574. lltype.free(pollfd, flavor='raw')
  575. if n < 0:
  576. return -1
  577. if n == 0:
  578. return 1
  579. return 0
  580. else:
  581. # Version witout poll(): use select()
  582. def _select(self, for_writing):
  583. """Returns 0 when reading/writing is possible,
  584. 1 when timing out and -1 on error."""
  585. timeout = self.timeout
  586. if timeout <= 0.0 or self.fd == _c.INVALID_SOCKET:
  587. # blocking I/O or no socket.
  588. return 0
  589. tv = rffi.make(_c.timeval)
  590. rffi.setintfield(tv, 'c_tv_sec', int(timeout))
  591. rffi.setintfield(tv, 'c_tv_usec', int((timeout-int(timeout))
  592. * 1000000))
  593. fds = lltype.malloc(_c.fd_set.TO, flavor='raw')
  594. _c.FD_ZERO(fds)
  595. _c.FD_SET(self.fd, fds)
  596. null = lltype.nullptr(_c.fd_set.TO)
  597. if for_writing:
  598. n = _c.select(self.fd + 1, null, fds, null, tv)
  599. else:
  600. n = _c.select(self.fd + 1, fds, null, null, tv)
  601. lltype.free(fds, flavor='raw')
  602. lltype.free(tv, flavor='raw')
  603. if n < 0:
  604. return -1
  605. if n == 0:
  606. return 1
  607. return 0
  608. def error_handler(self):
  609. return last_error()
  610. # convert an Address into an app-level object
  611. def addr_as_object(self, space, address):
  612. return address.as_object(self.fd, space)
  613. # convert an app-level object into an Address
  614. # based on the current socket's family
  615. def addr_from_object(self, space, w_address):
  616. return af_get(self.family).from_object(space, w_address)
  617. # build a null address object, ready to be used as output argument to
  618. # C functions that return an address. It must be unlock()ed after you
  619. # are done using addr_p.
  620. def _addrbuf(self):
  621. addr, maxlen = make_null_address(self.family)
  622. addrlen_p = lltype.malloc(_c.socklen_t_ptr.TO, flavor='raw')
  623. addrlen_p[0] = rffi.cast(_c.socklen_t, maxlen)
  624. return addr, addr.addr_p, addrlen_p
  625. def accept(self):
  626. """Wait for an incoming connection.
  627. Return (new socket fd, client address)."""
  628. if self._select(False) == 1:
  629. raise SocketTimeout
  630. address, addr_p, addrlen_p = self._addrbuf()
  631. try:
  632. newfd = _c.socketaccept(self.fd, addr_p, addrlen_p)
  633. addrlen = addrlen_p[0]
  634. finally:
  635. lltype.free(addrlen_p, flavor='raw')
  636. address.unlock()
  637. if _c.invalid_socket(newfd):
  638. raise self.error_handler()
  639. address.addrlen = rffi.cast(lltype.Signed, addrlen)
  640. return (newfd, address)
  641. def bind(self, address):
  642. """Bind the socket to a local address."""
  643. addr = address.lock()
  644. res = _c.socketbind(self.fd, addr, address.addrlen)
  645. address.unlock()
  646. if res < 0:
  647. raise self.error_handler()
  648. def close(self):
  649. """Close the socket. It cannot be used after this call."""
  650. fd = self.fd
  651. if fd != _c.INVALID_SOCKET:
  652. self.fd = _c.INVALID_SOCKET
  653. res = _c.socketclose(fd)
  654. if res != 0:
  655. raise self.error_handler()
  656. def detach(self):
  657. fd = self.fd
  658. self.fd = _c.INVALID_SOCKET
  659. return fd
  660. if _c.WIN32:
  661. def _connect(self, address):
  662. """Connect the socket to a remote address."""
  663. addr = address.lock()
  664. res = _c.socketconnect(self.fd, addr, address.addrlen)
  665. address.unlock()
  666. errno = _c.geterrno()
  667. timeout = self.timeout
  668. if timeout > 0.0 and res < 0 and errno == _c.EWOULDBLOCK:
  669. tv = rffi.make(_c.timeval)
  670. rffi.setintfield(tv, 'c_tv_sec', int(timeout))
  671. rffi.setintfield(tv, 'c_tv_usec',
  672. int((timeout-int(timeout)) * 1000000))
  673. fds = lltype.malloc(_c.fd_set.TO, flavor='raw')
  674. _c.FD_ZERO(fds)
  675. _c.FD_SET(self.fd, fds)
  676. fds_exc = lltype.malloc(_c.fd_set.TO, flavor='raw')
  677. _c.FD_ZERO(fds_exc)
  678. _c.FD_SET(self.fd, fds_exc)
  679. null = lltype.nullptr(_c.fd_set.TO)
  680. try:
  681. n = _c.select(self.fd + 1, null, fds, fds_exc, tv)
  682. if n > 0:
  683. if _c.FD_ISSET(self.fd, fds):
  684. # socket writable == connected
  685. return (0, False)
  686. else:
  687. # per MS docs, call getsockopt() to get error
  688. assert _c.FD_ISSET(self.fd, fds_exc)
  689. return (self.getsockopt_int(_c.SOL_SOCKET,
  690. _c.SO_ERROR), False)
  691. elif n == 0:
  692. return (_c.EWOULDBLOCK, True)
  693. else:
  694. return (_c.geterrno(), False)
  695. finally:
  696. lltype.free(fds, flavor='raw')
  697. lltype.free(fds_exc, flavor='raw')
  698. lltype.free(tv, flavor='raw')
  699. if res == 0:
  700. errno = 0
  701. return (errno, False)
  702. else:
  703. def _connect(self, address):
  704. """Connect the socket to a remote address."""
  705. addr = address.lock()
  706. res = _c.socketconnect(self.fd, addr, address.addrlen)
  707. address.unlock()
  708. errno = _c.geterrno()
  709. if self.timeout > 0.0 and res < 0 and errno == _c.EINPROGRESS:
  710. timeout = self._select(True)
  711. if timeout == 0:
  712. res = self.getsockopt_int(_c.SOL_SOCKET, _c.SO_ERROR)
  713. if res == _c.EISCONN:
  714. res = 0
  715. errno = res
  716. elif timeout == -1:
  717. return (_c.geterrno(), False)
  718. else:
  719. return (_c.EWOULDBLOCK, True)
  720. if res < 0:
  721. res = errno
  722. return (res, False)
  723. def connect(self, address):
  724. """Connect the socket to a remote address."""
  725. err, timeout = self._connect(address)
  726. if timeout:
  727. raise SocketTimeout
  728. if err:
  729. raise CSocketError(err)
  730. def connect_ex(self, address):
  731. """This is like connect(address), but returns an error code (the errno
  732. value) instead of raising an exception when an error occurs."""
  733. err, timeout = self._connect(address)
  734. return err
  735. if hasattr(_c, 'dup'):
  736. def dup(self, SocketClass=None):
  737. if SocketClass is None:
  738. SocketClass = RSocket
  739. fd = _c.dup(self.fd)
  740. if fd < 0:
  741. raise self.error_handler()
  742. return make_socket(fd, self.family, self.type, self.proto,
  743. SocketClass=SocketClass)
  744. def getpeername(self):
  745. """Return the address of the remote endpoint."""
  746. address, addr_p, addrlen_p = self._addrbuf()
  747. try:
  748. res = _c.socketgetpeername(self.fd, addr_p, addrlen_p)
  749. addrlen = addrlen_p[0]
  750. finally:
  751. lltype.free(addrlen_p, flavor='raw')
  752. address.unlock()
  753. if res < 0:
  754. raise self.error_handler()
  755. address.addrlen = rffi.cast(lltype.Signed, addrlen)
  756. return address
  757. def getsockname(self):
  758. """Return the address of the local endpoint."""
  759. address, addr_p, addrlen_p = self._addrbuf()
  760. try:
  761. res = _c.socketgetsockname(self.fd, addr_p, addrlen_p)
  762. addrlen = addrlen_p[0]
  763. finally:
  764. lltype.free(addrlen_p, flavor='raw')
  765. address.unlock()
  766. if res < 0:
  767. raise self.error_handler()
  768. address.addrlen = rffi.cast(lltype.Signed, addrlen)
  769. return address
  770. def getsockopt(self, level, option, maxlen):
  771. buf = mallocbuf(maxlen)
  772. try:
  773. bufsize_p = lltype.malloc(_c.socklen_t_ptr.TO, flavor='raw')
  774. try:
  775. bufsize_p[0] = rffi.cast(_c.socklen_t, maxlen)
  776. res = _c.socketgetsockopt(self.fd, level, option,
  777. buf, bufsize_p)
  778. if res < 0:
  779. raise self.error_handler()
  780. size = rffi.cast(lltype.Signed, bufsize_p[0])
  781. assert size >= 0 # socklen_t is signed on Windows
  782. result = ''.join([buf[i] for i in range(size)])
  783. finally:
  784. lltype.free(bufsize_p, flavor='raw')
  785. finally:
  786. lltype.free(buf, flavor='raw')
  787. return result
  788. def getsockopt_int(self, level, option):
  789. flag_p = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
  790. try:
  791. flagsize_p = lltype.malloc(_c.socklen_t_ptr.TO, flavor='raw')
  792. try:
  793. flagsize_p[0] = rffi.cast(_c.socklen_t, rffi.sizeof(rffi.INT))
  794. res = _c.socketgetsockopt(self.fd, level, option,
  795. rffi.cast(rffi.VOIDP, flag_p),
  796. flagsize_p)
  797. if res < 0:
  798. raise self.error_handler()
  799. result = rffi.cast(lltype.Signed, flag_p[0])
  800. finally:
  801. lltype.free(flagsize_p, flavor='raw')
  802. finally:
  803. lltype.free(flag_p, flavor='raw')
  804. return result
  805. def gettimeout(self):
  806. """Return the timeout of the socket. A timeout < 0 means that
  807. timeouts are disabled in the socket."""
  808. return self.timeout
  809. def listen(self, backlog):
  810. """Enable a server to accept connections. The backlog argument
  811. must be at least 1; it specifies the number of unaccepted connections
  812. that the system will allow before refusing new connections."""
  813. if backlog < 1:
  814. backlog = 1
  815. res = _c.socketlisten(self.fd, backlog)
  816. if res < 0:
  817. raise self.error_handler()
  818. def recv(self, buffersize, flags=0):
  819. """Receive up to buffersize bytes from the socket. For the optional
  820. flags argument, see the Unix manual. When no data is available, block
  821. until at least one byte is available or until the remote end is closed.
  822. When the remote end is closed and all data is read, return the empty
  823. string."""
  824. timeout = self._select(False)
  825. if timeout == 1:
  826. raise SocketTimeout
  827. elif timeout == 0:
  828. raw_buf, gc_buf = rffi.alloc_buffer(buffersize)
  829. try:
  830. read_bytes = _c.socketrecv(self.fd, raw_buf, buffersize, flags)
  831. if read_bytes >= 0:
  832. return rffi.str_from_buffer(raw_buf, gc_buf, buffersize, read_bytes)
  833. finally:
  834. rffi.keep_buffer_alive_until_here(raw_buf, gc_buf)
  835. raise self.error_handler()
  836. def recvinto(self, rwbuffer, nbytes, flags=0):
  837. buf = self.recv(nbytes, flags)
  838. rwbuffer.setslice(0, buf)
  839. return len(buf)
  840. def recvfrom(self, buffersize, flags=0):
  841. """Like recv(buffersize, flags) but also return the sender's
  842. address."""
  843. read_bytes = -1
  844. timeout = self._select(False)
  845. if timeout == 1:
  846. raise SocketTimeout
  847. elif timeout == 0:
  848. raw_buf, gc_buf = rffi.alloc_buffer(buffersize)
  849. try:
  850. address, addr_p, addrlen_p = self._addrbuf()
  851. try:
  852. read_bytes = _c.recvfrom(self.fd, raw_buf, buffersize, flags,
  853. addr_p, addrlen_p)
  854. addrlen = rffi.cast(lltype.Signed, addrlen_p[0])
  855. finally:
  856. lltype.free(addrlen_p, flavor='raw')
  857. address.unlock()
  858. if read_bytes >= 0:
  859. if addrlen:
  860. address.addrlen = addrlen
  861. else:
  862. address = None
  863. data = rffi.str_from_buffer(raw_buf, gc_buf, buffersize, read_bytes)
  864. return (data, address)
  865. finally:
  866. rffi.keep_buffer_alive_until_here(raw_buf, gc_buf)
  867. raise self.error_handler()
  868. def recvfrom_into(self, rwbuffer, nbytes, flags=0):
  869. buf, addr = self.recvfrom(nbytes, flags)
  870. rwbuffer.setslice(0, buf)
  871. return len(buf), addr
  872. def send_raw(self, dataptr, length, flags=0):
  873. """Send data from a CCHARP buffer."""
  874. res = -1
  875. timeout = self._select(True)
  876. if timeout == 1:
  877. raise SocketTimeout
  878. elif timeout == 0:
  879. res = _c.send(self.fd, dataptr, length, flags)
  880. if res < 0:
  881. raise self.error_handler()
  882. return res
  883. def send(self, data, flags=0):
  884. """Send a data string to the socket. For the optional flags
  885. argument, see the Unix manual. Return the number of bytes
  886. sent; this may be less than len(data) if the network is busy."""
  887. dataptr = rffi.get_nonmovingbuffer(data)
  888. try:
  889. return self.send_raw(dataptr, len(data), flags)
  890. finally:
  891. rffi.free_nonmovingbuffer(data, dataptr)
  892. def sendall(self, data, flags=0, signal_checker=None):
  893. """Send a data string to the socket. For the optional flags
  894. argument, see the Unix manual. This calls send() repeatedly
  895. until all data is sent. If an error occurs, it's impossible
  896. to tell how much data has been sent."""
  897. dataptr = rffi.get_nonmovingbuffer(data)
  898. try:
  899. remaining = len(data)
  900. p = dataptr
  901. while remaining > 0:
  902. try:
  903. res = self.send_raw(p, remaining, flags)
  904. p = rffi.ptradd(p, res)
  905. remaining -= res
  906. except CSocketError, e:
  907. if e.errno != _c.EINTR:
  908. raise
  909. if signal_checker:
  910. signal_checker.check()
  911. finally:
  912. rffi.free_nonmovingbuffer(data, dataptr)
  913. def sendto(self, data, flags, address):
  914. """Like send(data, flags) but allows specifying the destination
  915. address. (Note that 'flags' is mandatory here.)"""
  916. res = -1
  917. timeout = self._select(True)
  918. if timeout == 1:
  919. raise SocketTimeout
  920. elif timeout == 0:
  921. addr = address.lock()
  922. res = _c.sendto(self.fd, data, len(data), flags,
  923. addr, address.addrlen)
  924. address.unlock()
  925. if res < 0:
  926. raise self.error_handler()
  927. return res
  928. def setblocking(self, block):
  929. if block:
  930. timeout = -1.0
  931. else:
  932. timeout = 0.0
  933. self.settimeout(timeout)
  934. def setsockopt(self, level, option, value):
  935. with rffi.scoped_str2charp(value) as buf:
  936. res = _c.socketsetsockopt(self.fd, level, option,
  937. rffi.cast(rffi.VOIDP, buf),
  938. len(value))
  939. if res < 0:
  940. raise self.error_handler()
  941. def setsockopt_int(self, level, option, value):
  942. with lltype.scoped_alloc(rffi.INTP.TO, 1) as flag_p:
  943. flag_p[0] = rffi.cast(rffi.INT, value)
  944. res = _c.socketsetsockopt(self.fd, level, option,
  945. rffi.cast(rffi.VOIDP, flag_p),
  946. rffi.sizeof(rffi.INT))
  947. if res < 0:
  948. raise self.error_handler()
  949. def settimeout(self, timeout):
  950. """Set the timeout of the socket. A timeout < 0 means that
  951. timeouts are dissabled in the socket."""
  952. if timeout < 0.0:
  953. self.timeout = -1.0
  954. else:
  955. self.timeout = timeout
  956. self._setblocking(self.timeout < 0.0)
  957. def shutdown(self, how):
  958. """Shut down the reading side of the socket (flag == SHUT_RD), the
  959. writing side of the socket (flag == SHUT_WR), or both ends
  960. (flag == SHUT_RDWR)."""
  961. res = _c.socketshutdown(self.fd, how)
  962. if res < 0:
  963. raise self.error_handler()
  964. # ____________________________________________________________
  965. def make_socket(fd, family, type, proto, SocketClass=RSocket):
  966. result = instantiate(SocketClass)
  967. result.fd = fd
  968. result.family = family
  969. result.type = type
  970. result.proto = proto
  971. result.timeout = defaults.timeout
  972. return result
  973. make_socket._annspecialcase_ = 'specialize:arg(4)'
  974. class SocketError(Exception):
  975. applevelerrcls = 'error'
  976. def __init__(self):
  977. pass
  978. def get_msg(self):
  979. return ''
  980. def __str__(self):
  981. return self.get_msg()
  982. class SocketErrorWithErrno(SocketError):
  983. def __init__(self, errno):
  984. self.errno = errno
  985. class RSocketError(SocketError):
  986. def __init__(self, message):
  987. self.message = message
  988. def get_msg(self):
  989. return self.message
  990. class CSocketError(SocketErrorWithErrno):
  991. def get_msg(self):
  992. return _c.socket_strerror_str(self.errno)
  993. if _c.WIN32:
  994. def last_error():
  995. return CSocketError(rwin32.GetLastError())
  996. else:
  997. def last_error():
  998. return CSocketError(_c.geterrno())
  999. class GAIError(SocketErrorWithErrno):
  1000. applevelerrcls = 'gaierror'
  1001. def get_msg(self):
  1002. return _c.gai_strerror_str(self.errno)
  1003. class HSocketError(SocketError):
  1004. applevelerrcls = 'herror'
  1005. def __init__(self, host):
  1006. self.host = host
  1007. # XXX h_errno is not easily available, and hstrerror() is
  1008. # marked as deprecated in the Linux man pages
  1009. def get_msg(self):
  1010. return "host lookup failed: '%s'" % (self.host,)
  1011. class SocketTimeout(SocketError):
  1012. applevelerrcls = 'timeout'
  1013. def get_msg(self):
  1014. return 'timed out'
  1015. class Defaults:
  1016. timeout = -1.0 # Blocking
  1017. defaults = Defaults()
  1018. # ____________________________________________________________
  1019. if 'AF_UNIX' not in constants or AF_UNIX is None:
  1020. socketpair_default_family = AF_INET
  1021. else:
  1022. socketpair_default_family = AF_UNIX
  1023. if hasattr(_c, 'socketpair'):
  1024. def socketpair(family=socketpair_default_family, type=SOCK_STREAM, proto=0,
  1025. SocketClass=RSocket):
  1026. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  1027. Create a pair of socket objects from the sockets returned by the platform
  1028. socketpair() function.
  1029. The arguments are the same as for socket() except the default family is
  1030. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  1031. """
  1032. result = lltype.malloc(_c.socketpair_t, 2, flavor='raw')
  1033. res = _c.socketpair(family, type, proto, result)
  1034. if res < 0:
  1035. raise last_error()
  1036. fd0 = rffi.cast(lltype.Signed, result[0])
  1037. fd1 = rffi.cast(lltype.Signed, result[1])
  1038. lltype.free(result, flavor='raw')
  1039. return (make_socket(fd0, family, type, proto, SocketClass),
  1040. make_socket(fd1, family, type, proto, SocketClass))
  1041. if hasattr(_c, 'dup'):
  1042. def fromfd(fd, family, type, proto=0, SocketClass=RSocket):
  1043. # Dup the fd so it and the socket can be closed independently
  1044. fd = _c.dup(fd)
  1045. if fd < 0:
  1046. raise last_error()
  1047. return make_socket(fd, family, type, proto, SocketClass)
  1048. def getdefaulttimeout():
  1049. return defaults.timeout
  1050. def gethostname():
  1051. size = 1024
  1052. buf = lltype.malloc(rffi.CCHARP.TO, size, flavor='raw')
  1053. try:
  1054. res = _c.gethostname(buf, size)
  1055. if res < 0:
  1056. raise last_error()
  1057. return rffi.charp2strn(buf, size)
  1058. finally:
  1059. lltype.free(buf, flavor='raw')
  1060. def gethostbyname(name):
  1061. # this is explicitly not working with IPv6, because the docs say it
  1062. # should not. Just use makeipaddr(name) for an IPv6-friendly version...
  1063. result = instantiate(INETAddress)
  1064. makeipaddr(name, result)
  1065. return result
  1066. def gethost_common(hostname, hostent, addr=None):
  1067. if not hostent:
  1068. raise HSocketError(hostname)
  1069. family = rffi.getintfield(hostent, 'c_h_addrtype')
  1070. if addr is not None and addr.family != family:
  1071. raise CSocketError(_c.EAFNOSUPPORT)
  1072. h_aliases = hostent.c_h_aliases
  1073. if h_aliases: # h_aliases can be NULL, according to SF #1511317
  1074. aliases = rffi.charpp2liststr(h_aliases)
  1075. else:
  1076. aliases = []
  1077. address_list = []
  1078. h_addr_list = hostent.c_h_addr_list
  1079. i = 0
  1080. paddr = h_addr_list[0]
  1081. while paddr:
  1082. if family == AF_INET:
  1083. p = rffi.cast(lltype.Ptr(_c.in_addr), paddr)
  1084. addr = INETAddress.from_in_addr(p)
  1085. elif AF_INET6 is not None and family == AF_INET6:
  1086. p = rffi.cast(lltype.Ptr(_c.in6_addr), paddr)
  1087. addr = INET6Address.from_in6_addr(p)
  1088. else:
  1089. raise RSocketError("unknown address family")
  1090. address_list.append(addr)
  1091. i += 1
  1092. paddr = h_addr_list[i]
  1093. return (rffi.charp2str(hostent.c_h_name), aliases, address_list)
  1094. def gethostbyname_ex(name):
  1095. # XXX use gethostbyname_r() if available, and/or use locks if not
  1096. addr = gethostbyname(name)
  1097. hostent = _c.gethostbyname(name)
  1098. return gethost_common(name, hostent, addr)
  1099. def gethostbyaddr(ip):
  1100. # XXX use gethostbyaddr_r() if available, and/or use locks if not
  1101. addr = makeipaddr(ip)
  1102. assert isinstance(addr, IPAddress)
  1103. p, size = addr.lock_in_addr()
  1104. try:
  1105. hostent = _c.gethostbyaddr(p, size, addr.family)
  1106. finally:
  1107. addr.unlock()
  1108. return gethost_common(ip, hostent, addr)
  1109. def getaddrinfo(host, port_or_service,
  1110. family=AF_UNSPEC, socktype=0, proto=0, flags=0,
  1111. address_to_fill=None):
  1112. # port_or_service is a string, not an int (but try str(port_number)).
  1113. assert port_or_service is None or isinstance(port_or_service, str)
  1114. hints = lltype.malloc(_c.addrinfo, flavor='raw', zero=True)
  1115. rffi.setintfield(hints, 'c_ai_family', family)
  1116. rffi.setintfield(hints, 'c_ai_socktype', socktype)
  1117. rffi.setintfield(hints, 'c_ai_protocol', proto)
  1118. rffi.setintfield(hints, 'c_ai_flags' , flags)
  1119. # XXX need to lock around getaddrinfo() calls?
  1120. p_res = lltype.malloc(rffi.CArray(_c.addrinfo_ptr), 1, flavor='raw')
  1121. error = intmask(_c.getaddrinfo(host, port_or_service, hints, p_res))
  1122. res = p_res[0]
  1123. lltype.free(p_res, flavor='raw')
  1124. lltype.free(hints, flavor='raw')
  1125. if error:
  1126. raise GAIError(error)
  1127. try:
  1128. result = []
  1129. info = res
  1130. while info:
  1131. addr = make_address(info.c_ai_addr,
  1132. rffi.getintfield(info, 'c_ai_addrlen'),
  1133. address_to_fill)
  1134. if info.c_ai_canonname:
  1135. canonname = rffi.charp2str(info.c_ai_canonname)
  1136. else:
  1137. canonname = ""
  1138. result.append((rffi.cast(lltype.Signed, info.c_ai_family),
  1139. rffi.cast(lltype.Signed, info.c_ai_socktype),
  1140. rffi.cast(lltype.Signed, info.c_ai_protocol),
  1141. canonname,
  1142. addr))
  1143. info = info.c_ai_next
  1144. address_to_fill = None # don't fill the same address repeatedly
  1145. finally:
  1146. _c.freeaddrinfo(res)
  1147. return result
  1148. def getservbyname(name, proto=None):
  1149. servent = _c.getservbyname(name, proto)
  1150. if not servent:
  1151. raise RSocketError("service/proto not found")
  1152. port = rffi.cast(rffi.UINT, servent.c_s_port)
  1153. return ntohs(port)
  1154. def getservbyport(port, proto=None):
  1155. # This function is only called from pypy/module/_socket and the range of
  1156. # port is checked there
  1157. port = rffi.cast(rffi.USHORT, port)
  1158. servent = _c.getservbyport(htons(port), proto)
  1159. if not servent:
  1160. raise RSocketError("port/proto not found")
  1161. return rffi.charp2str(servent.c_s_name)
  1162. def getprotobyname(name):
  1163. protoent = _c.getprotobyname(name)
  1164. if not protoent:
  1165. raise RSocketError("protocol not found")
  1166. proto = protoent.c_p_proto
  1167. return rffi.cast(lltype.Signed, proto)
  1168. def getnameinfo(address, flags):
  1169. host = lltype.malloc(rffi.CCHARP.TO, NI_MAXHOST, flavor='raw')
  1170. try:
  1171. serv = lltype.malloc(rffi.CCHARP.TO, NI_MAXSERV, flavor='raw')
  1172. try:
  1173. addr = address.lock()
  1174. error = intmask(_c.getnameinfo(addr, address.addrlen,
  1175. host, NI_MAXHOST,
  1176. serv, NI_MAXSERV, flags))
  1177. address.unlock()
  1178. if error:
  1179. raise GAIError(error)
  1180. return rffi.charp2str(host), rffi.charp2str(serv)
  1181. finally:
  1182. lltype.free(serv, flavor='raw')
  1183. finally:
  1184. lltype.free(host, flavor='raw')
  1185. if hasattr(_c, 'inet_aton'):
  1186. def inet_aton(ip):
  1187. "IPv4 dotted string -> packed 32-bits string"
  1188. size = sizeof(_c.in_addr)
  1189. buf = mallocbuf(size)
  1190. try:
  1191. if _c.inet_aton(ip, rffi.cast(lltype.Ptr(_c.in_addr), buf)):
  1192. return ''.join([buf[i] for i in range(size)])
  1193. else:
  1194. raise RSocketError("illegal IP address string passed to inet_aton")
  1195. finally:
  1196. lltype.free(buf, flavor='raw')
  1197. else:
  1198. def inet_aton(ip):
  1199. "IPv4 dotted string -> packed 32-bits string"
  1200. if ip == "255.255.255.255":
  1201. return "\xff\xff\xff\xff"
  1202. packed_addr = _c.inet_addr(ip)
  1203. if packed_addr == rffi.cast(lltype.Unsigned, INADDR_NONE):
  1204. raise RSocketError("illegal IP address string passed to inet_aton")
  1205. size = sizeof(_c.in_addr)
  1206. buf = mallocbuf(size)
  1207. try:
  1208. rffi.cast(rffi.UINTP, buf)[0] = packed_addr
  1209. return ''.join([buf[i] for i in range(size)])
  1210. finally:
  1211. lltype.free(buf, flavor='raw')
  1212. def inet_ntoa(packed):
  1213. "packet 32-bits string -> IPv4 dotted string"
  1214. if len(packed) != sizeof(_c.in_addr):
  1215. raise RSocketError("packed IP wrong length for inet_ntoa")
  1216. buf = rffi.make(_c.in_addr)
  1217. try:
  1218. for i in range(sizeof(_c.in_addr)):
  1219. rffi.cast(rffi.CCHARP, buf)[i] = packed[i]
  1220. return rffi.charp2str(_c.inet_ntoa(buf))
  1221. finally:
  1222. lltype.free(buf, flavor='raw')
  1223. if hasattr(_c, 'inet_pton'):
  1224. def inet_pton(family, ip):
  1225. "human-readable string -> packed string"
  1226. if family == AF_INET:
  1227. size = sizeof(_c.in_addr)
  1228. elif AF_INET6 is not None and family == AF_INET6:
  1229. size = sizeof(_c.in6_addr)
  1230. else:
  1231. raise RSocketError("unknown address family")
  1232. buf = mallocbuf(size)
  1233. try:
  1234. res = _c.inet_pton(family, ip, buf)
  1235. if res < 0:
  1236. raise last_error()
  1237. elif res == 0:
  1238. raise RSocketError("illegal IP address string passed "
  1239. "to inet_pton")
  1240. else:
  1241. return ''.join([buf[i] for i in range(size)])
  1242. finally:
  1243. lltype.free(buf, flavor='raw')
  1244. if hasattr(_c, 'inet_ntop'):
  1245. def inet_ntop(family, packed):
  1246. "packed string -> human-readable string"
  1247. if family == AF_INET:
  1248. srcsize = sizeof(_c.in_addr)
  1249. dstsize = _c.INET_ADDRSTRLEN
  1250. elif AF_INET6 is not None and family == AF_INET6:
  1251. srcsize = sizeof(_c.in6_addr)
  1252. dstsize = _c.INET6_ADDRSTRLEN
  1253. else:
  1254. raise RSocketError("unknown address family")
  1255. if len(packed) != srcsize:
  1256. raise ValueError("packed IP wrong length for inet_ntop")
  1257. srcbuf = rffi.get_nonmovingbuffer(packed)
  1258. try:
  1259. dstbuf = mallocbuf(dstsize)
  1260. try:
  1261. res = _c.inet_ntop(family, srcbuf, dstbuf, dstsize)
  1262. if not res:
  1263. raise last_error()
  1264. return rffi.charp2str(res)
  1265. finally:
  1266. lltype.free(dstbuf, flavor='raw')
  1267. finally:
  1268. rffi.free_nonmovingbuffer(packed, srcbuf)
  1269. def setdefaulttimeout(timeout):
  1270. if timeout < 0.0:
  1271. timeout = -1.0
  1272. defaults.timeout = timeout