summaryrefslogtreecommitdiffhomepage
path: root/Storage/LocalFiles.hs
blob: 083a74ee981556c33c53be50295a289e635d9d2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
{- Copyright 2016 Joey Hess <id@joeyh.name>
 -
 - Licensed under the GNU AGPL version 3 or higher.
 -}

{-# LANGUAGE OverloadedStrings #-}

module Storage.LocalFiles (localFiles) where

import Types
import Storage
import Serialization ()
import qualified Data.ByteString as B
import qualified Data.ByteString.UTF8 as U8
import Data.Monoid
import Data.List
import System.Posix.User
import System.IO
import System.Directory
import System.Posix
import System.FilePath
import Raaz.Core.Encode
import Control.DeepSeq
import Control.Exception

localFiles :: Storage
localFiles = Storage
	{ storeShard = store
	, retrieveShard = retrieve
	, obscureShards = obscure
	}

store :: StorableObjectIdent -> Shard -> IO StoreResult
store i s = onError (StoreFailure . show) $ do
	dir <- shardDir
	createDirectoryIfMissing True dir
	fd <- openFd (dir </> shardFile i) WriteOnly (Just 0o666)
		(defaultFileFlags { exclusive = True } )
	h <- fdToHandle fd
	B.hPut h (toByteString s)
	hClose h
	return StoreSuccess

retrieve :: ShardNum -> StorableObjectIdent -> IO RetrieveResult
retrieve n i = onError (RetrieveFailure . show) $ do
	dir <- shardDir
	fd <- openFd (dir </> shardFile i) ReadOnly Nothing defaultFileFlags
	h <- fdToHandle fd
	b <- B.hGetContents h
	b `deepseq` hClose h
	return $ RetrieveSuccess $ Shard n (StorableObject b)

-- | Set atime and mtime to epoch, to obscure access and modification
-- patterns.
--
-- There is no way to set the ctime to the epoch, but setting the other
-- times does at least set it to the current time, which makes all
-- currently stored files look alike.
obscure :: IO ObscureResult
obscure = onError (ObscureFailure . show) $ do
	dir <- shardDir
	fs <- filter (ext `isSuffixOf`) <$> getDirectoryContents dir
	mapM_ (\f -> setFileTimes (dir </> f) 0 0) fs
	return ObscureSuccess

onError :: (IOException -> a) -> IO a -> IO a
onError f a = do
	v <- try a
	return $ case v of
		Left e -> f e
		Right r -> r

shardDir :: IO FilePath
shardDir = do
	u <- getUserEntryForID =<< getEffectiveUserID
	return $ homeDirectory u </> dotdir

shardFile :: StorableObjectIdent -> String
shardFile i = U8.toString (toByteString i) <> ext

ext :: String
ext = ".keysafe"

dotdir :: FilePath
dotdir = ".keysafe" </> "objects"