scoop:scoop.http.client:0.1.0
src/body/digest.scoop
Selected production source · src/body/digest.scoop
1
package scoop.http.client3
import scoop.asyncio.*4
import scoop.collections.emptyList5
import scoop.crypto.*6
import scoop.platform.memory.NativeByteBuffer7
import scoop.text.toHexString9
internal class ClientEntityDigest(val algorithm: DigestAlgorithm, val bytes: Array<Byte>)11
internal fun replaceClientEntityDigest(existing: List<ClientEntityDigest>, algorithm: HttpDigestAlgorithm,12
bytes: List<Byte>): Array<ClientEntityDigest> {13
val actual = clientDigestAlgorithm(algorithm)14
val snapshot = bytes.toArray()15
if (snapshot.size != (if (actual == DigestAlgorithm.Md5) 16L else 32L))16
throw IllegalArgumentException(Some("incorrect HTTP entity digest length"))17
val result = ArrayList<ClientEntityDigest>()18
for (entry in existing) if (entry.algorithm != actual) result.add(entry)19
result.add(ClientEntityDigest(actual, snapshot))20
return result.toArray()21
}23
internal suspend fun clientDigestEntity(call: ClientCall, scope: ClientAuthenticationScope, algorithm: HttpDigestAlgorithm): String {24
val actual = clientDigestAlgorithm(algorithm)25
if (scope.usesConnect(call)) return digest(actual, emptyList<Byte>()).toHexString()26
val body = call.originalRequest.body27
for (entry in body.entityDigests) if (entry.algorithm == actual) return entry.bytes.toHexString()28
if (body.contentLength == Some(0L)) return digest(actual, emptyList<Byte>()).toHexString()29
if (!body.isReplayable) throw HttpAuthenticationException(HttpAuthenticationFailure.BodyNotReplayable, scope.url(call))30
return Digest(actual).use suspend { hash ->31
body.writeWithTrailersTo(ClientDigestSink(call, hash))32
requireClientCall(call)33
hash.finish().toHexString()34
}35
}37
private class ClientDigestSink(val call: ClientCall, val hash: Digest) : AsyncByteSink {38
public override suspend fun writeFrom(buffer: NativeByteBuffer, count: Long): Long {39
ensureActive()40
requireClientCall(call)41
if (count < 0L) throw IllegalArgumentException(Some("negative digest byte count"))42
if (count > buffer.readableBytes) throw IndexOutOfBoundsException()43
val amount = if (count > 8192L) 8192L else count44
hash.update(buffer.getBytes(buffer.readPosition, amount))45
buffer.skip(amount)46
return amount47
}48
public override suspend fun flush() { ensureActive(); requireClientCall(call) }49
}