From a259c0f4dbcb72ff726d0d6808a8b8f602700bab Mon Sep 17 00:00:00 2001 From: Doug Coleman Date: Sun, 24 Mar 2024 12:14:11 -0500 Subject: [PATCH] io.files: implement (file-writer-secure) We want a way to open a temp file securely and return the stream. Opening a file to reserve the filename is not enough in some cases according to https://tldp.org/HOWTO/Secure-Programs-HOWTO/avoid-race.html --- basis/io/files/unix/unix.factor | 8 ++++++++ basis/io/files/windows/windows.factor | 5 +++++ core/io/files/files.factor | 8 ++++++++ 3 files changed, 21 insertions(+) diff --git a/basis/io/files/unix/unix.factor b/basis/io/files/unix/unix.factor index 6f4e78c720..cd74c4a9c3 100644 --- a/basis/io/files/unix/unix.factor +++ b/basis/io/files/unix/unix.factor @@ -34,6 +34,14 @@ CONSTANT: write-flags flags{ O_WRONLY O_CREAT O_TRUNC } M: unix (file-writer) open-write init-fd ; +CONSTANT: secure-write-flags flags{ O_WRONLY O_CREAT O_TRUNC O_EXCL } + +: open-secure-write ( path -- fd ) + secure-write-flags file-mode open-file ; + +M: unix (file-writer-secure) + open-secure-write init-fd ; + CONSTANT: append-flags flags{ O_WRONLY O_APPEND O_CREAT } : open-append ( path -- fd ) diff --git a/basis/io/files/windows/windows.factor b/basis/io/files/windows/windows.factor index d7c848f23f..51fe2e8236 100644 --- a/basis/io/files/windows/windows.factor +++ b/basis/io/files/windows/windows.factor @@ -247,6 +247,8 @@ M: windows init-stdio : open-write ( path -- win32-file ) GENERIC_WRITE CREATE_ALWAYS 0 open-file 0 >>ptr ; +: open-secure-write ( path -- win32-file ) + GENERIC_WRITE CREATE_NEW FILE_ATTRIBUTE_TEMPORARY open-file 0 >>ptr ; ; +M: windows (file-writer-secure) + open-secure-write ; + M: windows (file-appender) open-append ; diff --git a/core/io/files/files.factor b/core/io/files/files.factor index c67c8e2e65..4a68452a6b 100644 --- a/core/io/files/files.factor +++ b/core/io/files/files.factor @@ -30,6 +30,8 @@ HOOK: (file-reader) io-backend ( path -- stream ) HOOK: (file-writer) io-backend ( path -- stream ) +HOOK: (file-writer-secure) io-backend ( path -- stream ) + HOOK: (file-appender) io-backend ( path -- stream ) : ( path encoding -- stream ) @@ -38,6 +40,9 @@ HOOK: (file-appender) io-backend ( path -- stream ) : ( path encoding -- stream ) [ normalize-path (file-writer) { file-writer } declare ] dip ; inline +: ( path encoding -- stream ) + [ normalize-path (file-writer-secure) { file-writer } declare ] dip ; inline + : ( path encoding -- stream ) [ normalize-path (file-appender) { file-writer } declare ] dip ; inline @@ -53,6 +58,9 @@ HOOK: (file-appender) io-backend ( path -- stream ) : with-file-writer ( path encoding quot -- ) [ ] dip with-output-stream ; inline +: with-file-writer-secure ( path encoding quot -- ) + [ ] dip with-output-stream ; inline + : set-file-lines ( seq path encoding -- ) [ [ print ] each ] with-file-writer ; -- 2.34.1