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