1a9f8458a0175916c9daf8df7056ccdf2b36a143
[ghc-base.git] / System / Posix / Internals.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 {-# OPTIONS_GHC -fno-warn-unused-binds #-}
3 {-# OPTIONS_HADDOCK hide #-}
4
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module      :  System.Posix.Internals
8 -- Copyright   :  (c) The University of Glasgow, 1992-2002
9 -- License     :  see libraries/base/LICENSE
10 -- 
11 -- Maintainer  :  cvs-ghc@haskell.org
12 -- Stability   :  internal
13 -- Portability :  non-portable (requires POSIX)
14 --
15 -- POSIX support layer for the standard libraries.
16 -- This library is built on *every* platform, including Win32.
17 --
18 -- Non-posix compliant in order to support the following features:
19 --      * S_ISSOCK (no sockets in POSIX)
20 --
21 -----------------------------------------------------------------------------
22
23 -- #hide
24 module System.Posix.Internals where
25
26 #include "HsBaseConfig.h"
27
28 #if ! (defined(mingw32_HOST_OS) || defined(__MINGW32__))
29 import Control.Monad
30 #endif
31 import System.Posix.Types
32
33 import Foreign
34 import Foreign.C
35
36 import Data.Bits
37 import Data.Maybe
38
39 #if __GLASGOW_HASKELL__
40 import GHC.Base
41 import GHC.Num
42 import GHC.Real
43 import GHC.IOBase
44 #elif __HUGS__
45 import Hugs.Prelude (IOException(..), IOErrorType(..))
46 import Hugs.IO (IOMode(..))
47 #else
48 import System.IO
49 #endif
50
51 #ifdef __HUGS__
52 {-# CFILES cbits/PrelIOUtils.c cbits/dirUtils.c cbits/consUtils.c #-}
53 #endif
54
55 -- ---------------------------------------------------------------------------
56 -- Types
57
58 type CDir       = ()
59 type CDirent    = ()
60 type CFLock     = ()
61 type CGroup     = ()
62 type CLconv     = ()
63 type CPasswd    = ()
64 type CSigaction = ()
65 type CSigset    = ()
66 type CStat      = ()
67 type CTermios   = ()
68 type CTm        = ()
69 type CTms       = ()
70 type CUtimbuf   = ()
71 type CUtsname   = ()
72
73 #ifndef __GLASGOW_HASKELL__
74 type FD = CInt
75 #endif
76
77 -- ---------------------------------------------------------------------------
78 -- stat()-related stuff
79
80 fdFileSize :: FD -> IO Integer
81 fdFileSize fd = 
82   allocaBytes sizeof_stat $ \ p_stat -> do
83     throwErrnoIfMinus1Retry "fileSize" $
84         c_fstat fd p_stat
85     c_mode <- st_mode p_stat :: IO CMode 
86     if not (s_isreg c_mode)
87         then return (-1)
88         else do
89     c_size <- st_size p_stat
90     return (fromIntegral c_size)
91
92 data FDType  = Directory | Stream | RegularFile | RawDevice
93                deriving (Eq)
94
95 fileType :: FilePath -> IO FDType
96 fileType file =
97   allocaBytes sizeof_stat $ \ p_stat -> do
98   withCString file $ \p_file -> do
99     throwErrnoIfMinus1Retry "fileType" $
100       c_stat p_file p_stat
101     statGetType p_stat
102
103 -- NOTE: On Win32 platforms, this will only work with file descriptors
104 -- referring to file handles. i.e., it'll fail for socket FDs.
105 fdStat :: FD -> IO (FDType, CDev, CIno)
106 fdStat fd = 
107   allocaBytes sizeof_stat $ \ p_stat -> do
108     throwErrnoIfMinus1Retry "fdType" $
109         c_fstat fd p_stat
110     ty <- statGetType p_stat
111     dev <- st_dev p_stat
112     ino <- st_ino p_stat
113     return (ty,dev,ino)
114     
115 fdType :: FD -> IO FDType
116 fdType fd = do (ty,_,_) <- fdStat fd; return ty
117
118 statGetType :: Ptr CStat -> IO FDType
119 statGetType p_stat = do
120   c_mode <- st_mode p_stat :: IO CMode
121   case () of
122       _ | s_isdir c_mode        -> return Directory
123         | s_isfifo c_mode || s_issock c_mode || s_ischr  c_mode
124                                 -> return Stream
125         | s_isreg c_mode        -> return RegularFile
126          -- Q: map char devices to RawDevice too?
127         | s_isblk c_mode        -> return RawDevice
128         | otherwise             -> ioError ioe_unknownfiletype
129     
130 ioe_unknownfiletype :: IOException
131 ioe_unknownfiletype = IOError Nothing UnsupportedOperation "fdType"
132                         "unknown file type" Nothing
133
134 #if __GLASGOW_HASKELL__ && (defined(mingw32_HOST_OS) || defined(__MINGW32__))
135 closeFd :: Bool -> CInt -> IO CInt
136 closeFd isStream fd 
137   | isStream  = c_closesocket fd
138   | otherwise = c_close fd
139
140 foreign import stdcall unsafe "HsBase.h closesocket"
141    c_closesocket :: CInt -> IO CInt
142 #endif
143
144 fdGetMode :: FD -> IO IOMode
145 #if defined(mingw32_HOST_OS) || defined(__MINGW32__)
146 fdGetMode _ = do
147     -- We don't have a way of finding out which flags are set on FDs
148     -- on Windows, so make a handle that thinks that anything goes.
149     let flags = o_RDWR
150 #else
151 fdGetMode fd = do
152     flags <- throwErrnoIfMinus1Retry "fdGetMode" 
153                 (c_fcntl_read fd const_f_getfl)
154 #endif
155     let
156        wH  = (flags .&. o_WRONLY) /= 0
157        aH  = (flags .&. o_APPEND) /= 0
158        rwH = (flags .&. o_RDWR) /= 0
159
160        mode
161          | wH && aH  = AppendMode
162          | wH        = WriteMode
163          | rwH       = ReadWriteMode
164          | otherwise = ReadMode
165           
166     return mode
167
168 -- ---------------------------------------------------------------------------
169 -- Terminal-related stuff
170
171 fdIsTTY :: FD -> IO Bool
172 fdIsTTY fd = c_isatty fd >>= return.toBool
173
174 #if defined(HTYPE_TCFLAG_T)
175
176 setEcho :: FD -> Bool -> IO ()
177 setEcho fd on = do
178   tcSetAttr fd $ \ p_tios -> do
179     lflag <- c_lflag p_tios :: IO CTcflag
180     let new_lflag
181          | on        = lflag .|. fromIntegral const_echo
182          | otherwise = lflag .&. complement (fromIntegral const_echo)
183     poke_c_lflag p_tios (new_lflag :: CTcflag)
184
185 getEcho :: FD -> IO Bool
186 getEcho fd = do
187   tcSetAttr fd $ \ p_tios -> do
188     lflag <- c_lflag p_tios :: IO CTcflag
189     return ((lflag .&. fromIntegral const_echo) /= 0)
190
191 setCooked :: FD -> Bool -> IO ()
192 setCooked fd cooked = 
193   tcSetAttr fd $ \ p_tios -> do
194
195     -- turn on/off ICANON
196     lflag <- c_lflag p_tios :: IO CTcflag
197     let new_lflag | cooked    = lflag .|. (fromIntegral const_icanon)
198                   | otherwise = lflag .&. complement (fromIntegral const_icanon)
199     poke_c_lflag p_tios (new_lflag :: CTcflag)
200
201     -- set VMIN & VTIME to 1/0 respectively
202     when (not cooked) $ do
203             c_cc <- ptr_c_cc p_tios
204             let vmin  = (c_cc `plusPtr` (fromIntegral const_vmin))  :: Ptr Word8
205                 vtime = (c_cc `plusPtr` (fromIntegral const_vtime)) :: Ptr Word8
206             poke vmin  1
207             poke vtime 0
208
209 tcSetAttr :: FD -> (Ptr CTermios -> IO a) -> IO a
210 tcSetAttr fd fun = do
211      allocaBytes sizeof_termios  $ \p_tios -> do
212         throwErrnoIfMinus1Retry "tcSetAttr"
213            (c_tcgetattr fd p_tios)
214
215 #ifdef __GLASGOW_HASKELL__
216         -- Save a copy of termios, if this is a standard file descriptor.
217         -- These terminal settings are restored in hs_exit().
218         when (fd <= 2) $ do
219           p <- get_saved_termios fd
220           when (p == nullPtr) $ do
221              saved_tios <- mallocBytes sizeof_termios
222              copyBytes saved_tios p_tios sizeof_termios
223              set_saved_termios fd saved_tios
224 #endif
225
226         -- tcsetattr() when invoked by a background process causes the process
227         -- to be sent SIGTTOU regardless of whether the process has TOSTOP set
228         -- in its terminal flags (try it...).  This function provides a
229         -- wrapper which temporarily blocks SIGTTOU around the call, making it
230         -- transparent.
231         allocaBytes sizeof_sigset_t $ \ p_sigset -> do
232         allocaBytes sizeof_sigset_t $ \ p_old_sigset -> do
233              c_sigemptyset p_sigset
234              c_sigaddset   p_sigset const_sigttou
235              c_sigprocmask const_sig_block p_sigset p_old_sigset
236              r <- fun p_tios  -- do the business
237              throwErrnoIfMinus1Retry_ "tcSetAttr" $
238                  c_tcsetattr fd const_tcsanow p_tios
239              c_sigprocmask const_sig_setmask p_old_sigset nullPtr
240              return r
241
242 #ifdef __GLASGOW_HASKELL__
243 foreign import ccall unsafe "HsBase.h __hscore_get_saved_termios"
244    get_saved_termios :: CInt -> IO (Ptr CTermios)
245
246 foreign import ccall unsafe "HsBase.h __hscore_set_saved_termios"
247    set_saved_termios :: CInt -> (Ptr CTermios) -> IO ()
248 #endif
249
250 #else
251
252 -- 'raw' mode for Win32 means turn off 'line input' (=> buffering and
253 -- character translation for the console.) The Win32 API for doing
254 -- this is GetConsoleMode(), which also requires echoing to be disabled
255 -- when turning off 'line input' processing. Notice that turning off
256 -- 'line input' implies enter/return is reported as '\r' (and it won't
257 -- report that character until another character is input..odd.) This
258 -- latter feature doesn't sit too well with IO actions like IO.hGetLine..
259 -- consider yourself warned.
260 setCooked :: FD -> Bool -> IO ()
261 setCooked fd cooked = do
262   x <- set_console_buffering fd (if cooked then 1 else 0)
263   if (x /= 0)
264    then ioError (ioe_unk_error "setCooked" "failed to set buffering")
265    else return ()
266
267 ioe_unk_error :: String -> String -> IOException
268 ioe_unk_error loc msg 
269  = IOError Nothing OtherError loc msg Nothing
270
271 -- Note: echoing goes hand in hand with enabling 'line input' / raw-ness
272 -- for Win32 consoles, hence setEcho ends up being the inverse of setCooked.
273 setEcho :: FD -> Bool -> IO ()
274 setEcho fd on = do
275   x <- set_console_echo fd (if on then 1 else 0)
276   if (x /= 0)
277    then ioError (ioe_unk_error "setEcho" "failed to set echoing")
278    else return ()
279
280 getEcho :: FD -> IO Bool
281 getEcho fd = do
282   r <- get_console_echo fd
283   if (r == (-1))
284    then ioError (ioe_unk_error "getEcho" "failed to get echoing")
285    else return (r == 1)
286
287 foreign import ccall unsafe "consUtils.h set_console_buffering__"
288    set_console_buffering :: CInt -> CInt -> IO CInt
289
290 foreign import ccall unsafe "consUtils.h set_console_echo__"
291    set_console_echo :: CInt -> CInt -> IO CInt
292
293 foreign import ccall unsafe "consUtils.h get_console_echo__"
294    get_console_echo :: CInt -> IO CInt
295
296 #endif
297
298 -- ---------------------------------------------------------------------------
299 -- Turning on non-blocking for a file descriptor
300
301 setNonBlockingFD :: FD -> IO ()
302 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
303 setNonBlockingFD fd = do
304   flags <- throwErrnoIfMinus1Retry "setNonBlockingFD"
305                  (c_fcntl_read fd const_f_getfl)
306   -- An error when setting O_NONBLOCK isn't fatal: on some systems 
307   -- there are certain file handles on which this will fail (eg. /dev/null
308   -- on FreeBSD) so we throw away the return code from fcntl_write.
309   unless (testBit flags (fromIntegral o_NONBLOCK)) $ do
310     c_fcntl_write fd const_f_setfl (fromIntegral (flags .|. o_NONBLOCK))
311     return ()
312 #else
313
314 -- bogus defns for win32
315 setNonBlockingFD _ = return ()
316
317 #endif
318
319 -- -----------------------------------------------------------------------------
320 -- foreign imports
321
322 foreign import ccall unsafe "HsBase.h access"
323    c_access :: CString -> CInt -> IO CInt
324
325 foreign import ccall unsafe "HsBase.h chmod"
326    c_chmod :: CString -> CMode -> IO CInt
327
328 foreign import ccall unsafe "HsBase.h close"
329    c_close :: CInt -> IO CInt
330
331 foreign import ccall unsafe "HsBase.h closedir" 
332    c_closedir :: Ptr CDir -> IO CInt
333
334 foreign import ccall unsafe "HsBase.h creat"
335    c_creat :: CString -> CMode -> IO CInt
336
337 foreign import ccall unsafe "HsBase.h dup"
338    c_dup :: CInt -> IO CInt
339
340 foreign import ccall unsafe "HsBase.h dup2"
341    c_dup2 :: CInt -> CInt -> IO CInt
342
343 foreign import ccall unsafe "HsBase.h __hscore_fstat"
344    c_fstat :: CInt -> Ptr CStat -> IO CInt
345
346 foreign import ccall unsafe "HsBase.h isatty"
347    c_isatty :: CInt -> IO CInt
348
349 #if defined(mingw32_HOST_OS) || defined(__MINGW32__)
350 foreign import ccall unsafe "HsBase.h __hscore_lseek"
351    c_lseek :: CInt -> Int64 -> CInt -> IO Int64
352 #else
353 foreign import ccall unsafe "HsBase.h __hscore_lseek"
354    c_lseek :: CInt -> COff -> CInt -> IO COff
355 #endif
356
357 foreign import ccall unsafe "HsBase.h __hscore_lstat"
358    lstat :: CString -> Ptr CStat -> IO CInt
359
360 foreign import ccall unsafe "HsBase.h __hscore_open"
361    c_open :: CString -> CInt -> CMode -> IO CInt
362
363 foreign import ccall unsafe "HsBase.h opendir" 
364    c_opendir :: CString  -> IO (Ptr CDir)
365
366 foreign import ccall unsafe "HsBase.h __hscore_mkdir"
367    mkdir :: CString -> CInt -> IO CInt
368
369 foreign import ccall unsafe "HsBase.h read" 
370    c_read :: CInt -> Ptr CChar -> CSize -> IO CSsize
371
372 foreign import ccall unsafe "HsBase.h rewinddir"
373    c_rewinddir :: Ptr CDir -> IO ()
374
375 foreign import ccall unsafe "HsBase.h __hscore_stat"
376    c_stat :: CString -> Ptr CStat -> IO CInt
377
378 foreign import ccall unsafe "HsBase.h umask"
379    c_umask :: CMode -> IO CMode
380
381 foreign import ccall unsafe "HsBase.h write" 
382    c_write :: CInt -> Ptr CChar -> CSize -> IO CSsize
383
384 foreign import ccall unsafe "HsBase.h __hscore_ftruncate"
385    c_ftruncate :: CInt -> COff -> IO CInt
386
387 foreign import ccall unsafe "HsBase.h unlink"
388    c_unlink :: CString -> IO CInt
389
390 foreign import ccall unsafe "HsBase.h getpid"
391    c_getpid :: IO CPid
392
393 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
394 foreign import ccall unsafe "HsBase.h fcntl"
395    c_fcntl_read  :: CInt -> CInt -> IO CInt
396
397 foreign import ccall unsafe "HsBase.h fcntl"
398    c_fcntl_write :: CInt -> CInt -> CLong -> IO CInt
399
400 foreign import ccall unsafe "HsBase.h fcntl"
401    c_fcntl_lock  :: CInt -> CInt -> Ptr CFLock -> IO CInt
402
403 foreign import ccall unsafe "HsBase.h fork"
404    c_fork :: IO CPid 
405
406 foreign import ccall unsafe "HsBase.h link"
407    c_link :: CString -> CString -> IO CInt
408
409 foreign import ccall unsafe "HsBase.h mkfifo"
410    c_mkfifo :: CString -> CMode -> IO CInt
411
412 foreign import ccall unsafe "HsBase.h pipe"
413    c_pipe :: Ptr CInt -> IO CInt
414
415 foreign import ccall unsafe "HsBase.h __hscore_sigemptyset"
416    c_sigemptyset :: Ptr CSigset -> IO CInt
417
418 foreign import ccall unsafe "HsBase.h __hscore_sigaddset"
419    c_sigaddset :: Ptr CSigset -> CInt -> IO CInt
420
421 foreign import ccall unsafe "HsBase.h sigprocmask"
422    c_sigprocmask :: CInt -> Ptr CSigset -> Ptr CSigset -> IO CInt
423
424 foreign import ccall unsafe "HsBase.h tcgetattr"
425    c_tcgetattr :: CInt -> Ptr CTermios -> IO CInt
426
427 foreign import ccall unsafe "HsBase.h tcsetattr"
428    c_tcsetattr :: CInt -> CInt -> Ptr CTermios -> IO CInt
429
430 foreign import ccall unsafe "HsBase.h utime"
431    c_utime :: CString -> Ptr CUtimbuf -> IO CInt
432
433 foreign import ccall unsafe "HsBase.h waitpid"
434    c_waitpid :: CPid -> Ptr CInt -> CInt -> IO CPid
435 #endif
436
437 -- traversing directories
438 foreign import ccall unsafe "dirUtils.h __hscore_readdir"
439   readdir  :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt
440  
441 foreign import ccall unsafe "HsBase.h __hscore_free_dirent"
442   freeDirEnt  :: Ptr CDirent -> IO ()
443  
444 foreign import ccall unsafe "HsBase.h __hscore_end_of_dir"
445   end_of_dir :: CInt
446  
447 foreign import ccall unsafe "HsBase.h __hscore_d_name"
448   d_name :: Ptr CDirent -> IO CString
449
450 -- POSIX flags only:
451 foreign import ccall unsafe "HsBase.h __hscore_o_rdonly" o_RDONLY :: CInt
452 foreign import ccall unsafe "HsBase.h __hscore_o_wronly" o_WRONLY :: CInt
453 foreign import ccall unsafe "HsBase.h __hscore_o_rdwr"   o_RDWR   :: CInt
454 foreign import ccall unsafe "HsBase.h __hscore_o_append" o_APPEND :: CInt
455 foreign import ccall unsafe "HsBase.h __hscore_o_creat"  o_CREAT  :: CInt
456 foreign import ccall unsafe "HsBase.h __hscore_o_excl"   o_EXCL   :: CInt
457 foreign import ccall unsafe "HsBase.h __hscore_o_trunc"  o_TRUNC  :: CInt
458
459 -- non-POSIX flags.
460 foreign import ccall unsafe "HsBase.h __hscore_o_noctty"   o_NOCTTY   :: CInt
461 foreign import ccall unsafe "HsBase.h __hscore_o_nonblock" o_NONBLOCK :: CInt
462 foreign import ccall unsafe "HsBase.h __hscore_o_binary"   o_BINARY   :: CInt
463
464 foreign import ccall unsafe "HsBase.h __hscore_s_isreg"  c_s_isreg  :: CMode -> CInt
465 foreign import ccall unsafe "HsBase.h __hscore_s_ischr"  c_s_ischr  :: CMode -> CInt
466 foreign import ccall unsafe "HsBase.h __hscore_s_isblk"  c_s_isblk  :: CMode -> CInt
467 foreign import ccall unsafe "HsBase.h __hscore_s_isdir"  c_s_isdir  :: CMode -> CInt
468 foreign import ccall unsafe "HsBase.h __hscore_s_isfifo" c_s_isfifo :: CMode -> CInt
469
470 s_isreg  :: CMode -> Bool
471 s_isreg cm = c_s_isreg cm /= 0
472 s_ischr  :: CMode -> Bool
473 s_ischr cm = c_s_ischr cm /= 0
474 s_isblk  :: CMode -> Bool
475 s_isblk cm = c_s_isblk cm /= 0
476 s_isdir  :: CMode -> Bool
477 s_isdir cm = c_s_isdir cm /= 0
478 s_isfifo :: CMode -> Bool
479 s_isfifo cm = c_s_isfifo cm /= 0
480
481 foreign import ccall unsafe "HsBase.h __hscore_sizeof_stat" sizeof_stat :: Int
482 foreign import ccall unsafe "HsBase.h __hscore_st_mtime" st_mtime :: Ptr CStat -> IO CTime
483 #ifdef mingw32_HOST_OS
484 foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO Int64
485 #else
486 foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO COff
487 #endif
488 foreign import ccall unsafe "HsBase.h __hscore_st_mode" st_mode :: Ptr CStat -> IO CMode
489 foreign import ccall unsafe "HsBase.h __hscore_st_dev" st_dev :: Ptr CStat -> IO CDev
490 foreign import ccall unsafe "HsBase.h __hscore_st_ino" st_ino :: Ptr CStat -> IO CIno
491
492 foreign import ccall unsafe "HsBase.h __hscore_echo"         const_echo :: CInt
493 foreign import ccall unsafe "HsBase.h __hscore_tcsanow"      const_tcsanow :: CInt
494 foreign import ccall unsafe "HsBase.h __hscore_icanon"       const_icanon :: CInt
495 foreign import ccall unsafe "HsBase.h __hscore_vmin"         const_vmin   :: CInt
496 foreign import ccall unsafe "HsBase.h __hscore_vtime"        const_vtime  :: CInt
497 foreign import ccall unsafe "HsBase.h __hscore_sigttou"      const_sigttou :: CInt
498 foreign import ccall unsafe "HsBase.h __hscore_sig_block"    const_sig_block :: CInt
499 foreign import ccall unsafe "HsBase.h __hscore_sig_setmask"  const_sig_setmask :: CInt
500 foreign import ccall unsafe "HsBase.h __hscore_f_getfl"      const_f_getfl :: CInt
501 foreign import ccall unsafe "HsBase.h __hscore_f_setfl"      const_f_setfl :: CInt
502
503 #if defined(HTYPE_TCFLAG_T)
504 foreign import ccall unsafe "HsBase.h __hscore_sizeof_termios"  sizeof_termios :: Int
505 foreign import ccall unsafe "HsBase.h __hscore_sizeof_sigset_t" sizeof_sigset_t :: Int
506
507 foreign import ccall unsafe "HsBase.h __hscore_lflag" c_lflag :: Ptr CTermios -> IO CTcflag
508 foreign import ccall unsafe "HsBase.h __hscore_poke_lflag" poke_c_lflag :: Ptr CTermios -> CTcflag -> IO ()
509 foreign import ccall unsafe "HsBase.h __hscore_ptr_c_cc" ptr_c_cc  :: Ptr CTermios -> IO (Ptr Word8)
510 #endif
511
512 s_issock :: CMode -> Bool
513 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
514 s_issock cmode = c_s_issock cmode /= 0
515 foreign import ccall unsafe "HsBase.h __hscore_s_issock" c_s_issock :: CMode -> CInt
516 #else
517 s_issock _ = False
518 #endif