summaryrefslogtreecommitdiff
path: root/Presence/Server.hs
blob: deab779b0e1379809ea60e6b6f6b9e035baa61b4 (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
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
module Server where

import Network.Socket
import Data.ByteString.Lazy.Char8 as L 
    ( fromChunks
    , putStrLn )
import Data.ByteString.Char8 
    ( hGetNonBlocking
    )
import System.IO 
    ( IOMode(..)
    , hSetBuffering
    , BufferMode(..)
    , hWaitForInput
    , hClose
    , hIsEOF
    )
import Control.Monad
import Control.Concurrent (forkIO)
import Control.Exception (handle,SomeException(..))
import Data.HList
import Data.HList.TypeEqGeneric1()
import Data.HList.TypeCastGeneric1()
import System.IO.Error
import ByteStringOperators


newtype ConnId = ConnId Int
  deriving Eq

newtype ConnectionFinalizer = ConnectionFinalizer (IO ())

getPacket h = do { hWaitForInput h (-1) ; fmap (fromChunks . (:[])) $ hGetNonBlocking h 1024 }

{-
doServer ::
  HList st 
  => PortNumber :*: st
      -> ( Handle :*: ConnId :*: PortNumber :*: st
            -> S.ByteString 
            -> (() -> IO ()) 
            -> IO () )
      -> IO b
-}
doServer port g startCon = runServer2 port (runConn2 g)
 where
    runConn2 g st (sock,_) = do
        h <- socketToHandle sock ReadWriteMode
        hSetBuffering h NoBuffering
        st'' <- startCon sock (h .*. st)
        let doException (SomeException e) = Prelude.putStrLn ("\n\nexception: " ++ show e ++ "\n\n")
        handle doException $ fix $ \loop -> do
            let continue () = hIsEOF h >>= flip when loop . not
            packet <- getPacket h
            g st'' packet continue
        let ConnectionFinalizer cleanup = hOccursFst st''
        cleanup
        hClose h

    {-
    runServer2 ::
      Num num =>
      PortNumber -> (num -> (Socket, SockAddr) -> IO b -> IO b) -> IO b
    -}
    runServer2 st@(HCons port _) go = do
        sock <- socket AF_INET Stream 0
        setSocketOption sock ReuseAddr 1
        bindSocket sock (SockAddrInet port iNADDR_ANY)
        listen sock 2
        forkIO $ do
            mainLoop sock (ConnId 0) go
            -- L.putStrLn $ "quit accept loop"
        return sock
     where
        mainLoop sock idnum@(ConnId n) go = do
            let doException ioerror = do
                let typ = ioeGetErrorType ioerror
                if -- typ == InvalidArgument  
                   -- but the symbol is not exported :/
                   bshow typ=="invalid argument" 
                  then do
                    L.putStrLn $ "quit accept-loop."
                  else do
                    L.putStrLn ("accept-loop exception: " <++> bshow ioerror <++> "\n")
                return Nothing
            mcon <- handle doException $ fix $ \loop -> do
                con <- accept sock
                return $ Just con
            case mcon of
              Just con -> do
                forkIO $ go (idnum .*. st) con 
                mainLoop sock (ConnId (n+1)) go
              Nothing -> return ()