960f84c2be24b09a5aeb21f0193cb662fe8ce867
[ghc-base.git] / System / Posix / Internals.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
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
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 #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 "dirUtils.h __hscore_renameFile"
373    c_rename :: CString -> CString -> IO CInt
374                      
375 foreign import ccall unsafe "HsBase.h rewinddir"
376    c_rewinddir :: Ptr CDir -> IO ()
377
378 foreign import ccall unsafe "HsBase.h rmdir"
379    c_rmdir :: CString -> IO CInt
380
381 foreign import ccall unsafe "HsBase.h __hscore_stat"
382    c_stat :: CString -> Ptr CStat -> IO CInt
383
384 foreign import ccall unsafe "HsBase.h umask"
385    c_umask :: CMode -> IO CMode
386
387 foreign import ccall unsafe "HsBase.h write" 
388    c_write :: CInt -> Ptr CChar -> CSize -> IO CSsize
389
390 foreign import ccall unsafe "HsBase.h __hscore_ftruncate"
391    c_ftruncate :: CInt -> COff -> IO CInt
392
393 foreign import ccall unsafe "HsBase.h unlink"
394    c_unlink :: CString -> IO CInt
395
396 foreign import ccall unsafe "HsBase.h getpid"
397    c_getpid :: IO CPid
398
399 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
400 foreign import ccall unsafe "HsBase.h fcntl"
401    c_fcntl_read  :: CInt -> CInt -> IO CInt
402
403 foreign import ccall unsafe "HsBase.h fcntl"
404    c_fcntl_write :: CInt -> CInt -> CLong -> IO CInt
405
406 foreign import ccall unsafe "HsBase.h fcntl"
407    c_fcntl_lock  :: CInt -> CInt -> Ptr CFLock -> IO CInt
408
409 foreign import ccall unsafe "HsBase.h fork"
410    c_fork :: IO CPid 
411
412 foreign import ccall unsafe "HsBase.h link"
413    c_link :: CString -> CString -> IO CInt
414
415 foreign import ccall unsafe "HsBase.h mkfifo"
416    c_mkfifo :: CString -> CMode -> IO CInt
417
418 foreign import ccall unsafe "HsBase.h pipe"
419    c_pipe :: Ptr CInt -> IO CInt
420
421 foreign import ccall unsafe "HsBase.h __hscore_sigemptyset"
422    c_sigemptyset :: Ptr CSigset -> IO CInt
423
424 foreign import ccall unsafe "HsBase.h __hscore_sigaddset"
425    c_sigaddset :: Ptr CSigset -> CInt -> IO CInt
426
427 foreign import ccall unsafe "HsBase.h sigprocmask"
428    c_sigprocmask :: CInt -> Ptr CSigset -> Ptr CSigset -> IO CInt
429
430 foreign import ccall unsafe "HsBase.h tcgetattr"
431    c_tcgetattr :: CInt -> Ptr CTermios -> IO CInt
432
433 foreign import ccall unsafe "HsBase.h tcsetattr"
434    c_tcsetattr :: CInt -> CInt -> Ptr CTermios -> IO CInt
435
436 foreign import ccall unsafe "HsBase.h utime"
437    c_utime :: CString -> Ptr CUtimbuf -> IO CInt
438
439 foreign import ccall unsafe "HsBase.h waitpid"
440    c_waitpid :: CPid -> Ptr CInt -> CInt -> IO CPid
441 #endif
442
443 -- traversing directories
444 foreign import ccall unsafe "dirUtils.h __hscore_readdir"
445   readdir  :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt
446  
447 foreign import ccall unsafe "HsBase.h __hscore_free_dirent"
448   freeDirEnt  :: Ptr CDirent -> IO ()
449  
450 foreign import ccall unsafe "HsBase.h __hscore_end_of_dir"
451   end_of_dir :: CInt
452  
453 foreign import ccall unsafe "HsBase.h __hscore_d_name"
454   d_name :: Ptr CDirent -> IO CString
455
456 -- POSIX flags only:
457 foreign import ccall unsafe "HsBase.h __hscore_o_rdonly" o_RDONLY :: CInt
458 foreign import ccall unsafe "HsBase.h __hscore_o_wronly" o_WRONLY :: CInt
459 foreign import ccall unsafe "HsBase.h __hscore_o_rdwr"   o_RDWR   :: CInt
460 foreign import ccall unsafe "HsBase.h __hscore_o_append" o_APPEND :: CInt
461 foreign import ccall unsafe "HsBase.h __hscore_o_creat"  o_CREAT  :: CInt
462 foreign import ccall unsafe "HsBase.h __hscore_o_excl"   o_EXCL   :: CInt
463 foreign import ccall unsafe "HsBase.h __hscore_o_trunc"  o_TRUNC  :: CInt
464
465 -- non-POSIX flags.
466 foreign import ccall unsafe "HsBase.h __hscore_o_noctty"   o_NOCTTY   :: CInt
467 foreign import ccall unsafe "HsBase.h __hscore_o_nonblock" o_NONBLOCK :: CInt
468 foreign import ccall unsafe "HsBase.h __hscore_o_binary"   o_BINARY   :: CInt
469
470 foreign import ccall unsafe "HsBase.h __hscore_s_isreg"  c_s_isreg  :: CMode -> CInt
471 foreign import ccall unsafe "HsBase.h __hscore_s_ischr"  c_s_ischr  :: CMode -> CInt
472 foreign import ccall unsafe "HsBase.h __hscore_s_isblk"  c_s_isblk  :: CMode -> CInt
473 foreign import ccall unsafe "HsBase.h __hscore_s_isdir"  c_s_isdir  :: CMode -> CInt
474 foreign import ccall unsafe "HsBase.h __hscore_s_isfifo" c_s_isfifo :: CMode -> CInt
475
476 s_isreg  :: CMode -> Bool
477 s_isreg cm = c_s_isreg cm /= 0
478 s_ischr  :: CMode -> Bool
479 s_ischr cm = c_s_ischr cm /= 0
480 s_isblk  :: CMode -> Bool
481 s_isblk cm = c_s_isblk cm /= 0
482 s_isdir  :: CMode -> Bool
483 s_isdir cm = c_s_isdir cm /= 0
484 s_isfifo :: CMode -> Bool
485 s_isfifo cm = c_s_isfifo cm /= 0
486
487 foreign import ccall unsafe "HsBase.h __hscore_sizeof_stat" sizeof_stat :: Int
488 foreign import ccall unsafe "HsBase.h __hscore_st_mtime" st_mtime :: Ptr CStat -> IO CTime
489 #ifdef mingw32_HOST_OS
490 foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO Int64
491 #else
492 foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO COff
493 #endif
494 foreign import ccall unsafe "HsBase.h __hscore_st_mode" st_mode :: Ptr CStat -> IO CMode
495 foreign import ccall unsafe "HsBase.h __hscore_st_dev" st_dev :: Ptr CStat -> IO CDev
496 foreign import ccall unsafe "HsBase.h __hscore_st_ino" st_ino :: Ptr CStat -> IO CIno
497
498 foreign import ccall unsafe "HsBase.h __hscore_echo"         const_echo :: CInt
499 foreign import ccall unsafe "HsBase.h __hscore_tcsanow"      const_tcsanow :: CInt
500 foreign import ccall unsafe "HsBase.h __hscore_icanon"       const_icanon :: CInt
501 foreign import ccall unsafe "HsBase.h __hscore_vmin"         const_vmin   :: CInt
502 foreign import ccall unsafe "HsBase.h __hscore_vtime"        const_vtime  :: CInt
503 foreign import ccall unsafe "HsBase.h __hscore_sigttou"      const_sigttou :: CInt
504 foreign import ccall unsafe "HsBase.h __hscore_sig_block"    const_sig_block :: CInt
505 foreign import ccall unsafe "HsBase.h __hscore_sig_setmask"  const_sig_setmask :: CInt
506 foreign import ccall unsafe "HsBase.h __hscore_f_getfl"      const_f_getfl :: CInt
507 foreign import ccall unsafe "HsBase.h __hscore_f_setfl"      const_f_setfl :: CInt
508
509 #if defined(HTYPE_TCFLAG_T)
510 foreign import ccall unsafe "HsBase.h __hscore_sizeof_termios"  sizeof_termios :: Int
511 foreign import ccall unsafe "HsBase.h __hscore_sizeof_sigset_t" sizeof_sigset_t :: Int
512
513 foreign import ccall unsafe "HsBase.h __hscore_lflag" c_lflag :: Ptr CTermios -> IO CTcflag
514 foreign import ccall unsafe "HsBase.h __hscore_poke_lflag" poke_c_lflag :: Ptr CTermios -> CTcflag -> IO ()
515 foreign import ccall unsafe "HsBase.h __hscore_ptr_c_cc" ptr_c_cc  :: Ptr CTermios -> IO (Ptr Word8)
516 #endif
517
518 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
519 foreign import ccall unsafe "HsBase.h __hscore_s_issock" c_s_issock :: CMode -> CInt
520 s_issock :: CMode -> Bool
521 s_issock cmode = c_s_issock cmode /= 0
522 #else
523 s_issock :: CMode -> Bool
524 s_issock cmode = False
525 #endif