Skip to content

Commit

Permalink
Add LinuxEntropySource (#208)
Browse files Browse the repository at this point in the history
  • Loading branch information
illarionov authored Aug 27, 2024
1 parent 44f58c1 commit 5859156
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ internal actual fun createDefaultEmbedderHost(builder: Builder): EmbedderHost =
clock = builder.clock ?: CommonClock(),
localTimeFormatter = builder.localTimeFormatter ?: LinuxLocalTimeFormatter,
timeZoneInfo = builder.timeZoneInfo ?: LinuxTimeZoneInfoProvider,
entropySource = builder.entropySource ?: LinuxEntropySource(),
entropySource = builder.entropySource ?: LinuxEntropySource,
)
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ public class LinuxEmbedderHost(
override val clock: Clock = CommonClock(),
override val localTimeFormatter: LocalTimeFormatter = LinuxLocalTimeFormatter,
override val timeZoneInfo: TimeZoneInfoProvider = LinuxTimeZoneInfoProvider,
override val entropySource: EntropySource = LinuxEntropySource(),
override val entropySource: EntropySource = LinuxEntropySource,
) : EmbedderHost
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,27 @@

package ru.pixnews.wasm.sqlite.open.helper.host.linux

import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import platform.linux.SYS_getrandom
import platform.posix.errno
import platform.posix.syscall
import ru.pixnews.wasm.sqlite.open.helper.host.EmbedderHost.EntropySource

internal class LinuxEntropySource : EntropySource {
internal object LinuxEntropySource : EntropySource {
override fun generateEntropy(size: Int): ByteArray {
TODO("Not yet implemented")
val bytes = ByteArray(size)
var bytesLeft: Int = size
bytes.usePinned {
while (bytesLeft != 0) {
val startPosition = size - bytesLeft
val bytesWritten = syscall(SYS_getrandom.toLong(), it.addressOf(startPosition), bytesLeft.toULong(), 0U)
if (bytesWritten < 0) {
error("Can not generate entropy. Errno: $errno")
}
bytesLeft -= bytesWritten.toInt()
}
}
return bytes
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/

package ru.pixnews.wasm.sqlite.open.helper.host.linux

import assertk.assertThat
import assertk.assertions.isFalse
import kotlin.test.Test

class LinuxEntropySourceTest {
@Test
@Suppress("MagicNumber")
fun entropy_source_should_work() {
val entropy = LinuxEntropySource.generateEntropy(102400)
// XXX may be a more appropriate test
assertThat(entropy.all { it == 0.toByte() }).isFalse()
}
}

0 comments on commit 5859156

Please sign in to comment.