summaryrefslogtreecommitdiff
path: root/dht/examples/whosocket.hs
blob: f84e31780b243eb7b9805978ffc5df411ef19296 (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
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}
module Main where

import LocalPeerCred
import ControlMaybe
import UTmp
import ByteStringOperators

import System.Directory
import Data.Char
import System.Posix.Types
import System.Posix.Files
import qualified Data.ByteString.Lazy.Char8 as L 
    ( unpack
    , pack
    , take
    , putStrLn
    )
import Data.List (groupBy)
import Data.Maybe (listToMaybe,mapMaybe,catMaybes)

import Network.Socket
import System.Environment
import Control.Arrow (first)
import System.Endian

usage = do
    putStrLn $ "whosocket numeric-address port"

main = do
    args <- getArgs
    case (args??0,args??1) of
        (Just addr_str,Just port_str) -> whosocket addr_str port_str
        _                             -> usage

whosocket :: HostName -> ServiceName -> IO ()
whosocket addr_str port_str = do
    info <- getAddrInfo (Just $ defaultHints { addrFlags = [ AI_NUMERICHOST ] }) 
                        (Just addr_str) 
                        (Just port_str)
    let addr = head $ map addrAddress info
    r <- getLocalPeerCred' addr
    putStrLn $ "r{"++show addr++"} = " ++ show r

    us <- UTmp.users
    let filterTTYs (_,tty,pid) = 
            if L.take 3 tty == "tty"
              then Just (tty,pid)
              else Nothing
        tty_pids = mapMaybe filterTTYs us

    tty <- maybe (return Nothing)
                 (fmap fst . uncurry (identifyTTY tty_pids))
                 r
    putStrLn $ "uid = " ++ show (fmap fst r)
    L.putStrLn $ "tty = " <++?> tty

    return ()