[backport] Fix style issues in lib/, tools/, and testament/. Fixes #12687. (#12754)

This commit is contained in:
3n-k1
2019-11-28 02:32:11 -05:00
committed by Miran
parent a7aeabb9d2
commit 0944b0f441
11 changed files with 109 additions and 109 deletions

View File

@@ -97,7 +97,7 @@ proc bufSubstr(b: cstring, sPos, ePos: int): string {.inline.} =
## Don't assume cstring is '\0' terminated ## Don't assume cstring is '\0' terminated
let sz = ePos - sPos let sz = ePos - sPos
result = newString(sz+1) result = newString(sz+1)
copyMem(addr(result[0]), unsafeaddr(b[sPos]), sz) copyMem(addr(result[0]), unsafeAddr(b[sPos]), sz)
result.setLen(sz) result.setLen(sz)
proc matchOrFind(buf: cstring, pattern: Regex, matches: var openArray[string], proc matchOrFind(buf: cstring, pattern: Regex, matches: var openArray[string],

View File

@@ -189,7 +189,7 @@ proc newAsyncSocket*(domain, sockType, protocol: cint,
when defineSsl: when defineSsl:
proc getSslError(handle: SslPtr, err: cint): cint = proc getSslError(handle: SslPtr, err: cint): cint =
assert err < 0 assert err < 0
var ret = SSLGetError(handle, err.cint) var ret = SSL_get_error(handle, err.cint)
case ret case ret
of SSL_ERROR_ZERO_RETURN: of SSL_ERROR_ZERO_RETURN:
raiseSSLError("TLS/SSL connection failed to initiate, socket closed prematurely.") raiseSSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
@@ -211,9 +211,9 @@ when defineSsl:
let read = bioRead(socket.bioOut, addr data[0], len) let read = bioRead(socket.bioOut, addr data[0], len)
assert read != 0 assert read != 0
if read < 0: if read < 0:
raiseSslError() raiseSSLError()
data.setLen(read) data.setLen(read)
await socket.fd.AsyncFd.send(data, flags) await socket.fd.AsyncFD.send(data, flags)
proc appeaseSsl(socket: AsyncSocket, flags: set[SocketFlag], proc appeaseSsl(socket: AsyncSocket, flags: set[SocketFlag],
sslError: cint): owned(Future[bool]) {.async.} = sslError: cint): owned(Future[bool]) {.async.} =
@@ -692,13 +692,13 @@ proc close*(socket: AsyncSocket) =
defer: defer:
socket.fd.AsyncFD.closeSocket() socket.fd.AsyncFD.closeSocket()
when defineSsl: when defineSsl:
if socket.isSSL: if socket.isSsl:
let res = SslShutdown(socket.sslHandle) let res = SSL_shutdown(socket.sslHandle)
SSLFree(socket.sslHandle) SSL_free(socket.sslHandle)
if res == 0: if res == 0:
discard discard
elif res != 1: elif res != 1:
raiseSslError() raiseSSLError()
socket.closed = true # TODO: Add extra debugging checks for this. socket.closed = true # TODO: Add extra debugging checks for this.
when defineSsl: when defineSsl:
@@ -710,12 +710,12 @@ when defineSsl:
## prone to security vulnerabilities. ## prone to security vulnerabilities.
socket.isSsl = true socket.isSsl = true
socket.sslContext = ctx socket.sslContext = ctx
socket.sslHandle = SSLNew(socket.sslContext.context) socket.sslHandle = SSL_new(socket.sslContext.context)
if socket.sslHandle == nil: if socket.sslHandle == nil:
raiseSslError() raiseSSLError()
socket.bioIn = bioNew(bio_s_mem()) socket.bioIn = bioNew(bioSMem())
socket.bioOut = bioNew(bio_s_mem()) socket.bioOut = bioNew(bioSMem())
sslSetBio(socket.sslHandle, socket.bioIn, socket.bioOut) sslSetBio(socket.sslHandle, socket.bioIn, socket.bioOut)
proc wrapConnectedSocket*(ctx: SslContext, socket: AsyncSocket, proc wrapConnectedSocket*(ctx: SslContext, socket: AsyncSocket,

View File

@@ -112,7 +112,7 @@ template encodeInternal(s: typed): untyped =
result.setLen(outputIndex) result.setLen(outputIndex)
proc encode*[T: SomeInteger|char](s: openarray[T]): string = proc encode*[T: SomeInteger|char](s: openArray[T]): string =
## Encodes `s` into base64 representation. ## Encodes `s` into base64 representation.
## ##
## This procedure encodes an openarray (array or sequence) of either integers ## This procedure encodes an openarray (array or sequence) of either integers
@@ -186,7 +186,7 @@ proc decode*(s: string): string =
return (size * 3 div 4) + 6 return (size * 3 div 4) + 6
template inputChar(x: untyped) = template inputChar(x: untyped) =
let x = int decode_table[ord(s[inputIndex])] let x = int decodeTable[ord(s[inputIndex])]
inc inputIndex inc inputIndex
if x == invalidChar: if x == invalidChar:
raise newException(ValueError, raise newException(ValueError,

View File

@@ -280,10 +280,10 @@ proc fileError(msg: string) =
when not defined(ssl): when not defined(ssl):
type SSLContext = ref object type SslContext = ref object
var defaultSslContext {.threadvar.}: SSLContext var defaultSslContext {.threadvar.}: SslContext
proc getDefaultSSL(): SSLContext = proc getDefaultSSL(): SslContext =
result = defaultSslContext result = defaultSslContext
when defined(ssl): when defined(ssl):
if result == nil: if result == nil:

View File

@@ -124,8 +124,8 @@ type
bufLen: int # current length of buffer bufLen: int # current length of buffer
when defineSsl: when defineSsl:
isSsl: bool isSsl: bool
sslHandle: SSLPtr sslHandle: SslPtr
sslContext: SSLContext sslContext: SslContext
sslNoHandshake: bool # True if needs handshake. sslNoHandshake: bool # True if needs handshake.
sslHasPeekChar: bool sslHasPeekChar: bool
sslPeekChar: char sslPeekChar: char
@@ -450,30 +450,30 @@ proc fromSockAddr*(sa: Sockaddr_storage | SockAddr | Sockaddr_in | Sockaddr_in6,
when defineSsl: when defineSsl:
CRYPTO_malloc_init() CRYPTO_malloc_init()
doAssert SslLibraryInit() == 1 doAssert SslLibraryInit() == 1
SslLoadErrorStrings() SSL_load_error_strings()
ErrLoadBioStrings() ERR_load_BIO_strings()
OpenSSL_add_all_algorithms() OpenSSL_add_all_algorithms()
proc raiseSSLError*(s = "") = proc raiseSSLError*(s = "") =
## Raises a new SSL error. ## Raises a new SSL error.
if s != "": if s != "":
raise newException(SSLError, s) raise newException(SslError, s)
let err = ErrPeekLastError() let err = ERR_peek_last_error()
if err == 0: if err == 0:
raise newException(SSLError, "No error reported.") raise newException(SslError, "No error reported.")
if err == -1: if err == -1:
raiseOSError(osLastError()) raiseOSError(osLastError())
var errStr = $ErrErrorString(err, nil) var errStr = $ERR_error_string(err, nil)
case err case err
of 336032814, 336032784: of 336032814, 336032784:
errStr = "Please upgrade your OpenSSL library, it does not support the " & errStr = "Please upgrade your OpenSSL library, it does not support the " &
"necessary protocols. OpenSSL error is: " & errStr "necessary protocols. OpenSSL error is: " & errStr
else: else:
discard discard
raise newException(SSLError, errStr) raise newException(SslError, errStr)
proc getExtraData*(ctx: SSLContext, index: int): RootRef = proc getExtraData*(ctx: SslContext, index: int): RootRef =
## Retrieves arbitrary data stored inside SSLContext. ## Retrieves arbitrary data stored inside SslContext.
if index notin ctx.referencedData: if index notin ctx.referencedData:
raise newException(IndexError, "No data with that index.") raise newException(IndexError, "No data with that index.")
let res = ctx.context.SSL_CTX_get_ex_data(index.cint) let res = ctx.context.SSL_CTX_get_ex_data(index.cint)
@@ -481,8 +481,8 @@ when defineSsl:
raiseSSLError() raiseSSLError()
return cast[RootRef](res) return cast[RootRef](res)
proc setExtraData*(ctx: SSLContext, index: int, data: RootRef) = proc setExtraData*(ctx: SslContext, index: int, data: RootRef) =
## Stores arbitrary data inside SSLContext. The unique `index` ## Stores arbitrary data inside SslContext. The unique `index`
## should be retrieved using getSslContextExtraDataIndex. ## should be retrieved using getSslContextExtraDataIndex.
if index in ctx.referencedData: if index in ctx.referencedData:
GC_unref(getExtraData(ctx, index)) GC_unref(getExtraData(ctx, index))
@@ -495,7 +495,7 @@ when defineSsl:
GC_ref(data) GC_ref(data)
# http://simplestcodings.blogspot.co.uk/2010/08/secure-server-client-using-openssl-in-c.html # http://simplestcodings.blogspot.co.uk/2010/08/secure-server-client-using-openssl-in-c.html
proc loadCertificates(ctx: SSL_CTX, certFile, keyFile: string) = proc loadCertificates(ctx: SslCtx, certFile, keyFile: string) =
if certFile != "" and not existsFile(certFile): if certFile != "" and not existsFile(certFile):
raise newException(system.IOError, raise newException(system.IOError,
"Certificate file could not be found: " & certFile) "Certificate file could not be found: " & certFile)
@@ -503,7 +503,7 @@ when defineSsl:
raise newException(system.IOError, "Key file could not be found: " & keyFile) raise newException(system.IOError, "Key file could not be found: " & keyFile)
if certFile != "": if certFile != "":
var ret = SSLCTXUseCertificateChainFile(ctx, certFile) var ret = SSL_CTX_use_certificate_chain_file(ctx, certFile)
if ret != 1: if ret != 1:
raiseSSLError() raiseSSLError()
@@ -517,7 +517,7 @@ when defineSsl:
raiseSSLError("Verification of private key file failed.") raiseSSLError("Verification of private key file failed.")
proc newContext*(protVersion = protSSLv23, verifyMode = CVerifyPeer, proc newContext*(protVersion = protSSLv23, verifyMode = CVerifyPeer,
certFile = "", keyFile = "", cipherList = "ALL"): SSLContext = certFile = "", keyFile = "", cipherList = "ALL"): SslContext =
## Creates an SSL context. ## Creates an SSL context.
## ##
## Protocol version specifies the protocol to use. SSLv2, SSLv3, TLSv1 ## Protocol version specifies the protocol to use. SSLv2, SSLv3, TLSv1
@@ -537,38 +537,38 @@ when defineSsl:
## or using ECDSA: ## or using ECDSA:
## - ``openssl ecparam -out mykey.pem -name secp256k1 -genkey`` ## - ``openssl ecparam -out mykey.pem -name secp256k1 -genkey``
## - ``openssl req -new -key mykey.pem -x509 -nodes -days 365 -out mycert.pem`` ## - ``openssl req -new -key mykey.pem -x509 -nodes -days 365 -out mycert.pem``
var newCTX: SSL_CTX var newCTX: SslCtx
case protVersion case protVersion
of protSSLv23: of protSSLv23:
newCTX = SSL_CTX_new(SSLv23_method()) # SSlv2,3 and TLS1 support. newCTX = SSL_CTX_new(SSLv23_method()) # SSlv2,3 and TLS1 support.
of protSSLv2: of protSSLv2:
raiseSslError("SSLv2 is no longer secure and has been deprecated, use protSSLv23") raiseSSLError("SSLv2 is no longer secure and has been deprecated, use protSSLv23")
of protSSLv3: of protSSLv3:
raiseSslError("SSLv3 is no longer secure and has been deprecated, use protSSLv23") raiseSSLError("SSLv3 is no longer secure and has been deprecated, use protSSLv23")
of protTLSv1: of protTLSv1:
newCTX = SSL_CTX_new(TLSv1_method()) newCTX = SSL_CTX_new(TLSv1_method())
if newCTX.SSLCTXSetCipherList(cipherList) != 1: if newCTX.SSL_CTX_set_cipher_list(cipherList) != 1:
raiseSSLError() raiseSSLError()
case verifyMode case verifyMode
of CVerifyPeer: of CVerifyPeer:
newCTX.SSLCTXSetVerify(SSLVerifyPeer, nil) newCTX.SSL_CTX_set_verify(SSL_VERIFY_PEER, nil)
of CVerifyNone: of CVerifyNone:
newCTX.SSLCTXSetVerify(SSLVerifyNone, nil) newCTX.SSL_CTX_set_verify(SSL_VERIFY_NONE, nil)
if newCTX == nil: if newCTX == nil:
raiseSSLError() raiseSSLError()
discard newCTX.SSLCTXSetMode(SSL_MODE_AUTO_RETRY) discard newCTX.SSLCTXSetMode(SSL_MODE_AUTO_RETRY)
newCTX.loadCertificates(certFile, keyFile) newCTX.loadCertificates(certFile, keyFile)
result = SSLContext(context: newCTX, referencedData: initSet[int](), result = SslContext(context: newCTX, referencedData: initSet[int](),
extraInternal: new(SslContextExtraInternal)) extraInternal: new(SslContextExtraInternal))
proc getExtraInternal(ctx: SSLContext): SslContextExtraInternal = proc getExtraInternal(ctx: SslContext): SslContextExtraInternal =
return ctx.extraInternal return ctx.extraInternal
proc destroyContext*(ctx: SSLContext) = proc destroyContext*(ctx: SslContext) =
## Free memory referenced by SSLContext. ## Free memory referenced by SslContext.
# We assume here that OpenSSL's internal indexes increase by 1 each time. # We assume here that OpenSSL's internal indexes increase by 1 each time.
# That means we can assume that the next internal index is the length of # That means we can assume that the next internal index is the length of
@@ -577,20 +577,20 @@ when defineSsl:
GC_unref(getExtraData(ctx, i).RootRef) GC_unref(getExtraData(ctx, i).RootRef)
ctx.context.SSL_CTX_free() ctx.context.SSL_CTX_free()
proc `pskIdentityHint=`*(ctx: SSLContext, hint: string) = proc `pskIdentityHint=`*(ctx: SslContext, hint: string) =
## Sets the identity hint passed to server. ## Sets the identity hint passed to server.
## ##
## Only used in PSK ciphersuites. ## Only used in PSK ciphersuites.
if ctx.context.SSL_CTX_use_psk_identity_hint(hint) <= 0: if ctx.context.SSL_CTX_use_psk_identity_hint(hint) <= 0:
raiseSSLError() raiseSSLError()
proc clientGetPskFunc*(ctx: SSLContext): SslClientGetPskFunc = proc clientGetPskFunc*(ctx: SslContext): SslClientGetPskFunc =
return ctx.getExtraInternal().clientGetPskFunc return ctx.getExtraInternal().clientGetPskFunc
proc pskClientCallback(ssl: SslPtr; hint: cstring; identity: cstring; proc pskClientCallback(ssl: SslPtr; hint: cstring; identity: cstring;
max_identity_len: cuint; psk: ptr cuchar; max_identity_len: cuint; psk: ptr cuchar;
max_psk_len: cuint): cuint {.cdecl.} = max_psk_len: cuint): cuint {.cdecl.} =
let ctx = SSLContext(context: ssl.SSL_get_SSL_CTX) let ctx = SslContext(context: ssl.SSL_get_SSL_CTX)
let hintString = if hint == nil: "" else: $hint let hintString = if hint == nil: "" else: $hint
let (identityString, pskString) = (ctx.clientGetPskFunc)(hintString) let (identityString, pskString) = (ctx.clientGetPskFunc)(hintString)
if psk.len.cuint > max_psk_len: if psk.len.cuint > max_psk_len:
@@ -603,7 +603,7 @@ when defineSsl:
return pskString.len.cuint return pskString.len.cuint
proc `clientGetPskFunc=`*(ctx: SSLContext, fun: SslClientGetPskFunc) = proc `clientGetPskFunc=`*(ctx: SslContext, fun: SslClientGetPskFunc) =
## Sets function that returns the client identity and the PSK based on identity ## Sets function that returns the client identity and the PSK based on identity
## hint from the server. ## hint from the server.
## ##
@@ -612,12 +612,12 @@ when defineSsl:
ctx.context.SSL_CTX_set_psk_client_callback( ctx.context.SSL_CTX_set_psk_client_callback(
if fun == nil: nil else: pskClientCallback) if fun == nil: nil else: pskClientCallback)
proc serverGetPskFunc*(ctx: SSLContext): SslServerGetPskFunc = proc serverGetPskFunc*(ctx: SslContext): SslServerGetPskFunc =
return ctx.getExtraInternal().serverGetPskFunc return ctx.getExtraInternal().serverGetPskFunc
proc pskServerCallback(ssl: SslCtx; identity: cstring; psk: ptr cuchar; proc pskServerCallback(ssl: SslCtx; identity: cstring; psk: ptr cuchar;
max_psk_len: cint): cuint {.cdecl.} = max_psk_len: cint): cuint {.cdecl.} =
let ctx = SSLContext(context: ssl.SSL_get_SSL_CTX) let ctx = SslContext(context: ssl.SSL_get_SSL_CTX)
let pskString = (ctx.serverGetPskFunc)($identity) let pskString = (ctx.serverGetPskFunc)($identity)
if psk.len.cint > max_psk_len: if psk.len.cint > max_psk_len:
return 0 return 0
@@ -625,7 +625,7 @@ when defineSsl:
return pskString.len.cuint return pskString.len.cuint
proc `serverGetPskFunc=`*(ctx: SSLContext, fun: SslServerGetPskFunc) = proc `serverGetPskFunc=`*(ctx: SslContext, fun: SslServerGetPskFunc) =
## Sets function that returns PSK based on the client identity. ## Sets function that returns PSK based on the client identity.
## ##
## Only used in PSK ciphersuites. ## Only used in PSK ciphersuites.
@@ -635,10 +635,10 @@ when defineSsl:
proc getPskIdentity*(socket: Socket): string = proc getPskIdentity*(socket: Socket): string =
## Gets the PSK identity provided by the client. ## Gets the PSK identity provided by the client.
assert socket.isSSL assert socket.isSsl
return $(socket.sslHandle.SSL_get_psk_identity) return $(socket.sslHandle.SSL_get_psk_identity)
proc wrapSocket*(ctx: SSLContext, socket: Socket) = proc wrapSocket*(ctx: SslContext, socket: Socket) =
## Wraps a socket in an SSL context. This function effectively turns ## Wraps a socket in an SSL context. This function effectively turns
## ``socket`` into an SSL socket. ## ``socket`` into an SSL socket.
## ##
@@ -648,19 +648,19 @@ when defineSsl:
## **Disclaimer**: This code is not well tested, may be very unsafe and ## **Disclaimer**: This code is not well tested, may be very unsafe and
## prone to security vulnerabilities. ## prone to security vulnerabilities.
assert(not socket.isSSL) assert(not socket.isSsl)
socket.isSSL = true socket.isSsl = true
socket.sslContext = ctx socket.sslContext = ctx
socket.sslHandle = SSLNew(socket.sslContext.context) socket.sslHandle = SSL_new(socket.sslContext.context)
socket.sslNoHandshake = false socket.sslNoHandshake = false
socket.sslHasPeekChar = false socket.sslHasPeekChar = false
if socket.sslHandle == nil: if socket.sslHandle == nil:
raiseSSLError() raiseSSLError()
if SSLSetFd(socket.sslHandle, socket.fd) != 1: if SSL_set_fd(socket.sslHandle, socket.fd) != 1:
raiseSSLError() raiseSSLError()
proc wrapConnectedSocket*(ctx: SSLContext, socket: Socket, proc wrapConnectedSocket*(ctx: SslContext, socket: Socket,
handshake: SslHandshakeType, handshake: SslHandshakeType,
hostname: string = "") = hostname: string = "") =
## Wraps a connected socket in an SSL context. This function effectively ## Wraps a connected socket in an SSL context. This function effectively
@@ -680,10 +680,10 @@ when defineSsl:
# Discard result in case OpenSSL version doesn't support SNI, or we're # Discard result in case OpenSSL version doesn't support SNI, or we're
# not using TLSv1+ # not using TLSv1+
discard SSL_set_tlsext_host_name(socket.sslHandle, hostname) discard SSL_set_tlsext_host_name(socket.sslHandle, hostname)
let ret = SSLConnect(socket.sslHandle) let ret = SSL_connect(socket.sslHandle)
socketError(socket, ret) socketError(socket, ret)
of handshakeAsServer: of handshakeAsServer:
let ret = SSLAccept(socket.sslHandle) let ret = SSL_accept(socket.sslHandle)
socketError(socket, ret) socketError(socket, ret)
proc getSocketError*(socket: Socket): OSErrorCode = proc getSocketError*(socket: Socket): OSErrorCode =
@@ -697,7 +697,7 @@ proc getSocketError*(socket: Socket): OSErrorCode =
proc socketError*(socket: Socket, err: int = -1, async = false, proc socketError*(socket: Socket, err: int = -1, async = false,
lastError = (-1).OSErrorCode) = lastError = (-1).OSErrorCode) =
## Raises an OSError based on the error code returned by ``SSLGetError`` ## Raises an OSError based on the error code returned by ``SSL_get_error``
## (for SSL sockets) and ``osLastError`` otherwise. ## (for SSL sockets) and ``osLastError`` otherwise.
## ##
## If ``async`` is ``true`` no error will be thrown in the case when the ## If ``async`` is ``true`` no error will be thrown in the case when the
@@ -705,9 +705,9 @@ proc socketError*(socket: Socket, err: int = -1, async = false,
## ##
## If ``err`` is not lower than 0 no exception will be raised. ## If ``err`` is not lower than 0 no exception will be raised.
when defineSsl: when defineSsl:
if socket.isSSL: if socket.isSsl:
if err <= 0: if err <= 0:
var ret = SSLGetError(socket.sslHandle, err.cint) var ret = SSL_get_error(socket.sslHandle, err.cint)
case ret case ret
of SSL_ERROR_ZERO_RETURN: of SSL_ERROR_ZERO_RETURN:
raiseSSLError("TLS/SSL connection failed to initiate, socket closed prematurely.") raiseSSLError("TLS/SSL connection failed to initiate, socket closed prematurely.")
@@ -723,13 +723,13 @@ proc socketError*(socket: Socket, err: int = -1, async = false,
raiseSSLError("Function for x509 lookup has been called.") raiseSSLError("Function for x509 lookup has been called.")
of SSL_ERROR_SYSCALL: of SSL_ERROR_SYSCALL:
var errStr = "IO error has occurred " var errStr = "IO error has occurred "
let sslErr = ErrPeekLastError() let sslErr = ERR_peek_last_error()
if sslErr == 0 and err == 0: if sslErr == 0 and err == 0:
errStr.add "because an EOF was observed that violates the protocol" errStr.add "because an EOF was observed that violates the protocol"
elif sslErr == 0 and err == -1: elif sslErr == 0 and err == -1:
errStr.add "in the BIO layer" errStr.add "in the BIO layer"
else: else:
let errStr = $ErrErrorString(sslErr, nil) let errStr = $ERR_error_string(sslErr, nil)
raiseSSLError(errStr & ": " & errStr) raiseSSLError(errStr & ": " & errStr)
let osErr = osLastError() let osErr = osLastError()
raiseOSError(osErr, errStr) raiseOSError(osErr, errStr)
@@ -737,7 +737,7 @@ proc socketError*(socket: Socket, err: int = -1, async = false,
raiseSSLError() raiseSSLError()
else: raiseSSLError("Unknown Error") else: raiseSSLError("Unknown Error")
if err == -1 and not (when defineSsl: socket.isSSL else: false): if err == -1 and not (when defineSsl: socket.isSsl else: false):
var lastE = if lastError.int == -1: getSocketError(socket) else: lastError var lastE = if lastError.int == -1: getSocketError(socket) else: lastError
if async: if async:
when useWinVersion: when useWinVersion:
@@ -812,16 +812,16 @@ proc acceptAddr*(server: Socket, client: var owned(Socket), address: var string,
# Handle SSL. # Handle SSL.
when defineSsl: when defineSsl:
if server.isSSL: if server.isSsl:
# We must wrap the client sock in a ssl context. # We must wrap the client sock in a ssl context.
server.sslContext.wrapSocket(client) server.sslContext.wrapSocket(client)
let ret = SSLAccept(client.sslHandle) let ret = SSL_accept(client.sslHandle)
socketError(client, ret, false) socketError(client, ret, false)
when false: #defineSsl: when false: #defineSsl:
proc acceptAddrSSL*(server: Socket, client: var Socket, proc acceptAddrSSL*(server: Socket, client: var Socket,
address: var string): SSLAcceptResult {. address: var string): SSL_acceptResult {.
tags: [ReadIOEffect].} = tags: [ReadIOEffect].} =
## This procedure should only be used for non-blocking **SSL** sockets. ## This procedure should only be used for non-blocking **SSL** sockets.
## It will immediately return with one of the following values: ## It will immediately return with one of the following values:
@@ -839,15 +839,15 @@ when false: #defineSsl:
## to connect. ## to connect.
template doHandshake(): untyped = template doHandshake(): untyped =
when defineSsl: when defineSsl:
if server.isSSL: if server.isSsl:
client.setBlocking(false) client.setBlocking(false)
# We must wrap the client sock in a ssl context. # We must wrap the client sock in a ssl context.
if not client.isSSL or client.sslHandle == nil: if not client.isSsl or client.sslHandle == nil:
server.sslContext.wrapSocket(client) server.sslContext.wrapSocket(client)
let ret = SSLAccept(client.sslHandle) let ret = SSL_accept(client.sslHandle)
while ret <= 0: while ret <= 0:
let err = SSLGetError(client.sslHandle, ret) let err = SSL_get_error(client.sslHandle, ret)
if err != SSL_ERROR_WANT_ACCEPT: if err != SSL_ERROR_WANT_ACCEPT:
case err case err
of SSL_ERROR_ZERO_RETURN: of SSL_ERROR_ZERO_RETURN:
@@ -864,7 +864,7 @@ when false: #defineSsl:
raiseSSLError("Unknown error") raiseSSLError("Unknown error")
client.sslNoHandshake = false client.sslNoHandshake = false
if client.isSSL and client.sslNoHandshake: if client.isSsl and client.sslNoHandshake:
doHandshake() doHandshake()
return AcceptSuccess return AcceptSuccess
else: else:
@@ -887,21 +887,21 @@ proc close*(socket: Socket) =
## Closes a socket. ## Closes a socket.
try: try:
when defineSsl: when defineSsl:
if socket.isSSL and socket.sslHandle != nil: if socket.isSsl and socket.sslHandle != nil:
ErrClearError() ErrClearError()
# As we are closing the underlying socket immediately afterwards, # As we are closing the underlying socket immediately afterwards,
# it is valid, under the TLS standard, to perform a unidirectional # it is valid, under the TLS standard, to perform a unidirectional
# shutdown i.e not wait for the peers "close notify" alert with a second # shutdown i.e not wait for the peers "close notify" alert with a second
# call to SSLShutdown # call to SSL_shutdown
let res = SSLShutdown(socket.sslHandle) let res = SSL_shutdown(socket.sslHandle)
if res == 0: if res == 0:
discard discard
elif res != 1: elif res != 1:
socketError(socket, res) socketError(socket, res)
finally: finally:
when defineSsl: when defineSsl:
if socket.isSSL and socket.sslHandle != nil: if socket.isSsl and socket.sslHandle != nil:
SSLFree(socket.sslHandle) SSL_free(socket.sslHandle)
socket.sslHandle = nil socket.sslHandle = nil
socket.fd.close() socket.fd.close()
@@ -980,7 +980,7 @@ when defined(ssl):
## and the server that ``socket`` is connected to. ## and the server that ``socket`` is connected to.
## ##
## Throws SslError if ``socket`` is not an SSL socket. ## Throws SslError if ``socket`` is not an SSL socket.
if socket.isSSL: if socket.isSsl:
return not socket.sslNoHandshake return not socket.sslNoHandshake
else: else:
raiseSSLError("Socket is not an SSL socket.") raiseSSLError("Socket is not an SSL socket.")
@@ -992,7 +992,7 @@ proc hasDataBuffered*(s: Socket): bool =
result = s.bufLen > 0 and s.currPos != s.bufLen result = s.bufLen > 0 and s.currPos != s.bufLen
when defineSsl: when defineSsl:
if s.isSSL and not result: if s.isSsl and not result:
result = s.sslHasPeekChar result = s.sslHasPeekChar
proc select(readfd: Socket, timeout = 500): int = proc select(readfd: Socket, timeout = 500): int =
@@ -1015,7 +1015,7 @@ proc uniRecv(socket: Socket, buffer: pointer, size, flags: cint): int =
assert(not socket.isClosed, "Cannot `recv` on a closed socket") assert(not socket.isClosed, "Cannot `recv` on a closed socket")
when defineSsl: when defineSsl:
if socket.isSsl: if socket.isSsl:
return SSLRead(socket.sslHandle, buffer, size) return SSL_read(socket.sslHandle, buffer, size)
return recv(socket.fd, buffer, size, flags) return recv(socket.fd, buffer, size, flags)
@@ -1067,7 +1067,7 @@ proc recv*(socket: Socket, data: pointer, size: int): int {.tags: [
result = read result = read
else: else:
when defineSsl: when defineSsl:
if socket.isSSL: if socket.isSsl:
if socket.sslHasPeekChar: # TODO: Merge this peek char mess into uniRecv if socket.sslHasPeekChar: # TODO: Merge this peek char mess into uniRecv
copyMem(data, addr(socket.sslPeekChar), 1) copyMem(data, addr(socket.sslPeekChar), 1)
socket.sslHasPeekChar = false socket.sslHasPeekChar = false
@@ -1106,11 +1106,11 @@ proc waitFor(socket: Socket, waited: var Duration, timeout, size: int,
raise newException(TimeoutError, "Call to '" & funcName & "' timed out.") raise newException(TimeoutError, "Call to '" & funcName & "' timed out.")
when defineSsl: when defineSsl:
if socket.isSSL: if socket.isSsl:
if socket.hasDataBuffered: if socket.hasDataBuffered:
# sslPeekChar is present. # sslPeekChar is present.
return 1 return 1
let sslPending = SSLPending(socket.sslHandle) let sslPending = SSL_pending(socket.sslHandle)
if sslPending != 0: if sslPending != 0:
return min(sslPending, size) return min(sslPending, size)
@@ -1212,7 +1212,7 @@ proc peekChar(socket: Socket, c: var char): int {.tags: [ReadIOEffect].} =
c = socket.buffer[socket.currPos] c = socket.buffer[socket.currPos]
else: else:
when defineSsl: when defineSsl:
if socket.isSSL: if socket.isSsl:
if not socket.sslHasPeekChar: if not socket.sslHasPeekChar:
result = uniRecv(socket, addr(socket.sslPeekChar), 1, 0'i32) result = uniRecv(socket, addr(socket.sslPeekChar), 1, 0'i32)
socket.sslHasPeekChar = true socket.sslHasPeekChar = true
@@ -1351,8 +1351,8 @@ proc send*(socket: Socket, data: pointer, size: int): int {.
## the version below. ## the version below.
assert(not socket.isClosed, "Cannot `send` on a closed socket") assert(not socket.isClosed, "Cannot `send` on a closed socket")
when defineSsl: when defineSsl:
if socket.isSSL: if socket.isSsl:
return SSLWrite(socket.sslHandle, cast[cstring](data), size) return SSL_write(socket.sslHandle, cast[cstring](data), size)
when useWinVersion or defined(macosx): when useWinVersion or defined(macosx):
result = send(socket.fd, data, size.cint, 0'i32) result = send(socket.fd, data, size.cint, 0'i32)
@@ -1431,7 +1431,7 @@ proc sendTo*(socket: Socket, address: string, port: Port,
proc isSsl*(socket: Socket): bool = proc isSsl*(socket: Socket): bool =
## Determines whether ``socket`` is a SSL socket. ## Determines whether ``socket`` is a SSL socket.
when defineSsl: when defineSsl:
result = socket.isSSL result = socket.isSsl
else: else:
result = false result = false
@@ -1629,14 +1629,14 @@ proc connect*(socket: Socket, address: string,
if not success: raiseOSError(lastError) if not success: raiseOSError(lastError)
when defineSsl: when defineSsl:
if socket.isSSL: if socket.isSsl:
# RFC3546 for SNI specifies that IP addresses are not allowed. # RFC3546 for SNI specifies that IP addresses are not allowed.
if not isIpAddress(address): if not isIpAddress(address):
# Discard result in case OpenSSL version doesn't support SNI, or we're # Discard result in case OpenSSL version doesn't support SNI, or we're
# not using TLSv1+ # not using TLSv1+
discard SSL_set_tlsext_host_name(socket.sslHandle, address) discard SSL_set_tlsext_host_name(socket.sslHandle, address)
let ret = SSLConnect(socket.sslHandle) let ret = SSL_connect(socket.sslHandle)
socketError(socket, ret) socketError(socket, ret)
proc connectAsync(socket: Socket, name: string, port = Port(0), proc connectAsync(socket: Socket, name: string, port = Port(0),
@@ -1693,7 +1693,7 @@ proc connect*(socket: Socket, address: string, port = Port(0),
if res != 0: if res != 0:
raiseOSError(OSErrorCode(res)) raiseOSError(OSErrorCode(res))
when defineSsl and not defined(nimdoc): when defineSsl and not defined(nimdoc):
if socket.isSSL: if socket.isSsl:
socket.fd.setBlocking(true) socket.fd.setBlocking(true)
doAssert socket.gotHandshake() doAssert socket.gotHandshake()
socket.fd.setBlocking(true) socket.fd.setBlocking(true)

View File

@@ -199,7 +199,7 @@ when (NimMajor, NimMinor) >= (1, 1):
doAssert a.outplace(insert(10)).outplace(sort()) == sorted(aCopy) doAssert a.outplace(insert(10)).outplace(sort()) == sorted(aCopy)
expectKind call, nnkCallKinds expectKind call, nnkCallKinds
let tmp = gensym(nskVar, "outplaceResult") let tmp = genSym(nskVar, "outplaceResult")
var callsons = call[0..^1] var callsons = call[0..^1]
callsons.insert(tmp, inplaceArgPosition) callsons.insert(tmp, inplaceArgPosition)
result = newTree(nnkStmtListExpr, result = newTree(nnkStmtListExpr,

View File

@@ -23,8 +23,8 @@ var
proc getMachine*(): MachineId = proc getMachine*(): MachineId =
var name = execProcess("hostname").string.strip var name = execProcess("hostname").string.strip
if name.len == 0: if name.len == 0:
name = when defined(posix): getenv("HOSTNAME").string name = when defined(posix): getEnv("HOSTNAME").string
else: getenv("COMPUTERNAME").string else: getEnv("COMPUTERNAME").string
if name.len == 0: if name.len == 0:
quit "cannot determine the machine name" quit "cannot determine the machine name"

View File

@@ -301,7 +301,7 @@ proc testNimInAction(r: var TResults, cat: Category, options: string) =
testSpec r, makeTest(filename, options, cat), {targetJS} testSpec r, makeTest(filename, options, cat), {targetJS}
template testCPP(filename: untyped) = template testCPP(filename: untyped) =
testSpec r, makeTest(filename, options, cat), {targetCPP} testSpec r, makeTest(filename, options, cat), {targetCpp}
let tests = [ let tests = [
"niminaction/Chapter1/various1", "niminaction/Chapter1/various1",
@@ -388,7 +388,7 @@ proc findMainFile(dir: string): string =
elif file.endsWith(".nim"): elif file.endsWith(".nim"):
if result.len == 0: result = file if result.len == 0: result = file
inc nimFiles inc nimFiles
if nimFiles != 1: result.setlen(0) if nimFiles != 1: result.setLen(0)
proc manyLoc(r: var TResults, cat: Category, options: string) = proc manyLoc(r: var TResults, cat: Category, options: string) =
for kind, dir in os.walkDir("tests/manyloc"): for kind, dir in os.walkDir("tests/manyloc"):
@@ -540,7 +540,7 @@ const MegaTestCat = "megatest"
proc `&.?`(a, b: string): string = proc `&.?`(a, b: string): string =
# candidate for the stdlib? # candidate for the stdlib?
result = if b.startswith(a): b else: a & b result = if b.startsWith(a): b else: a & b
proc processSingleTest(r: var TResults, cat: Category, options, test: string) = proc processSingleTest(r: var TResults, cat: Category, options, test: string) =
let test = testsDir &.? cat.string / test let test = testsDir &.? cat.string / test

View File

@@ -63,7 +63,7 @@ proc generateTestResultPanelPartial(outfile: File, testResultRow: JsonNode) =
type type
AllTests = object AllTests = object
data: JSonNode data: JsonNode
totalCount, successCount, ignoredCount, failedCount: int totalCount, successCount, ignoredCount, failedCount: int
successPercentage, ignoredPercentage, failedPercentage: BiggestFloat successPercentage, ignoredPercentage, failedPercentage: BiggestFloat

View File

@@ -90,7 +90,7 @@ proc getFileDir(filename: string): string =
if not result.isAbsolute(): if not result.isAbsolute():
result = getCurrentDir() / result result = getCurrentDir() / result
proc execCmdEx2(command: string, args: openarray[string]; workingDir, input: string = ""): tuple[ proc execCmdEx2(command: string, args: openArray[string]; workingDir, input: string = ""): tuple[
cmdLine: string, cmdLine: string,
output: TaintedString, output: TaintedString,
exitCode: int] {.tags: exitCode: int] {.tags:
@@ -465,7 +465,7 @@ proc testSpecHelper(r: var TResults, test: TTest, expected: TSpec, target: TTarg
if exitCode != expected.exitCode: if exitCode != expected.exitCode:
r.addResult(test, target, "exitcode: " & $expected.exitCode, r.addResult(test, target, "exitcode: " & $expected.exitCode,
"exitcode: " & $exitCode & "\n\nOutput:\n" & "exitcode: " & $exitCode & "\n\nOutput:\n" &
bufB, reExitCodesDiffer) bufB, reExitcodesDiffer)
elif (expected.outputCheck == ocEqual and expected.output != bufB) or elif (expected.outputCheck == ocEqual and expected.output != bufB) or
(expected.outputCheck == ocSubstr and expected.output notin bufB): (expected.outputCheck == ocSubstr and expected.output notin bufB):
given.err = reOutputsDiffer given.err = reOutputsDiffer
@@ -522,7 +522,7 @@ proc testC(r: var TResults, test: TTest, action: TTestAction) =
elif action == actionRun: elif action == actionRun:
let exeFile = changeFileExt(test.name, ExeExt) let exeFile = changeFileExt(test.name, ExeExt)
var (_, exitCode) = execCmdEx(exeFile, options = {poStdErrToStdOut, poUsePath}) var (_, exitCode) = execCmdEx(exeFile, options = {poStdErrToStdOut, poUsePath})
if exitCode != 0: given.err = reExitCodesDiffer if exitCode != 0: given.err = reExitcodesDiffer
if given.err == reSuccess: inc(r.passed) if given.err == reSuccess: inc(r.passed)
proc testExec(r: var TResults, test: TTest) = proc testExec(r: var TResults, test: TTest) =
@@ -535,7 +535,7 @@ proc testExec(r: var TResults, test: TTest) =
if errC == 0: if errC == 0:
given.err = reSuccess given.err = reSuccess
else: else:
given.err = reExitCodesDiffer given.err = reExitcodesDiffer
given.msg = outp.string given.msg = outp.string
if given.err == reSuccess: inc(r.passed) if given.err == reSuccess: inc(r.passed)
@@ -599,8 +599,8 @@ proc loadSkipFrom(name: string): seq[string] =
result.add sline result.add sline
proc main() = proc main() =
os.putenv "NIMTEST_COLOR", "never" os.putEnv "NIMTEST_COLOR", "never"
os.putenv "NIMTEST_OUTPUT_LVL", "PRINT_FAILURES" os.putEnv "NIMTEST_OUTPUT_LVL", "PRINT_FAILURES"
backend.open() backend.open()
var optPrintResults = false var optPrintResults = false
@@ -612,7 +612,7 @@ proc main() =
var p = initOptParser() var p = initOptParser()
p.next() p.next()
while p.kind in {cmdLongoption, cmdShortOption}: while p.kind in {cmdLongOption, cmdShortOption}:
case p.key.string.normalize case p.key.string.normalize
of "print", "verbose": optPrintResults = true of "print", "verbose": optPrintResults = true
of "failing": optFailing = true of "failing": optFailing = true

View File

@@ -183,10 +183,10 @@ proc processCmdLine*(pass: TCmdLinePass, cmd: string; conf: ConfigRef) =
parseopt.next(p) parseopt.next(p)
case p.kind case p.kind
of cmdEnd: break of cmdEnd: break
of cmdLongoption, cmdShortOption: of cmdLongOption, cmdShortOption:
case p.key.normalize case p.key.normalize
of "help", "h": of "help", "h":
stdout.writeline(Usage) stdout.writeLine(Usage)
quit() quit()
of "project": of "project":
conf.projectName = p.val conf.projectName = p.val
@@ -216,7 +216,7 @@ proc handleCmdLine(cache: IdentCache; conf: ConfigRef) =
self.initDefinesProg(conf, "nimfind") self.initDefinesProg(conf, "nimfind")
if paramCount() == 0: if paramCount() == 0:
stdout.writeline(Usage) stdout.writeLine(Usage)
return return
self.processCmdLineAndProjectPath(conf) self.processCmdLineAndProjectPath(conf)
@@ -232,4 +232,4 @@ proc handleCmdLine(cache: IdentCache; conf: ConfigRef) =
discard self.loadConfigsAndRunMainCommand(cache, conf) discard self.loadConfigsAndRunMainCommand(cache, conf)
handleCmdline(newIdentCache(), newConfigRef()) handleCmdLine(newIdentCache(), newConfigRef())