aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/Windows/Registry.hs
blob: cb44ffec4a808be82a4488ec8889bb3d822460b4 (plain) (blame)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
-- |
-- Copyright   : (c) 2015 Egor Tensin <Egor.Tensin@gmail.com>
-- License     : MIT
-- Maintainer  : Egor.Tensin@gmail.com
-- Stability   : experimental
--
-- Low-level utility functions for reading and writing registry values.

{-# OPTIONS_GHC -XTupleSections #-}

module Windows.Registry
    ( IsKeyPath(..)
    , RootKey(..)
    , KeyPath(..)

    , ValueName
    , ValueType
    , ValueData

    , open
    , close

    , deleteValue

    , queryValue

    , getValue
    , GetValueFlag(..)
    , getExpandedString

    , setValue
    , setString
    , setExpandableString
    ) where

import           Data.Bits             ((.|.))
import qualified Data.ByteString       as B
import           Data.List             (intercalate)
import           Data.Maybe            (fromJust)
import           Data.Tuple            (swap)
import qualified Data.Text             as T
import           Data.Text.Encoding    (decodeUtf16LE, encodeUtf16LE)
import           Control.Exception     (bracket)
import           Foreign.ForeignPtr    (withForeignPtr)
import           Foreign.Marshal.Alloc (alloca, allocaBytes)
import           Foreign.Marshal.Array (peekArray, pokeArray)
import           Foreign.Storable      (peek, poke)
import           System.IO.Error       (catchIOError, isDoesNotExistError)

import qualified System.Win32.Types    as WinAPI
import qualified System.Win32.Registry as WinAPI

type Handle = WinAPI.HKEY

class IsKeyPath a where
    openUnsafe :: a -> IO Handle

close :: Handle -> IO ()
close = WinAPI.regCloseKey

open :: IsKeyPath a => a -> IO (Either IOError Handle)
open a = catchIOError (Right <$> openUnsafe a) $ return . Left

data RootKey = CurrentUser
             | LocalMachine
             deriving (Eq)

instance IsKeyPath RootKey where
    openUnsafe CurrentUser = return WinAPI.hKEY_CURRENT_USER
    openUnsafe LocalMachine = return WinAPI.hKEY_LOCAL_MACHINE

instance Show RootKey where
    show CurrentUser = "HKCU"
    show LocalMachine = "HKLM"

data KeyPath = KeyPath RootKey [String]

pathSep :: String
pathSep = "\\"

instance IsKeyPath KeyPath where
    openUnsafe (KeyPath root path) = do
        rootHandle <- openUnsafe root
        WinAPI.regOpenKey rootHandle $ intercalate pathSep path

instance Show KeyPath where
    show (KeyPath root path) = intercalate pathSep $ show root : path

type ValueName = String

data ValueType = TypeNone
               | TypeBinary
               | TypeDWord
               | TypeDWordBE
               | TypeQWord
               | TypeString
               | TypeMultiString
               | TypeExpandableString
               | TypeLink
               deriving (Eq, Show)

instance Enum ValueType where
    fromEnum = fromJust . flip lookup valueTypeTable
    toEnum = fromJust . flip lookup (map swap valueTypeTable)

valueTypeTable :: [(ValueType, Int)]
valueTypeTable =
    [ (TypeNone,     0)
    , (TypeBinary,   3)
    , (TypeDWord,    4)
    , (TypeDWordBE,  5)
    , (TypeQWord,   11)
    , (TypeString,   1)
    , (TypeMultiString,      7)
    , (TypeExpandableString, 2)
    , (TypeLink,     6)
    ]

type ValueData = (ValueType, B.ByteString)

encodeString :: String -> B.ByteString
encodeString str = encodeUtf16LE addLastZero
  where
    text = T.pack str
    addLastZero | T.null text = text
                | T.last text == '\0' = text
                | otherwise = T.snoc text '\0'

decodeString :: ValueData -> String
decodeString (_, bytes) = T.unpack dropLastZero
  where
    text = decodeUtf16LE bytes
    dropLastZero | T.null text = text
                 | T.last text == '\0' = T.init text
                 | otherwise = text

openCloseCatch :: IsKeyPath a => a -> (Handle -> IO b) -> IO (Either IOError b)
openCloseCatch keyPath f = catchIOError (fmap Right openClose) $ return . Left
  where
    openClose = bracket (openUnsafe keyPath) close f

foreign import ccall unsafe "Windows.h RegQueryValueExW"
    c_RegQueryValueEx :: WinAPI.PKEY -> WinAPI.LPCTSTR -> WinAPI.LPDWORD -> WinAPI.LPDWORD -> WinAPI.LPBYTE -> WinAPI.LPDWORD -> IO WinAPI.ErrCode

foreign import ccall unsafe "Windows.h RegSetValueExW"
    c_RegSetValueEx :: WinAPI.PKEY -> WinAPI.LPCTSTR -> WinAPI.DWORD -> WinAPI.DWORD -> WinAPI.LPBYTE -> WinAPI.DWORD -> IO WinAPI.ErrCode

foreign import ccall unsafe "Windows.h RegGetValueW"
    c_RegGetValue :: WinAPI.PKEY -> WinAPI.LPCTSTR -> WinAPI.LPCTSTR -> WinAPI.DWORD -> WinAPI.LPDWORD -> WinAPI.LPBYTE -> WinAPI.LPDWORD -> IO WinAPI.ErrCode

queryValue :: IsKeyPath a => a -> ValueName -> IO (Either IOError ValueData)
queryValue keyPath valueName =
    openCloseCatch keyPath $ \keyHandle ->
    withForeignPtr keyHandle $ \keyHandlePtr ->
    WinAPI.withTString valueName $ \valueNamePtr ->
    alloca $ \valueSizePtr -> do
        poke valueSizePtr 0
        WinAPI.failUnlessSuccess "RegQueryValueExW" $
            c_RegQueryValueEx keyHandlePtr valueNamePtr WinAPI.nullPtr WinAPI.nullPtr WinAPI.nullPtr valueSizePtr
        valueSize <- fromIntegral <$> peek valueSizePtr
        alloca $ \valueTypePtr ->
            allocaBytes valueSize $ \bufferPtr -> do
                WinAPI.failUnlessSuccess "RegQueryValueExW" $
                    c_RegQueryValueEx keyHandlePtr valueNamePtr WinAPI.nullPtr valueTypePtr bufferPtr valueSizePtr
                buffer <- B.pack <$> peekArray valueSize bufferPtr
                valueType <- toEnum . fromIntegral <$> peek valueTypePtr
                return (valueType, buffer)

queryType :: IsKeyPath a => a -> ValueName -> IO (Either IOError ValueType)
queryType keyPath valueName =
    openCloseCatch keyPath $ \keyHandle ->
    withForeignPtr keyHandle $ \keyHandlePtr ->
    WinAPI.withTString valueName $ \valueNamePtr ->
    alloca $ \valueTypePtr -> do
        WinAPI.failUnlessSuccess "RegQueryValueExW" $
            c_RegQueryValueEx keyHandlePtr valueNamePtr WinAPI.nullPtr valueTypePtr WinAPI.nullPtr WinAPI.nullPtr
        valueType <- toEnum . fromIntegral <$> peek valueTypePtr
        return valueType

data GetValueFlag = RestrictAny
                  | RestrictNone
                  | RestrictBinary
                  | RestrictDWord
                  | RestrictQWord
                  | RestrictString
                  | RestrictMultiString
                  | RestrictExpandableString
                  | DoNotExpand
                  deriving (Eq, Show)

instance Enum GetValueFlag where
    fromEnum = fromJust . flip lookup getValueFlagsTable
    toEnum = fromJust . flip lookup (map swap getValueFlagsTable)

getValueFlagsTable :: [(GetValueFlag, Int)]
getValueFlagsTable =
    [ (RestrictAny,    0x0000ffff)
    , (RestrictNone,   0x00000001)
    , (RestrictBinary, 0x00000008)
    , (RestrictDWord,  0x00000010)
    , (RestrictQWord,  0x00000040)
    , (RestrictString, 0x00000002)
    , (RestrictMultiString,      0x00000020)
    , (RestrictExpandableString, 0x00000004)
    , (DoNotExpand,    0x10000000)
    ]

getValue :: IsKeyPath a => a -> ValueName -> [GetValueFlag] -> IO (Either IOError ValueData)
getValue keyPath valueName flags =
    openCloseCatch keyPath $ \keyHandle ->
    withForeignPtr keyHandle $ \keyHandlePtr ->
    WinAPI.withTString valueName $ \valueNamePtr ->
    alloca $ \valueSizePtr -> do
        poke valueSizePtr 0
        WinAPI.failUnlessSuccess "RegGetValueW" $
            c_RegGetValue keyHandlePtr WinAPI.nullPtr valueNamePtr rawFlags WinAPI.nullPtr WinAPI.nullPtr valueSizePtr
        bufferCapacity <- fromIntegral <$> peek valueSizePtr
        alloca $ \valueTypePtr ->
            allocaBytes bufferCapacity $ \bufferPtr -> do
                WinAPI.failUnlessSuccess "RegGetValueW" $
                    c_RegGetValue keyHandlePtr WinAPI.nullPtr valueNamePtr rawFlags valueTypePtr bufferPtr valueSizePtr
                bufferSize <- fromIntegral <$> peek valueSizePtr
                buffer <- B.pack <$> peekArray bufferSize bufferPtr
                valueType <- toEnum . fromIntegral <$> peek valueTypePtr
                return (valueType, buffer)
  where
    rawFlags = fromIntegral $ foldr (.|.) 0 $ map fromEnum flags

getType :: IsKeyPath a => a -> ValueName -> [GetValueFlag] -> IO (Either IOError ValueType)
getType keyPath valueName flags =
    openCloseCatch keyPath $ \keyHandle ->
    withForeignPtr keyHandle $ \keyHandlePtr ->
    WinAPI.withTString valueName $ \valueNamePtr ->
    alloca $ \valueTypePtr -> do
        WinAPI.failUnlessSuccess "RegGetValueW" $
            c_RegGetValue keyHandlePtr WinAPI.nullPtr valueNamePtr rawFlags valueTypePtr WinAPI.nullPtr WinAPI.nullPtr
        valueType <- toEnum . fromIntegral <$> peek valueTypePtr
        return valueType
  where
    rawFlags = fromIntegral $ foldr (.|.) 0 $ map fromEnum $ DoNotExpand : flags

getExpandedString :: IsKeyPath a => a -> ValueName -> IO (Either IOError String)
getExpandedString keyPath valueName = do
    valueData <- getValue keyPath valueName [RestrictString, RestrictExpandableString]
    return $ fmap decodeString valueData

setValue :: IsKeyPath a => a -> ValueName -> ValueData -> IO (Either IOError ())
setValue keyPath valueName (valueType, valueData) =
    openCloseCatch keyPath $ \keyHandle ->
    withForeignPtr keyHandle $ \keyHandlePtr ->
    WinAPI.withTString valueName $ \valueNamePtr ->
    allocaBytes bufferSize $ \bufferPtr -> do
        pokeArray bufferPtr buffer
        WinAPI.failUnlessSuccess "RegSetValueExW" $
            c_RegSetValueEx keyHandlePtr valueNamePtr 0 rawValueType bufferPtr (fromIntegral bufferSize)
  where
    rawValueType = fromIntegral $ fromEnum valueType
    buffer = B.unpack valueData
    bufferSize = B.length valueData

setString :: IsKeyPath a => a -> ValueName -> String -> IO (Either IOError ())
setString keyPath valueName valueData =
    setValue keyPath valueName (TypeString, encodeString valueData)

setExpandableString :: IsKeyPath a => a -> ValueName -> String -> IO (Either IOError ())
setExpandableString keyPath valueName valueData =
    setValue keyPath valueName (TypeExpandableString, encodeString valueData)

setStringPreserveType :: IsKeyPath a => a -> ValueName -> String -> IO (Either IOError ())
setStringPreserveType keyPath valueName valueData = do
    valueType <- stringIfMissing <$> getType keyPath valueName [RestrictString, RestrictExpandableString]
    either (return . Left) (setValue keyPath valueName . (, encodeString valueData)) valueType
  where
    stringIfMissing (Left e) | isDoesNotExistError e = Right TypeString
                             | otherwise = Left e
    stringIfMissing (Right x) = Right x

deleteValue :: IsKeyPath a => a -> ValueName -> IO (Either IOError ())
deleteValue keyPath valueName =
    openCloseCatch keyPath $ \keyHandle ->
    withForeignPtr keyHandle $ \keyHandlePtr ->
    WinAPI.withTString valueName $ \valueNamePtr ->
    WinAPI.failUnlessSuccess "RegDeleteValueW" $
        WinAPI.c_RegDeleteValue keyHandlePtr valueNamePtr