summaryrefslogtreecommitdiff
path: root/Hsbot/Utils.hs
blob: 2a8f58c206c12ca1b2bd342427c18f3c4b63720b (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
module Hsbot.Utils
    ( addThreadIdToQuitMVar
    , delThreadIdFromQuitMVar
    , hasAccess
    , initTLSEnv
    , sendStr
    , setGlobalQuitMVar
    ) where

import Control.Concurrent
import Control.Monad.Reader
import Control.Monad.State
import qualified Data.ByteString.Lazy.UTF8 as L
import qualified Data.List as L
import qualified Network.IRC as IRC
import Network.TLS
import System.IO

import Hsbot.Types

-- utility functions
addThreadIdToQuitMVar :: ThreadId -> Env IO ()
addThreadIdToQuitMVar thrId = do
    threadIdsMv <- asks envThreadIdsMv
    liftIO $ modifyMVar_ threadIdsMv (\l -> return $ thrId:l)

delThreadIdFromQuitMVar :: ThreadId -> Env IO ()
delThreadIdFromQuitMVar thrId = do
    threadIdsMv <- asks envThreadIdsMv
    liftIO $ modifyMVar_ threadIdsMv (return . L.delete thrId)

setGlobalQuitMVar :: BotStatus -> Env IO ()
setGlobalQuitMVar status = do
    quitMv <- asks envQuitMv
    liftIO $ putMVar quitMv status

-- Access rights
hasAccess :: Maybe IRC.Prefix -> AccessRight -> Env IO Bool
hasAccess Nothing _ = return False
hasAccess (Just mask) right = do
    botMVar <- asks envBotState
    liftIO (readMVar botMVar) >>= evalStateT (fmap (any accessMatch) (gets botAccess))
  where
    accessMatch :: AccessList -> Bool
    accessMatch (AccessList amask arights)
      | mask == amask = or [Admin `L.elem` arights, right `L.elem` arights]
      | otherwise = False

-- Helpers
sendStr :: Handle -> Maybe TLSCtx -> String -> IO ()
sendStr _ (Just ctx) msg = sendData ctx . L.fromString $ msg ++ "\r\n"
sendStr handle Nothing msg = hPutStrLn handle $ msg ++ "\r\n"

-- TLS utils
initTLSEnv :: TLSConfig -> IO TLSParams
initTLSEnv ssl = do
    let versions = sslVersions ssl
        ciphers  = sslCiphers ssl
    return $ defaultParams { pAllowedVersions = versions
                           , pCiphers = ciphers }