Scoop API

scoop:scoop.http.client:0.1.0

src/body/digest.scoop

Selected production source · src/body/digest.scoop

1package scoop.http.client
3import scoop.asyncio.*
4import scoop.collections.emptyList
5import scoop.crypto.*
6import scoop.platform.memory.NativeByteBuffer
7import scoop.text.toHexString
9internal class ClientEntityDigest(val algorithm: DigestAlgorithm, val bytes: Array<Byte>)
11internal 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()
23internal 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.body
27 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 }
37private 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 count
44 hash.update(buffer.getBytes(buffer.readPosition, amount))
45 buffer.skip(amount)
46 return amount
47 }
48 public override suspend fun flush() { ensureActive(); requireClientCall(call) }