-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRemoteHandler.hs
75 lines (59 loc) · 2.07 KB
/
RemoteHandler.hs
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
{-# LANGUAGE RecordWildCards, ScopedTypeVariables #-}
module Main where
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Control.Monad.Trans
import qualified Data.ByteString as B
import Network.Socket
import Network.BSD
import System.IO
import System.Exit
import Control.Exception
import Dispatch
import Message
import Compat
import Protocol
type TryCatch a = IO (Either SomeException a)
wLog mbH lock s = do
let toPrint = "[Remote] " ++ s
withMVar lock $ \ () -> do
maybe (return ()) (`hPutStrLn` toPrint) mbH
try (hPutStrLn stderr $ "[Remote] " ++ s) :: TryCatch ()
return ()
main = do
logLock <- newMVar ()
eiLogFile <- try (openFile "/tmp/remote.log" WriteMode) :: TryCatch Handle
let mbLogFile = either (const Nothing) Just eiLogFile
maybe (return ()) (`hSetBuffering` NoBuffering) mbLogFile
let writeLog = wLog mbLogFile logLock
writeLog "Startup"
waitForCallable $ \ putCallable -> forkIO $ do
(rMsg, wMsg) <- mkStdIOTransport writeLog putCallable
-- First message: tells about forward mode.
(HandShake fwdOpt) <- rMsg
writeLog (show fwdOpt)
chanMan <- mkChanManager
let protoState = ProtocolState fwdOpt rMsg wMsg writeLog chanMan
runProtocol protoState $ case fwdOpt of
FwdLocal {..} -> runPortForwarder
FwdLocalDynamic {..} -> runPortForwarder
FwdRemote {..} -> runLocalServer handleLocalFwdReq
FwdRemoteDynamic {..} -> runLocalServer handleSocks5ClientReq
mkStdIOTransport :: (String -> IO ()) -> (IO () -> IO ()) ->
IO (ReadMsg, WriteMsg)
mkStdIOTransport wLog callInMain = do
forM_ [stdin, stdout] $ \ h -> do
hSetBuffering h NoBuffering
hSetBinaryMode h True
rChan <- newChan
wChan <- newChan
let
handleErr (e :: SomeException) = do
wLog $ "stdin/out got EOF: exiting"
callInMain $ do
wLog "Shutdown"
exitWith ExitSuccess
forkIO $ (`catchEx` handleErr) $ dispatchToChan stdin rChan
forkIO $ (`catchEx` handleErr) $ dispatchFromChan wChan stdout
return (readChan rChan, writeChan wChan)