From 41392c5fa77cccfd9c05a84e01c4a40abd410ee9 Mon Sep 17 00:00:00 2001 From: Emil Ivanichkov Date: Tue, 19 Mar 2024 16:22:58 +0200 Subject: [PATCH] feat(file utils): Add `filepaths.nim` --- src/status_node_manager/filepaths.nim | 51 +++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/status_node_manager/filepaths.nim diff --git a/src/status_node_manager/filepaths.nim b/src/status_node_manager/filepaths.nim new file mode 100644 index 0000000..090425a --- /dev/null +++ b/src/status_node_manager/filepaths.nim @@ -0,0 +1,51 @@ +# TODO: consider importing utils of this file from nimbus-eth2 + +{.push raises: [].} + +import chronicles +import stew/io2 + +when defined(windows): + import stew/[windows/acl] + +type + ByteChar = byte | char + +proc secureCreatePath*(path: string): IoResult[void] = + when defined(windows): + let sres = createFoldersUserOnlySecurityDescriptor() + if sres.isErr(): + error "Could not allocate security descriptor", path = path, + errorMsg = ioErrorMsg(sres.error), errorCode = $sres.error + err(sres.error) + else: + var sd = sres.get() + createPath(path, 0o700, secDescriptor = sd.getDescriptor()) + else: + createPath(path, 0o700) + +proc secureWriteFile*[T: ByteChar](path: string, + data: openArray[T]): IoResult[void] = + when defined(windows): + let sres = createFilesUserOnlySecurityDescriptor() + if sres.isErr(): + error "Could not allocate security descriptor", path = path, + errorMsg = ioErrorMsg(sres.error), errorCode = $sres.error + err(sres.error()) + else: + var sd = sres.get() + let res = writeFile(path, data, 0o600, sd.getDescriptor()) + if res.isErr(): + # writeFile() will not attempt to remove file on failure + discard removeFile(path) + err(res.error()) + else: + ok() + else: + let res = writeFile(path, data, 0o600) + if res.isErr(): + # writeFile() will not attempt to remove file on failure + discard removeFile(path) + err(res.error()) + else: + ok()