asyncnet.nim 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2017 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 high-level asynchronous sockets API based on the
  10. ## asynchronous dispatcher defined in the `asyncdispatch` module.
  11. ##
  12. ## Asynchronous IO in Nim
  13. ## ======================
  14. ##
  15. ## Async IO in Nim consists of multiple layers (from highest to lowest):
  16. ##
  17. ## * `asyncnet` module
  18. ##
  19. ## * Async await
  20. ##
  21. ## * `asyncdispatch` module (event loop)
  22. ##
  23. ## * `selectors` module
  24. ##
  25. ## Each builds on top of the layers below it. The selectors module is an
  26. ## abstraction for the various system `select()` mechanisms such as epoll or
  27. ## kqueue. If you wish you can use it directly, and some people have done so
  28. ## `successfully <http://goran.krampe.se/2014/10/25/nim-socketserver/>`_.
  29. ## But you must be aware that on Windows it only supports
  30. ## `select()`.
  31. ##
  32. ## The async dispatcher implements the proactor pattern and also has an
  33. ## implementation of IOCP. It implements the proactor pattern for other
  34. ## OS' via the selectors module. Futures are also implemented here, and
  35. ## indeed all the procedures return a future.
  36. ##
  37. ## The final layer is the async await transformation. This allows you to
  38. ## write asynchronous code in a synchronous style and works similar to
  39. ## C#'s await. The transformation works by converting any async procedures
  40. ## into an iterator.
  41. ##
  42. ## This is all single threaded, fully non-blocking and does give you a
  43. ## lot of control. In theory you should be able to work with any of these
  44. ## layers interchangeably (as long as you only care about non-Windows
  45. ## platforms).
  46. ##
  47. ## For most applications using `asyncnet` is the way to go as it builds
  48. ## over all the layers, providing some extra features such as buffering.
  49. ##
  50. ## SSL
  51. ## ===
  52. ##
  53. ## SSL can be enabled by compiling with the `-d:ssl` flag.
  54. ##
  55. ## You must create a new SSL context with the `newContext` function defined
  56. ## in the `net` module. You may then call `wrapSocket` on your socket using
  57. ## the newly created SSL context to get an SSL socket.
  58. ##
  59. ## Examples
  60. ## ========
  61. ##
  62. ## Chat server
  63. ## -----------
  64. ##
  65. ## The following example demonstrates a simple chat server.
  66. ##
  67. ## ```Nim
  68. ## import std/[asyncnet, asyncdispatch]
  69. ##
  70. ## var clients {.threadvar.}: seq[AsyncSocket]
  71. ##
  72. ## proc processClient(client: AsyncSocket) {.async.} =
  73. ## while true:
  74. ## let line = await client.recvLine()
  75. ## if line.len == 0: break
  76. ## for c in clients:
  77. ## await c.send(line & "\c\L")
  78. ##
  79. ## proc serve() {.async.} =
  80. ## clients = @[]
  81. ## var server = newAsyncSocket()
  82. ## server.setSockOpt(OptReuseAddr, true)
  83. ## server.bindAddr(Port(12345))
  84. ## server.listen()
  85. ##
  86. ## while true:
  87. ## let client = await server.accept()
  88. ## clients.add client
  89. ##
  90. ## asyncCheck processClient(client)
  91. ##
  92. ## asyncCheck serve()
  93. ## runForever()
  94. ## ```
  95. import std/private/since
  96. when defined(nimPreviewSlimSystem):
  97. import std/[assertions, syncio]
  98. import asyncdispatch, nativesockets, net, os
  99. export SOBool
  100. # TODO: Remove duplication introduced by PR #4683.
  101. const defineSsl = defined(ssl) or defined(nimdoc)
  102. const useNimNetLite = defined(nimNetLite) or defined(freertos) or defined(zephyr) or
  103. defined(nuttx)
  104. when defineSsl:
  105. import openssl
  106. type
  107. # TODO: I would prefer to just do:
  108. # AsyncSocket* {.borrow: `.`.} = distinct Socket. But that doesn't work.
  109. AsyncSocketDesc = object
  110. fd: SocketHandle
  111. closed: bool ## determines whether this socket has been closed
  112. isBuffered: bool ## determines whether this socket is buffered.
  113. buffer: array[0..BufferSize, char]
  114. currPos: int # current index in buffer
  115. bufLen: int # current length of buffer
  116. isSsl: bool
  117. when defineSsl:
  118. sslHandle: SslPtr
  119. sslContext: SslContext
  120. bioIn: BIO
  121. bioOut: BIO
  122. sslNoShutdown: bool
  123. domain: Domain
  124. sockType: SockType
  125. protocol: Protocol
  126. AsyncSocket* = ref AsyncSocketDesc
  127. proc newAsyncSocket*(fd: AsyncFD, domain: Domain = AF_INET,
  128. sockType: SockType = SOCK_STREAM,
  129. protocol: Protocol = IPPROTO_TCP,
  130. buffered = true,
  131. inheritable = defined(nimInheritHandles)): owned(AsyncSocket) =
  132. ## Creates a new `AsyncSocket` based on the supplied params.
  133. ##
  134. ## The supplied `fd`'s non-blocking state will be enabled implicitly.
  135. ##
  136. ## If `inheritable` is false (the default), the supplied `fd` will not
  137. ## be inheritable by child processes.
  138. ##
  139. ## **Note**: This procedure will **NOT** register `fd` with the global
  140. ## async dispatcher. You need to do this manually. If you have used
  141. ## `newAsyncNativeSocket` to create `fd` then it's already registered.
  142. assert fd != osInvalidSocket.AsyncFD
  143. new(result)
  144. result.fd = fd.SocketHandle
  145. fd.SocketHandle.setBlocking(false)
  146. if not fd.SocketHandle.setInheritable(inheritable):
  147. raiseOSError(osLastError())
  148. result.isBuffered = buffered
  149. result.domain = domain
  150. result.sockType = sockType
  151. result.protocol = protocol
  152. if buffered:
  153. result.currPos = 0
  154. proc newAsyncSocket*(domain: Domain = AF_INET, sockType: SockType = SOCK_STREAM,
  155. protocol: Protocol = IPPROTO_TCP, buffered = true,
  156. inheritable = defined(nimInheritHandles)): owned(AsyncSocket) =
  157. ## Creates a new asynchronous socket.
  158. ##
  159. ## This procedure will also create a brand new file descriptor for
  160. ## this socket.
  161. ##
  162. ## If `inheritable` is false (the default), the new file descriptor will not
  163. ## be inheritable by child processes.
  164. let fd = createAsyncNativeSocket(domain, sockType, protocol, inheritable)
  165. if fd.SocketHandle == osInvalidSocket:
  166. raiseOSError(osLastError())
  167. result = newAsyncSocket(fd, domain, sockType, protocol, buffered, inheritable)
  168. proc getLocalAddr*(socket: AsyncSocket): (string, Port) =
  169. ## Get the socket's local address and port number.
  170. ##
  171. ## This is high-level interface for `getsockname`:idx:.
  172. getLocalAddr(socket.fd, socket.domain)
  173. when not useNimNetLite:
  174. proc getPeerAddr*(socket: AsyncSocket): (string, Port) =
  175. ## Get the socket's peer address and port number.
  176. ##
  177. ## This is high-level interface for `getpeername`:idx:.
  178. getPeerAddr(socket.fd, socket.domain)
  179. proc newAsyncSocket*(domain, sockType, protocol: cint,
  180. buffered = true,
  181. inheritable = defined(nimInheritHandles)): owned(AsyncSocket) =
  182. ## Creates a new asynchronous socket.
  183. ##
  184. ## This procedure will also create a brand new file descriptor for
  185. ## this socket.
  186. ##
  187. ## If `inheritable` is false (the default), the new file descriptor will not
  188. ## be inheritable by child processes.
  189. let fd = createAsyncNativeSocket(domain, sockType, protocol, inheritable)
  190. if fd.SocketHandle == osInvalidSocket:
  191. raiseOSError(osLastError())
  192. result = newAsyncSocket(fd, Domain(domain), SockType(sockType),
  193. Protocol(protocol), buffered, inheritable)
  194. when defineSsl:
  195. proc getSslError(socket: AsyncSocket, err: cint): cint =
  196. assert socket.isSsl
  197. assert err < 0
  198. var ret = SSL_get_error(socket.sslHandle, err.cint)
  199. case ret
  200. of SSL_ERROR_ZERO_RETURN:
  201. raiseSSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
  202. of SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT:
  203. return ret
  204. of SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_READ:
  205. return ret
  206. of SSL_ERROR_WANT_X509_LOOKUP:
  207. raiseSSLError("Function for x509 lookup has been called.")
  208. of SSL_ERROR_SYSCALL, SSL_ERROR_SSL:
  209. socket.sslNoShutdown = true
  210. raiseSSLError()
  211. else: raiseSSLError("Unknown Error")
  212. proc sendPendingSslData(socket: AsyncSocket,
  213. flags: set[SocketFlag]) {.async.} =
  214. let len = bioCtrlPending(socket.bioOut)
  215. if len > 0:
  216. var data = newString(len)
  217. let read = bioRead(socket.bioOut, cast[cstring](addr data[0]), len)
  218. assert read != 0
  219. if read < 0:
  220. raiseSSLError()
  221. data.setLen(read)
  222. await socket.fd.AsyncFD.send(data, flags)
  223. proc appeaseSsl(socket: AsyncSocket, flags: set[SocketFlag],
  224. sslError: cint): owned(Future[bool]) {.async.} =
  225. ## Returns `true` if `socket` is still connected, otherwise `false`.
  226. result = true
  227. case sslError
  228. of SSL_ERROR_WANT_WRITE:
  229. await sendPendingSslData(socket, flags)
  230. of SSL_ERROR_WANT_READ:
  231. var data = await recv(socket.fd.AsyncFD, BufferSize, flags)
  232. let length = len(data)
  233. if length > 0:
  234. let ret = bioWrite(socket.bioIn, cast[cstring](addr data[0]), length.cint)
  235. if ret < 0:
  236. raiseSSLError()
  237. elif length == 0:
  238. # connection not properly closed by remote side or connection dropped
  239. SSL_set_shutdown(socket.sslHandle, SSL_RECEIVED_SHUTDOWN)
  240. result = false
  241. else:
  242. raiseSSLError("Cannot appease SSL.")
  243. template sslLoop(socket: AsyncSocket, flags: set[SocketFlag],
  244. op: untyped) =
  245. var opResult {.inject.} = -1.cint
  246. while opResult < 0:
  247. ErrClearError()
  248. # Call the desired operation.
  249. opResult = op
  250. # Send any remaining pending SSL data.
  251. await sendPendingSslData(socket, flags)
  252. # If the operation failed, try to see if SSL has some data to read
  253. # or write.
  254. if opResult < 0:
  255. let err = getSslError(socket, opResult.cint)
  256. let fut = appeaseSsl(socket, flags, err.cint)
  257. yield fut
  258. if not fut.read():
  259. # Socket disconnected.
  260. if SocketFlag.SafeDisconn in flags:
  261. opResult = 0.cint
  262. break
  263. else:
  264. raiseSSLError("Socket has been disconnected")
  265. proc dial*(address: string, port: Port, protocol = IPPROTO_TCP,
  266. buffered = true): owned(Future[AsyncSocket]) {.async.} =
  267. ## Establishes connection to the specified `address`:`port` pair via the
  268. ## specified protocol. The procedure iterates through possible
  269. ## resolutions of the `address` until it succeeds, meaning that it
  270. ## seamlessly works with both IPv4 and IPv6.
  271. ## Returns AsyncSocket ready to send or receive data.
  272. let asyncFd = await asyncdispatch.dial(address, port, protocol)
  273. let sockType = protocol.toSockType()
  274. let domain = getSockDomain(asyncFd.SocketHandle)
  275. result = newAsyncSocket(asyncFd, domain, sockType, protocol, buffered)
  276. proc connect*(socket: AsyncSocket, address: string, port: Port) {.async.} =
  277. ## Connects `socket` to server at `address:port`.
  278. ##
  279. ## Returns a `Future` which will complete when the connection succeeds
  280. ## or an error occurs.
  281. await connect(socket.fd.AsyncFD, address, port, socket.domain)
  282. if socket.isSsl:
  283. when defineSsl:
  284. if not isIpAddress(address):
  285. # Set the SNI address for this connection. This call can fail if
  286. # we're not using TLSv1+.
  287. discard SSL_set_tlsext_host_name(socket.sslHandle, address)
  288. let flags = {SocketFlag.SafeDisconn}
  289. sslSetConnectState(socket.sslHandle)
  290. sslLoop(socket, flags, sslDoHandshake(socket.sslHandle))
  291. template readInto(buf: pointer, size: int, socket: AsyncSocket,
  292. flags: set[SocketFlag]): int =
  293. ## Reads **up to** `size` bytes from `socket` into `buf`. Note that
  294. ## this is a template and not a proc.
  295. assert(not socket.closed, "Cannot `recv` on a closed socket")
  296. var res = 0
  297. if socket.isSsl:
  298. when defineSsl:
  299. # SSL mode.
  300. sslLoop(socket, flags,
  301. sslRead(socket.sslHandle, cast[cstring](buf), size.cint))
  302. res = opResult
  303. else:
  304. # Not in SSL mode.
  305. res = await asyncdispatch.recvInto(socket.fd.AsyncFD, buf, size, flags)
  306. res
  307. template readIntoBuf(socket: AsyncSocket,
  308. flags: set[SocketFlag]): int =
  309. var size = readInto(addr socket.buffer[0], BufferSize, socket, flags)
  310. socket.currPos = 0
  311. socket.bufLen = size
  312. size
  313. proc recvInto*(socket: AsyncSocket, buf: pointer, size: int,
  314. flags = {SocketFlag.SafeDisconn}): owned(Future[int]) {.async.} =
  315. ## Reads **up to** `size` bytes from `socket` into `buf`.
  316. ##
  317. ## For buffered sockets this function will attempt to read all the requested
  318. ## data. It will read this data in `BufferSize` chunks.
  319. ##
  320. ## For unbuffered sockets this function makes no effort to read
  321. ## all the data requested. It will return as much data as the operating system
  322. ## gives it.
  323. ##
  324. ## If socket is disconnected during the
  325. ## recv operation then the future may complete with only a part of the
  326. ## requested data.
  327. ##
  328. ## If socket is disconnected and no data is available
  329. ## to be read then the future will complete with a value of `0`.
  330. if socket.isBuffered:
  331. let originalBufPos = socket.currPos
  332. if socket.bufLen == 0:
  333. let res = socket.readIntoBuf(flags - {SocketFlag.Peek})
  334. if res == 0:
  335. return 0
  336. var read = 0
  337. var cbuf = cast[cstring](buf)
  338. while read < size:
  339. if socket.currPos >= socket.bufLen:
  340. if SocketFlag.Peek in flags:
  341. # We don't want to get another buffer if we're peeking.
  342. break
  343. let res = socket.readIntoBuf(flags - {SocketFlag.Peek})
  344. if res == 0:
  345. break
  346. let chunk = min(socket.bufLen-socket.currPos, size-read)
  347. copyMem(addr(cbuf[read]), addr(socket.buffer[socket.currPos]), chunk)
  348. read.inc(chunk)
  349. socket.currPos.inc(chunk)
  350. if SocketFlag.Peek in flags:
  351. # Restore old buffer cursor position.
  352. socket.currPos = originalBufPos
  353. result = read
  354. else:
  355. result = readInto(buf, size, socket, flags)
  356. proc recv*(socket: AsyncSocket, size: int,
  357. flags = {SocketFlag.SafeDisconn}): owned(Future[string]) {.async.} =
  358. ## Reads **up to** `size` bytes from `socket`.
  359. ##
  360. ## For buffered sockets this function will attempt to read all the requested
  361. ## data. It will read this data in `BufferSize` chunks.
  362. ##
  363. ## For unbuffered sockets this function makes no effort to read
  364. ## all the data requested. It will return as much data as the operating system
  365. ## gives it.
  366. ##
  367. ## If socket is disconnected during the
  368. ## recv operation then the future may complete with only a part of the
  369. ## requested data.
  370. ##
  371. ## If socket is disconnected and no data is available
  372. ## to be read then the future will complete with a value of `""`.
  373. if socket.isBuffered:
  374. result = newString(size)
  375. when not defined(nimSeqsV2):
  376. shallow(result)
  377. let originalBufPos = socket.currPos
  378. if socket.bufLen == 0:
  379. let res = socket.readIntoBuf(flags - {SocketFlag.Peek})
  380. if res == 0:
  381. result.setLen(0)
  382. return
  383. var read = 0
  384. while read < size:
  385. if socket.currPos >= socket.bufLen:
  386. if SocketFlag.Peek in flags:
  387. # We don't want to get another buffer if we're peeking.
  388. break
  389. let res = socket.readIntoBuf(flags - {SocketFlag.Peek})
  390. if res == 0:
  391. break
  392. let chunk = min(socket.bufLen-socket.currPos, size-read)
  393. copyMem(addr(result[read]), addr(socket.buffer[socket.currPos]), chunk)
  394. read.inc(chunk)
  395. socket.currPos.inc(chunk)
  396. if SocketFlag.Peek in flags:
  397. # Restore old buffer cursor position.
  398. socket.currPos = originalBufPos
  399. result.setLen(read)
  400. else:
  401. result = newString(size)
  402. let read = readInto(addr result[0], size, socket, flags)
  403. result.setLen(read)
  404. proc send*(socket: AsyncSocket, buf: pointer, size: int,
  405. flags = {SocketFlag.SafeDisconn}) {.async.} =
  406. ## Sends `size` bytes from `buf` to `socket`. The returned future will complete once all
  407. ## data has been sent.
  408. assert socket != nil
  409. assert(not socket.closed, "Cannot `send` on a closed socket")
  410. if socket.isSsl:
  411. when defineSsl:
  412. sslLoop(socket, flags,
  413. sslWrite(socket.sslHandle, cast[cstring](buf), size.cint))
  414. await sendPendingSslData(socket, flags)
  415. else:
  416. await send(socket.fd.AsyncFD, buf, size, flags)
  417. proc send*(socket: AsyncSocket, data: string,
  418. flags = {SocketFlag.SafeDisconn}) {.async.} =
  419. ## Sends `data` to `socket`. The returned future will complete once all
  420. ## data has been sent.
  421. assert socket != nil
  422. if socket.isSsl:
  423. when defineSsl:
  424. var copy = data
  425. sslLoop(socket, flags,
  426. sslWrite(socket.sslHandle, cast[cstring](addr copy[0]), copy.len.cint))
  427. await sendPendingSslData(socket, flags)
  428. else:
  429. await send(socket.fd.AsyncFD, data, flags)
  430. proc acceptAddr*(socket: AsyncSocket, flags = {SocketFlag.SafeDisconn},
  431. inheritable = defined(nimInheritHandles)):
  432. owned(Future[tuple[address: string, client: AsyncSocket]]) =
  433. ## Accepts a new connection. Returns a future containing the client socket
  434. ## corresponding to that connection and the remote address of the client.
  435. ##
  436. ## If `inheritable` is false (the default), the resulting client socket will
  437. ## not be inheritable by child processes.
  438. ##
  439. ## The future will complete when the connection is successfully accepted.
  440. var retFuture = newFuture[tuple[address: string, client: AsyncSocket]]("asyncnet.acceptAddr")
  441. var fut = acceptAddr(socket.fd.AsyncFD, flags, inheritable)
  442. fut.callback =
  443. proc (future: Future[tuple[address: string, client: AsyncFD]]) =
  444. assert future.finished
  445. if future.failed:
  446. retFuture.fail(future.readError)
  447. else:
  448. let resultTup = (future.read.address,
  449. newAsyncSocket(future.read.client, socket.domain,
  450. socket.sockType, socket.protocol, socket.isBuffered, inheritable))
  451. retFuture.complete(resultTup)
  452. return retFuture
  453. proc accept*(socket: AsyncSocket,
  454. flags = {SocketFlag.SafeDisconn}): owned(Future[AsyncSocket]) =
  455. ## Accepts a new connection. Returns a future containing the client socket
  456. ## corresponding to that connection.
  457. ## If `inheritable` is false (the default), the resulting client socket will
  458. ## not be inheritable by child processes.
  459. ## The future will complete when the connection is successfully accepted.
  460. var retFut = newFuture[AsyncSocket]("asyncnet.accept")
  461. var fut = acceptAddr(socket, flags)
  462. fut.callback =
  463. proc (future: Future[tuple[address: string, client: AsyncSocket]]) =
  464. assert future.finished
  465. if future.failed:
  466. retFut.fail(future.readError)
  467. else:
  468. retFut.complete(future.read.client)
  469. return retFut
  470. proc recvLineInto*(socket: AsyncSocket, resString: FutureVar[string],
  471. flags = {SocketFlag.SafeDisconn}, maxLength = MaxLineLength) {.async.} =
  472. ## Reads a line of data from `socket` into `resString`.
  473. ##
  474. ## If a full line is read `\r\L` is not
  475. ## added to `line`, however if solely `\r\L` is read then `line`
  476. ## will be set to it.
  477. ##
  478. ## If the socket is disconnected, `line` will be set to `""`.
  479. ##
  480. ## If the socket is disconnected in the middle of a line (before `\r\L`
  481. ## is read) then line will be set to `""`.
  482. ## The partial line **will be lost**.
  483. ##
  484. ## The `maxLength` parameter determines the maximum amount of characters
  485. ## that can be read. `resString` will be truncated after that.
  486. ##
  487. ## .. warning:: The `Peek` flag is not yet implemented.
  488. ##
  489. ## .. warning:: `recvLineInto` on unbuffered sockets assumes that the protocol uses `\r\L` to delimit a new line.
  490. assert SocketFlag.Peek notin flags ## TODO:
  491. result = newFuture[void]("asyncnet.recvLineInto")
  492. # TODO: Make the async transformation check for FutureVar params and complete
  493. # them when the result future is completed.
  494. # Can we replace the result future with the FutureVar?
  495. template addNLIfEmpty(): untyped =
  496. if resString.mget.len == 0:
  497. resString.mget.add("\c\L")
  498. if socket.isBuffered:
  499. if socket.bufLen == 0:
  500. let res = socket.readIntoBuf(flags)
  501. if res == 0:
  502. resString.complete()
  503. return
  504. var lastR = false
  505. while true:
  506. if socket.currPos >= socket.bufLen:
  507. let res = socket.readIntoBuf(flags)
  508. if res == 0:
  509. resString.mget.setLen(0)
  510. resString.complete()
  511. return
  512. case socket.buffer[socket.currPos]
  513. of '\r':
  514. lastR = true
  515. addNLIfEmpty()
  516. of '\L':
  517. addNLIfEmpty()
  518. socket.currPos.inc()
  519. resString.complete()
  520. return
  521. else:
  522. if lastR:
  523. socket.currPos.inc()
  524. resString.complete()
  525. return
  526. else:
  527. resString.mget.add socket.buffer[socket.currPos]
  528. socket.currPos.inc()
  529. # Verify that this isn't a DOS attack: #3847.
  530. if resString.mget.len > maxLength: break
  531. else:
  532. var c = ""
  533. while true:
  534. c = await recv(socket, 1, flags)
  535. if c.len == 0:
  536. resString.mget.setLen(0)
  537. resString.complete()
  538. return
  539. if c == "\r":
  540. c = await recv(socket, 1, flags) # Skip \L
  541. assert c == "\L"
  542. addNLIfEmpty()
  543. resString.complete()
  544. return
  545. elif c == "\L":
  546. addNLIfEmpty()
  547. resString.complete()
  548. return
  549. resString.mget.add c
  550. # Verify that this isn't a DOS attack: #3847.
  551. if resString.mget.len > maxLength: break
  552. resString.complete()
  553. proc recvLine*(socket: AsyncSocket,
  554. flags = {SocketFlag.SafeDisconn},
  555. maxLength = MaxLineLength): owned(Future[string]) {.async.} =
  556. ## Reads a line of data from `socket`. Returned future will complete once
  557. ## a full line is read or an error occurs.
  558. ##
  559. ## If a full line is read `\r\L` is not
  560. ## added to `line`, however if solely `\r\L` is read then `line`
  561. ## will be set to it.
  562. ##
  563. ## If the socket is disconnected, `line` will be set to `""`.
  564. ##
  565. ## If the socket is disconnected in the middle of a line (before `\r\L`
  566. ## is read) then line will be set to `""`.
  567. ## The partial line **will be lost**.
  568. ##
  569. ## The `maxLength` parameter determines the maximum amount of characters
  570. ## that can be read. The result is truncated after that.
  571. ##
  572. ## .. warning:: The `Peek` flag is not yet implemented.
  573. ##
  574. ## .. warning:: `recvLine` on unbuffered sockets assumes that the protocol uses `\r\L` to delimit a new line.
  575. assert SocketFlag.Peek notin flags ## TODO:
  576. # TODO: Optimise this
  577. var resString = newFutureVar[string]("asyncnet.recvLine")
  578. resString.mget() = ""
  579. await socket.recvLineInto(resString, flags, maxLength)
  580. result = resString.mget()
  581. proc listen*(socket: AsyncSocket, backlog = SOMAXCONN) {.tags: [
  582. ReadIOEffect].} =
  583. ## Marks `socket` as accepting connections.
  584. ## `Backlog` specifies the maximum length of the
  585. ## queue of pending connections.
  586. ##
  587. ## Raises an OSError error upon failure.
  588. if listen(socket.fd, backlog) < 0'i32: raiseOSError(osLastError())
  589. proc bindAddr*(socket: AsyncSocket, port = Port(0), address = "") {.
  590. tags: [ReadIOEffect].} =
  591. ## Binds `address`:`port` to the socket.
  592. ##
  593. ## If `address` is "" then ADDR_ANY will be bound.
  594. var realaddr = address
  595. if realaddr == "":
  596. case socket.domain
  597. of AF_INET6: realaddr = "::"
  598. of AF_INET: realaddr = "0.0.0.0"
  599. else:
  600. raise newException(ValueError,
  601. "Unknown socket address family and no address specified to bindAddr")
  602. var aiList = getAddrInfo(realaddr, port, socket.domain)
  603. if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
  604. freeAddrInfo(aiList)
  605. raiseOSError(osLastError())
  606. freeAddrInfo(aiList)
  607. proc hasDataBuffered*(s: AsyncSocket): bool {.since: (1, 5).} =
  608. ## Determines whether an AsyncSocket has data buffered.
  609. # xxx dedup with std/net
  610. s.isBuffered and s.bufLen > 0 and s.currPos != s.bufLen
  611. when defined(posix) and not useNimNetLite:
  612. proc connectUnix*(socket: AsyncSocket, path: string): owned(Future[void]) =
  613. ## Binds Unix socket to `path`.
  614. ## This only works on Unix-style systems: Mac OS X, BSD and Linux
  615. when not defined(nimdoc):
  616. let retFuture = newFuture[void]("connectUnix")
  617. result = retFuture
  618. proc cb(fd: AsyncFD): bool =
  619. let ret = SocketHandle(fd).getSockOptInt(cint(SOL_SOCKET), cint(SO_ERROR))
  620. if ret == 0:
  621. retFuture.complete()
  622. return true
  623. elif ret == EINTR:
  624. return false
  625. else:
  626. retFuture.fail(newException(OSError, osErrorMsg(OSErrorCode(ret))))
  627. return true
  628. var socketAddr = makeUnixAddr(path)
  629. let ret = socket.fd.connect(cast[ptr SockAddr](addr socketAddr),
  630. (sizeof(socketAddr.sun_family) + path.len).SockLen)
  631. if ret == 0:
  632. # Request to connect completed immediately.
  633. retFuture.complete()
  634. else:
  635. let lastError = osLastError()
  636. if lastError.int32 == EINTR or lastError.int32 == EINPROGRESS:
  637. addWrite(AsyncFD(socket.fd), cb)
  638. else:
  639. retFuture.fail(newException(OSError, osErrorMsg(lastError)))
  640. proc bindUnix*(socket: AsyncSocket, path: string) {.
  641. tags: [ReadIOEffect].} =
  642. ## Binds Unix socket to `path`.
  643. ## This only works on Unix-style systems: Mac OS X, BSD and Linux
  644. when not defined(nimdoc):
  645. var socketAddr = makeUnixAddr(path)
  646. if socket.fd.bindAddr(cast[ptr SockAddr](addr socketAddr),
  647. (sizeof(socketAddr.sun_family) + path.len).SockLen) != 0'i32:
  648. raiseOSError(osLastError())
  649. elif defined(nimdoc):
  650. proc connectUnix*(socket: AsyncSocket, path: string): owned(Future[void]) =
  651. ## Binds Unix socket to `path`.
  652. ## This only works on Unix-style systems: Mac OS X, BSD and Linux
  653. discard
  654. proc bindUnix*(socket: AsyncSocket, path: string) =
  655. ## Binds Unix socket to `path`.
  656. ## This only works on Unix-style systems: Mac OS X, BSD and Linux
  657. discard
  658. proc close*(socket: AsyncSocket) =
  659. ## Closes the socket.
  660. if socket.closed: return
  661. defer:
  662. socket.fd.AsyncFD.closeSocket()
  663. socket.closed = true # TODO: Add extra debugging checks for this.
  664. when defineSsl:
  665. if socket.isSsl:
  666. let res =
  667. # Don't call SSL_shutdown if the connection has not been fully
  668. # established, see:
  669. # https://github.com/openssl/openssl/issues/710#issuecomment-253897666
  670. if not socket.sslNoShutdown and SSL_in_init(socket.sslHandle) == 0:
  671. ErrClearError()
  672. SSL_shutdown(socket.sslHandle)
  673. else:
  674. 0
  675. SSL_free(socket.sslHandle)
  676. if res == 0:
  677. discard
  678. elif res != 1:
  679. raiseSSLError()
  680. when defineSsl:
  681. proc sslHandle*(self: AsyncSocket): SslPtr =
  682. ## Retrieve the ssl pointer of `socket`.
  683. ## Useful for interfacing with `openssl`.
  684. self.sslHandle
  685. proc wrapSocket*(ctx: SslContext, socket: AsyncSocket) =
  686. ## Wraps a socket in an SSL context. This function effectively turns
  687. ## `socket` into an SSL socket.
  688. ##
  689. ## **Disclaimer**: This code is not well tested, may be very unsafe and
  690. ## prone to security vulnerabilities.
  691. socket.isSsl = true
  692. socket.sslContext = ctx
  693. socket.sslHandle = SSL_new(socket.sslContext.context)
  694. if socket.sslHandle == nil:
  695. raiseSSLError()
  696. socket.bioIn = bioNew(bioSMem())
  697. socket.bioOut = bioNew(bioSMem())
  698. sslSetBio(socket.sslHandle, socket.bioIn, socket.bioOut)
  699. socket.sslNoShutdown = true
  700. proc wrapConnectedSocket*(ctx: SslContext, socket: AsyncSocket,
  701. handshake: SslHandshakeType,
  702. hostname: string = "") =
  703. ## Wraps a connected socket in an SSL context. This function effectively
  704. ## turns `socket` into an SSL socket.
  705. ## `hostname` should be specified so that the client knows which hostname
  706. ## the server certificate should be validated against.
  707. ##
  708. ## This should be called on a connected socket, and will perform
  709. ## an SSL handshake immediately.
  710. ##
  711. ## **Disclaimer**: This code is not well tested, may be very unsafe and
  712. ## prone to security vulnerabilities.
  713. wrapSocket(ctx, socket)
  714. case handshake
  715. of handshakeAsClient:
  716. if hostname.len > 0 and not isIpAddress(hostname):
  717. # Set the SNI address for this connection. This call can fail if
  718. # we're not using TLSv1+.
  719. discard SSL_set_tlsext_host_name(socket.sslHandle, hostname)
  720. sslSetConnectState(socket.sslHandle)
  721. of handshakeAsServer:
  722. sslSetAcceptState(socket.sslHandle)
  723. proc getPeerCertificates*(socket: AsyncSocket): seq[Certificate] {.since: (1, 1).} =
  724. ## Returns the certificate chain received by the peer we are connected to
  725. ## through the given socket.
  726. ## The handshake must have been completed and the certificate chain must
  727. ## have been verified successfully or else an empty sequence is returned.
  728. ## The chain is ordered from leaf certificate to root certificate.
  729. if not socket.isSsl:
  730. result = newSeq[Certificate]()
  731. else:
  732. result = getPeerCertificates(socket.sslHandle)
  733. proc getSockOpt*(socket: AsyncSocket, opt: SOBool, level = SOL_SOCKET): bool {.
  734. tags: [ReadIOEffect].} =
  735. ## Retrieves option `opt` as a boolean value.
  736. var res = getSockOptInt(socket.fd, cint(level), toCInt(opt))
  737. result = res != 0
  738. proc setSockOpt*(socket: AsyncSocket, opt: SOBool, value: bool,
  739. level = SOL_SOCKET) {.tags: [WriteIOEffect].} =
  740. ## Sets option `opt` to a boolean value specified by `value`.
  741. var valuei = cint(if value: 1 else: 0)
  742. setSockOptInt(socket.fd, cint(level), toCInt(opt), valuei)
  743. proc isSsl*(socket: AsyncSocket): bool =
  744. ## Determines whether `socket` is a SSL socket.
  745. socket.isSsl
  746. proc getFd*(socket: AsyncSocket): SocketHandle =
  747. ## Returns the socket's file descriptor.
  748. return socket.fd
  749. proc isClosed*(socket: AsyncSocket): bool =
  750. ## Determines whether the socket has been closed.
  751. return socket.closed
  752. proc sendTo*(socket: AsyncSocket, address: string, port: Port, data: string,
  753. flags = {SocketFlag.SafeDisconn}): owned(Future[void])
  754. {.async, since: (1, 3).} =
  755. ## This proc sends `data` to the specified `address`, which may be an IP
  756. ## address or a hostname. If a hostname is specified this function will try
  757. ## each IP of that hostname. The returned future will complete once all data
  758. ## has been sent.
  759. ##
  760. ## If an error occurs an OSError exception will be raised.
  761. ##
  762. ## This proc is normally used with connectionless sockets (UDP sockets).
  763. assert(socket.protocol != IPPROTO_TCP,
  764. "Cannot `sendTo` on a TCP socket. Use `send` instead")
  765. assert(not socket.closed, "Cannot `sendTo` on a closed socket")
  766. let aiList = getAddrInfo(address, port, socket.domain, socket.sockType,
  767. socket.protocol)
  768. var
  769. it = aiList
  770. success = false
  771. lastException: ref Exception
  772. while it != nil:
  773. let fut = sendTo(socket.fd.AsyncFD, cstring(data), len(data), it.ai_addr,
  774. it.ai_addrlen.SockLen, flags)
  775. yield fut
  776. if not fut.failed:
  777. success = true
  778. break
  779. lastException = fut.readError()
  780. it = it.ai_next
  781. freeAddrInfo(aiList)
  782. if not success:
  783. if lastException != nil:
  784. raise lastException
  785. else:
  786. raise newException(IOError, "Couldn't resolve address: " & address)
  787. proc recvFrom*(socket: AsyncSocket, data: FutureVar[string], size: int,
  788. address: FutureVar[string], port: FutureVar[Port],
  789. flags = {SocketFlag.SafeDisconn}): owned(Future[int])
  790. {.async, since: (1, 3).} =
  791. ## Receives a datagram data from `socket` into `data`, which must be at
  792. ## least of size `size`. The address and port of datagram's sender will be
  793. ## stored into `address` and `port`, respectively. Returned future will
  794. ## complete once one datagram has been received, and will return size of
  795. ## packet received.
  796. ##
  797. ## If an error occurs an OSError exception will be raised.
  798. ##
  799. ## This proc is normally used with connectionless sockets (UDP sockets).
  800. ##
  801. ## **Notes**
  802. ## * `data` must be initialized to the length of `size`.
  803. ## * `address` must be initialized to 46 in length.
  804. template adaptRecvFromToDomain(domain: Domain) =
  805. var lAddr = sizeof(sAddr).SockLen
  806. result = await recvFromInto(AsyncFD(getFd(socket)), cstring(data.mget()), size,
  807. cast[ptr SockAddr](addr sAddr), addr lAddr,
  808. flags)
  809. data.mget().setLen(result)
  810. data.complete()
  811. getAddrString(cast[ptr SockAddr](addr sAddr), address.mget())
  812. address.complete()
  813. when domain == AF_INET6:
  814. port.complete(ntohs(sAddr.sin6_port).Port)
  815. else:
  816. port.complete(ntohs(sAddr.sin_port).Port)
  817. assert(socket.protocol != IPPROTO_TCP,
  818. "Cannot `recvFrom` on a TCP socket. Use `recv` or `recvInto` instead")
  819. assert(not socket.closed, "Cannot `recvFrom` on a closed socket")
  820. assert(size == len(data.mget()),
  821. "`date` was not initialized correctly. `size` != `len(data.mget())`")
  822. assert(46 == len(address.mget()),
  823. "`address` was not initialized correctly. 46 != `len(address.mget())`")
  824. case socket.domain
  825. of AF_INET6:
  826. var sAddr: Sockaddr_in6
  827. adaptRecvFromToDomain(AF_INET6)
  828. of AF_INET:
  829. var sAddr: Sockaddr_in
  830. adaptRecvFromToDomain(AF_INET)
  831. else:
  832. raise newException(ValueError, "Unknown socket address family")
  833. proc recvFrom*(socket: AsyncSocket, size: int,
  834. flags = {SocketFlag.SafeDisconn}):
  835. owned(Future[tuple[data: string, address: string, port: Port]])
  836. {.async, since: (1, 3).} =
  837. ## Receives a datagram data from `socket`, which must be at least of size
  838. ## `size`. Returned future will complete once one datagram has been received
  839. ## and will return tuple with: data of packet received; and address and port
  840. ## of datagram's sender.
  841. ##
  842. ## If an error occurs an OSError exception will be raised.
  843. ##
  844. ## This proc is normally used with connectionless sockets (UDP sockets).
  845. var
  846. data = newFutureVar[string]()
  847. address = newFutureVar[string]()
  848. port = newFutureVar[Port]()
  849. data.mget().setLen(size)
  850. address.mget().setLen(46)
  851. let read = await recvFrom(socket, data, size, address, port, flags)
  852. result = (data.mget(), address.mget(), port.mget())
  853. when not defined(testing) and isMainModule:
  854. type
  855. TestCases = enum
  856. HighClient, LowClient, LowServer
  857. const test = HighClient
  858. when test == HighClient:
  859. proc main() {.async.} =
  860. var sock = newAsyncSocket()
  861. await sock.connect("irc.freenode.net", Port(6667))
  862. while true:
  863. let line = await sock.recvLine()
  864. if line == "":
  865. echo("Disconnected")
  866. break
  867. else:
  868. echo("Got line: ", line)
  869. asyncCheck main()
  870. elif test == LowClient:
  871. var sock = newAsyncSocket()
  872. var f = connect(sock, "irc.freenode.net", Port(6667))
  873. f.callback =
  874. proc (future: Future[void]) =
  875. echo("Connected in future!")
  876. for i in 0 .. 50:
  877. var recvF = recv(sock, 10)
  878. recvF.callback =
  879. proc (future: Future[string]) =
  880. echo("Read ", future.read.len, ": ", future.read.repr)
  881. elif test == LowServer:
  882. var sock = newAsyncSocket()
  883. sock.bindAddr(Port(6667))
  884. sock.listen()
  885. proc onAccept(future: Future[AsyncSocket]) =
  886. let client = future.read
  887. echo "Accepted ", client.fd.cint
  888. var t = send(client, "test\c\L")
  889. t.callback =
  890. proc (future: Future[void]) =
  891. echo("Send")
  892. client.close()
  893. var f = accept(sock)
  894. f.callback = onAccept
  895. var f = accept(sock)
  896. f.callback = onAccept
  897. runForever()