packages feed

moesocks 1.0.0.40 → 1.0.0.41

raw patch · 23 files changed

+556/−261 lines, 23 files

Files

CHANGELOG.md view
@@ -1,3 +1,8 @@+1.0.0.41+--------+* Update README for GHC 7.10.3+* Add instructions to configure system wide proxy for NixOS+ 1.0.0.40 --------- * Fix UDP packet size
README.md view
@@ -3,13 +3,13 @@  A SOCKS5 proxy using the client / server architecture. -MoeSocks is greatly inspired by [ss] and can be used in place of it.+MoeSocks is compatible with [ss] at the protocal and most of the configuration level.  Installation ============ -Easy-----+From binary+-----------  ### Install [Nix] @@ -19,10 +19,14 @@      nix-env -i -A nixpkgs.haskellPackages.moesocks -Hard-----+### Run -### Install GHC 7.10.2 and cabal-install+    moesocks ++From source+-----------++### Install GHC and cabal-install      ### Download moesocks @@ -53,37 +57,41 @@          moesocks -s $REMOTE_IP -k birthday! -* Now you have a SOCKS5 proxy running inside a firewall using port-  `1080`.--* SS compatible obfuscation can be turned on with the `-o` flag to make-  statistical analysis on packet length a bit more confusing.+* Now you have a SOCKS5 proxy running inside a firewall on port `1080`.  * See more options:          moesocks --help -* You might want to run `moesocks` under some kind of a supervising daemon to-  auto restart the program if it crashes, likely due to [#10590], the fix of-  which was not included in the `7.10.2` release.+* Not tested in `OSX`, but it should just work. -* On `OSX`, If you only run `moesocks -r local`, then it should work. Occasional-  manual restart should be expected. `fastOpen` field should be `false` for now.+System wide proxy for NixOS+=========================== +* Add `moesocks.nix` and `moesocks-bento.nix` to `/etc/nixos` +* Modify the following and add it to `configuration.nix`: +        imports = [ ./moesocks-bento.nix ];+  +        networking.moesocks-bento =+          {+            enable = true;+            remote = "my-server";+            remotePort = 8388;+            password = "birthday!";+          };+ Features ======== -* SOCKS5 proxy service, obviously+* SOCKS5 proxy service * TCP port forwarding-* UDP port forwarding, for example `-U 5300:8.8.8.8:53`-* TCP per connection throttling (as a side effect of trying to find a bug in the-remote)+* UDP port forwarding, for example to tunnel DNS request: `-U 5300:8.8.8.8:53` * SOCKS5 service on local can be turned off-* Understand ss's configuration file+* Understand `ss`' configuration file -Drawbacks-==========+Know issues+===========  * UDP over SOCKS5 is not implemented. * TCP bind over SOCKS5 is not implemented@@ -96,11 +104,9 @@ TCP Fast Open (TFO) ==================== -## [TFO] is perfect for proxies.+## Benefit of using [TFO] -Both local and remote will use TFO when instructed. If the browser in use and-the website to visit both support TFO, you can enjoy TFO all the way through.-This could lead to a huge reduction of latency.+TFO can bypass the TCP three-way handshake in successive connections, thus reducing latency.  ## Enable TFO in your OS runtime. @@ -115,7 +121,7 @@ ## Enable TFO in MoeSocks  TFO can be turned on by adding a `"fastOpen":true` field in `config.json` or-specifying a `--fast-open` flag in the command line arguments.+adding a `--fast-open` argument in the command line.  ## Verify 
− config.json
@@ -1,10 +0,0 @@-{-  "remoteHost":"0.0.0.0",-  "remotePort":8388,-  "localHost":"localhost",-  "localPort":1080,-  "password":"birthday!",-  "fastOpen":false,-  "method":"aes-256-cfb"-}-
+ moesocks-bento.nix view
@@ -0,0 +1,114 @@+{ config, pkgs, lib, ... }:++with lib;++let+  cfg = config.networking.moesocks-bento+; in++{+  imports = [ ./moesocks.nix ]++; options =+    {+      networking.moesocks-bento =+        { enable = mkEnableOption "moesocks bento proxy suite"++        ; socks5ProxyPort = mkOption+            { type = types.int+            ; default = 1080+            ; description = "port for the SOCKS5 proxy server"+            ; }++        ; httpProxyPort = mkOption+            { type = types.int+            ; default = 8118+            ; description = "port for the HTTP proxy server"+            ; }++        ; dnsPort = mkOption+           { type = types.int+           ; default = 5300+           ; description = "port for tunneling DNS"+           ; }++        ; remote = mkOption+            { type = types.str+            ; default = ""+            ; description = "moesocks remote address"+            ; }++        ; local = mkOption+            { type = types.str+            ; default = "[::1]"+            ; description = "local address"+            ; }++        ; remotePort = mkOption+            { type = types.int+            ; default = 8388+            ; description = "moesocks remote port"+            ; }++        ; remoteDNS = mkOption+            { type = types.str+            ; default = "8.8.8.8"+            ; description = "remote DNS address"+            ; }++        ; password = mkOption+            {  type = types.str+            ; default = ""+            ; description = "moesocks password"+            ; }+        ; }+    ; }++; config = mkIf cfg.enable+    { assertions =+        [+          { assertion = cfg.remote != ""+          ; message = "moesocks' remote address must be set"+          ; }+        ]++    ; boot.kernel.sysctl."net.ipv4.tcp_fastopen" = 3++    ; services.nscd.enable = pkgs.lib.mkForce false++    ; services.moesocks =+        { enable = true+        ; udp = [ "${toString cfg.dnsPort}:${cfg.remoteDNS}:53" ]+        ; remote = cfg.remote+        ; remotePort = cfg.remotePort+        ; localPort = cfg.socks5ProxyPort+        ; password = cfg.password+        ; fastOpen = true+        ; }++    ; networking =+        { proxy.default = "socks5://${cfg.local}:${toString cfg.socks5ProxyPort}"+        ; dhcpcd.extraConfig =+            ''+            nooption domain_name_servers+            nohook resolv.conf+            ''+        ; }++    ; services.privoxy =+        { enable = true+        ; listenAddress = "${cfg.local}:${toString cfg.httpProxyPort}"+        ; extraConfig = "forward-socks5 / ${cfg.local}:${toString cfg.socks5ProxyPort} ."+        ; }++    ; services.dnsmasq =+        let dnsmasqHost = removeSuffix "]" (removePrefix "[" cfg.local)+        ; in++        { enable = true+        ; servers = [ "${dnsmasqHost}#${toString cfg.dnsPort}" ]+        ; }++    ; }++; }
moesocks.cabal view
@@ -1,6 +1,6 @@ name:               moesocks category:           Network-version:            1.0.0.40+version:            1.0.0.41 license:            Apache-2.0 synopsis:           A functional firewall killer description:        A SOCKS5 proxy using the client / server architecture.@@ -11,11 +11,13 @@ build-type:         Simple cabal-version:      >=1.10 copyright:          Copyright (C) 2015 Jinjing Wang-tested-with:        GHC == 7.10.2+tested-with:        GHC == 7.10.3 -extra-doc-files:        config.json-                      , README.md+extra-doc-files:        +                        README.md                       , CHANGELOG.md+                      , moesocks.nix+                      , moesocks-bento.nix  source-repository head   type: git
+ moesocks.nix view
@@ -0,0 +1,188 @@+{ config, pkgs, lib, ... }:++with lib;++let+  cfg = config.services.moesocks;+  configFile = pkgs.writeText "moesocks.json" (builtins.toJSON cfg);+  localIPs =+    [+      "0.0.0.0/8"+      "10.0.0.0/8"+      "100.64.0.0/10"+      "127.0.0.0/8"+      "169.254.0.0/16"+      "172.16.0.0/12"+      "192.0.0.0/24"+      "192.0.2.0/24"+      "192.88.99.0/24"+      "192.168.0.0/16"+      "198.18.0.0/15"+      "198.51.100.0/24"+      "203.0.113.0/24"+      "224.0.0.0/4"+      "240.0.0.0/4"+      "255.255.255.255/32"+      "::/128"+      "::1/128"+      "::ffff:0:0/96,"+      "100::/64"+      "64:ff9b::/96"+      "2001::/32"+      "2001:10::/28"+      "2001:20::/28"+      "2001:db8::/32"+      "2002::/16"+      "fc00::/7"+      "fe80::/10"+      "ff00::/8"+    ];+in++{ options =+    { services.moesocks =+        { enable = mkEnableOption "moesocks SOCKS5 proxy server";++          verbose = mkOption {+            type = types.bool;+            default = false;+            description = "Turn on logging";+          };++          role = mkOption {+            type = types.str;+            default = "local";+            description = "Tell moesocks to run as local or remote";+          };++          tcp = mkOption {+            type = types.listOf types.str;+            default = [];+            example = [ "5300:8.8.8.8:53" ];+            description =+              ''+                Specify that the given TCP port on the local(client)+                host is to be forwarded to the given host and port on+                the remote side.+              '';+          };++          udp = mkOption {+            type = types.listOf types.str;+            default = [];+            example = [ "5300:8.8.8.8:53" ];+            description =+              ''+                Specify that the given UDP port on the local(client)+                host is to be forwarded to the given host and port on+                the remote side.+              '';+          };++          disableSOCKS5 = mkOption {+            type = types.bool;+            default = false;+            description =+              ''+                Do not start a SOCKS5 server on local. It can be+                useful to run moesocks only as a secure tunnel+              '';+          };++          forbiddenIP = mkOption {+            type = types.listOf types.str;+            default = localIPs;+            description = "IP list declared invalid as destinations";+          };++          remote = mkOption {+            type = types.str;+            default = "::";+            description = "remote address";+          };++          remotePort = mkOption {+            type = types.int;+            default = 8388;+            description = "remote port";+          };++          local = mkOption {+            type = types.str;+            # Default to listening on an IPv6 localhost address since otherwise+            # initial start of moesocks will mysteriously fail.+            default = "::1";+            description = "local address";+          };++          localPort = mkOption {+            type = types.int;+            default = 1080;+            description = "local port";+          };++          timeout = mkOption {+            type = types.int;+            default = 3600;+            description = "timeout connection in seconds";+          };++          password = mkOption {+            type = types.str;+            default = "";+            description = "password";+          };++          method = mkOption {+            type = types.str;+            default = "aes-256-cfb";+            description = "encryption method";+          };++          fastOpen = mkOption {+            type = types.bool;+            default = false;+            description = "Use TCP_FASTOPEN, requires Linux 3.7+";+          };+        };+    };++  config = mkIf cfg.enable {++    assertions =+      [+        { assertion = cfg.password != "";+          message = "moesocks' password must be set";+        }+      ];++    users.extraUsers = singleton {+      name = "moesocks";+      # uid = config.ids.uids.moesocks;+      uid = 2000;+      description = "moesocks user";+    };++    systemd.services.moesocks =+      { wantedBy = [ "multi-user.target" ];+        after = [ "network.target" ];+        description = "moesocks SOCKS5 proxy server";+        serviceConfig =+          { User = "moesocks";+            ExecStart =+              concatStringsSep " "+                (splitString "\n"+                  ''+                    ${pkgs.haskellPackages.moesocks}/bin/moesocks+                    ${optionalString (cfg.verbose) "-v"}+                    -r ${cfg.role}+                    ${optionalString (cfg.tcp != []) "-T '${concatStringsSep " " cfg.tcp}'"}+                    ${optionalString (cfg.udp != []) "-U '${concatStringsSep " " cfg.udp}'"}+                    ${optionalString (cfg.disableSOCKS5) "--disable-socks5"}+                    -c ${configFile}+                  ''+                );+          };+      };+  };+}
src/Main.hs view
@@ -12,7 +12,7 @@ main :: IO () main = do   _options <- execParser opts-  +   withGateOptions _options - do     r <- runExceptT - moeApp _options     case r of
src/Network/MoeSocks/App.hs view
@@ -4,12 +4,11 @@ module Network.MoeSocks.App where  import Control.Concurrent.Async hiding (waitBoth)-{-import Control.Concurrent.STM-} import Control.Lens import Control.Monad-import Network.MoeSocks.Handler (runRemoteRelay, runLocalService)-import Network.MoeSocks.Helper  import Network.MoeSocks.Bootstrap (loadConfig)+import Network.MoeSocks.Handler (runRemoteRelay, runLocalService)+import Network.MoeSocks.Helper import Network.MoeSocks.Runtime (initRuntime) import Network.MoeSocks.Type import Prelude hiding ((-), take)@@ -34,6 +33,6 @@   let _options = someOptions   _config <- loadConfig - _options -  _runtime <- initRuntime _config _options +  _runtime <- initRuntime _config _options    io - runApp (_runtime ^. env) (_runtime ^. jobs)
src/Network/MoeSocks/Bootstrap.hs view
@@ -49,7 +49,7 @@       putStrLn "Supported:"       itraverse_ (\k _ -> putStrLn - "\t\t" <> k ^. _Text) - unsafeMethods -    else +    else       if someOptions ^. O.showDefaultConfig         then           putStrLn - showConfig defaultConfig ^. _Text
src/Network/MoeSocks/BuilderAndParser.hs view
@@ -19,7 +19,6 @@ import qualified Prelude as P  - _No_authentication :: Word8 _No_authentication = 0 
src/Network/MoeSocks/Common.hs view
@@ -18,7 +18,7 @@  check_IP_List :: AddressType -> [IPRange] -> Bool check_IP_List _address@(IPv4_Address _) a_IP_List =-  isJust - +  isJust -     do       _ip <- show _address  ^? _Show       findOf (each . _IPv4Range) (isMatchedTo _ip) a_IP_List@@ -31,13 +31,13 @@  check_IP_List _ _ = False -withChecked_IP_List :: AddressType -> ([IPRange], Maybe [IPRange]) +withChecked_IP_List :: AddressType -> ([IPRange], Maybe [IPRange])                         -> IO a -> IO ()-withChecked_IP_List aAddressType (aDenyList, aAllowList) aIO = +withChecked_IP_List aAddressType (aDenyList, aAllowList) aIO =   if check_IP_List aAddressType aDenyList     then error_ - show aAddressType                 <> " is in the denied list"-    else +    else       case aAllowList of         Nothing -> () <$ aIO         Just _allowList ->@@ -56,13 +56,13 @@ showConnectionType UDP_Port                = "UDP       "  showRequest :: ClientRequest -> String-showRequest _r =  +showRequest _r =                    _r ^. addressType . to show                 <> ":"                 <> _r ^. portNumber . to show  showRelay :: SockAddr -> ClientRequest -> String-showRelay aSockAddr aClientRequest = +showRelay aSockAddr aClientRequest =       show aSockAddr <> " -> " <> showRequest aClientRequest  addressType_To_Family :: AddressType -> Family@@ -91,13 +91,13 @@       _hostName   = _clientRequest ^. addressType . to show . re _Text       _port       = _clientRequest ^. portNumber       _family     = _clientRequest ^. addressType . to addressType_To_Family-  +   getSocketWithHint _family _hostName _port _socketType   setSocketConfig:: Env -> Socket -> IO () setSocketConfig aEnv aSocket = do-  setSocketOption aSocket NoDelay 1 +  setSocketOption aSocket NoDelay 1   when (aEnv ^. socketOption_TCP_NOTSENT_LOWAT) - do     tryIO "setSocket_TCP_NOTSENT_LOWAT" - setSocket_TCP_NOTSENT_LOWAT aSocket     pure ()
src/Network/MoeSocks/Default.hs view
@@ -18,7 +18,7 @@ defaultConfig = C.Config   {     C._remoteHost = "0.0.0.0"-  , C._remotePort = 8388 +  , C._remotePort = 8388   , C._localHost = "127.0.0.1"   , C._localPort = 1080   , C._password = "moesocks"@@ -85,7 +85,7 @@   , O._showDefaultConfig = False   , O._params = []   , O._denyList = mempty-  } +  }  parseIPRangeList :: [Text] -> [IPRange] parseIPRangeList =@@ -93,8 +93,8 @@                               . to T.strip                               . _Text                               . _Show-                      + defaultEnv :: Env defaultEnv =   let _c = defaultConfig@@ -106,11 +106,11 @@     , _tcpBufferSize                  = _c ^. C.tcpBufferSize     , _throttle                       = _c ^. C.throttle     , _throttleSpeed                  = _c ^. C.throttleSpeed-    , _obfuscationFlushBound          = _c ^. C.obfuscationFlushBound +    , _obfuscationFlushBound          = _c ^. C.obfuscationFlushBound     , _fastOpen                       = _c ^. C.fastOpen     , _socketOption_TCP_NOTSENT_LOWAT = _c ^. C.socketOption_TCP_NOTSENT_LOWAT     , _obfuscation                    = _o ^. O.obfuscation-    , _forbidden_IPs                  = _c ^. C.forbidden_IPs +    , _forbidden_IPs                  = _c ^. C.forbidden_IPs                                             & parseIPRangeList     , _denyList                       = []     {-, _config = defaultConfig-}
src/Network/MoeSocks/Encrypt.hs view
@@ -5,7 +5,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} -module Network.MoeSocks.Encrypt +module Network.MoeSocks.Encrypt (   initCipherBox , constCipherBox@@ -46,7 +46,7 @@ type KeyLength = Int type IV_Length = Int -type Cipher = S.Maybe ByteString -> IO ByteString +type Cipher = S.Maybe ByteString -> IO ByteString type IV = ByteString type CipherBuilder = IV -> IO Cipher @@ -60,8 +60,8 @@ type Methods = Map Text KeyLength  safeMethods :: Methods-safeMethods = fromList - -  [ +safeMethods = fromList -+  [     ("aes-128-cfb"        , 16)   , ("aes-192-cfb"        , 24)   , ("aes-256-cfb"        , 32)@@ -101,7 +101,7 @@   unsafeMethods :: Methods-unsafeMethods = fromList - +unsafeMethods = fromList -   [     ("rc2-cfb"            , 16) -- unsafe   , ("rc4"                , 16) -- unsafe@@ -111,13 +111,13 @@ methods = safeMethods <> unsafeMethods  hashKey :: ByteString -> KeyLength -> IV_Length -> ByteString-hashKey aPassword aKeyLen a_IV_len = loop mempty mempty +hashKey aPassword aKeyLen a_IV_len = loop mempty mempty   where     _stopLength = aKeyLen + a_IV_len      loop :: ByteString -> ByteString -> ByteString     loop _lastHashedBytes _accumHashedBytes-      | S.length _accumHashedBytes >= _stopLength +      | S.length _accumHashedBytes >= _stopLength         = S.take aKeyLen _accumHashedBytes       | otherwise = let _new = hash - _lastHashedBytes <> aPassword                     in@@ -138,16 +138,16 @@ identityCipher = pure . S.fromMaybe mempty  constCipherBox :: CipherBox-constCipherBox = +constCipherBox =   let constCipher = const - pure identityCipher-  in +  in   (0, pure mempty, constCipher, constCipher)   initCipherBox :: Text -> Text -> IO (Maybe CipherBox)-initCipherBox aMethod aPassword +initCipherBox aMethod aPassword   | aMethod == "none" = pure - Just constCipherBox-  | otherwise = ssl - +  | otherwise = ssl -       fmap (preview _Right) - runExceptT - initCipherBox' aMethod aPassword  initCipherBox' :: Text -> Text -> ExceptT_IO CipherBox@@ -174,7 +174,7 @@            pure _encrypt -      _decryptBuilder :: CipherBuilder +      _decryptBuilder :: CipherBuilder       _decryptBuilder _iv = do           _ctx <- E.cipherInitBS _method _hashed _iv Decrypt @@ -183,11 +183,10 @@                   S.Nothing -> E.cipherFinalBS _ctx                   S.Just _bytes -> do                     if (_bytes & isn't _Empty)-                      then E.cipherUpdateBS _ctx _bytes +                      then E.cipherUpdateBS _ctx _bytes                       else pure mempty-          +           pure _decrypt-           -  pure - (_IV_Length, _IV_Maker, _encryptBuilder, _decryptBuilder) +  pure - (_IV_Length, _IV_Maker, _encryptBuilder, _decryptBuilder)
src/Network/MoeSocks/Handler.hs view
@@ -77,7 +77,7 @@ showWrapped x = "[" <> show x <> "]"  local_SOCKS5 :: Env -> Text -> Int -> (Socket, SockAddr) -> IO ()-local_SOCKS5 _env _remoteHost _remotePort _s = +local_SOCKS5 _env _remoteHost _remotePort _s =   localService _env TCP_Service                 ("SOCKS5 proxy " <> showWrapped (_s ^. _2))                 (local_SOCKS5_RequestHandler _env@@ -95,25 +95,25 @@                 <> "]"  -localForward_TCP :: Env -> Text -> Int -> Forward -> (Socket, SockAddr) +localForward_TCP :: Env -> Text -> Int -> Forward -> (Socket, SockAddr)                                                               -> IO () localForward_TCP _env _remoteHost _remotePort _f _s = do   let _m = showForwarding _f   localService _env TCP_Service ("TCP port forwarding " <> _m)-                          (local_TCP_ForwardRequestHandler +                          (local_TCP_ForwardRequestHandler                             _env                             _remoteHost                             _remotePort                             _f)                           _s -localForward_UDP :: Env -> Text -> Int -> Forward -> (Socket, SockAddr) +localForward_UDP :: Env -> Text -> Int -> Forward -> (Socket, SockAddr)                                                               -> IO () localForward_UDP _env _remoteHost _remotePort _f _s = do   let _m = showForwarding _f   localService _env UDP_Service ("UDP port forwarding " <> _m)-                          (local_UDP_ForwardRequestHandler -                            _env +                          (local_UDP_ForwardRequestHandler+                            _env                             _remoteHost                             _remotePort                             _f)@@ -188,7 +188,7 @@         getSocket (_localService ^. localServiceHost)           (forwarding ^. forwardLocalPort)           Stream-        >>= localForward_TCP _env +        >>= localForward_TCP _env                             (_localService ^. localServiceRemoteHost)                             (_localService ^. localServiceRemotePort)                             forwarding@@ -198,7 +198,7 @@         getSocket (_localService ^. localServiceHost)           (forwarding ^. forwardLocalPort)           Datagram-        >>= localForward_UDP _env +        >>= localForward_UDP _env                             (_localService ^. localServiceRemoteHost)                             (_localService ^. localServiceRemotePort)                             forwarding@@ -206,7 +206,6 @@     LocalService_SOCKS5 _port ->       catchExceptAsyncLog "L SOCKS5" - do         getSocket (_localService ^. localServiceHost) _port Stream-          >>= local_SOCKS5 _env +          >>= local_SOCKS5 _env                             (_localService ^. localServiceRemoteHost)                             (_localService ^. localServiceRemotePort)-
src/Network/MoeSocks/Helper.hs view
@@ -15,19 +15,19 @@ import Data.Binary.Put import Data.ByteString (ByteString) import Data.Char (isUpper)+import Data.Foldable (for_)+import Data.List (sortOn) import Data.Maybe import Data.Monoid import Data.Text (Text) import Data.Text.Lens import Data.Time.Clock-import Data.List (sortOn) import Debug.Trace (trace) import Network.MoeSocks.Internal.Socket (sendAllToFastOpen) import Network.Socket hiding (send, recv) import Network.Socket.ByteString-import Prelude hiding (take, (-)) +import Prelude hiding (take, (-)) import System.Log.Logger--- import System.Posix.IO (FdOption(CloseOnExec), setFdOption) import System.Random import System.Timeout (timeout) import qualified Data.ByteString as S@@ -41,14 +41,14 @@ infixr 0 - {-# INLINE (-) #-} (-) :: (a -> b) -> a -> b-f - x = f x +f - x = f x  -- END backports  is :: APrism s t a b -> s -> Bool is x = not . isn't x -type HCipher = S.Maybe ByteString -> IO ByteString +type HCipher = S.Maybe ByteString -> IO ByteString type HQueue = TBQueue (S.Maybe ByteString)  io :: (MonadIO m) => IO a -> m a@@ -74,19 +74,19 @@   {-aIO-}  debug_ :: String -> IO ()-debug_ = debugM "moe" +debug_ = debugM "moe"  error_ :: String -> IO ()-error_ = errorM "moe" +error_ = errorM "moe"  warning_ :: String -> IO ()-warning_ = warningM "moe" +warning_ = warningM "moe"  info_ :: String -> IO ()-info_ = infoM "moe" +info_ = infoM "moe"  notice_ :: String -> IO ()-notice_ = noticeM "moe" +notice_ = noticeM "moe"  error_T :: Text -> IO () error_T = error_ . view _Text@@ -108,18 +108,18 @@ logClose aID aSocket = do   pure aID   debug_ - "Closing socket " <> aID-  close aSocket +  close aSocket  -logSocketWithAddress :: String -> IO (Socket, SockAddr) -> +logSocketWithAddress :: String -> IO (Socket, SockAddr) ->                         ((Socket, SockAddr) -> IO a) -> IO a logSocketWithAddress aID _init f = do-  catch (bracket _init (logClose aID . fst) f) - +  catch (bracket _init (logClose aID . fst) f) -       \(e :: SomeException) -> do       debug_ - "logSocket: Exception in " <> aID <> ": " <> show e       throw e -logSA:: String -> IO (Socket, SockAddr) -> +logSA:: String -> IO (Socket, SockAddr) ->                         ((Socket, SockAddr) -> IO a) -> IO a logSA = logSocketWithAddress @@ -130,41 +130,41 @@       throw e  catchExceptAsyncLog :: String -> IO a -> IO ()-catchExceptAsyncLog aID aIO = catches (() <$ aIO) -                [ +catchExceptAsyncLog aID aIO = catches (() <$ aIO)+                [                   Handler - \(e :: AsyncException) -> do-                            error_ - "ASyncException in " +                            error_ - "ASyncException in "                                     <> aID                                     <> " : " <> show e                             throw e-                , Handler - \(e :: SomeException) -> +                , Handler - \(e :: SomeException) ->                             error_ - aID                                     <> ": " <> show e                 ]  catchIO:: String -> IO a -> IO () catchIO aID aIO = catch (() <$ aIO) - \e ->-                error_ - "IOError in " <> aID <> ": " +                error_ - "IOError in " <> aID <> ": "                   <> show (e :: IOException)-                + logException :: String -> IO a -> IO ()-logException aID aIO = catch (() <$ aIO) - \e -> +logException aID aIO = catch (() <$ aIO) - \e ->                         do-                          debug_ - "Error in " <> aID <> ": " +                          debug_ - "Error in " <> aID <> ": "                             <> show (e :: SomeException)                           throw e  logWaitIO :: (Maybe String, IO a) -> IO () logWaitIO x = do   let _io = wrapIO x-      aID = x ^. _1 . _Just +      aID = x ^. _1 . _Just    debug_ - "waiting for : " <> aID   _io-  + wrapIO :: (Maybe String, IO c) -> IO () wrapIO (s,  _io) = do-  logException (fromMaybe "" s) _io +  logException (fromMaybe "" s) _io  waitBoth :: IO () -> IO () -> IO () waitBoth x y = do@@ -180,18 +180,18 @@ waitBothDebug :: (Maybe String, IO ()) -> (Maybe String, IO ()) -> IO () waitBothDebug x y = do   concurrently (logWaitIO x) (logWaitIO y)-  let _xID = x ^. _1 . _Just +  let _xID = x ^. _1 . _Just       _yID = y ^. _1 . _Just       _hID = _xID <> " / " <> _yID   debug_ - "All done for " <> _hID   pure ()  connectTunnel :: (Maybe String, IO ()) -> (Maybe String, IO ()) -> IO ()-connectTunnel x y = +connectTunnel x y =   let _prolong _io = _io >> sleep 5   in -  race_ (_prolong - logWaitIO x) +  race_ (_prolong - logWaitIO x)         (_prolong - logWaitIO y)  connectMarket :: (Maybe String, IO ()) -> (Maybe String, IO ()) -> IO ()@@ -201,14 +201,14 @@                                       IO (Socket, SockAddr) getSocket = getSocketWithHint AF_UNSPEC -getSocketWithHint :: (Integral i, Show i) => -                        Family -> Text -> i -> SocketType -> +getSocketWithHint :: (Integral i, Show i) =>+                        Family -> Text -> i -> SocketType ->                         IO (Socket, SockAddr) getSocketWithHint aFamily aHost aPort aSocketType = do     {-info_ - "getSocketWithHint: " <> show aFamily <> -}               {-" " <> show aHost <> ":" <> show aPort-} -    _addrs <- getAddrInfo (Just hints) +    _addrs <- getAddrInfo (Just hints)                               (Just - aHost ^. _Text) (Just - show aPort)                <&> sortOn addrFamily@@ -218,7 +218,7 @@     maybeAddrInfo <- firstOf folded <$> pure _addrs      case maybeAddrInfo of-      Nothing -> error - "Error in getSocket for: " <> aHost ^. _Text +      Nothing -> error - "Error in getSocket for: " <> aHost ^. _Text                               <> ":" <> show aPort       Just addrInfo -> do           let family     = addrFamily addrInfo@@ -231,16 +231,16 @@            -- send immediately!           when (aSocketType == Stream) --            setSocketOption _socket NoDelay 1 +            setSocketOption _socket NoDelay 1            debug_ - "Got socket: " <> show addrInfo           {-debug_ - "Socket family: " <> show family-}           {-debug_ - "Socket protocol: " <> show protocol -}            pure (_socket, address)-          +   where-    hints = defaultHints +    hints = defaultHints             {               addrFlags = [AI_ADDRCONFIG, AI_NUMERICSERV]             , addrSocketType = aSocketType@@ -251,10 +251,10 @@ builder_To_ByteString = LB.toStrict . B.toLazyByteString  portPairToInt :: (Word8, Word8) -> Int-portPairToInt = fromIntegral . portPairToWord16 +portPairToInt = fromIntegral . portPairToWord16   where     portPairToWord16 :: (Word8, Word8) -> Word16-    portPairToWord16 = decode . runPut . put +    portPairToWord16 = decode . runPut . put   recv_ :: Socket -> IO ByteString@@ -295,7 +295,7 @@ sendBuilder _queue = sendBytes _queue . builder_To_ByteString  sendBuilderEncrypt :: HQueue -> HCipher -> B.Builder -> IO ()-sendBuilderEncrypt _queue _encrypt = +sendBuilderEncrypt _queue _encrypt =   sendBytesEncrypt _queue _encrypt . builder_To_ByteString  -- | An exception raised when parsing fails.@@ -337,25 +337,25 @@  -- throttle speed in kilobytes per second produceLoop :: String -> Timeout -> Maybe Double ->-              Socket -> HQueue -> +              Socket -> HQueue ->               HCipher -> IO () produceLoop aID aTimeout aThrottle aSocket aTBQueue f = do   _startTime <- getCurrentTime    let _shutdown = do                     tryIO aID - shutdown aSocket ShutdownReceive-                  +       _produce :: Int -> IO ()       _produce _bytesReceived = flip onException (f S.Nothing) - do         _r <- timeoutFor aID aTimeout - recv_ aSocket         {-when ("L" `isPrefixOf` aID) - do-}           {-notice_ - "Get chunk: " <> (show - S.length _r) <> " " <> aID-}-        -        if (_r & isn't _Empty) ++        if (_r & isn't _Empty)           then do-            forM_ aThrottle - \_throttle -> do+            for_ aThrottle - \_throttle -> do               _currentTime <- getCurrentTime-              let _timeDiff = realToFrac (diffUTCTime _currentTime +              let _timeDiff = realToFrac (diffUTCTime _currentTime                                                       _startTime) :: Double                    _bytesK = fromIntegral _bytesReceived / 1000 :: Double@@ -368,37 +368,37 @@                 let _sleepTime = ((_bytesK + (-_timeDiff * _throttle))                                       / _throttle ) * 1000 * 1000 -                debug_ - "Produce sleeping for: " <> show _sleepTime +                debug_ - "Produce sleeping for: " <> show _sleepTime                         <> " miliseconds."                 threadDelay - floor - _sleepTime-              +             f (S.Just _r) >>= atomically . writeTBQueue aTBQueue . S.Just             yield             _produce (_bytesReceived + S.length _r)           else do-            debug_ -  "Half closed: " <> aID +            debug_ -  "Half closed: " <> aID             f S.Nothing >>= atomically . writeTBQueue aTBQueue . S.Just             atomically - writeTBQueue aTBQueue S.Nothing    _produce 0 `onException` _shutdown   pure () -   + consumeLoop :: String -> Timeout -> Maybe Double ->                 Socket -> HQueue -> Bool -> Int -> IO () consumeLoop aID aTimeout aThrottle aSocket aTBQueue randomize aBound = do   _startTime <- getCurrentTime-  -  ++   let _shutdown = do                     tryIO aID - shutdown aSocket ShutdownSend        _consume :: Int -> IO ()       _consume _allBytesSent = do-        forM_ aThrottle - \_throttle -> do+        for_ aThrottle - \_throttle -> do           _currentTime <- getCurrentTime-          let _timeDiff = realToFrac (diffUTCTime _currentTime +          let _timeDiff = realToFrac (diffUTCTime _currentTime                                                   _startTime) :: Double                _bytesK = fromIntegral _allBytesSent / 1000 :: Double@@ -411,47 +411,47 @@             let _sleepTime = ((_bytesK + (-_timeDiff * _throttle))                                   / _throttle ) * 1000 * 1000 -            debug_ - "Consume sleeping for: " <> show _sleepTime +            debug_ - "Consume sleeping for: " <> show _sleepTime                     <> " miliseconds."             threadDelay - floor - _sleepTime -        -                            ++         _newPacket <- atomically - readTBQueue aTBQueue          case _newPacket of           S.Nothing -> () <$ _shutdown           S.Just _data -> do-                          let _send = if randomize +                          let _send = if randomize                                           then sendAllRandom aBound                                           else sendAll-                                                    -                          timeoutFor aID aTimeout - ++                          timeoutFor aID aTimeout -                                           _send aSocket _data                           yield-                          _consume - +                          _consume -                             _allBytesSent + S.length _data-  +   _consume 0 `onException` _shutdown   pure ()   setSocket_TCP_FAST_OPEN:: Socket -> IO ()-setSocket_TCP_FAST_OPEN aSocket = +setSocket_TCP_FAST_OPEN aSocket =   let _TCP_FASTOPEN = 23       _TCP_Option = 6   in-  setSocketOption aSocket (CustomSockOpt (_TCP_Option, _TCP_FASTOPEN)) 1 +  setSocketOption aSocket (CustomSockOpt (_TCP_Option, _TCP_FASTOPEN)) 1  setSocket_TCP_NOTSENT_LOWAT :: Socket -> IO ()-setSocket_TCP_NOTSENT_LOWAT aSocket = +setSocket_TCP_NOTSENT_LOWAT aSocket =   let _TCP_NOTSENT_LOWAT = 25       _TCP_Option = 6   in-  setSocketOption aSocket (CustomSockOpt (_TCP_Option, _TCP_NOTSENT_LOWAT)) 1 +  setSocketOption aSocket (CustomSockOpt (_TCP_Option, _TCP_NOTSENT_LOWAT)) 1  --- Copied and slightly modified from: +-- Copied and slightly modified from: -- https://github.com/mzero/plush/blob/master/src/Plush/Server/Warp.hs {-setSocketCloseOnExec :: Socket -> IO ()-} {-setSocketCloseOnExec aSocket =-}@@ -465,7 +465,7 @@ tryIO _ = try -- . logException aID  toHaskellNamingConvention :: Text -> Text-toHaskellNamingConvention x = +toHaskellNamingConvention x =   let xs = x & T.split (`elem` ['_', '-'])   in   if xs & anyOf each (T.all isUpper . T.dropWhile (== 's') . T.reverse)
src/Network/MoeSocks/Internal/Socket.hs view
@@ -24,7 +24,7 @@           -> SockAddr           -> Int           -> IO Int            -- Number of Bytes sent-sendBufToWithFlagNoRetry +sendBufToWithFlagNoRetry   (MkSocket s _family _stype _protocol _status) ptr nbytes addr flags = do    withSockAddr addr $ \p_addr sz -> do     liftM fromIntegral $@@ -37,7 +37,7 @@        -> Int        -> IO Int      -- ^ Number of bytes sent sendToWithFlagNoRetry sock xs addr flags =-    unsafeUseAsCStringLen xs $ \(str, len) -> +    unsafeUseAsCStringLen xs $ \(str, len) ->       sendBufToWithFlagNoRetry sock str len addr flags  sendAllToFastOpen :: Socket      -- ^ Socket@@ -45,8 +45,6 @@           -> SockAddr    -- ^ Recipient address           -> IO () sendAllToFastOpen sock xs addr = do-    let _MSG_FASTOPEN  = 0x20000000  +    let _MSG_FASTOPEN  = 0x20000000     sent <- sendToWithFlagNoRetry sock xs addr _MSG_FASTOPEN     when (sent < S.length xs) $ sendAll sock (S.drop sent xs)--
src/Network/MoeSocks/Options.hs view
@@ -29,12 +29,12 @@ textParam :: O.Mod O.OptionFields String -> O.Parser (Maybe Value) textParam = optional . fmap toJSON . textOption -commaSeperatedArrayParam :: O.Mod O.OptionFields String +commaSeperatedArrayParam :: O.Mod O.OptionFields String                           -> O.Parser (Maybe Value)-commaSeperatedArrayParam = +commaSeperatedArrayParam =   optional . fmap toJSON . fmap (filter (isn't _Empty)-                                    . map T.strip -                                    . T.splitOn ",") +                                    . map T.strip+                                    . T.splitOn ",")                           . textOption  intParam :: O.Mod O.OptionFields Int -> O.Parser (Maybe Value)@@ -80,7 +80,7 @@       _showDefaultConfig = switch -                       long "show-default-config"                   <>  help "Show default json configuration"-      +       _tcpBufferSize = intParam -                               long "tcp-buffer-size"                           <>  metavar "SIZE"@@ -101,8 +101,8 @@                         long "deny-list"                     <>  metavar "ACL"                     <>  help "Block IPs from an access control list file."-                               +       _remoteHost = textParam -                       short 's'                   <>  metavar "REMOTE"@@ -271,7 +271,7 @@               <*> _listMethods               <*> _showDefaultConfig               <*> _params-              <*> _denyList +              <*> _denyList  opts :: ParserInfo Options opts = info (helper <*> optionParser) -
src/Network/MoeSocks/Runtime.hs view
@@ -29,7 +29,7 @@ initLogger :: Priority -> IO () initLogger aLevel = do   stdoutHandler <- streamHandler IO.stdout DEBUG-  let formattedHandler = +  let formattedHandler =           LogHandler.setFormatter stdoutHandler -             --"[$time : $loggername : $prio]             simpleLogFormatter "$time $prio\t $msg"@@ -43,33 +43,33 @@   loadJobs :: C.Config -> O.Options -> [Job]-loadJobs aConfig someOptions = +loadJobs aConfig someOptions =   let _c = aConfig -      _remote_TCP_Relay =   +      _remote_TCP_Relay =           RemoteRelay             Remote_TCP_Relay             (_c ^. C.remoteHost)             (_c ^. C.remotePort) -      _remote_UDP_Relay = +      _remote_UDP_Relay =           RemoteRelay             Remote_UDP_Relay             (_c ^. C.remoteHost)             (_c ^. C.remotePort)        _localService :: LocalServiceType -> LocalService-      _localService = LocalService +      _localService = LocalService                         (_c ^. C.localHost)                         (_c ^. C.remoteHost)                         (_c ^. C.remotePort) -      _localService_TCP_Forwards = -          someOptions ^. O.forward_TCPs +      _localService_TCP_Forwards =+          someOptions ^. O.forward_TCPs             & map (_localService . LocalService_TCP_Forward)        _localService_UDP_Forwards =-          someOptions ^. O.forward_UDPs +          someOptions ^. O.forward_UDPs             & map (_localService . LocalService_UDP_Forward)        _localService_SOCKS5 =@@ -77,9 +77,9 @@             & _localService        _remoteRelays = [_remote_TCP_Relay, _remote_UDP_Relay]-      _localServices = +      _localServices =         let-          _localService_SOCKS5s = +          _localService_SOCKS5s =             if someOptions ^. O.disable_SOCKS5               then []               else pure _localService_SOCKS5@@ -107,7 +107,7 @@    io - initLogger - _o ^. O.verbosity   io - debug_ - show _o-  +   _config <- loadConfig - _o    let _method = _c ^. C.method@@ -118,15 +118,15 @@     Just (a, b, c, d) -> pure - CipherBox a b c d    let _readDenyList :: IO [IPRange]-      _readDenyList = +      _readDenyList =         case someOptions ^. O.denyList of           Nothing -> pure []           Just _denyListPath ->             T.readFile (_denyListPath ^. _Text)-              <&> T.lines +              <&> T.lines               <&> parseIPRangeList-                 +   _denyList <- io - _readDenyList    io - debug_ - "denyList: " <> show (length _denyList) <> " items"@@ -144,21 +144,21 @@       _s = _c ^. C.socketOption_TCP_NOTSENT_LOWAT    _env <- initEnv aConfig someOptions-  +   let _env' = _env         & timeout                        .~ _c ^. C.timeout         & tcpBufferSize                  .~ _c ^. C.tcpBufferSize         & throttle                       .~ _c ^. C.throttle         & throttleSpeed                  .~ _c ^. C.throttleSpeed-        & obfuscationFlushBound          .~ _c ^. C.obfuscationFlushBound +        & obfuscationFlushBound          .~ _c ^. C.obfuscationFlushBound         & fastOpen                       .~ _c ^. C.fastOpen         & socketOption_TCP_NOTSENT_LOWAT .~ _s         & obfuscation                    .~ _o ^. O.obfuscation         & forbidden_IPs                  .~ (_c ^. C.forbidden_IPs                                                 & parseIPRangeList)-                                            -                                        -  +++   let _jobs = loadJobs _c _o & filterJobs (_o ^. O.runningMode)    pure -  ( defaultRuntime
src/Network/MoeSocks/TCP.hs view
@@ -25,32 +25,32 @@ local_SOCKS5_RequestHandler :: Env                             -> Text                             -> Int-                            -> ByteString -                            -> (Socket, SockAddr) +                            -> ByteString+                            -> (Socket, SockAddr)                             -> IO () local_SOCKS5_RequestHandler aEnv aRemoteHost aRemotePort _ (aSocket,_) = do-  (_partialBytesAfterGreeting, _r) <- +  (_partialBytesAfterGreeting, _r) <-       parseSocket "clientGreeting" mempty identityCipher         greetingParser aSocket -  when (not - _No_authentication `elem` (_r ^. authenticationMethods)) - +  when (not - _No_authentication `elem` (_r ^. authenticationMethods)) -     throwIO - ParseException                "Client does not support no authentication method" -  send_ aSocket - builder_To_ByteString greetingReplyBuilder +  send_ aSocket - builder_To_ByteString greetingReplyBuilder -  _parsedRequest <- parseSocket -                                "clientRequest" +  _parsedRequest <- parseSocket+                                "clientRequest"                                 _partialBytesAfterGreeting                                 identityCipher                                 connectionParser                                 aSocket -  local_TCP_RequestHandler  aEnv -                            aRemoteHost -                            aRemotePort -                            _parsedRequest -                            True +  local_TCP_RequestHandler  aEnv+                            aRemoteHost+                            aRemotePort+                            _parsedRequest+                            True                             aSocket  @@ -58,23 +58,23 @@ local_TCP_ForwardRequestHandler :: Env                                 -> Text                                 -> Int-                                -> Forward -                                -> ByteString -                                -> (Socket, SockAddr) +                                -> Forward+                                -> ByteString+                                -> (Socket, SockAddr)                                 -> IO ()-local_TCP_ForwardRequestHandler aEnv aRemoteHost aRemotePort aForwarding _ +local_TCP_ForwardRequestHandler aEnv aRemoteHost aRemotePort aForwarding _                                                               (aSocket,_) = do   let _clientRequest = ClientRequest                           TCP_IP_StreamConnection-                          (DomainName - aForwarding ^. +                          (DomainName - aForwarding ^.                             forwardTargetHost)                           (aForwarding ^. forwardTargetPort)-              +   local_TCP_RequestHandler  aEnv                             aRemoteHost                             aRemotePort-                            (mempty, _clientRequest) -                            False +                            (mempty, _clientRequest)+                            False                             aSocket  @@ -82,65 +82,65 @@ local_TCP_RequestHandler :: Env                           -> Text                           -> Int-                          -> (ByteString, ClientRequest) -                          -> Bool -                          -> Socket +                          -> (ByteString, ClientRequest)+                          -> Bool+                          -> Socket                           -> IO () local_TCP_RequestHandler aEnv                         aRemoteHost                         aRemotePort-                        (_partialBytesAfterClientRequest, _clientRequest) +                        (_partialBytesAfterClientRequest, _clientRequest)                         shouldReplyClient aSocket = do   let _addr = _clientRequest ^. addressType       _IPLists = getIPLists aEnv -  debug_ - "checking: " <> show _addr +  debug_ - "checking: " <> show _addr   withChecked_IP_List _addr _IPLists - do-    let +    let         _cipherBox = aEnv ^. cipherBox         _obfuscation = aEnv ^. obfuscation         _flushBound = aEnv ^. obfuscationFlushBound -        _initSocket = -            getSocket aRemoteHost aRemotePort Stream +        _initSocket =+            getSocket aRemoteHost aRemotePort Stream      debug_ - "L: " <> show _clientRequest-    -    logSA "L remote socket" _initSocket - ++    logSA "L remote socket" _initSocket -       \(_remoteSocket, _remoteHost) -> do       setSocketConfig aEnv _remoteSocket        _remoteSocketName <- getSocketName _remoteSocket-      +       when shouldReplyClient - do         let _connectionReplyBuilder = connectionReplyBuilder _remoteSocketName         send_ aSocket - builder_To_ByteString _connectionReplyBuilder-       +       _localPeerAddr <- getPeerName aSocket       let _msg = showRelay _localPeerAddr _clientRequest-      +       info_ - "LT: " <> _msg        let handleLocal _remoteSocket = do-            _encodeIV <- _cipherBox ^. generate_IV +            _encodeIV <- _cipherBox ^. generate_IV             _encrypt <- _cipherBox ^. encryptBuilder - _encodeIV-            -            let ++            let                 _header = shadowSocksRequestBuilder _clientRequest-            +             _sendChannel <- newTBQueueIO - aEnv ^. tcpBufferSize             _receiveChannel <- newTBQueueIO - aEnv ^. tcpBufferSize              let info_Id x = x <> " " <> _msg                 _timeout = aEnv ^. timeout * 1000 * 1000-                _throttle = +                _throttle =                   if aEnv ^. throttle                     then Just - aEnv ^. throttleSpeed                     else Nothing              _eHeader <- _encrypt - S.Just - builder_To_ByteString _header-            _ePartial <- _encrypt - S.Just _partialBytesAfterClientRequest +            _ePartial <- _encrypt - S.Just _partialBytesAfterClientRequest             let _padding = S.length (_eHeader <> _ePartial)              _eInit <- _encrypt . S.Just =<< recv aSocket (4096 + (-_padding))@@ -159,15 +159,15 @@                                     produceLoop (info_Id "L --> + Loop")                                       _timeout                                       _NoThrottle-                                      aSocket -                                      _sendChannel +                                      aSocket+                                      _sendChannel                                       _encrypt                    let _consume = do                                     consumeLoop (info_Id "L --> - Loop")                                       _timeout                                       _throttle-                                      _remoteSocket +                                      _remoteSocket                                       _sendChannel                                       _obfuscation                                       _flushBound@@ -178,7 +178,7 @@                     ) -                     pure () -            +             let receiveThread = do                   _decodeIV <- recv _remoteSocket (_cipherBox ^. ivLength)                   _decrypt <- _cipherBox ^. decryptBuilder - _decodeIV@@ -186,7 +186,7 @@                   let _produce = produceLoop (info_Id "L <-- + Loop")                                     _timeout                                     _NoThrottle-                                    _remoteSocket +                                    _remoteSocket                                     _receiveChannel                                     _decrypt @@ -194,11 +194,11 @@                                     consumeLoop (info_Id "L <-- - Loop")                                       _timeout                                       _NoThrottle-                                      aSocket +                                      aSocket                                       _receiveChannel                                       False                                       _flushBound-                  finally +                  finally                     (                       connectMarket (Just - info_Id "L <-- +", _produce)                                     (Just - info_Id "L <-- -", _consume)@@ -223,20 +223,20 @@   _decodeIV <- recv aSocket (_cipherBox ^. ivLength)   _decrypt <- _cipherBox ^. decryptBuilder - _decodeIV -  (_partialBytesAfterRequest, _clientRequest) <- parseSocket +  (_partialBytesAfterRequest, _clientRequest) <- parseSocket                                           "clientRequest"                                           mempty                                           _decrypt-                                          (shadowSocksRequestParser +                                          (shadowSocksRequestParser                                             TCP_IP_StreamConnection)                                           aSocket-  +   logSA "R target socket" (initTarget _clientRequest) - \_r -> do-    let (_targetSocket, _targetHost) = _r +    let (_targetSocket, _targetHost) = _r         (_addr, _) = sockAddr_To_Pair _targetHost         _IPLists = getIPLists aEnv -    debug_ - "checking: " <> show _addr +    debug_ - "checking: " <> show _addr     withChecked_IP_List _addr _IPLists - do       setSocketConfig aEnv _targetSocket @@ -244,7 +244,7 @@       let _msg = showRelay _remotePeerAddr _clientRequest        info_ - "RT: " <> _msg-      +       let _initBytes = _partialBytesAfterRequest        if aEnv ^. fastOpen@@ -253,8 +253,8 @@         else do           connect _targetSocket _targetHost           send_ _targetSocket _initBytes-      -      let ++      let           handleTarget __targetSocket = do             _sendChannel <- newTBQueueIO - aEnv ^. tcpBufferSize             _receiveChannel <- newTBQueueIO - aEnv ^. tcpBufferSize@@ -263,8 +263,8 @@                 -- let remote wait slightly longer, so local can timeout                 -- and disconnect                 _timeout = (aEnv ^. timeout + 30) * 1000 * 1000-                -                _throttle = ++                _throttle =                   if aEnv ^. throttle                     then Just - aEnv ^. throttleSpeed                     else Nothing@@ -273,7 +273,7 @@                   let _produce = do                                     produceLoop (info_Id "R --> + Loop")                                       _timeout-                                      _NoThrottle +                                      _NoThrottle                                       aSocket                                       _sendChannel                                       _decrypt@@ -294,14 +294,14 @@                     pure ()              let receiveThread = do-                  _encodeIV <- _cipherBox ^. generate_IV +                  _encodeIV <- _cipherBox ^. generate_IV                   _encrypt <- _cipherBox ^. encryptBuilder - _encodeIV                   sendBytes _receiveChannel _encodeIV                    let _produce = do                                     produceLoop (info_Id "R <-- + Loop")                                       _timeout-                                      _NoThrottle +                                      _NoThrottle                                       _targetSocket                                       _receiveChannel                                       _encrypt@@ -316,7 +316,7 @@                                       _obfuscation                                       _flushBound -                  finally +                  finally                     (                       connectMarket (Just - info_Id "R <-- +", _produce)                                     (Just - info_Id "R <-- -", _consume)@@ -326,5 +326,5 @@             connectTunnel               (Just - info_Id "R -->", sendThread)               (Just - info_Id "R <--", receiveThread)-            +       handleTarget _targetSocket
src/Network/MoeSocks/Type.hs view
@@ -1,14 +1,12 @@ {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} -module Network.MoeSocks.Type +module Network.MoeSocks.Type (   module Network.MoeSocks.Type.Runtime , module Network.MoeSocks.Type.Common ) where -import Network.MoeSocks.Type.Runtime +import Network.MoeSocks.Type.Runtime import Network.MoeSocks.Type.Common--
src/Network/MoeSocks/Type/Common.hs view
@@ -1,4 +1,3 @@- {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} 
src/Network/MoeSocks/Type/Runtime.hs view
@@ -29,7 +29,7 @@   | UDP_Port   deriving (Show, Eq) -data AddressType = +data AddressType =     IPv4_Address (Word8, Word8, Word8, Word8)   | DomainName Text   | IPv6_Address [Word16]@@ -40,12 +40,12 @@     where       showAddressType :: AddressType -> String       showAddressType (IPv4_Address xs) = xs ^.. each . to show-                                             ^.. folding +                                             ^.. folding                                                   (concat . L.intersperse ".")-                                            +       showAddressType (DomainName x)   = x ^. _Text       showAddressType (IPv6_Address xs) = xs ^.. each . to (flip showHex "")-                                             ^.. folding +                                             ^.. folding                                                   (concat . L.intersperse ":") data ClientRequest = ClientRequest   {@@ -61,7 +61,7 @@ data Verbosity = Normal | Verbose       deriving (Show, Eq) -type Cipher = S.Maybe ByteString -> IO ByteString +type Cipher = S.Maybe ByteString -> IO ByteString type IV = ByteString type CipherBuilder = IV -> IO Cipher @@ -113,7 +113,7 @@  makeLenses ''RemoteRelay -data Job = +data Job =       RemoteRelayJob RemoteRelay     | LocalServiceJob LocalService     deriving (Show, Eq)@@ -147,4 +147,3 @@ makeLenses ''Runtime  type MoeMonad = ExceptT String IO-
src/Network/MoeSocks/UDP.hs view
@@ -52,7 +52,7 @@                                 aMessage                                 (aSocket, aSockAddr) = do -  let +  let       _cipherBox = aEnv ^. cipherBox    let _clientRequest = ClientRequest@@ -66,7 +66,7 @@   let _addr = _clientRequest ^. addressType       _IPLists = getIPLists aEnv -  debug_ - "checking: " <> show _addr +  debug_ - "checking: " <> show _addr    withChecked_IP_List _addr _IPLists - do     _sa <- getSocket aRemoteHost aRemotePort Datagram@@ -132,7 +132,7 @@         (_addr, _) = sockAddr_To_Pair _targetSocketAddress         _IPLists = getIPLists aEnv -    debug_ - "checking: " <> show _addr +    debug_ - "checking: " <> show _addr     withChecked_IP_List _addr _IPLists - do       let _msg = showRelay aSockAddr _clientRequest       info_ - "RU: " <> _msg