aboutsummaryrefslogtreecommitdiffstats
path: root/src/Reaktor.hs
blob: 042fcfe5075658cd81cb0a95dc3db3b0dbcea23f (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
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Reaktor
    ( module Exports
    , privmsg
    , run
    ) where

import Blessings.Text
import Control.Concurrent.Extended
import Control.Exception
import Control.Monad (forM_)
import Data.Attoparsec.Text (feed,parse)
import Data.Attoparsec.Text (IResult(Done,Fail,Partial))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8.Extended as BS
import qualified Data.Char as C
import Data.Function (on)
import qualified Data.Text.Encoding as T
import qualified Data.Text.Extended as T
import qualified Data.Text.IO as T
import Data.Time.Clock.System
import Data.Time.Format
import qualified Network.Simple.TCP as TCP
import qualified Network.Simple.TCP.TLS as TLS
import Network.Socket as Exports (HostName,ServiceName)
import Prelude.Extended
import Reaktor.Internal
import Reaktor.Internal as Exports (Actions(..))
import Reaktor.Internal as Exports (Message(Message,Start))
import Reaktor.IRC as Exports
import Reaktor.Internal as Exports (formatMessage)
import Reaktor.Nick as Exports
import Reaktor.Nick as Nick
import qualified Reaktor.Parser as Parser
import qualified System.IO
import System.IO (BufferMode(LineBuffering),hSetBuffering)
import System.IO (hIsTerminalDevice)
import System.Posix.Signals


run :: Config -> (Actions -> IO [Message -> IO ()]) -> IO ()
run Config{..} getPlugins =
    if cUseTLS then do
      s <- TLS.getDefaultClientSettings (cHostName, BS.pack cServiceName)
      TLS.connect s cHostName cServiceName $ \(ctx, sockAddr) ->
        withSocket sockAddr (TLS.send ctx) (TLS.recv ctx)
    else do
      TCP.connect cHostName cServiceName $ \(sock, sockAddr) ->
        withSocket sockAddr (TCP.send sock) (TCP.recv sock 512)
  where
    withSocket _sockAddr sockSend sockRecv = do

      hSetBuffering cLogHandle LineBuffering -- TODO reset
      logToTTY <- hIsTerminalDevice cLogHandle
      (putLog, takeLog0) <- newChan
      let
          takeLog1 = if cLogTime then takeLog0 >>= prefixTimestamp else takeLog0
          takeLog2 = showUnprintable <$> takeLog1
          takeLog3 = if logToTTY then takeLog2 else stripSGR <$> takeLog2
          takeLog = takeLog3

      (putInMsg, takeInMsg) <- newChan
      (putOutMsg, takeOutMsg) <- newChan
      (shutdown, awaitShutdown) <- newSemaphore
      (aSetNick,aGetNick) <- newRef =<< maybe Nick.getRandom return cNick

      let actions = Actions{..}
          aIsSecure = cUseTLS
          aLog = putLog
          aSend msg = logMsg msg >> putOutMsg msg

          logMsg msg =
              forM_ (logMsgFilter msg) $ \msg' -> do
                let bs = formatMessage msg'
                aLog $ SGR [38,5,235] "> " <> SGR [35,1] (Plain bs)

      mapM_ (\(s, f) -> installHandler s (Catch f) Nothing) [
          (sigINT, shutdown)
        ]

      plugins <- getPlugins actions

      threads <- mapM (\f -> forkIO $ f `finally` shutdown) [
          receiver actions putInMsg sockRecv,
          logger cLogHandle takeLog,
          pinger aSend,
          sender takeOutMsg sockSend,
          splitter plugins takeInMsg
        ]

      putInMsg Start

      awaitShutdown
      mapM_ killThread threads
      putStrLn ""


logger :: System.IO.Handle -> IO (Blessings Text) -> IO ()
logger h takeLog = forever $ takeLog >>= T.hPutStrLn h . pp


pinger :: (Message -> IO ()) -> IO ()
pinger aSend = forever $ do
    threadDelay time
    aSend (Message Nothing PING ["heartbeat"])
  where
    time = 300 * 1000000

receiver :: Actions -> (Message -> IO ()) -> IO (Maybe ByteString) -> IO ()
receiver Actions{..} putInMsg sockRecv =
    receive ""
  where
    decode :: ByteString -> Text
    decode = T.decodeUtf8With (\_err _c -> Just '?')

    receive :: Text -> IO ()
    receive "" =
        sockRecv >>= \case
          Nothing -> logErr "EOL"
          Just buf -> receive (decode buf)

    receive buf =
        go (parse Parser.message buf)
      where
        go :: IResult Text Message -> IO ()
        go = \case
            Done rest msg -> do
              logMsg msg
              putInMsg msg
              receive rest

            p@(Partial _) ->
              sockRecv >>= \case
                Nothing -> logErr ("EOF with partial " <> Plain (T.show p))
                Just buf' -> go (feed p (decode buf'))

            f@(Fail _i _errorContexts _errMessage) ->
              logErr ("failed to parse message: " <> Plain (T.show f))

    logErr s = aLog $ SGR [31,1] ("! receive: " <> s)

    logMsg msg =
        forM_ (logMsgFilter msg) $ \msg' -> do
          let bs = formatMessage msg'
          aLog $ SGR [38,5,235] "< " <> SGR [38,5,244] (Plain bs)


sender :: IO Message -> (ByteString -> IO ()) -> IO ()
sender takeOutMsg sockSend =
    forever $ takeOutMsg >>= sockSend . T.encodeUtf8 . formatMessage

splitter :: [Message -> IO ()] -> IO Message -> IO ()
splitter plugins takeInMsg =
    forever $ do
      msg <- takeInMsg
      mapM_ (\f -> forkIO (f msg)) plugins


logMsgFilter :: Message -> Maybe Message
logMsgFilter = \case
    Message _ PING _ -> Nothing
    Message _ PONG _ -> Nothing
    Message p PRIVMSG ["NickServ",xs] | check -> do
        Just (Message p PRIVMSG ["NickServ",xs'])
      where
        check = elem cmd ["IDENTIFY","REGAIN"] && length ws > 2
        ws = T.words xs
        (cmd:ws') = ws
        (nick:_) = ws'
        xs' = T.unwords [cmd, nick, "<password>"]
    msg -> Just msg


showUnprintable :: Blessings Text -> Blessings Text
showUnprintable =
    fmap' showU
  where
    showU :: Text -> Blessings Text
    showU =
        mconcat
          . map (either Plain (hi . Plain . showLitChars))
          . toEither (not . C.isPrint)

    -- like Blessings' fmap, but don't wrap the Plain case in another Plain
    fmap' :: (Text -> Blessings Text) -> Blessings Text -> Blessings Text
    fmap' f = \case
        Append t1 t2 -> Append (fmap' f t1) (fmap' f t2)
        Plain s -> f s
        SGR pm t -> SGR pm (fmap' f t)
        Empty -> Empty

    hi = SGR [38,5,79]

    showLitChars :: Text -> Text
    showLitChars = T.concatMap (T.pack . flip C.showLitChar "")

    toEither :: (Char -> Bool) -> Text -> [Either Text Text]
    toEither p =
      map (\s -> if p (T.head s) then Right s else Left s)
      . T.groupBy ((==) `on` p)


privmsg :: Text -> [Text] -> Message
privmsg msgtarget xs =
    Message Nothing PRIVMSG (msgtarget:T.intercalate " " xs:[])


prefixTimestamp :: Blessings Text -> IO (Blessings Text)
prefixTimestamp s = do
    t <- SGR [38,5,239] . Plain . T.pack <$> getTimestamp
    return (t <> " " <> s)


getTimestamp :: IO String
getTimestamp =
    formatTime defaultTimeLocale (iso8601DateFormat $ Just "%H:%M:%SZ")
    . systemToUTCTime <$> getSystemTime