2018-05-16 08:22:34 +00:00
|
|
|
#
|
|
|
|
# Asyncdispatch2 Stream Transport
|
|
|
|
# (c) Copyright 2018
|
|
|
|
# Status Research & Development GmbH
|
|
|
|
#
|
|
|
|
# Licensed under either of
|
|
|
|
# Apache License, version 2.0, (LICENSE-APACHEv2)
|
|
|
|
# MIT license (LICENSE-MIT)
|
|
|
|
|
2018-06-05 22:48:03 +00:00
|
|
|
import net, nativesockets, os, deques
|
|
|
|
import ../asyncloop, ../handles, ../sendfile
|
2018-05-16 08:22:34 +00:00
|
|
|
import common
|
|
|
|
|
|
|
|
when defined(windows):
|
|
|
|
import winlean
|
|
|
|
else:
|
|
|
|
import posix
|
|
|
|
|
|
|
|
type
|
2018-05-21 21:52:57 +00:00
|
|
|
VectorKind = enum
|
2018-05-22 21:03:13 +00:00
|
|
|
DataBuffer, # Simple buffer pointer/length
|
|
|
|
DataFile # File handle for sendfile/TransmitFile
|
2018-05-21 21:52:57 +00:00
|
|
|
|
|
|
|
StreamVector = object
|
2018-05-22 21:03:13 +00:00
|
|
|
kind: VectorKind # Writer vector source kind
|
|
|
|
buf: pointer # Writer buffer pointer
|
|
|
|
buflen: int # Writer buffer size
|
|
|
|
offset: uint # Writer vector offset
|
2018-06-05 20:21:07 +00:00
|
|
|
writer: Future[int] # Writer vector completion Future
|
2018-05-21 21:52:57 +00:00
|
|
|
|
2018-05-16 08:22:34 +00:00
|
|
|
TransportKind* {.pure.} = enum
|
2018-05-22 21:03:13 +00:00
|
|
|
Socket, # Socket transport
|
|
|
|
Pipe, # Pipe transport
|
|
|
|
File # File transport
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-10 23:08:17 +00:00
|
|
|
when defined(windows):
|
|
|
|
const SO_UPDATE_CONNECT_CONTEXT = 0x7010
|
|
|
|
|
|
|
|
type
|
|
|
|
StreamTransport* = ref object of RootRef
|
|
|
|
fd*: AsyncFD # File descriptor
|
|
|
|
state: set[TransportState] # Current Transport state
|
|
|
|
reader: Future[void] # Current reader Future
|
|
|
|
buffer: seq[byte] # Reading buffer
|
|
|
|
offset: int # Reading buffer offset
|
|
|
|
error: ref Exception # Current error
|
|
|
|
queue: Deque[StreamVector] # Writer queue
|
|
|
|
future: Future[void] # Stream life future
|
|
|
|
# Windows specific part
|
|
|
|
rwsabuf: TWSABuf # Reader WSABUF
|
|
|
|
wwsabuf: TWSABuf # Writer WSABUF
|
|
|
|
rovl: CustomOverlapped # Reader OVERLAPPED structure
|
|
|
|
wovl: CustomOverlapped # Writer OVERLAPPED structure
|
|
|
|
roffset: int # Pending reading offset
|
|
|
|
case kind*: TransportKind
|
|
|
|
of TransportKind.Socket:
|
|
|
|
domain: Domain # Socket transport domain (IPv4/IPv6)
|
|
|
|
local: TransportAddress # Local address
|
|
|
|
remote: TransportAddress # Remote address
|
|
|
|
of TransportKind.Pipe:
|
|
|
|
todo1: int
|
|
|
|
of TransportKind.File:
|
|
|
|
todo2: int
|
|
|
|
else:
|
|
|
|
type
|
|
|
|
StreamTransport* = ref object of RootRef
|
|
|
|
fd*: AsyncFD # File descriptor
|
|
|
|
state: set[TransportState] # Current Transport state
|
|
|
|
reader: Future[void] # Current reader Future
|
|
|
|
buffer: seq[byte] # Reading buffer
|
|
|
|
offset: int # Reading buffer offset
|
|
|
|
error: ref Exception # Current error
|
|
|
|
queue: Deque[StreamVector] # Writer queue
|
|
|
|
future: Future[void] # Stream life future
|
|
|
|
case kind*: TransportKind
|
|
|
|
of TransportKind.Socket:
|
|
|
|
domain: Domain # Socket transport domain (IPv4/IPv6)
|
|
|
|
local: TransportAddress # Local address
|
|
|
|
remote: TransportAddress # Remote address
|
|
|
|
of TransportKind.Pipe:
|
|
|
|
todo1: int
|
|
|
|
of TransportKind.File:
|
|
|
|
todo2: int
|
|
|
|
|
2018-05-16 08:22:34 +00:00
|
|
|
type
|
|
|
|
|
2018-05-22 22:29:07 +00:00
|
|
|
StreamCallback* = proc(server: StreamServer,
|
2018-06-06 21:29:37 +00:00
|
|
|
client: StreamTransport): Future[void] {.gcsafe.}
|
2018-05-28 23:35:15 +00:00
|
|
|
## New remote client connection callback
|
|
|
|
## ``server`` - StreamServer object.
|
|
|
|
## ``client`` - accepted client transport.
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-10 23:08:17 +00:00
|
|
|
TransportInitCallback* = proc(server: StreamServer,
|
|
|
|
fd: AsyncFD): StreamTransport {.gcsafe.}
|
|
|
|
## Custom transport initialization procedure, which can allocated inherited
|
|
|
|
## StreamTransport object.
|
|
|
|
|
2018-05-16 08:22:34 +00:00
|
|
|
StreamServer* = ref object of SocketServer
|
2018-06-10 23:08:17 +00:00
|
|
|
## StreamServer object
|
|
|
|
function*: StreamCallback # callback which will be called after new
|
|
|
|
# client accepted
|
|
|
|
init*: TransportInitCallback # callback which will be called before
|
|
|
|
# transport for new client
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc remoteAddress*(transp: StreamTransport): TransportAddress =
|
|
|
|
## Returns ``transp`` remote socket address.
|
|
|
|
if transp.kind != TransportKind.Socket:
|
|
|
|
raise newException(TransportError, "Socket required!")
|
|
|
|
if transp.remote.port == Port(0):
|
|
|
|
var saddr: Sockaddr_storage
|
|
|
|
var slen = SockLen(sizeof(saddr))
|
|
|
|
if getpeername(SocketHandle(transp.fd), cast[ptr SockAddr](addr saddr),
|
|
|
|
addr slen) != 0:
|
2018-06-15 00:28:02 +00:00
|
|
|
raiseTransportOsError(osLastError())
|
2018-05-16 08:22:34 +00:00
|
|
|
fromSockAddr(saddr, slen, transp.remote.address, transp.remote.port)
|
|
|
|
result = transp.remote
|
|
|
|
|
|
|
|
proc localAddress*(transp: StreamTransport): TransportAddress =
|
|
|
|
## Returns ``transp`` local socket address.
|
|
|
|
if transp.kind != TransportKind.Socket:
|
|
|
|
raise newException(TransportError, "Socket required!")
|
|
|
|
if transp.local.port == Port(0):
|
|
|
|
var saddr: Sockaddr_storage
|
|
|
|
var slen = SockLen(sizeof(saddr))
|
|
|
|
if getsockname(SocketHandle(transp.fd), cast[ptr SockAddr](addr saddr),
|
|
|
|
addr slen) != 0:
|
2018-06-15 00:28:02 +00:00
|
|
|
raiseTransportOsError(osLastError())
|
2018-05-16 08:22:34 +00:00
|
|
|
fromSockAddr(saddr, slen, transp.local.address, transp.local.port)
|
|
|
|
result = transp.local
|
|
|
|
|
|
|
|
template setReadError(t, e: untyped) =
|
|
|
|
(t).state.incl(ReadError)
|
|
|
|
(t).error = newException(TransportOsError, osErrorMsg((e)))
|
|
|
|
|
|
|
|
template finishReader(t: untyped) =
|
|
|
|
var reader = (t).reader
|
|
|
|
reader.complete()
|
|
|
|
|
|
|
|
template checkPending(t: untyped) =
|
|
|
|
if not isNil((t).reader):
|
|
|
|
raise newException(TransportError, "Read operation already pending!")
|
|
|
|
|
|
|
|
template shiftBuffer(t, c: untyped) =
|
|
|
|
if (t).offset > c:
|
|
|
|
moveMem(addr((t).buffer[0]), addr((t).buffer[(c)]), (t).offset - (c))
|
|
|
|
(t).offset = (t).offset - (c)
|
|
|
|
else:
|
|
|
|
(t).offset = 0
|
|
|
|
|
2018-05-21 21:52:57 +00:00
|
|
|
template shiftVectorBuffer(v, o: untyped) =
|
|
|
|
(v).buf = cast[pointer](cast[uint]((v).buf) + uint(o))
|
|
|
|
(v).buflen -= int(o)
|
|
|
|
|
|
|
|
template shiftVectorFile(v, o: untyped) =
|
|
|
|
(v).buf = cast[pointer](cast[uint]((v).buf) - cast[uint](o))
|
|
|
|
(v).offset += cast[uint]((o))
|
|
|
|
|
2018-05-16 08:22:34 +00:00
|
|
|
when defined(windows):
|
|
|
|
|
|
|
|
template zeroOvelappedOffset(t: untyped) =
|
|
|
|
(t).offset = 0
|
|
|
|
(t).offsetHigh = 0
|
|
|
|
|
|
|
|
template setOverlappedOffset(t, o: untyped) =
|
|
|
|
(t).offset = cast[int32](cast[uint64](o) and 0xFFFFFFFF'u64)
|
|
|
|
(t).offsetHigh = cast[int32](cast[uint64](o) shr 32)
|
|
|
|
|
2018-05-21 21:52:57 +00:00
|
|
|
template getFileSize(v: untyped): uint =
|
|
|
|
cast[uint]((v).buf)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-05-21 21:52:57 +00:00
|
|
|
template getFileHandle(v: untyped): Handle =
|
|
|
|
cast[Handle]((v).buflen)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
template slideBuffer(t, o: untyped) =
|
2018-05-21 21:52:57 +00:00
|
|
|
(t).wwsabuf.buf = cast[cstring](cast[uint]((t).wwsabuf.buf) + uint(o))
|
|
|
|
(t).wwsabuf.len -= int32(o)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-05-21 21:52:57 +00:00
|
|
|
template setReaderWSABuffer(t: untyped) =
|
|
|
|
(t).rwsabuf.buf = cast[cstring](
|
2018-05-16 08:22:34 +00:00
|
|
|
cast[uint](addr t.buffer[0]) + uint((t).roffset))
|
2018-05-21 21:52:57 +00:00
|
|
|
(t).rwsabuf.len = int32(len((t).buffer) - (t).roffset)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-05-21 21:52:57 +00:00
|
|
|
template setWriterWSABuffer(t, v: untyped) =
|
|
|
|
(t).wwsabuf.buf = cast[cstring](v.buf)
|
|
|
|
(t).wwsabuf.len = cast[int32](v.buflen)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-05-22 16:27:20 +00:00
|
|
|
proc writeStreamLoop(udata: pointer) {.gcsafe, nimcall.} =
|
2018-05-16 08:22:34 +00:00
|
|
|
var bytesCount: int32
|
2018-05-21 21:52:57 +00:00
|
|
|
var ovl = cast[PtrCustomOverlapped](udata)
|
2018-06-10 23:08:17 +00:00
|
|
|
var transp = cast[StreamTransport](ovl.data.udata)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
while len(transp.queue) > 0:
|
|
|
|
if WritePending in transp.state:
|
|
|
|
## Continuation
|
|
|
|
transp.state.excl(WritePending)
|
|
|
|
let err = transp.wovl.data.errCode
|
|
|
|
if err == OSErrorCode(-1):
|
|
|
|
bytesCount = transp.wovl.data.bytesCount
|
|
|
|
var vector = transp.queue.popFirst()
|
|
|
|
if bytesCount == 0:
|
2018-06-05 20:21:07 +00:00
|
|
|
vector.writer.complete(0)
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
if transp.kind == TransportKind.Socket:
|
|
|
|
if vector.kind == VectorKind.DataBuffer:
|
2018-05-21 21:52:57 +00:00
|
|
|
if bytesCount < transp.wwsabuf.len:
|
|
|
|
vector.shiftVectorBuffer(bytesCount)
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.queue.addFirst(vector)
|
|
|
|
else:
|
2018-06-05 20:21:07 +00:00
|
|
|
vector.writer.complete(transp.wwsabuf.len)
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
if uint(bytesCount) < getFileSize(vector):
|
2018-05-21 21:52:57 +00:00
|
|
|
vector.shiftVectorFile(bytesCount)
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.queue.addFirst(vector)
|
|
|
|
else:
|
2018-06-05 20:21:07 +00:00
|
|
|
vector.writer.complete(int(getFileSize(vector)))
|
2018-05-28 23:35:15 +00:00
|
|
|
elif int(err) == ERROR_OPERATION_ABORTED:
|
|
|
|
# CancelIO() interrupt
|
2018-06-05 20:21:07 +00:00
|
|
|
transp.state.incl(WritePaused)
|
|
|
|
let v = transp.queue.popFirst()
|
|
|
|
v.writer.complete(0)
|
|
|
|
break
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
2018-06-05 20:21:07 +00:00
|
|
|
let v = transp.queue.popFirst()
|
|
|
|
transp.state.incl(WriteError)
|
|
|
|
v.writer.fail(newException(TransportOsError, osErrorMsg(err)))
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
## Initiation
|
|
|
|
transp.state.incl(WritePending)
|
|
|
|
if transp.kind == TransportKind.Socket:
|
|
|
|
let sock = SocketHandle(transp.wovl.data.fd)
|
2018-05-16 15:28:23 +00:00
|
|
|
var vector = transp.queue.popFirst()
|
|
|
|
if vector.kind == VectorKind.DataBuffer:
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.wovl.zeroOvelappedOffset()
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.setWriterWSABuffer(vector)
|
|
|
|
let ret = WSASend(sock, addr transp.wwsabuf, 1,
|
2018-05-16 08:22:34 +00:00
|
|
|
addr bytesCount, DWORD(0),
|
|
|
|
cast[POVERLAPPED](addr transp.wovl), nil)
|
|
|
|
if ret != 0:
|
|
|
|
let err = osLastError()
|
2018-05-16 15:28:23 +00:00
|
|
|
if int(err) == ERROR_OPERATION_ABORTED:
|
2018-05-28 23:35:15 +00:00
|
|
|
# CancelIO() interrupt
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.state.excl(WritePending)
|
2018-05-16 15:28:23 +00:00
|
|
|
transp.state.incl(WritePaused)
|
2018-06-05 20:21:07 +00:00
|
|
|
vector.writer.complete(0)
|
2018-05-16 15:28:23 +00:00
|
|
|
elif int(err) == ERROR_IO_PENDING:
|
|
|
|
transp.queue.addFirst(vector)
|
|
|
|
else:
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.state.excl(WritePending)
|
2018-06-05 20:21:07 +00:00
|
|
|
transp.state = transp.state + {WritePaused, WriteError}
|
|
|
|
vector.writer.fail(newException(TransportOsError,
|
|
|
|
osErrorMsg(err)))
|
2018-05-16 15:28:23 +00:00
|
|
|
else:
|
|
|
|
transp.queue.addFirst(vector)
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
let loop = getGlobalDispatcher()
|
|
|
|
var size: int32
|
|
|
|
var flags: int32
|
|
|
|
|
|
|
|
if getFileSize(vector) > 2_147_483_646'u:
|
|
|
|
size = 2_147_483_646
|
|
|
|
else:
|
|
|
|
size = int32(getFileSize(vector))
|
|
|
|
|
|
|
|
transp.wovl.setOverlappedOffset(vector.offset)
|
|
|
|
var ret = loop.transmitFile(sock, getFileHandle(vector), size, 0,
|
|
|
|
cast[POVERLAPPED](addr transp.wovl),
|
|
|
|
nil, flags)
|
|
|
|
if ret == 0:
|
|
|
|
let err = osLastError()
|
2018-05-16 15:28:23 +00:00
|
|
|
if int(err) == ERROR_OPERATION_ABORTED:
|
2018-05-28 23:35:15 +00:00
|
|
|
# CancelIO() interrupt
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.state.excl(WritePending)
|
2018-05-16 15:28:23 +00:00
|
|
|
transp.state.incl(WritePaused)
|
2018-06-05 20:21:07 +00:00
|
|
|
vector.writer.complete(0)
|
2018-05-16 15:28:23 +00:00
|
|
|
elif int(err) == ERROR_IO_PENDING:
|
|
|
|
transp.queue.addFirst(vector)
|
|
|
|
else:
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.state.excl(WritePending)
|
2018-06-05 20:21:07 +00:00
|
|
|
transp.state = transp.state + {WritePaused, WriteError}
|
|
|
|
vector.writer.fail(newException(TransportOsError,
|
|
|
|
osErrorMsg(err)))
|
2018-05-16 15:28:23 +00:00
|
|
|
else:
|
|
|
|
transp.queue.addFirst(vector)
|
2018-05-16 08:22:34 +00:00
|
|
|
break
|
|
|
|
|
|
|
|
if len(transp.queue) == 0:
|
|
|
|
transp.state.incl(WritePaused)
|
|
|
|
|
2018-05-22 16:27:20 +00:00
|
|
|
proc readStreamLoop(udata: pointer) {.gcsafe, nimcall.} =
|
2018-05-21 21:52:57 +00:00
|
|
|
var ovl = cast[PtrCustomOverlapped](udata)
|
2018-06-10 23:08:17 +00:00
|
|
|
var transp = cast[StreamTransport](ovl.data.udata)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
while true:
|
|
|
|
if ReadPending in transp.state:
|
|
|
|
## Continuation
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.state.excl(ReadPending)
|
2018-05-16 08:22:34 +00:00
|
|
|
if ReadClosed in transp.state:
|
|
|
|
break
|
|
|
|
let err = transp.rovl.data.errCode
|
|
|
|
if err == OSErrorCode(-1):
|
|
|
|
let bytesCount = transp.rovl.data.bytesCount
|
|
|
|
if bytesCount == 0:
|
2018-06-14 06:49:59 +00:00
|
|
|
transp.state.incl({ReadEof, ReadPaused})
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
if transp.offset != transp.roffset:
|
|
|
|
moveMem(addr transp.buffer[transp.offset],
|
|
|
|
addr transp.buffer[transp.roffset],
|
|
|
|
bytesCount)
|
|
|
|
transp.offset += bytesCount
|
|
|
|
transp.roffset = transp.offset
|
|
|
|
if transp.offset == len(transp.buffer):
|
|
|
|
transp.state.incl(ReadPaused)
|
2018-05-28 23:35:15 +00:00
|
|
|
elif int(err) == ERROR_OPERATION_ABORTED:
|
|
|
|
# CancelIO() interrupt
|
|
|
|
discard
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
transp.setReadError(err)
|
|
|
|
if not isNil(transp.reader):
|
|
|
|
transp.finishReader()
|
2018-05-21 21:52:57 +00:00
|
|
|
if ReadPaused in transp.state:
|
|
|
|
# Transport buffer is full, so we will not continue on reading.
|
|
|
|
break
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
## Initiation
|
2018-05-21 21:52:57 +00:00
|
|
|
if transp.state * {ReadEof, ReadClosed, ReadError} == {}:
|
2018-05-16 08:22:34 +00:00
|
|
|
var flags = DWORD(0)
|
|
|
|
var bytesCount: int32 = 0
|
|
|
|
transp.state.excl(ReadPaused)
|
|
|
|
transp.state.incl(ReadPending)
|
|
|
|
if transp.kind == TransportKind.Socket:
|
|
|
|
let sock = SocketHandle(transp.rovl.data.fd)
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.roffset = transp.offset
|
|
|
|
transp.setReaderWSABuffer()
|
|
|
|
let ret = WSARecv(sock, addr transp.rwsabuf, 1,
|
2018-05-16 08:22:34 +00:00
|
|
|
addr bytesCount, addr flags,
|
|
|
|
cast[POVERLAPPED](addr transp.rovl), nil)
|
|
|
|
if ret != 0:
|
|
|
|
let err = osLastError()
|
|
|
|
if int(err) == ERROR_OPERATION_ABORTED:
|
2018-05-28 23:35:15 +00:00
|
|
|
# CancelIO() interrupt
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.state.excl(ReadPending)
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.state.incl(ReadPaused)
|
2018-06-04 09:57:17 +00:00
|
|
|
elif int32(err) in {WSAECONNRESET, WSAENETRESET}:
|
|
|
|
if not isNil(transp.reader):
|
|
|
|
transp.state = {ReadEof, ReadPaused}
|
|
|
|
transp.finishReader()
|
2018-05-16 08:22:34 +00:00
|
|
|
elif int32(err) != ERROR_IO_PENDING:
|
2018-06-04 09:57:17 +00:00
|
|
|
transp.state.excl(ReadPending)
|
|
|
|
transp.state.incl(ReadPaused)
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.setReadError(err)
|
|
|
|
if not isNil(transp.reader):
|
|
|
|
transp.finishReader()
|
|
|
|
## Finish Loop
|
|
|
|
break
|
|
|
|
|
2018-06-10 23:08:17 +00:00
|
|
|
proc newStreamSocketTransport(sock: AsyncFD, bufsize: int,
|
|
|
|
child: StreamTransport): StreamTransport =
|
|
|
|
var transp: StreamTransport
|
|
|
|
if not isNil(child):
|
|
|
|
transp = child
|
|
|
|
else:
|
|
|
|
transp = StreamTransport(kind: TransportKind.Socket)
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.fd = sock
|
|
|
|
transp.rovl.data = CompletionData(fd: sock, cb: readStreamLoop,
|
|
|
|
udata: cast[pointer](transp))
|
|
|
|
transp.wovl.data = CompletionData(fd: sock, cb: writeStreamLoop,
|
|
|
|
udata: cast[pointer](transp))
|
|
|
|
transp.buffer = newSeq[byte](bufsize)
|
|
|
|
transp.state = {ReadPaused, WritePaused}
|
|
|
|
transp.queue = initDeque[StreamVector]()
|
|
|
|
transp.future = newFuture[void]("stream.socket.transport")
|
|
|
|
GC_ref(transp)
|
2018-06-10 23:08:17 +00:00
|
|
|
result = transp
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc bindToDomain(handle: AsyncFD, domain: Domain): bool =
|
|
|
|
result = true
|
|
|
|
if domain == Domain.AF_INET6:
|
|
|
|
var saddr: Sockaddr_in6
|
|
|
|
saddr.sin6_family = int16(toInt(domain))
|
|
|
|
if bindAddr(SocketHandle(handle), cast[ptr SockAddr](addr(saddr)),
|
|
|
|
sizeof(saddr).SockLen) != 0'i32:
|
|
|
|
result = false
|
|
|
|
else:
|
|
|
|
var saddr: Sockaddr_in
|
|
|
|
saddr.sin_family = int16(toInt(domain))
|
|
|
|
if bindAddr(SocketHandle(handle), cast[ptr SockAddr](addr(saddr)),
|
|
|
|
sizeof(saddr).SockLen) != 0'i32:
|
|
|
|
result = false
|
|
|
|
|
|
|
|
proc connect*(address: TransportAddress,
|
2018-06-10 23:08:17 +00:00
|
|
|
bufferSize = DefaultStreamBufferSize,
|
|
|
|
child: StreamTransport = nil): Future[StreamTransport] =
|
2018-05-27 05:49:47 +00:00
|
|
|
## Open new connection to remote peer with address ``address`` and create
|
|
|
|
## new transport object ``StreamTransport`` for established connection.
|
2018-05-28 23:35:15 +00:00
|
|
|
## ``bufferSize`` is size of internal buffer for transport.
|
2018-05-16 08:22:34 +00:00
|
|
|
let loop = getGlobalDispatcher()
|
|
|
|
var
|
|
|
|
saddr: Sockaddr_storage
|
|
|
|
slen: SockLen
|
|
|
|
sock: AsyncFD
|
|
|
|
povl: RefCustomOverlapped
|
|
|
|
|
|
|
|
var retFuture = newFuture[StreamTransport]("stream.transport.connect")
|
|
|
|
toSockAddr(address.address, address.port, saddr, slen)
|
|
|
|
sock = createAsyncSocket(address.address.getDomain(), SockType.SOCK_STREAM,
|
|
|
|
Protocol.IPPROTO_TCP)
|
|
|
|
if sock == asyncInvalidSocket:
|
2018-06-05 20:21:07 +00:00
|
|
|
result.fail(newException(TransportOsError, osErrorMsg(osLastError())))
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
if not bindToDomain(sock, address.address.getDomain()):
|
|
|
|
sock.closeAsyncSocket()
|
2018-06-05 20:21:07 +00:00
|
|
|
result.fail(newException(TransportOsError, osErrorMsg(osLastError())))
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc continuation(udata: pointer) =
|
2018-05-22 16:27:20 +00:00
|
|
|
var ovl = cast[RefCustomOverlapped](udata)
|
2018-05-16 08:22:34 +00:00
|
|
|
if not retFuture.finished:
|
|
|
|
if ovl.data.errCode == OSErrorCode(-1):
|
|
|
|
if setsockopt(SocketHandle(sock), cint(SOL_SOCKET),
|
|
|
|
cint(SO_UPDATE_CONNECT_CONTEXT), nil,
|
|
|
|
SockLen(0)) != 0'i32:
|
|
|
|
sock.closeAsyncSocket()
|
2018-06-05 20:21:07 +00:00
|
|
|
retFuture.fail(newException(TransportOsError,
|
|
|
|
osErrorMsg(osLastError())))
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
retFuture.complete(newStreamSocketTransport(povl.data.fd,
|
2018-06-10 23:08:17 +00:00
|
|
|
bufferSize,
|
|
|
|
child))
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
sock.closeAsyncSocket()
|
2018-06-05 20:21:07 +00:00
|
|
|
retFuture.fail(newException(TransportOsError,
|
|
|
|
osErrorMsg(ovl.data.errCode)))
|
2018-05-22 16:27:20 +00:00
|
|
|
GC_unref(ovl)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
povl = RefCustomOverlapped()
|
2018-05-22 16:27:20 +00:00
|
|
|
GC_ref(povl)
|
2018-05-16 08:22:34 +00:00
|
|
|
povl.data = CompletionData(fd: sock, cb: continuation)
|
|
|
|
var res = loop.connectEx(SocketHandle(sock),
|
|
|
|
cast[ptr SockAddr](addr saddr),
|
|
|
|
DWORD(slen), nil, 0, nil,
|
|
|
|
cast[POVERLAPPED](povl))
|
|
|
|
# We will not process immediate completion, to avoid undefined behavior.
|
|
|
|
if not res:
|
|
|
|
let err = osLastError()
|
|
|
|
if int32(err) != ERROR_IO_PENDING:
|
2018-05-22 16:27:20 +00:00
|
|
|
GC_unref(povl)
|
2018-05-16 08:22:34 +00:00
|
|
|
sock.closeAsyncSocket()
|
2018-06-05 20:21:07 +00:00
|
|
|
retFuture.fail(newException(TransportOsError, osErrorMsg(err)))
|
2018-05-16 08:22:34 +00:00
|
|
|
return retFuture
|
|
|
|
|
2018-06-04 09:57:17 +00:00
|
|
|
proc acceptLoop(udata: pointer) {.gcsafe, nimcall.} =
|
|
|
|
var ovl = cast[PtrCustomOverlapped](udata)
|
|
|
|
var server = cast[StreamServer](ovl.data.udata)
|
|
|
|
var loop = getGlobalDispatcher()
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-04 09:57:17 +00:00
|
|
|
while true:
|
|
|
|
if server.apending:
|
|
|
|
## Continuation
|
|
|
|
server.apending = false
|
|
|
|
if server.status == ServerStatus.Stopped:
|
|
|
|
server.asock.closeAsyncSocket()
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
if ovl.data.errCode == OSErrorCode(-1):
|
2018-06-04 09:57:17 +00:00
|
|
|
if setsockopt(SocketHandle(server.asock), cint(SOL_SOCKET),
|
2018-05-16 08:22:34 +00:00
|
|
|
cint(SO_UPDATE_ACCEPT_CONTEXT),
|
2018-06-04 09:57:17 +00:00
|
|
|
addr server.sock,
|
2018-05-16 08:22:34 +00:00
|
|
|
SockLen(sizeof(SocketHandle))) != 0'i32:
|
2018-06-04 09:57:17 +00:00
|
|
|
server.asock.closeAsyncSocket()
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(osLastError())
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
2018-06-10 23:08:17 +00:00
|
|
|
if not isNil(server.init):
|
|
|
|
var transp = server.init(server, server.asock)
|
|
|
|
discard server.function(
|
|
|
|
server,
|
|
|
|
newStreamSocketTransport(server.asock, server.bufferSize,
|
|
|
|
transp)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
discard server.function(
|
|
|
|
server,
|
|
|
|
newStreamSocketTransport(server.asock, server.bufferSize, nil)
|
|
|
|
)
|
2018-05-23 11:03:18 +00:00
|
|
|
elif int32(ovl.data.errCode) == ERROR_OPERATION_ABORTED:
|
2018-05-28 23:35:15 +00:00
|
|
|
# CancelIO() interrupt
|
2018-06-04 09:57:17 +00:00
|
|
|
server.asock.closeAsyncSocket()
|
|
|
|
break
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
2018-06-04 09:57:17 +00:00
|
|
|
server.asock.closeAsyncSocket()
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(osLastError())
|
2018-06-04 09:57:17 +00:00
|
|
|
else:
|
|
|
|
## Initiation
|
2018-06-10 23:08:17 +00:00
|
|
|
if server.status in {ServerStatus.Stopped, ServerStatus.Closed}:
|
|
|
|
## Server was already stopped/closed exiting
|
|
|
|
break
|
|
|
|
|
2018-06-04 09:57:17 +00:00
|
|
|
server.apending = true
|
|
|
|
server.asock = createAsyncSocket(server.domain, SockType.SOCK_STREAM,
|
|
|
|
Protocol.IPPROTO_TCP)
|
|
|
|
if server.asock == asyncInvalidSocket:
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(osLastError())
|
2018-06-04 09:57:17 +00:00
|
|
|
|
|
|
|
var dwBytesReceived = DWORD(0)
|
|
|
|
let dwReceiveDataLength = DWORD(0)
|
|
|
|
let dwLocalAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
|
|
|
|
let dwRemoteAddressLength = DWORD(sizeof(Sockaddr_in6) + 16)
|
|
|
|
|
|
|
|
let res = loop.acceptEx(SocketHandle(server.sock),
|
|
|
|
SocketHandle(server.asock),
|
|
|
|
addr server.abuffer[0],
|
|
|
|
dwReceiveDataLength, dwLocalAddressLength,
|
|
|
|
dwRemoteAddressLength, addr dwBytesReceived,
|
|
|
|
cast[POVERLAPPED](addr server.aovl))
|
|
|
|
if not res:
|
|
|
|
let err = osLastError()
|
|
|
|
if int32(err) == ERROR_OPERATION_ABORTED:
|
|
|
|
server.apending = false
|
|
|
|
break
|
|
|
|
elif int32(err) == ERROR_IO_PENDING:
|
|
|
|
discard
|
|
|
|
else:
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(err)
|
2018-06-04 09:57:17 +00:00
|
|
|
break
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc resumeRead(transp: StreamTransport) {.inline.} =
|
2018-06-10 23:08:17 +00:00
|
|
|
transp.state.excl(ReadPaused)
|
|
|
|
readStreamLoop(cast[pointer](addr transp.rovl))
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc resumeWrite(transp: StreamTransport) {.inline.} =
|
2018-06-10 23:08:17 +00:00
|
|
|
transp.state.excl(WritePaused)
|
|
|
|
writeStreamLoop(cast[pointer](addr transp.wovl))
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-07 08:05:06 +00:00
|
|
|
proc pauseAccept(server: StreamServer) {.inline.} =
|
2018-06-04 09:57:17 +00:00
|
|
|
if server.apending:
|
|
|
|
discard cancelIO(Handle(server.sock))
|
|
|
|
|
2018-06-07 08:05:06 +00:00
|
|
|
proc resumeAccept(server: StreamServer) {.inline.} =
|
2018-06-04 09:57:17 +00:00
|
|
|
if not server.apending:
|
|
|
|
acceptLoop(cast[pointer](addr server.aovl))
|
2018-06-11 07:16:08 +00:00
|
|
|
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
|
|
|
|
template getVectorBuffer(v: untyped): pointer =
|
|
|
|
cast[pointer](cast[uint]((v).buf) + uint((v).boffset))
|
|
|
|
|
|
|
|
template getVectorLength(v: untyped): int =
|
|
|
|
cast[int]((v).buflen - int((v).boffset))
|
|
|
|
|
|
|
|
template initBufferStreamVector(v, p, n, t: untyped) =
|
|
|
|
(v).kind = DataBuffer
|
|
|
|
(v).buf = cast[pointer]((p))
|
|
|
|
(v).buflen = int(n)
|
|
|
|
(v).writer = (t)
|
|
|
|
|
|
|
|
proc writeStreamLoop(udata: pointer) {.gcsafe.} =
|
|
|
|
var cdata = cast[ptr CompletionData](udata)
|
2018-06-05 20:21:07 +00:00
|
|
|
if not isNil(cdata) and (int(cdata.fd) == 0 or isNil(cdata.udata)):
|
2018-05-29 09:59:39 +00:00
|
|
|
# Transport was closed earlier, exiting
|
|
|
|
return
|
2018-06-10 23:08:17 +00:00
|
|
|
var transp = cast[StreamTransport](cdata.udata)
|
2018-05-16 08:22:34 +00:00
|
|
|
let fd = SocketHandle(cdata.fd)
|
2018-05-28 23:35:15 +00:00
|
|
|
if len(transp.queue) > 0:
|
|
|
|
var vector = transp.queue.popFirst()
|
|
|
|
while true:
|
|
|
|
if transp.kind == TransportKind.Socket:
|
|
|
|
if vector.kind == VectorKind.DataBuffer:
|
|
|
|
let res = posix.send(fd, vector.buf, vector.buflen, MSG_NOSIGNAL)
|
|
|
|
if res >= 0:
|
|
|
|
if vector.buflen - res == 0:
|
2018-06-05 20:21:07 +00:00
|
|
|
vector.writer.complete(vector.buflen)
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
2018-05-28 23:35:15 +00:00
|
|
|
vector.shiftVectorBuffer(res)
|
|
|
|
transp.queue.addFirst(vector)
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
2018-05-28 23:35:15 +00:00
|
|
|
let err = osLastError()
|
|
|
|
if int(err) == EINTR:
|
|
|
|
continue
|
2018-05-21 21:52:57 +00:00
|
|
|
else:
|
2018-06-05 20:21:07 +00:00
|
|
|
vector.writer.fail(newException(TransportOsError,
|
|
|
|
osErrorMsg(err)))
|
2018-05-28 23:35:15 +00:00
|
|
|
else:
|
|
|
|
let res = sendfile(int(fd), cast[int](vector.buflen),
|
|
|
|
int(vector.offset),
|
|
|
|
cast[int](vector.buf))
|
|
|
|
if res >= 0:
|
|
|
|
if cast[int](vector.buf) - res == 0:
|
2018-06-05 20:21:07 +00:00
|
|
|
vector.writer.complete(cast[int](vector.buf))
|
2018-05-28 23:35:15 +00:00
|
|
|
else:
|
|
|
|
vector.shiftVectorFile(res)
|
|
|
|
transp.queue.addFirst(vector)
|
|
|
|
else:
|
|
|
|
let err = osLastError()
|
|
|
|
if int(err) == EINTR:
|
|
|
|
continue
|
|
|
|
else:
|
2018-06-05 20:21:07 +00:00
|
|
|
vector.writer.fail(newException(TransportOsError,
|
|
|
|
osErrorMsg(err)))
|
|
|
|
break
|
2018-05-28 23:35:15 +00:00
|
|
|
else:
|
|
|
|
transp.state.incl(WritePaused)
|
|
|
|
transp.fd.removeWriter()
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc readStreamLoop(udata: pointer) {.gcsafe.} =
|
|
|
|
var cdata = cast[ptr CompletionData](udata)
|
2018-06-05 20:21:07 +00:00
|
|
|
if not isNil(cdata) and (int(cdata.fd) == 0 or isNil(cdata.udata)):
|
2018-05-29 09:59:39 +00:00
|
|
|
# Transport was closed earlier, exiting
|
|
|
|
return
|
2018-06-10 23:08:17 +00:00
|
|
|
var transp = cast[StreamTransport](cdata.udata)
|
2018-05-16 08:22:34 +00:00
|
|
|
let fd = SocketHandle(cdata.fd)
|
2018-05-28 23:35:15 +00:00
|
|
|
while true:
|
|
|
|
var res = posix.recv(fd, addr transp.buffer[transp.offset],
|
|
|
|
len(transp.buffer) - transp.offset, cint(0))
|
|
|
|
if res < 0:
|
|
|
|
let err = osLastError()
|
|
|
|
if int(err) == EINTR:
|
|
|
|
continue
|
|
|
|
elif int(err) in {ECONNRESET}:
|
2018-06-05 20:21:07 +00:00
|
|
|
transp.state = transp.state + {ReadEof, ReadPaused}
|
2018-05-16 08:22:34 +00:00
|
|
|
cdata.fd.removeReader()
|
|
|
|
else:
|
2018-05-28 23:35:15 +00:00
|
|
|
transp.setReadError(err)
|
|
|
|
cdata.fd.removeReader()
|
|
|
|
elif res == 0:
|
2018-06-05 20:21:07 +00:00
|
|
|
transp.state = transp.state + {ReadEof, ReadPaused}
|
2018-05-28 23:35:15 +00:00
|
|
|
cdata.fd.removeReader()
|
|
|
|
else:
|
|
|
|
transp.offset += res
|
|
|
|
if transp.offset == len(transp.buffer):
|
|
|
|
transp.state.incl(ReadPaused)
|
|
|
|
cdata.fd.removeReader()
|
|
|
|
if not isNil(transp.reader):
|
|
|
|
transp.finishReader()
|
|
|
|
break
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-10 23:08:17 +00:00
|
|
|
proc newStreamSocketTransport(sock: AsyncFD, bufsize: int,
|
|
|
|
child: StreamTransport): StreamTransport =
|
|
|
|
var transp: StreamTransport
|
|
|
|
if not isNil(child):
|
|
|
|
transp = child
|
|
|
|
else:
|
|
|
|
transp = StreamTransport(kind: TransportKind.Socket)
|
|
|
|
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.fd = sock
|
|
|
|
transp.buffer = newSeq[byte](bufsize)
|
|
|
|
transp.state = {ReadPaused, WritePaused}
|
|
|
|
transp.queue = initDeque[StreamVector]()
|
|
|
|
transp.future = newFuture[void]("socket.stream.transport")
|
|
|
|
GC_ref(transp)
|
2018-06-10 23:08:17 +00:00
|
|
|
result = transp
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc connect*(address: TransportAddress,
|
2018-06-10 23:08:17 +00:00
|
|
|
bufferSize = DefaultStreamBufferSize,
|
|
|
|
child: StreamTransport = nil): Future[StreamTransport] =
|
2018-05-27 05:49:47 +00:00
|
|
|
## Open new connection to remote peer with address ``address`` and create
|
|
|
|
## new transport object ``StreamTransport`` for established connection.
|
|
|
|
## ``bufferSize`` - size of internal buffer for transport.
|
2018-05-16 08:22:34 +00:00
|
|
|
var
|
|
|
|
saddr: Sockaddr_storage
|
|
|
|
slen: SockLen
|
|
|
|
sock: AsyncFD
|
|
|
|
var retFuture = newFuture[StreamTransport]("transport.connect")
|
|
|
|
toSockAddr(address.address, address.port, saddr, slen)
|
|
|
|
sock = createAsyncSocket(address.address.getDomain(), SockType.SOCK_STREAM,
|
|
|
|
Protocol.IPPROTO_TCP)
|
|
|
|
if sock == asyncInvalidSocket:
|
2018-06-10 23:08:17 +00:00
|
|
|
retFuture.fail(newException(TransportOsError, osErrorMsg(osLastError())))
|
2018-06-07 19:07:17 +00:00
|
|
|
return retFuture
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc continuation(udata: pointer) =
|
|
|
|
var data = cast[ptr CompletionData](udata)
|
|
|
|
var err = 0
|
2018-05-23 11:03:18 +00:00
|
|
|
let fd = data.fd
|
|
|
|
if not fd.getSocketError(err):
|
|
|
|
fd.closeAsyncSocket()
|
2018-06-10 23:08:17 +00:00
|
|
|
retFuture.fail(newException(TransportOsError,
|
|
|
|
osErrorMsg(osLastError())))
|
2018-05-16 08:22:34 +00:00
|
|
|
return
|
|
|
|
if err != 0:
|
2018-05-23 11:03:18 +00:00
|
|
|
fd.closeAsyncSocket()
|
2018-06-10 23:08:17 +00:00
|
|
|
retFuture.fail(newException(TransportOsError,
|
|
|
|
osErrorMsg(OSErrorCode(err))))
|
2018-05-16 08:22:34 +00:00
|
|
|
return
|
2018-05-23 11:03:18 +00:00
|
|
|
fd.removeWriter()
|
2018-06-10 23:08:17 +00:00
|
|
|
retFuture.complete(newStreamSocketTransport(fd, bufferSize, child))
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
while true:
|
|
|
|
var res = posix.connect(SocketHandle(sock),
|
|
|
|
cast[ptr SockAddr](addr saddr), slen)
|
|
|
|
if res == 0:
|
2018-06-10 23:08:17 +00:00
|
|
|
retFuture.complete(newStreamSocketTransport(sock, bufferSize, child))
|
2018-05-16 08:22:34 +00:00
|
|
|
break
|
|
|
|
else:
|
|
|
|
let err = osLastError()
|
|
|
|
if int(err) == EINTR:
|
|
|
|
continue
|
|
|
|
elif int(err) == EINPROGRESS:
|
|
|
|
sock.addWriter(continuation)
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
sock.closeAsyncSocket()
|
2018-06-10 23:08:17 +00:00
|
|
|
retFuture.fail(newException(TransportOsError, osErrorMsg(err)))
|
2018-05-16 08:22:34 +00:00
|
|
|
break
|
|
|
|
return retFuture
|
|
|
|
|
2018-06-10 23:08:17 +00:00
|
|
|
proc acceptLoop(udata: pointer) =
|
2018-05-16 08:22:34 +00:00
|
|
|
var
|
|
|
|
saddr: Sockaddr_storage
|
|
|
|
slen: SockLen
|
|
|
|
var server = cast[StreamServer](cast[ptr CompletionData](udata).udata)
|
|
|
|
while true:
|
|
|
|
let res = posix.accept(SocketHandle(server.sock),
|
|
|
|
cast[ptr SockAddr](addr saddr), addr slen)
|
|
|
|
if int(res) > 0:
|
|
|
|
let sock = wrapAsyncSocket(res)
|
|
|
|
if sock != asyncInvalidSocket:
|
2018-06-10 23:08:17 +00:00
|
|
|
if not isNil(server.init):
|
|
|
|
var transp = server.init(server, sock)
|
|
|
|
discard server.function(server,
|
|
|
|
newStreamSocketTransport(sock, server.bufferSize, transp))
|
|
|
|
else:
|
|
|
|
discard server.function(server,
|
|
|
|
newStreamSocketTransport(sock, server.bufferSize, nil))
|
2018-05-16 08:22:34 +00:00
|
|
|
break
|
|
|
|
else:
|
|
|
|
let err = osLastError()
|
|
|
|
if int(err) == EINTR:
|
|
|
|
continue
|
2018-06-05 05:51:59 +00:00
|
|
|
else:
|
2018-05-16 08:22:34 +00:00
|
|
|
## Critical unrecoverable error
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(err)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-07 08:05:06 +00:00
|
|
|
proc resumeAccept(server: StreamServer) =
|
2018-06-10 23:08:17 +00:00
|
|
|
addReader(server.sock, acceptLoop, cast[pointer](server))
|
2018-06-04 09:57:17 +00:00
|
|
|
|
2018-06-07 08:05:06 +00:00
|
|
|
proc pauseAccept(server: StreamServer) =
|
2018-06-04 09:57:17 +00:00
|
|
|
removeReader(server.sock)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc resumeRead(transp: StreamTransport) {.inline.} =
|
|
|
|
transp.state.excl(ReadPaused)
|
|
|
|
addReader(transp.fd, readStreamLoop, cast[pointer](transp))
|
|
|
|
|
|
|
|
proc resumeWrite(transp: StreamTransport) {.inline.} =
|
|
|
|
transp.state.excl(WritePaused)
|
|
|
|
addWriter(transp.fd, writeStreamLoop, cast[pointer](transp))
|
|
|
|
|
2018-06-07 08:05:06 +00:00
|
|
|
proc start*(server: StreamServer) =
|
2018-05-21 21:52:57 +00:00
|
|
|
## Starts ``server``.
|
2018-06-04 09:57:17 +00:00
|
|
|
if server.status == ServerStatus.Starting:
|
|
|
|
server.resumeAccept()
|
|
|
|
server.status = ServerStatus.Running
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-07 08:05:06 +00:00
|
|
|
proc stop*(server: StreamServer) =
|
2018-05-22 21:03:13 +00:00
|
|
|
## Stops ``server``.
|
2018-06-04 09:57:17 +00:00
|
|
|
if server.status == ServerStatus.Running:
|
|
|
|
server.pauseAccept()
|
|
|
|
server.status = ServerStatus.Stopped
|
2018-06-07 08:05:06 +00:00
|
|
|
elif server.status == ServerStatus.Starting:
|
|
|
|
server.status = ServerStatus.Stopped
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-07 08:05:06 +00:00
|
|
|
proc join*(server: StreamServer) {.async.} =
|
2018-06-04 09:57:17 +00:00
|
|
|
## Waits until ``server`` is not closed.
|
2018-05-21 21:52:57 +00:00
|
|
|
if not server.loopFuture.finished:
|
|
|
|
await server.loopFuture
|
|
|
|
|
2018-06-07 08:05:06 +00:00
|
|
|
proc close*(server: StreamServer) =
|
2018-05-21 21:52:57 +00:00
|
|
|
## Release ``server`` resources.
|
2018-06-04 09:57:17 +00:00
|
|
|
if server.status == ServerStatus.Stopped:
|
|
|
|
closeAsyncSocket(server.sock)
|
2018-06-10 23:08:17 +00:00
|
|
|
server.status = ServerStatus.Closed
|
2018-06-04 09:57:17 +00:00
|
|
|
server.loopFuture.complete()
|
2018-06-06 21:29:37 +00:00
|
|
|
if not isNil(server.udata) and GCUserData in server.flags:
|
|
|
|
GC_unref(cast[ref int](server.udata))
|
2018-06-04 09:57:17 +00:00
|
|
|
GC_unref(server)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc createStreamServer*(host: TransportAddress,
|
|
|
|
cbproc: StreamCallback,
|
2018-05-31 08:03:58 +00:00
|
|
|
flags: set[ServerFlags] = {},
|
2018-05-16 08:22:34 +00:00
|
|
|
sock: AsyncFD = asyncInvalidSocket,
|
|
|
|
backlog: int = 100,
|
|
|
|
bufferSize: int = DefaultStreamBufferSize,
|
2018-06-10 23:08:17 +00:00
|
|
|
child: StreamServer = nil,
|
|
|
|
init: TransportInitCallback = nil,
|
2018-05-16 08:22:34 +00:00
|
|
|
udata: pointer = nil): StreamServer =
|
2018-05-28 23:35:15 +00:00
|
|
|
## Create new TCP stream server.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-27 05:49:47 +00:00
|
|
|
## ``host`` - address to which server will be bound.
|
|
|
|
## ``flags`` - flags to apply to server socket.
|
|
|
|
## ``cbproc`` - callback function which will be called, when new client
|
|
|
|
## connection will be established.
|
2018-05-28 23:35:15 +00:00
|
|
|
## ``sock`` - user-driven socket to use.
|
|
|
|
## ``backlog`` - number of outstanding connections in the socket's listen
|
|
|
|
## queue.
|
|
|
|
## ``bufferSize`` - size of internal buffer for transport.
|
2018-06-10 23:08:17 +00:00
|
|
|
## ``child`` - existing object ``StreamServer``object to initialize, can be
|
|
|
|
## used to initalize ``StreamServer`` inherited objects.
|
2018-05-28 23:35:15 +00:00
|
|
|
## ``udata`` - user-defined pointer.
|
2018-05-16 08:22:34 +00:00
|
|
|
var
|
|
|
|
saddr: Sockaddr_storage
|
|
|
|
slen: SockLen
|
|
|
|
serverSocket: AsyncFD
|
|
|
|
if sock == asyncInvalidSocket:
|
|
|
|
serverSocket = createAsyncSocket(host.address.getDomain(),
|
|
|
|
SockType.SOCK_STREAM,
|
|
|
|
Protocol.IPPROTO_TCP)
|
|
|
|
if serverSocket == asyncInvalidSocket:
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(osLastError())
|
2018-05-16 08:22:34 +00:00
|
|
|
else:
|
|
|
|
if not setSocketBlocking(SocketHandle(sock), false):
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(osLastError())
|
2018-05-16 08:22:34 +00:00
|
|
|
register(sock)
|
|
|
|
serverSocket = sock
|
|
|
|
|
|
|
|
if ServerFlags.ReuseAddr in flags:
|
|
|
|
if not setSockOpt(serverSocket, SOL_SOCKET, SO_REUSEADDR, 1):
|
|
|
|
let err = osLastError()
|
|
|
|
if sock == asyncInvalidSocket:
|
|
|
|
closeAsyncSocket(serverSocket)
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(err)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
toSockAddr(host.address, host.port, saddr, slen)
|
|
|
|
if bindAddr(SocketHandle(serverSocket), cast[ptr SockAddr](addr saddr),
|
|
|
|
slen) != 0:
|
|
|
|
let err = osLastError()
|
|
|
|
if sock == asyncInvalidSocket:
|
|
|
|
closeAsyncSocket(serverSocket)
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(err)
|
2018-05-21 21:52:57 +00:00
|
|
|
|
2018-05-16 08:22:34 +00:00
|
|
|
if nativesockets.listen(SocketHandle(serverSocket), cint(backlog)) != 0:
|
|
|
|
let err = osLastError()
|
|
|
|
if sock == asyncInvalidSocket:
|
|
|
|
closeAsyncSocket(serverSocket)
|
2018-06-10 23:08:17 +00:00
|
|
|
raiseTransportOsError(err)
|
|
|
|
|
|
|
|
if not isNil(child):
|
|
|
|
result = child
|
|
|
|
else:
|
|
|
|
result = StreamServer()
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
result.sock = serverSocket
|
|
|
|
result.function = cbproc
|
2018-06-10 23:08:17 +00:00
|
|
|
result.init = init
|
2018-05-16 08:22:34 +00:00
|
|
|
result.bufferSize = bufferSize
|
|
|
|
result.status = Starting
|
2018-06-04 09:57:17 +00:00
|
|
|
result.loopFuture = newFuture[void]("stream.server")
|
2018-05-16 08:22:34 +00:00
|
|
|
result.udata = udata
|
|
|
|
result.local = host
|
2018-06-04 09:57:17 +00:00
|
|
|
|
|
|
|
when defined(windows):
|
|
|
|
result.aovl.data = CompletionData(fd: serverSocket, cb: acceptLoop,
|
|
|
|
udata: cast[pointer](result))
|
|
|
|
result.domain = host.address.getDomain()
|
|
|
|
result.apending = false
|
2018-05-21 21:52:57 +00:00
|
|
|
GC_ref(result)
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-06 21:29:37 +00:00
|
|
|
proc createStreamServer*[T](host: TransportAddress,
|
|
|
|
cbproc: StreamCallback,
|
|
|
|
flags: set[ServerFlags] = {},
|
2018-06-10 23:08:17 +00:00
|
|
|
udata: ref T,
|
2018-06-06 21:29:37 +00:00
|
|
|
sock: AsyncFD = asyncInvalidSocket,
|
|
|
|
backlog: int = 100,
|
|
|
|
bufferSize: int = DefaultStreamBufferSize,
|
2018-06-11 19:54:08 +00:00
|
|
|
child: StreamServer = nil,
|
|
|
|
init: TransportInitCallback = nil): StreamServer =
|
2018-06-06 21:29:37 +00:00
|
|
|
var fflags = flags + {GCUserData}
|
|
|
|
GC_ref(udata)
|
|
|
|
result = createStreamServer(host, cbproc, flags, sock, backlog, bufferSize,
|
2018-06-11 19:54:08 +00:00
|
|
|
child, init, cast[pointer](udata))
|
2018-06-06 21:29:37 +00:00
|
|
|
|
2018-06-07 06:17:59 +00:00
|
|
|
proc getUserData*[T](server: StreamServer): T {.inline.} =
|
|
|
|
## Obtain user data stored in ``server`` object.
|
|
|
|
result = cast[T](server.udata)
|
2018-06-06 21:29:37 +00:00
|
|
|
|
2018-05-16 08:22:34 +00:00
|
|
|
proc write*(transp: StreamTransport, pbytes: pointer,
|
2018-06-05 20:21:07 +00:00
|
|
|
nbytes: int): Future[int] =
|
2018-05-27 05:49:47 +00:00
|
|
|
## Write data from buffer ``pbytes`` with size ``nbytes`` using transport
|
2018-05-22 21:03:13 +00:00
|
|
|
## ``transp``.
|
2018-06-05 20:21:07 +00:00
|
|
|
var retFuture = newFuture[int]()
|
|
|
|
transp.checkClosed(retFuture)
|
|
|
|
var vector = StreamVector(kind: DataBuffer, writer: retFuture,
|
2018-05-21 21:52:57 +00:00
|
|
|
buf: pbytes, buflen: nbytes)
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.queue.addLast(vector)
|
|
|
|
if WritePaused in transp.state:
|
|
|
|
transp.resumeWrite()
|
2018-06-05 20:21:07 +00:00
|
|
|
return retFuture
|
|
|
|
|
2018-06-11 20:50:45 +00:00
|
|
|
proc write*(transp: StreamTransport, msg: var string): Future[int] =
|
2018-06-05 20:21:07 +00:00
|
|
|
## Write data from string ``msg`` using transport ``transp``.
|
|
|
|
var retFuture = FutureGCString[int]()
|
|
|
|
transp.checkClosed(retFuture)
|
|
|
|
shallowCopy(retFuture.gcholder, msg)
|
|
|
|
var vector = StreamVector(kind: DataBuffer,
|
|
|
|
writer: cast[Future[int]](retFuture),
|
|
|
|
buf: unsafeAddr msg[0], buflen: len(msg))
|
|
|
|
transp.queue.addLast(vector)
|
|
|
|
if WritePaused in transp.state:
|
|
|
|
transp.resumeWrite()
|
|
|
|
return retFuture
|
|
|
|
|
2018-06-11 20:50:45 +00:00
|
|
|
proc write*[T](transp: StreamTransport, msg: var seq[T]): Future[int] =
|
2018-06-05 20:21:07 +00:00
|
|
|
## Write sequence ``msg`` using transport ``transp``.
|
|
|
|
var retFuture = FutureGCSeq[int, T]()
|
|
|
|
transp.checkClosed(retFuture)
|
|
|
|
shallowCopy(retFuture.gcholder, msg)
|
|
|
|
var vector = StreamVector(kind: DataBuffer,
|
|
|
|
writer: cast[Future[int]](retFuture),
|
|
|
|
buf: unsafeAddr msg[0],
|
|
|
|
buflen: len(msg) * sizeof(T))
|
|
|
|
transp.queue.addLast(vector)
|
|
|
|
if WritePaused in transp.state:
|
|
|
|
transp.resumeWrite()
|
|
|
|
return retFuture
|
2018-06-04 16:42:54 +00:00
|
|
|
|
2018-05-21 21:52:57 +00:00
|
|
|
proc writeFile*(transp: StreamTransport, handle: int,
|
2018-06-05 22:48:03 +00:00
|
|
|
offset: uint = 0, size: int = 0): Future[int] =
|
2018-05-22 21:03:13 +00:00
|
|
|
## Write data from file descriptor ``handle`` to transport ``transp``.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-22 21:03:13 +00:00
|
|
|
## You can specify starting ``offset`` in opened file and number of bytes
|
|
|
|
## to transfer from file to transport via ``size``.
|
2018-06-05 20:21:07 +00:00
|
|
|
var retFuture = newFuture[int]("transport.writeFile")
|
2018-06-05 22:48:03 +00:00
|
|
|
transp.checkClosed(retFuture)
|
2018-06-05 20:21:07 +00:00
|
|
|
var vector = StreamVector(kind: DataFile, writer: retFuture,
|
2018-05-21 21:52:57 +00:00
|
|
|
buf: cast[pointer](size), offset: offset,
|
|
|
|
buflen: handle)
|
|
|
|
transp.queue.addLast(vector)
|
|
|
|
if WritePaused in transp.state:
|
|
|
|
transp.resumeWrite()
|
2018-06-05 20:21:07 +00:00
|
|
|
return retFuture
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-04 16:42:54 +00:00
|
|
|
proc atEof*(transp: StreamTransport): bool {.inline.} =
|
|
|
|
## Returns ``true`` if ``transp`` is at EOF.
|
|
|
|
result = (transp.offset == 0) and (ReadEof in transp.state) and
|
|
|
|
(ReadPaused in transp.state)
|
|
|
|
|
2018-05-16 08:22:34 +00:00
|
|
|
proc readExactly*(transp: StreamTransport, pbytes: pointer,
|
2018-05-21 21:52:57 +00:00
|
|
|
nbytes: int) {.async.} =
|
2018-05-22 21:03:13 +00:00
|
|
|
## Read exactly ``nbytes`` bytes from transport ``transp`` and store it to
|
|
|
|
## ``pbytes``.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-22 21:03:13 +00:00
|
|
|
## If EOF is received and ``nbytes`` is not yet readed, the procedure
|
|
|
|
## will raise ``TransportIncompleteError``.
|
2018-05-16 08:22:34 +00:00
|
|
|
checkClosed(transp)
|
|
|
|
checkPending(transp)
|
|
|
|
var index = 0
|
|
|
|
while true:
|
|
|
|
if transp.offset == 0:
|
|
|
|
if (ReadError in transp.state):
|
|
|
|
raise transp.getError()
|
2018-06-05 05:51:59 +00:00
|
|
|
if (ReadClosed in transp.state) or transp.atEof():
|
2018-05-16 08:22:34 +00:00
|
|
|
raise newException(TransportIncompleteError, "Data incomplete!")
|
|
|
|
|
|
|
|
if transp.offset >= (nbytes - index):
|
|
|
|
copyMem(cast[pointer](cast[uint](pbytes) + uint(index)),
|
|
|
|
addr(transp.buffer[0]), nbytes - index)
|
|
|
|
transp.shiftBuffer(nbytes - index)
|
|
|
|
break
|
|
|
|
else:
|
2018-05-21 21:52:57 +00:00
|
|
|
if transp.offset != 0:
|
|
|
|
copyMem(cast[pointer](cast[uint](pbytes) + uint(index)),
|
|
|
|
addr(transp.buffer[0]), transp.offset)
|
|
|
|
index += transp.offset
|
|
|
|
|
|
|
|
transp.reader = newFuture[void]("stream.transport.readExactly")
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.offset = 0
|
|
|
|
if ReadPaused in transp.state:
|
|
|
|
transp.resumeRead()
|
|
|
|
await transp.reader
|
2018-06-04 10:40:41 +00:00
|
|
|
# we need to clear transp.reader to avoid double completion of this
|
|
|
|
# Future[T], because readLoop continues working.
|
|
|
|
transp.reader = nil
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc readOnce*(transp: StreamTransport, pbytes: pointer,
|
|
|
|
nbytes: int): Future[int] {.async.} =
|
|
|
|
## Perform one read operation on transport ``transp``.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-27 05:49:47 +00:00
|
|
|
## If internal buffer is not empty, ``nbytes`` bytes will be transferred from
|
|
|
|
## internal buffer, otherwise it will wait until some bytes will be received.
|
2018-05-16 08:22:34 +00:00
|
|
|
checkClosed(transp)
|
|
|
|
checkPending(transp)
|
|
|
|
while true:
|
|
|
|
if transp.offset == 0:
|
|
|
|
if (ReadError in transp.state):
|
|
|
|
raise transp.getError()
|
2018-06-05 05:51:59 +00:00
|
|
|
if (ReadClosed in transp.state) or transp.atEof():
|
2018-05-16 08:22:34 +00:00
|
|
|
result = 0
|
|
|
|
break
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.reader = newFuture[void]("stream.transport.readOnce")
|
2018-05-16 08:22:34 +00:00
|
|
|
if ReadPaused in transp.state:
|
|
|
|
transp.resumeRead()
|
|
|
|
await transp.reader
|
2018-06-04 10:40:41 +00:00
|
|
|
# we need to clear transp.reader to avoid double completion of this
|
|
|
|
# Future[T], because readLoop continues working.
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.reader = nil
|
|
|
|
else:
|
|
|
|
if transp.offset > nbytes:
|
|
|
|
copyMem(pbytes, addr(transp.buffer[0]), nbytes)
|
|
|
|
transp.shiftBuffer(nbytes)
|
|
|
|
result = nbytes
|
|
|
|
else:
|
|
|
|
copyMem(pbytes, addr(transp.buffer[0]), transp.offset)
|
|
|
|
result = transp.offset
|
|
|
|
break
|
|
|
|
|
|
|
|
proc readUntil*(transp: StreamTransport, pbytes: pointer, nbytes: int,
|
|
|
|
sep: seq[byte]): Future[int] {.async.} =
|
2018-05-22 21:03:13 +00:00
|
|
|
## Read data from the transport ``transp`` until separator ``sep`` is found.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-22 21:03:13 +00:00
|
|
|
## On success, the data and separator will be removed from the internal
|
|
|
|
## buffer (consumed). Returned data will NOT include the separator at the end.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-28 23:35:15 +00:00
|
|
|
## If EOF is received, and `sep` was not found, procedure will raise
|
|
|
|
## ``TransportIncompleteError``.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-28 23:35:15 +00:00
|
|
|
## If ``nbytes`` bytes has been received and `sep` was not found, procedure
|
|
|
|
## will raise ``TransportLimitError``.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-28 23:35:15 +00:00
|
|
|
## Procedure returns actual number of bytes read.
|
2018-05-16 08:22:34 +00:00
|
|
|
checkClosed(transp)
|
|
|
|
checkPending(transp)
|
|
|
|
|
|
|
|
var dest = cast[ptr UncheckedArray[byte]](pbytes)
|
|
|
|
var state = 0
|
|
|
|
var k = 0
|
|
|
|
var index = 0
|
|
|
|
|
|
|
|
while true:
|
2018-06-05 05:51:59 +00:00
|
|
|
if ReadError in transp.state:
|
|
|
|
raise transp.getError()
|
|
|
|
if (ReadClosed in transp.state) or transp.atEof():
|
|
|
|
raise newException(TransportIncompleteError, "Data incomplete!")
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
index = 0
|
|
|
|
while index < transp.offset:
|
|
|
|
let ch = transp.buffer[index]
|
|
|
|
if sep[state] == ch:
|
|
|
|
inc(state)
|
|
|
|
else:
|
|
|
|
state = 0
|
|
|
|
if k < nbytes:
|
|
|
|
dest[k] = ch
|
|
|
|
inc(k)
|
|
|
|
else:
|
|
|
|
raise newException(TransportLimitError, "Limit reached!")
|
|
|
|
if state == len(sep):
|
|
|
|
break
|
|
|
|
inc(index)
|
|
|
|
|
|
|
|
if state == len(sep):
|
2018-06-05 05:51:59 +00:00
|
|
|
transp.shiftBuffer(index + 1)
|
2018-05-16 08:22:34 +00:00
|
|
|
result = k
|
|
|
|
break
|
|
|
|
else:
|
2018-06-05 05:51:59 +00:00
|
|
|
transp.shiftBuffer(transp.offset)
|
|
|
|
transp.reader = newFuture[void]("stream.transport.readUntil")
|
|
|
|
if ReadPaused in transp.state:
|
|
|
|
transp.resumeRead()
|
|
|
|
await transp.reader
|
|
|
|
# we need to clear transp.reader to avoid double completion of this
|
|
|
|
# Future[T], because readLoop continues working.
|
|
|
|
transp.reader = nil
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc readLine*(transp: StreamTransport, limit = 0,
|
|
|
|
sep = "\r\n"): Future[string] {.async.} =
|
2018-05-22 21:03:13 +00:00
|
|
|
## Read one line from transport ``transp``, where "line" is a sequence of
|
|
|
|
## bytes ending with ``sep`` (default is "\r\n").
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-22 21:03:13 +00:00
|
|
|
## If EOF is received, and ``sep`` was not found, the method will return the
|
|
|
|
## partial read bytes.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-22 21:03:13 +00:00
|
|
|
## If the EOF was received and the internal buffer is empty, return an
|
|
|
|
## empty string.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-22 21:03:13 +00:00
|
|
|
## If ``limit`` more then 0, then read is limited to ``limit`` bytes.
|
2018-05-16 08:22:34 +00:00
|
|
|
checkClosed(transp)
|
|
|
|
checkPending(transp)
|
|
|
|
|
|
|
|
result = ""
|
|
|
|
var lim = if limit <= 0: -1 else: limit
|
|
|
|
var state = 0
|
|
|
|
var index = 0
|
|
|
|
|
|
|
|
while true:
|
2018-06-05 05:51:59 +00:00
|
|
|
if (ReadError in transp.state):
|
|
|
|
raise transp.getError()
|
|
|
|
if (ReadClosed in transp.state) or transp.atEof():
|
|
|
|
break
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
index = 0
|
|
|
|
while index < transp.offset:
|
|
|
|
let ch = char(transp.buffer[index])
|
|
|
|
if sep[state] == ch:
|
|
|
|
inc(state)
|
|
|
|
if state == len(sep):
|
|
|
|
transp.shiftBuffer(index + 1)
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
state = 0
|
|
|
|
result.add(ch)
|
|
|
|
if len(result) == lim:
|
|
|
|
transp.shiftBuffer(index + 1)
|
|
|
|
break
|
|
|
|
inc(index)
|
|
|
|
|
|
|
|
if (state == len(sep)) or (lim == len(result)):
|
|
|
|
break
|
|
|
|
else:
|
2018-06-05 05:51:59 +00:00
|
|
|
transp.shiftBuffer(transp.offset)
|
|
|
|
transp.reader = newFuture[void]("stream.transport.readLine")
|
|
|
|
if ReadPaused in transp.state:
|
|
|
|
transp.resumeRead()
|
|
|
|
await transp.reader
|
|
|
|
# we need to clear transp.reader to avoid double completion of this
|
|
|
|
# Future[T], because readLoop continues working.
|
|
|
|
transp.reader = nil
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc read*(transp: StreamTransport, n = -1): Future[seq[byte]] {.async.} =
|
2018-06-05 05:51:59 +00:00
|
|
|
## Read all bytes (n == -1) or exactly `n` bytes from transport ``transp``.
|
2018-06-04 09:57:17 +00:00
|
|
|
##
|
2018-05-28 23:35:15 +00:00
|
|
|
## This procedure allocates buffer seq[byte] and return it as result.
|
2018-05-16 08:22:34 +00:00
|
|
|
checkClosed(transp)
|
|
|
|
checkPending(transp)
|
|
|
|
result = newSeq[byte]()
|
|
|
|
while true:
|
|
|
|
if (ReadError in transp.state):
|
|
|
|
raise transp.getError()
|
2018-06-05 05:51:59 +00:00
|
|
|
if (ReadClosed in transp.state) or transp.atEof():
|
2018-05-16 08:22:34 +00:00
|
|
|
break
|
2018-06-05 22:48:03 +00:00
|
|
|
|
2018-05-16 08:22:34 +00:00
|
|
|
if transp.offset > 0:
|
|
|
|
let s = len(result)
|
|
|
|
let o = s + transp.offset
|
|
|
|
if n == -1:
|
|
|
|
# grabbing all incoming data, until EOF
|
|
|
|
result.setLen(o)
|
|
|
|
copyMem(cast[pointer](addr result[s]), addr(transp.buffer[0]),
|
|
|
|
transp.offset)
|
|
|
|
transp.offset = 0
|
|
|
|
else:
|
2018-06-05 05:51:59 +00:00
|
|
|
let left = n - s
|
|
|
|
if transp.offset >= left:
|
2018-05-16 08:22:34 +00:00
|
|
|
# size of buffer data is more then we need, grabbing only part
|
|
|
|
result.setLen(n)
|
|
|
|
copyMem(cast[pointer](addr result[s]), addr(transp.buffer[0]),
|
2018-06-05 05:51:59 +00:00
|
|
|
left)
|
|
|
|
transp.shiftBuffer(left)
|
2018-05-16 08:22:34 +00:00
|
|
|
break
|
|
|
|
else:
|
|
|
|
# there not enough data in buffer, grabbing all
|
|
|
|
result.setLen(o)
|
|
|
|
copyMem(cast[pointer](addr result[s]), addr(transp.buffer[0]),
|
|
|
|
transp.offset)
|
|
|
|
transp.offset = 0
|
|
|
|
|
2018-05-21 21:52:57 +00:00
|
|
|
transp.reader = newFuture[void]("stream.transport.read")
|
2018-05-16 08:22:34 +00:00
|
|
|
if ReadPaused in transp.state:
|
|
|
|
transp.resumeRead()
|
|
|
|
await transp.reader
|
2018-06-04 10:40:41 +00:00
|
|
|
# we need to clear transp.reader to avoid double completion of this
|
|
|
|
# Future[T], because readLoop continues working.
|
|
|
|
transp.reader = nil
|
2018-05-16 08:22:34 +00:00
|
|
|
|
2018-06-04 16:42:54 +00:00
|
|
|
proc consume*(transp: StreamTransport, n = -1): Future[int] {.async.} =
|
|
|
|
## Consume all bytes (n == -1) or ``n`` bytes from transport ``transp``.
|
|
|
|
##
|
|
|
|
## Return number of bytes actually consumed
|
|
|
|
checkClosed(transp)
|
|
|
|
checkPending(transp)
|
|
|
|
result = 0
|
|
|
|
while true:
|
|
|
|
if (ReadError in transp.state):
|
|
|
|
raise transp.getError()
|
|
|
|
if ReadClosed in transp.state or transp.atEof():
|
|
|
|
break
|
2018-06-05 05:51:59 +00:00
|
|
|
|
2018-06-04 16:42:54 +00:00
|
|
|
if transp.offset > 0:
|
|
|
|
if n == -1:
|
|
|
|
# consume all incoming data, until EOF
|
|
|
|
result += transp.offset
|
|
|
|
transp.offset = 0
|
|
|
|
else:
|
|
|
|
let left = n - result
|
|
|
|
if transp.offset >= left:
|
|
|
|
# size of buffer data is more then we need, consume only part
|
|
|
|
result += left
|
|
|
|
transp.shiftBuffer(left)
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
# there not enough data in buffer, consume all
|
|
|
|
result += transp.offset
|
|
|
|
transp.offset = 0
|
|
|
|
|
|
|
|
transp.reader = newFuture[void]("stream.transport.consume")
|
|
|
|
if ReadPaused in transp.state:
|
|
|
|
transp.resumeRead()
|
|
|
|
await transp.reader
|
|
|
|
# we need to clear transp.reader to avoid double completion of this
|
|
|
|
# Future[T], because readLoop continues working.
|
|
|
|
transp.reader = nil
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc join*(transp: StreamTransport) {.async.} =
|
|
|
|
## Wait until ``transp`` will not be closed.
|
2018-05-21 21:52:57 +00:00
|
|
|
if not transp.future.finished:
|
|
|
|
await transp.future
|
2018-05-16 08:22:34 +00:00
|
|
|
|
|
|
|
proc close*(transp: StreamTransport) =
|
|
|
|
## Closes and frees resources of transport ``transp``.
|
2018-06-04 09:57:17 +00:00
|
|
|
if {ReadClosed, WriteClosed} * transp.state == {}:
|
2018-05-16 08:22:34 +00:00
|
|
|
when defined(windows):
|
|
|
|
discard cancelIo(Handle(transp.fd))
|
|
|
|
closeAsyncSocket(transp.fd)
|
2018-06-14 06:49:59 +00:00
|
|
|
transp.state.incl({WriteClosed, ReadClosed})
|
2018-05-16 08:22:34 +00:00
|
|
|
transp.future.complete()
|
2018-05-21 21:52:57 +00:00
|
|
|
GC_unref(transp)
|