]> gitweb.factorcode.org Git - factor.git/blob - extra/sodium/secure-memory/secure-memory.factor
Switch to https urls
[factor.git] / extra / sodium / secure-memory / secure-memory.factor
1 ! Copyright (C) 2020 Alexander Ilin.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING:
4     accessors alien combinators.short-circuit continuations destructors kernel
5     libc
6     sodium sodium.ffi
7 ;
8
9 IN: sodium.secure-memory
10
11 TUPLE: secure-memory < disposable
12     size underlying ;
13
14 : new-secure-memory ( size -- obj )
15     dup sodium-malloc secure-memory new-disposable
16     swap >>underlying swap >>size ;
17
18 : allow-no-access ( secure-memory -- )
19     check-disposed underlying>> sodium_mprotect_noaccess check0 ;
20
21 : allow-read-access ( secure-memory -- )
22     check-disposed underlying>> sodium_mprotect_readonly check0 ;
23
24 : with-read-access ( ..a secure-memory quot: ( ..a secure-memory -- ..b ) -- ..b )
25     over dup allow-read-access [ allow-no-access ] curry finally ; inline
26
27 : allow-write-access ( secure-memory -- )
28     check-disposed underlying>> sodium_mprotect_readwrite check0 ;
29
30 : with-write-access ( ..a secure-memory quot: ( ..a secure-memory -- ..b ) -- ..b )
31     over dup allow-write-access [ allow-no-access ] curry finally ; inline
32
33 : with-new-secure-memory ( ..a size quot: ( ..a secure-memory -- ..b ) -- ..b )
34     [ new-secure-memory ] dip with-write-access ; inline
35
36 : secure-memory= ( a b -- ? )
37     [ check-disposed ] bi@ {
38         [ [ size>> ] bi@ = ]
39         [ [ [ >c-ptr ] bi@ ] keep size>> sodium_memcmp 0 = ]
40     } 2&& ;
41
42 M: secure-memory dispose* ( disposable -- )
43     [ sodium_free f ] change-underlying f swap size<<  ;
44
45 M: secure-memory byte-length ( obj -- n )
46     size>> ;
47
48 M: secure-memory clone ( obj -- cloned )
49     check-disposed [
50         size>> new-secure-memory dup underlying>>
51     ] [ underlying>> ] [ size>> ] tri memcpy ;