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