aboutsummaryrefslogtreecommitdiffstats
path: root/src/Reaktor/Plugins/System.hs
blob: 3d6ec5c4629a652ecc7477bca35e176900cd47f8 (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
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
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Reaktor.Plugins.System (new) where

import Blessings
import Control.Applicative
import Control.Concurrent (forkIO,threadDelay)
import Control.Concurrent.Async (race)
import Control.Exception
import Control.Monad (forM_)
import qualified Data.HashMap.Lazy as M
import qualified Data.List as L
import qualified Data.Text.Extended as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.IO as T
import qualified Data.Vector as V
import Prelude.Extended
import Reaktor
import Reaktor.Plugins.System.Internal
import System.Environment (getEnvironment)
import System.Exit
import System.FilePath.Posix (takeBaseName)
import System.IO (BufferMode(LineBuffering),hSetBuffering)
import System.IO (Handle,hClose,hPutStr,hIsEOF)
import System.IO.Error (catchIOError,isDoesNotExistError)
import System.Process
import System.Posix.Process (getProcessGroupIDOf)
import System.Posix.Signals (Signal,signalProcessGroup,killProcess)
import System.Posix.Types (ProcessGroupID)
import qualified Text.Regex.PCRE.Light as RE


new :: Config -> Actions -> IO (Message -> IO ())
new config@Config{..} actions@Actions{..} = do
    pure $ \case
        Message (Just prefix) cmd (msgtarget:text:[]) | elem cmd ["PRIVMSG", "JOIN"] -> do
          let hooks = maybe [] id (M.lookup cmd cHooks)
          mapM_ (\h -> run1 config actions h prefix msgtarget text) hooks

        Message (Just prefix) "JOIN" (channel:[]) -> do
          let hooks = maybe [] id (M.lookup "JOIN" cHooks)
          mapM_ (\h -> run1 config actions h prefix channel "") hooks

        _ -> pure ()


run1 :: Config -> Actions -> Hook -> Text -> Text -> Text -> IO ()
run1 Config{..} Actions{..} Hook{..} prefix msgtarget text = do
    nick <- aGetNick

    let
        match =
          case hPattern of
            Just p -> \s ->
              fmap (map T.decodeUtf8) $
              RE.match p (T.encodeUtf8 s) [RE.exec_no_utf8_check]
            Nothing -> const Nothing

        isActivated =
          case hActivate of
            Always -> pure ""
            Match -> match text >> pure ""
            Query ->
              let me = nick <> ":" in
              if
                | isQuery -> pure ""
                | T.isPrefixOf me text -> pure me
                | T.isPrefixOf "*:" text -> pure "*:"
                | otherwise -> mempty

        audience = if isQuery then from else msgtarget

        from = T.takeWhile (/='!') prefix

        -- TODO check if msgtarget is one of our channels?
        --      what if our nick has changed?
        isQuery = msgtarget == nick

    forM_ isActivated $ \activationPrefix -> do
      let
          text' = T.drop (T.length activationPrefix) text
          resultPrefix = if isQuery then [] else [from <> ":"]

          captures = V.fromList $ fromMaybe [] (match text')
          capture i = captures V.!? i

          name =
            case hCommand of
              Capture i -> fromMaybe "<unnamed>" (capture i)
              CaptureOr Command{..} -> T.pack $ takeBaseName $ commandPath

          command =
            case hCommand of
              Capture i -> (`M.lookup` hCommands) =<< capture i
              CaptureOr c -> Just c

          args =
            map (maybe "" T.unpack)
              $ L.dropWhileEnd isNothing
              $ flip map hArguments
              $ \case
                Capture i -> capture i
                CaptureOr s -> Just s

      case command of
        Just Command{..} -> do
          baseEnv <- getEnvironment

          let
              logStr pid s = do
                let p = name <> "[" <> T.show pid <> "] "
                aLog $ SGR [38,5,247] (Plain p <> s)

              red :: Text -> Blessings Text
              red = SGR [31] . Plain

              onStart pid = logStr pid "started"
              onErrLine pid s = logStr pid $ "stderr: " <> red s
              onOutLine _ s = aSend (privmsg audience [s])
              onError pid e = logStr pid $ "failed: " <> red (T.show e)

              onExit pid = \case
                ExitSuccess ->
                  logStr pid "stopped"
                ExitFailure i ->
                  logStr pid $ "stopped with exit code " <>
                    red (T.show $ if i <= 127 then i else -256 + i)

              extraEnv =
                  [ ("_prefix", T.unpack prefix)
                  , ("_from", T.unpack from)
                  , ("_msgtarget", T.unpack msgtarget)
                  ]

              env =
                M.toList $ mconcat
                  [ M.fromList extraEnv
                  , maybe mempty id commandEnv
                  , M.fromList baseEnv
                  ]

              cwd = commandWorkDir <|> hWorkDir <|> cWorkDir

          fork commandPath args cwd (Just env) "" hTimeout Callbacks{..}

        Nothing -> do
          let s = name <> ": command not found"
          aSend (privmsg audience (resultPrefix <> [s]))


data Callbacks = Callbacks
    { onOutLine :: Pid -> Text -> IO ()
    , onErrLine :: Pid -> Text -> IO ()
    , onError :: Pid -> SomeException -> IO ()
    , onExit :: Pid -> ExitCode -> IO ()
    , onStart :: Pid -> IO ()
    }

fork :: FilePath
     -> [String]
     -> Maybe FilePath
     -> Maybe [(String, String)]
     -> String
     -> Maybe Int
     -> Callbacks
     -> IO ()
fork path args cwd env input hTimeout Callbacks{..} =
    forkIO (f `catch` onError (-1)) >> return ()
  where
    f = withCreateProcess p $ \(Just inh) (Just outh) (Just errh) ph -> do
      Just pid <- getPid ph
      pgid <- getProcessGroupIDOf pid

      onStart pid

      mapM_ forkIO [
          hPutStr inh input `finally` hClose inh,
          hWithLines outh (onOutLine pid),
          hWithLines errh (onErrLine pid)
        ]

      case hTimeout of
        Just time ->
          race (threadDelay time) (waitForProcess ph) >>= \case
            Left () -> onError pid (SomeException (ErrorCall "timeout"))
            Right code -> onExit pid code
        Nothing ->
          waitForProcess ph >>= onExit pid

      killProcessGroup pgid

    p = (proc path args)
          { cwd = cwd
          , env = env
          , std_in = CreatePipe
          , std_out = CreatePipe
          , std_err = CreatePipe
          , close_fds = True
          , create_group = True
          , new_session = True
          }


killProcessGroup :: ProcessGroupID -> IO ()
killProcessGroup = signalProcessGroup' killProcess

signalProcessGroup' :: Signal -> ProcessGroupID -> IO ()
signalProcessGroup' sig pgid =
    catchIOError
      (signalProcessGroup sig pgid)
      (\e -> if isDoesNotExistError e then return () else ioError e)


hWithLines :: Handle -> (Text -> IO ()) -> IO ()
hWithLines h f = do
    hSetBuffering h LineBuffering
    go `finally` hClose h
  where
    go =
      hIsEOF h >>= \case
        True -> return ()
        False -> T.hGetLine h >>= f >> go