Skip to content

Commit 881ac79

Browse files
authored
make sure AsyncSocketImpl.write() throws only IOException (#183)
1 parent a88d0b3 commit 881ac79

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

ziti/src/main/kotlin/org/openziti/net/nio/AsyncSocketImpl.kt

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2018-2020 NetFoundry, Inc.
2+
* Copyright (c) 2018-2021 NetFoundry, Inc.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -43,7 +43,7 @@ internal class AsyncSocketImpl(private val connector: Connector = DefaultConnect
4343
val cf = ch.connect(addr)
4444
try {
4545
if (timeout > 0) {
46-
cf.get(timeout.toLong(), TimeUnit.MILLISECONDS);
46+
cf.get(timeout.toLong(), TimeUnit.MILLISECONDS)
4747
} else {
4848
cf.get()
4949
}
@@ -174,22 +174,19 @@ internal class AsyncSocketImpl(private val connector: Connector = DefaultConnect
174174
}
175175
})
176176

177-
try {
177+
val result = runCatching {
178178
val read = if (to > 0) rf.get(to, TimeUnit.MILLISECONDS) else rf.get()
179179
if (read == -1) {
180-
return -1
180+
return@runCatching -1
181181
}
182182
inputLock.acquire()
183183
val count1 = min(len, input.remaining())
184184
input.get(b, off, count1)
185185
inputLock.release()
186-
return count1
187-
} catch (toex: TimeoutException) {
188-
throw SocketTimeoutException(toex.message)
189-
} catch (exx: ExecutionException) {
190-
exx.cause?.let { throw it }
191-
throw exx
186+
count1
192187
}
188+
189+
return result.getOrElse { ex -> throwIOException(ex) }
193190
}
194191
}
195192

@@ -224,8 +221,13 @@ internal class AsyncSocketImpl(private val connector: Connector = DefaultConnect
224221
}
225222

226223
override fun write(b: ByteArray, off: Int, len: Int) {
227-
val wf = channel.write(ByteBuffer.wrap(b, off, len))
228-
wf.get()
224+
runCatching {
225+
val wf = channel.write(ByteBuffer.wrap(b, off, len))
226+
wf.get()
227+
}.onFailure { ex ->
228+
e(ex) { "unexpected exception during write[buf.len=${b.size}, off=$off, len=$len]" }
229+
throwIOException(ex)
230+
}
229231
}
230232
}
231233

@@ -236,4 +238,15 @@ internal class AsyncSocketImpl(private val connector: Connector = DefaultConnect
236238
override fun sendUrgentData(data: Int) {
237239
outputStream.write(data)
238240
}
241+
242+
private fun throwIOException(ex: Throwable): Nothing {
243+
if (ex is IOException) throw ex
244+
245+
if (ex is TimeoutException) throw SocketTimeoutException(ex.message)
246+
247+
val cause = ex.cause
248+
if (cause is IOException) throw cause
249+
250+
throw IOException("unexpected exception", ex)
251+
}
239252
}

0 commit comments

Comments
 (0)