nativesockets.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Dominik Picheta
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a low-level cross-platform sockets interface. Look
  10. ## at the ``net`` module for the higher-level version.
  11. # TODO: Clean up the exports a bit and everything else in general.
  12. import os, options
  13. when hostOS == "solaris":
  14. {.passl: "-lsocket -lnsl".}
  15. const useWinVersion = defined(Windows) or defined(nimdoc)
  16. when useWinVersion:
  17. import winlean
  18. export WSAEWOULDBLOCK, WSAECONNRESET, WSAECONNABORTED, WSAENETRESET,
  19. WSANOTINITIALISED, WSAENOTSOCK, WSAEINPROGRESS, WSAEINTR,
  20. WSAEDISCON, ERROR_NETNAME_DELETED
  21. else:
  22. import posix
  23. export fcntl, F_GETFL, O_NONBLOCK, F_SETFL, EAGAIN, EWOULDBLOCK, MSG_NOSIGNAL,
  24. EINTR, EINPROGRESS, ECONNRESET, EPIPE, ENETRESET, EBADF
  25. export Sockaddr_storage, Sockaddr_un, Sockaddr_un_path_length
  26. export SocketHandle, Sockaddr_in, Addrinfo, INADDR_ANY, SockAddr, SockLen,
  27. Sockaddr_in6, Sockaddr_storage,
  28. inet_ntoa, recv, `==`, connect, send, accept, recvfrom, sendto,
  29. freeAddrInfo
  30. export
  31. SO_ERROR,
  32. SOL_SOCKET,
  33. SOMAXCONN,
  34. SO_ACCEPTCONN, SO_BROADCAST, SO_DEBUG, SO_DONTROUTE,
  35. SO_KEEPALIVE, SO_OOBINLINE, SO_REUSEADDR, SO_REUSEPORT,
  36. MSG_PEEK
  37. when defined(macosx) and not defined(nimdoc):
  38. export SO_NOSIGPIPE
  39. type
  40. Port* = distinct uint16 ## port type
  41. Domain* = enum ## \
  42. ## domain, which specifies the protocol family of the
  43. ## created socket. Other domains than those that are listed
  44. ## here are unsupported.
  45. AF_UNSPEC = 0, ## unspecified domain (can be detected automatically by
  46. ## some procedures, such as getaddrinfo)
  47. AF_UNIX = 1, ## for local socket (using a file). Unsupported on Windows.
  48. AF_INET = 2, ## for network protocol IPv4 or
  49. AF_INET6 = when defined(macosx): 30 else: 23 ## for network protocol IPv6.
  50. SockType* = enum ## second argument to `socket` proc
  51. SOCK_STREAM = 1, ## reliable stream-oriented service or Stream Sockets
  52. SOCK_DGRAM = 2, ## datagram service or Datagram Sockets
  53. SOCK_RAW = 3, ## raw protocols atop the network layer.
  54. SOCK_SEQPACKET = 5 ## reliable sequenced packet service
  55. Protocol* = enum ## third argument to `socket` proc
  56. IPPROTO_TCP = 6, ## Transmission control protocol.
  57. IPPROTO_UDP = 17, ## User datagram protocol.
  58. IPPROTO_IP, ## Internet protocol. Unsupported on Windows.
  59. IPPROTO_IPV6, ## Internet Protocol Version 6. Unsupported on Windows.
  60. IPPROTO_RAW, ## Raw IP Packets Protocol. Unsupported on Windows.
  61. IPPROTO_ICMP ## Control message protocol. Unsupported on Windows.
  62. IPPROTO_ICMPV6 ## Control message protocol for IPv6. Unsupported on Windows.
  63. Servent* = object ## information about a service
  64. name*: string
  65. aliases*: seq[string]
  66. port*: Port
  67. proto*: string
  68. Hostent* = object ## information about a given host
  69. name*: string
  70. aliases*: seq[string]
  71. addrtype*: Domain
  72. length*: int
  73. addrList*: seq[string]
  74. when useWinVersion:
  75. let
  76. osInvalidSocket* = winlean.INVALID_SOCKET
  77. const
  78. IOCPARM_MASK* = 127
  79. IOC_IN* = int(-2147483648)
  80. FIONBIO* = IOC_IN.int32 or ((sizeof(int32) and IOCPARM_MASK) shl 16) or
  81. (102 shl 8) or 126
  82. nativeAfInet = winlean.AF_INET
  83. nativeAfInet6 = winlean.AF_INET6
  84. proc ioctlsocket*(s: SocketHandle, cmd: clong,
  85. argptr: ptr clong): cint {.
  86. stdcall, importc: "ioctlsocket", dynlib: "ws2_32.dll".}
  87. else:
  88. let
  89. osInvalidSocket* = posix.INVALID_SOCKET
  90. nativeAfInet = posix.AF_INET
  91. nativeAfInet6 = posix.AF_INET6
  92. nativeAfUnix = posix.AF_UNIX
  93. proc `==`*(a, b: Port): bool {.borrow.}
  94. ## ``==`` for ports.
  95. proc `$`*(p: Port): string {.borrow.}
  96. ## returns the port number as a string
  97. proc toInt*(domain: Domain): cint
  98. ## Converts the Domain enum to a platform-dependent ``cint``.
  99. proc toInt*(typ: SockType): cint
  100. ## Converts the SockType enum to a platform-dependent ``cint``.
  101. proc toInt*(p: Protocol): cint
  102. ## Converts the Protocol enum to a platform-dependent ``cint``.
  103. when not useWinVersion:
  104. proc toInt(domain: Domain): cint =
  105. case domain
  106. of AF_UNSPEC: result = posix.AF_UNSPEC.cint
  107. of AF_UNIX: result = posix.AF_UNIX.cint
  108. of AF_INET: result = posix.AF_INET.cint
  109. of AF_INET6: result = posix.AF_INET6.cint
  110. proc toKnownDomain*(family: cint): Option[Domain] =
  111. ## Converts the platform-dependent ``cint`` to the Domain or none(),
  112. ## if the ``cint`` is not known.
  113. result = if family == posix.AF_UNSPEC: some(Domain.AF_UNSPEC)
  114. elif family == posix.AF_UNIX: some(Domain.AF_UNIX)
  115. elif family == posix.AF_INET: some(Domain.AF_INET)
  116. elif family == posix.AF_INET6: some(Domain.AF_INET6)
  117. else: none(Domain)
  118. proc toInt(typ: SockType): cint =
  119. case typ
  120. of SOCK_STREAM: result = posix.SOCK_STREAM
  121. of SOCK_DGRAM: result = posix.SOCK_DGRAM
  122. of SOCK_SEQPACKET: result = posix.SOCK_SEQPACKET
  123. of SOCK_RAW: result = posix.SOCK_RAW
  124. proc toInt(p: Protocol): cint =
  125. case p
  126. of IPPROTO_TCP: result = posix.IPPROTO_TCP
  127. of IPPROTO_UDP: result = posix.IPPROTO_UDP
  128. of IPPROTO_IP: result = posix.IPPROTO_IP
  129. of IPPROTO_IPV6: result = posix.IPPROTO_IPV6
  130. of IPPROTO_RAW: result = posix.IPPROTO_RAW
  131. of IPPROTO_ICMP: result = posix.IPPROTO_ICMP
  132. of IPPROTO_ICMPV6: result = posix.IPPROTO_ICMPV6
  133. else:
  134. proc toInt(domain: Domain): cint =
  135. result = toU32(ord(domain)).cint
  136. proc toKnownDomain*(family: cint): Option[Domain] =
  137. ## Converts the platform-dependent ``cint`` to the Domain or none(),
  138. ## if the ``cint`` is not known.
  139. result = if family == winlean.AF_UNSPEC: some(Domain.AF_UNSPEC)
  140. elif family == winlean.AF_INET: some(Domain.AF_INET)
  141. elif family == winlean.AF_INET6: some(Domain.AF_INET6)
  142. else: none(Domain)
  143. proc toInt(typ: SockType): cint =
  144. result = cint(ord(typ))
  145. proc toInt(p: Protocol): cint =
  146. result = cint(ord(p))
  147. proc toSockType*(protocol: Protocol): SockType =
  148. result = case protocol
  149. of IPPROTO_TCP:
  150. SOCK_STREAM
  151. of IPPROTO_UDP:
  152. SOCK_DGRAM
  153. of IPPROTO_IP, IPPROTO_IPV6, IPPROTO_RAW, IPPROTO_ICMP, IPPROTO_ICMPV6:
  154. SOCK_RAW
  155. proc createNativeSocket*(domain: Domain = AF_INET,
  156. sockType: SockType = SOCK_STREAM,
  157. protocol: Protocol = IPPROTO_TCP): SocketHandle =
  158. ## Creates a new socket; returns `osInvalidSocket` if an error occurs.
  159. socket(toInt(domain), toInt(sockType), toInt(protocol))
  160. proc createNativeSocket*(domain: cint, sockType: cint,
  161. protocol: cint): SocketHandle =
  162. ## Creates a new socket; returns `osInvalidSocket` if an error occurs.
  163. ##
  164. ## Use this overload if one of the enums specified above does
  165. ## not contain what you need.
  166. socket(domain, sockType, protocol)
  167. proc newNativeSocket*(domain: Domain = AF_INET,
  168. sockType: SockType = SOCK_STREAM,
  169. protocol: Protocol = IPPROTO_TCP): SocketHandle
  170. {.deprecated: "deprecated since v0.18.0; use 'createNativeSocket' instead".} =
  171. ## Creates a new socket; returns `osInvalidSocket` if an error occurs.
  172. createNativeSocket(domain, sockType, protocol)
  173. proc newNativeSocket*(domain: cint, sockType: cint,
  174. protocol: cint): SocketHandle
  175. {.deprecated: "deprecated since v0.18.0; use 'createNativeSocket' instead".} =
  176. ## Creates a new socket; returns `osInvalidSocket` if an error occurs.
  177. ##
  178. ## Use this overload if one of the enums specified above does
  179. ## not contain what you need.
  180. createNativeSocket(domain, sockType, protocol)
  181. proc close*(socket: SocketHandle) =
  182. ## closes a socket.
  183. when useWinVersion:
  184. discard winlean.closesocket(socket)
  185. else:
  186. discard posix.close(socket)
  187. # TODO: These values should not be discarded. An OSError should be raised.
  188. # http://stackoverflow.com/questions/12463473/what-happens-if-you-call-close-on-a-bsd-socket-multiple-times
  189. proc bindAddr*(socket: SocketHandle, name: ptr SockAddr,
  190. namelen: SockLen): cint =
  191. result = bindSocket(socket, name, namelen)
  192. proc listen*(socket: SocketHandle, backlog = SOMAXCONN): cint {.tags: [
  193. ReadIOEffect].} =
  194. ## Marks ``socket`` as accepting connections.
  195. ## ``Backlog`` specifies the maximum length of the
  196. ## queue of pending connections.
  197. when useWinVersion:
  198. result = winlean.listen(socket, cint(backlog))
  199. else:
  200. result = posix.listen(socket, cint(backlog))
  201. proc getAddrInfo*(address: string, port: Port, domain: Domain = AF_INET,
  202. sockType: SockType = SOCK_STREAM,
  203. protocol: Protocol = IPPROTO_TCP): ptr AddrInfo =
  204. ##
  205. ##
  206. ## **Warning**: The resulting ``ptr AddrInfo`` must be freed using ``freeAddrInfo``!
  207. var hints: AddrInfo
  208. result = nil
  209. hints.ai_family = toInt(domain)
  210. hints.ai_socktype = toInt(sockType)
  211. hints.ai_protocol = toInt(protocol)
  212. # OpenBSD doesn't support AI_V4MAPPED and doesn't define the macro AI_V4MAPPED.
  213. # FreeBSD, Haiku don't support AI_V4MAPPED but defines the macro.
  214. # https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=198092
  215. # https://dev.haiku-os.org/ticket/14323
  216. when not defined(freebsd) and not defined(openbsd) and not defined(netbsd) and
  217. not defined(android) and not defined(haiku):
  218. if domain == AF_INET6:
  219. hints.ai_flags = AI_V4MAPPED
  220. let socketPort = if sockType == SOCK_RAW: "" else: $port
  221. var gaiResult = getaddrinfo(address, socketPort, addr(hints), result)
  222. if gaiResult != 0'i32:
  223. when useWinVersion:
  224. raiseOSError(osLastError())
  225. else:
  226. raiseOSError(osLastError(), $gai_strerror(gaiResult))
  227. proc ntohl*(x: uint32): uint32 =
  228. ## Converts 32-bit unsigned integers from network to host byte order.
  229. ## On machines where the host byte order is the same as network byte order,
  230. ## this is a no-op; otherwise, it performs a 4-byte swap operation.
  231. when cpuEndian == bigEndian: result = x
  232. else: result = (x shr 24'u32) or
  233. (x shr 8'u32 and 0xff00'u32) or
  234. (x shl 8'u32 and 0xff0000'u32) or
  235. (x shl 24'u32)
  236. proc ntohs*(x: uint16): uint16 =
  237. ## Converts 16-bit unsigned integers from network to host byte order. On
  238. ## machines where the host byte order is the same as network byte order,
  239. ## this is a no-op; otherwise, it performs a 2-byte swap operation.
  240. when cpuEndian == bigEndian: result = x
  241. else: result = (x shr 8'u16) or (x shl 8'u16)
  242. template htonl*(x: uint32): untyped =
  243. ## Converts 32-bit unsigned integers from host to network byte order. On
  244. ## machines where the host byte order is the same as network byte order,
  245. ## this is a no-op; otherwise, it performs a 4-byte swap operation.
  246. nativesockets.ntohl(x)
  247. template htons*(x: uint16): untyped =
  248. ## Converts 16-bit unsigned integers from host to network byte order.
  249. ## On machines where the host byte order is the same as network byte
  250. ## order, this is a no-op; otherwise, it performs a 2-byte swap operation.
  251. nativesockets.ntohs(x)
  252. proc getServByName*(name, proto: string): Servent {.tags: [ReadIOEffect].} =
  253. ## Searches the database from the beginning and finds the first entry for
  254. ## which the service name specified by ``name`` matches the s_name member
  255. ## and the protocol name specified by ``proto`` matches the s_proto member.
  256. ##
  257. ## On posix this will search through the ``/etc/services`` file.
  258. when useWinVersion:
  259. var s = winlean.getservbyname(name, proto)
  260. else:
  261. var s = posix.getservbyname(name, proto)
  262. if s == nil: raiseOSError(osLastError(), "Service not found.")
  263. result.name = $s.s_name
  264. result.aliases = cstringArrayToSeq(s.s_aliases)
  265. result.port = Port(s.s_port)
  266. result.proto = $s.s_proto
  267. proc getServByPort*(port: Port, proto: string): Servent {.tags: [ReadIOEffect].} =
  268. ## Searches the database from the beginning and finds the first entry for
  269. ## which the port specified by ``port`` matches the s_port member and the
  270. ## protocol name specified by ``proto`` matches the s_proto member.
  271. ##
  272. ## On posix this will search through the ``/etc/services`` file.
  273. when useWinVersion:
  274. var s = winlean.getservbyport(ze(int16(port)).cint, proto)
  275. else:
  276. var s = posix.getservbyport(ze(int16(port)).cint, proto)
  277. if s == nil: raiseOSError(osLastError(), "Service not found.")
  278. result.name = $s.s_name
  279. result.aliases = cstringArrayToSeq(s.s_aliases)
  280. result.port = Port(s.s_port)
  281. result.proto = $s.s_proto
  282. proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
  283. ## This function will lookup the hostname of an IP Address.
  284. var myaddr: InAddr
  285. myaddr.s_addr = inet_addr(ip)
  286. when useWinVersion:
  287. var s = winlean.gethostbyaddr(addr(myaddr), sizeof(myaddr).cuint,
  288. cint(AF_INET))
  289. if s == nil: raiseOSError(osLastError())
  290. else:
  291. var s =
  292. when defined(android4):
  293. posix.gethostbyaddr(cast[cstring](addr(myaddr)), sizeof(myaddr).cint,
  294. cint(posix.AF_INET))
  295. else:
  296. posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).SockLen,
  297. cint(posix.AF_INET))
  298. if s == nil:
  299. raiseOSError(osLastError(), $hstrerror(h_errno))
  300. result.name = $s.h_name
  301. result.aliases = cstringArrayToSeq(s.h_aliases)
  302. when useWinVersion:
  303. result.addrtype = Domain(s.h_addrtype)
  304. else:
  305. if s.h_addrtype == posix.AF_INET:
  306. result.addrtype = AF_INET
  307. elif s.h_addrtype == posix.AF_INET6:
  308. result.addrtype = AF_INET6
  309. else:
  310. raiseOSError(osLastError(), "unknown h_addrtype")
  311. if result.addrtype == AF_INET:
  312. result.addrList = @[]
  313. var i = 0
  314. while not isNil(s.h_addr_list[i]):
  315. var inaddrPtr = cast[ptr InAddr](s.h_addr_list[i])
  316. result.addrList.add($inet_ntoa(inaddrPtr[]))
  317. inc(i)
  318. else:
  319. result.addrList = cstringArrayToSeq(s.h_addr_list)
  320. result.length = int(s.h_length)
  321. proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} =
  322. ## This function will lookup the IP address of a hostname.
  323. when useWinVersion:
  324. var s = winlean.gethostbyname(name)
  325. else:
  326. var s = posix.gethostbyname(name)
  327. if s == nil: raiseOSError(osLastError())
  328. result.name = $s.h_name
  329. result.aliases = cstringArrayToSeq(s.h_aliases)
  330. when useWinVersion:
  331. result.addrtype = Domain(s.h_addrtype)
  332. else:
  333. if s.h_addrtype == posix.AF_INET:
  334. result.addrtype = AF_INET
  335. elif s.h_addrtype == posix.AF_INET6:
  336. result.addrtype = AF_INET6
  337. else:
  338. raiseOSError(osLastError(), "unknown h_addrtype")
  339. if result.addrtype == AF_INET:
  340. result.addrList = @[]
  341. var i = 0
  342. while not isNil(s.h_addr_list[i]):
  343. var inaddrPtr = cast[ptr InAddr](s.h_addr_list[i])
  344. result.addrList.add($inet_ntoa(inaddrPtr[]))
  345. inc(i)
  346. else:
  347. result.addrList = cstringArrayToSeq(s.h_addr_list)
  348. result.length = int(s.h_length)
  349. proc getHostname*(): string {.tags: [ReadIOEffect].} =
  350. ## Returns the local hostname (not the FQDN)
  351. # https://tools.ietf.org/html/rfc1035#section-2.3.1
  352. # https://tools.ietf.org/html/rfc2181#section-11
  353. const size = 64
  354. result = newString(size)
  355. when useWinVersion:
  356. let success = winlean.gethostname(result, size)
  357. else:
  358. # Posix
  359. let success = posix.gethostname(result, size)
  360. if success != 0.cint:
  361. raiseOSError(osLastError())
  362. let x = len(cstring(result))
  363. result.setLen(x)
  364. proc getSockDomain*(socket: SocketHandle): Domain =
  365. ## returns the socket's domain (AF_INET or AF_INET6).
  366. var name: Sockaddr_in6
  367. var namelen = sizeof(name).SockLen
  368. if getsockname(socket, cast[ptr SockAddr](addr(name)),
  369. addr(namelen)) == -1'i32:
  370. raiseOSError(osLastError())
  371. try:
  372. result = toKnownDomain(name.sin6_family.cint).get()
  373. except UnpackError:
  374. raise newException(IOError, "Unknown socket family in getSockDomain")
  375. proc getAddrString*(sockAddr: ptr SockAddr): string =
  376. ## return the string representation of address within sockAddr
  377. if sockAddr.sa_family.cint == nativeAfInet:
  378. result = $inet_ntoa(cast[ptr Sockaddr_in](sockAddr).sin_addr)
  379. elif sockAddr.sa_family.cint == nativeAfInet6:
  380. let addrLen = when not useWinVersion: posix.INET6_ADDRSTRLEN
  381. else: 46 # it's actually 46 in both cases
  382. result = newString(addrLen)
  383. let addr6 = addr cast[ptr Sockaddr_in6](sockAddr).sin6_addr
  384. when not useWinVersion:
  385. if posix.inet_ntop(posix.AF_INET6, addr6, addr result[0],
  386. result.len.int32) == nil:
  387. raiseOSError(osLastError())
  388. if posix.IN6_IS_ADDR_V4MAPPED(addr6) != 0:
  389. result = result.substr("::ffff:".len)
  390. else:
  391. if winlean.inet_ntop(winlean.AF_INET6, addr6, addr result[0],
  392. result.len.int32) == nil:
  393. raiseOSError(osLastError())
  394. setLen(result, len(cstring(result)))
  395. else:
  396. when defined(posix) and not defined(nimdoc):
  397. if sockAddr.sa_family.cint == nativeAfUnix:
  398. return "unix"
  399. raise newException(IOError, "Unknown socket family in getAddrString")
  400. when defined(posix) and not defined(nimdoc):
  401. proc makeUnixAddr*(path: string): Sockaddr_un =
  402. result.sun_family = AF_UNIX.TSa_Family
  403. if path.len >= Sockaddr_un_path_length:
  404. raise newException(ValueError, "socket path too long")
  405. copyMem(addr result.sun_path, path.cstring, path.len + 1)
  406. proc getSockName*(socket: SocketHandle): Port =
  407. ## returns the socket's associated port number.
  408. var name: Sockaddr_in
  409. when useWinVersion:
  410. name.sin_family = uint16(ord(AF_INET))
  411. else:
  412. name.sin_family = TSa_Family(posix.AF_INET)
  413. #name.sin_port = htons(cint16(port))
  414. #name.sin_addr.s_addr = htonl(INADDR_ANY)
  415. var namelen = sizeof(name).SockLen
  416. if getsockname(socket, cast[ptr SockAddr](addr(name)),
  417. addr(namelen)) == -1'i32:
  418. raiseOSError(osLastError())
  419. result = Port(nativesockets.ntohs(name.sin_port))
  420. proc getLocalAddr*(socket: SocketHandle, domain: Domain): (string, Port) =
  421. ## returns the socket's local address and port number.
  422. ##
  423. ## Similar to POSIX's `getsockname`:idx:.
  424. case domain
  425. of AF_INET:
  426. var name: Sockaddr_in
  427. when useWinVersion:
  428. name.sin_family = uint16(ord(AF_INET))
  429. else:
  430. name.sin_family = TSa_Family(posix.AF_INET)
  431. var namelen = sizeof(name).SockLen
  432. if getsockname(socket, cast[ptr SockAddr](addr(name)),
  433. addr(namelen)) == -1'i32:
  434. raiseOSError(osLastError())
  435. result = ($inet_ntoa(name.sin_addr),
  436. Port(nativesockets.ntohs(name.sin_port)))
  437. of AF_INET6:
  438. var name: Sockaddr_in6
  439. when useWinVersion:
  440. name.sin6_family = uint16(ord(AF_INET6))
  441. else:
  442. name.sin6_family = TSa_Family(posix.AF_INET6)
  443. var namelen = sizeof(name).SockLen
  444. if getsockname(socket, cast[ptr SockAddr](addr(name)),
  445. addr(namelen)) == -1'i32:
  446. raiseOSError(osLastError())
  447. # Cannot use INET6_ADDRSTRLEN here, because it's a C define.
  448. result[0] = newString(64)
  449. if inet_ntop(name.sin6_family.cint,
  450. addr name.sin6_addr, addr result[0][0], (result[0].len+1).int32).isNil:
  451. raiseOSError(osLastError())
  452. setLen(result[0], result[0].cstring.len)
  453. result[1] = Port(nativesockets.ntohs(name.sin6_port))
  454. else:
  455. raiseOSError(OSErrorCode(-1), "invalid socket family in getLocalAddr")
  456. proc getPeerAddr*(socket: SocketHandle, domain: Domain): (string, Port) =
  457. ## returns the socket's peer address and port number.
  458. ##
  459. ## Similar to POSIX's `getpeername`:idx:
  460. case domain
  461. of AF_INET:
  462. var name: Sockaddr_in
  463. when useWinVersion:
  464. name.sin_family = uint16(ord(AF_INET))
  465. else:
  466. name.sin_family = TSa_Family(posix.AF_INET)
  467. var namelen = sizeof(name).SockLen
  468. if getpeername(socket, cast[ptr SockAddr](addr(name)),
  469. addr(namelen)) == -1'i32:
  470. raiseOSError(osLastError())
  471. result = ($inet_ntoa(name.sin_addr),
  472. Port(nativesockets.ntohs(name.sin_port)))
  473. of AF_INET6:
  474. var name: Sockaddr_in6
  475. when useWinVersion:
  476. name.sin6_family = uint16(ord(AF_INET6))
  477. else:
  478. name.sin6_family = TSa_Family(posix.AF_INET6)
  479. var namelen = sizeof(name).SockLen
  480. if getpeername(socket, cast[ptr SockAddr](addr(name)),
  481. addr(namelen)) == -1'i32:
  482. raiseOSError(osLastError())
  483. # Cannot use INET6_ADDRSTRLEN here, because it's a C define.
  484. result[0] = newString(64)
  485. if inet_ntop(name.sin6_family.cint,
  486. addr name.sin6_addr, addr result[0][0], (result[0].len+1).int32).isNil:
  487. raiseOSError(osLastError())
  488. setLen(result[0], result[0].cstring.len)
  489. result[1] = Port(nativesockets.ntohs(name.sin6_port))
  490. else:
  491. raiseOSError(OSErrorCode(-1), "invalid socket family in getLocalAddr")
  492. proc getSockOptInt*(socket: SocketHandle, level, optname: int): int {.
  493. tags: [ReadIOEffect].} =
  494. ## getsockopt for integer options.
  495. var res: cint
  496. var size = sizeof(res).SockLen
  497. if getsockopt(socket, cint(level), cint(optname),
  498. addr(res), addr(size)) < 0'i32:
  499. raiseOSError(osLastError())
  500. result = int(res)
  501. proc setSockOptInt*(socket: SocketHandle, level, optname, optval: int) {.
  502. tags: [WriteIOEffect].} =
  503. ## setsockopt for integer options.
  504. var value = cint(optval)
  505. if setsockopt(socket, cint(level), cint(optname), addr(value),
  506. sizeof(value).SockLen) < 0'i32:
  507. raiseOSError(osLastError())
  508. proc setBlocking*(s: SocketHandle, blocking: bool) =
  509. ## Sets blocking mode on socket.
  510. ##
  511. ## Raises OSError on error.
  512. when useWinVersion:
  513. var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking
  514. if ioctlsocket(s, FIONBIO, addr(mode)) == -1:
  515. raiseOSError(osLastError())
  516. else: # BSD sockets
  517. var x: int = fcntl(s, F_GETFL, 0)
  518. if x == -1:
  519. raiseOSError(osLastError())
  520. else:
  521. var mode = if blocking: x and not O_NONBLOCK else: x or O_NONBLOCK
  522. if fcntl(s, F_SETFL, mode) == -1:
  523. raiseOSError(osLastError())
  524. proc timeValFromMilliseconds(timeout = 500): Timeval =
  525. if timeout != -1:
  526. var seconds = timeout div 1000
  527. when useWinVersion:
  528. result.tv_sec = seconds.int32
  529. result.tv_usec = ((timeout - seconds * 1000) * 1000).int32
  530. else:
  531. result.tv_sec = seconds.Time
  532. result.tv_usec = ((timeout - seconds * 1000) * 1000).Suseconds
  533. proc createFdSet(fd: var TFdSet, s: seq[SocketHandle], m: var int) =
  534. FD_ZERO(fd)
  535. for i in items(s):
  536. m = max(m, int(i))
  537. FD_SET(i, fd)
  538. proc pruneSocketSet(s: var seq[SocketHandle], fd: var TFdSet) =
  539. var i = 0
  540. var L = s.len
  541. while i < L:
  542. if FD_ISSET(s[i], fd) == 0'i32:
  543. s[i] = s[L-1]
  544. dec(L)
  545. else:
  546. inc(i)
  547. setLen(s, L)
  548. proc selectRead*(readfds: var seq[SocketHandle], timeout = 500): int =
  549. ## When a socket in ``readfds`` is ready to be read from then a non-zero
  550. ## value will be returned specifying the count of the sockets which can be
  551. ## read from. The sockets which can be read from will also be removed
  552. ## from ``readfds``.
  553. ##
  554. ## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
  555. ## an unlimited time.
  556. var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
  557. var rd: TFdSet
  558. var m = 0
  559. createFdSet((rd), readfds, m)
  560. if timeout != -1:
  561. result = int(select(cint(m+1), addr(rd), nil, nil, addr(tv)))
  562. else:
  563. result = int(select(cint(m+1), addr(rd), nil, nil, nil))
  564. pruneSocketSet(readfds, (rd))
  565. proc selectWrite*(writefds: var seq[SocketHandle],
  566. timeout = 500): int {.tags: [ReadIOEffect].} =
  567. ## When a socket in ``writefds`` is ready to be written to then a non-zero
  568. ## value will be returned specifying the count of the sockets which can be
  569. ## written to. The sockets which can be written to will also be removed
  570. ## from ``writefds``.
  571. ##
  572. ## ``timeout`` is specified in milliseconds and ``-1`` can be specified for
  573. ## an unlimited time.
  574. var tv {.noinit.}: Timeval = timeValFromMilliseconds(timeout)
  575. var wr: TFdSet
  576. var m = 0
  577. createFdSet((wr), writefds, m)
  578. if timeout != -1:
  579. result = int(select(cint(m+1), nil, addr(wr), nil, addr(tv)))
  580. else:
  581. result = int(select(cint(m+1), nil, addr(wr), nil, nil))
  582. pruneSocketSet(writefds, (wr))
  583. proc accept*(fd: SocketHandle): (SocketHandle, string) =
  584. ## Accepts a new client connection.
  585. ##
  586. ## Returns (osInvalidSocket, "") if an error occurred.
  587. var sockAddress: Sockaddr_in
  588. var addrLen = sizeof(sockAddress).SockLen
  589. var sock = accept(fd, cast[ptr SockAddr](addr(sockAddress)),
  590. addr(addrLen))
  591. if sock == osInvalidSocket:
  592. return (osInvalidSocket, "")
  593. else:
  594. return (sock, $inet_ntoa(sockAddress.sin_addr))
  595. when defined(Windows):
  596. var wsa: WSAData
  597. if wsaStartup(0x0101'i16, addr wsa) != 0: raiseOSError(osLastError())