[project @ 2004-08-13 13:29:00 by simonmar]
[ghc-base.git] / System / Posix / Internals.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  System.Posix.Internals
6 -- Copyright   :  (c) The University of Glasgow, 1992-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable
12 --
13 -- POSIX support layer for the standard libraries.
14 -- This library is built on *every* platform, including Win32.
15 --
16 -- Non-posix compliant in order to support the following features:
17 --      * S_ISSOCK (no sockets in POSIX)
18 --
19 -----------------------------------------------------------------------------
20
21 -- #hide
22 module System.Posix.Internals where
23
24 #include "ghcconfig.h"
25
26 import Control.Monad
27 import System.Posix.Types
28
29 import Foreign
30 import Foreign.C
31
32 import Data.Bits
33 import Data.Maybe
34
35 #ifdef __GLASGOW_HASKELL__
36 import GHC.Base
37 import GHC.Num
38 import GHC.Real
39 import GHC.IOBase
40 #else
41 import System.IO
42 #endif
43
44 #ifdef __HUGS__
45 import Hugs.Prelude (IOException(..), IOErrorType(..))
46
47 {-# CBITS PrelIOUtils.c dirUtils.c consUtils.c #-}
48 ioException = ioError
49 #endif
50
51 -- ---------------------------------------------------------------------------
52 -- Types
53
54 type CDir       = ()
55 type CDirent    = ()
56 type CFLock     = ()
57 type CGroup     = ()
58 type CLconv     = ()
59 type CPasswd    = ()
60 type CSigaction = ()
61 type CSigset    = ()
62 type CStat      = ()
63 type CTermios   = ()
64 type CTm        = ()
65 type CTms       = ()
66 type CUtimbuf   = ()
67 type CUtsname   = ()
68
69 #ifndef __GLASGOW_HASKELL__
70 type FD = Int
71 #endif
72
73 -- ---------------------------------------------------------------------------
74 -- stat()-related stuff
75
76 fdFileSize :: Int -> IO Integer
77 fdFileSize fd = 
78   allocaBytes sizeof_stat $ \ p_stat -> do
79     throwErrnoIfMinus1Retry "fileSize" $
80         c_fstat (fromIntegral fd) p_stat
81     c_mode <- st_mode p_stat :: IO CMode 
82     if not (s_isreg c_mode)
83         then return (-1)
84         else do
85     c_size <- st_size p_stat :: IO COff
86     return (fromIntegral c_size)
87
88 data FDType  = Directory | Stream | RegularFile
89                deriving (Eq)
90
91 fileType :: FilePath -> IO FDType
92 fileType file =
93   allocaBytes sizeof_stat $ \ p_stat -> do
94   withCString file $ \p_file -> do
95     throwErrnoIfMinus1Retry "fileType" $
96       c_stat p_file p_stat
97     statGetType p_stat
98
99 -- NOTE: On Win32 platforms, this will only work with file descriptors
100 -- referring to file handles. i.e., it'll fail for socket FDs.
101 fdType :: Int -> IO FDType
102 fdType fd = 
103   allocaBytes sizeof_stat $ \ p_stat -> do
104     throwErrnoIfMinus1Retry "fdType" $
105         c_fstat (fromIntegral fd) p_stat
106     statGetType p_stat
107
108 statGetType p_stat = do
109   c_mode <- st_mode p_stat :: IO CMode
110   case () of
111       _ | s_isdir c_mode        -> return Directory
112         | s_isfifo c_mode || s_issock c_mode || s_ischr  c_mode
113                                 -> return Stream
114         | s_isreg c_mode        -> return RegularFile
115         | otherwise             -> ioError ioe_unknownfiletype
116     
117
118 ioe_unknownfiletype = IOError Nothing UnsupportedOperation "fdType"
119                         "unknown file type" Nothing
120
121 -- It isn't clear whether ftruncate is POSIX or not (I've read several
122 -- manpages and they seem to conflict), so we truncate using open/2.
123 fileTruncate :: FilePath -> IO ()
124 fileTruncate file = do
125   let flags = o_WRONLY .|. o_TRUNC
126   withCString file $ \file_cstr -> do
127     fd <- fromIntegral `liftM`
128             throwErrnoIfMinus1Retry "fileTruncate"
129                 (c_open file_cstr (fromIntegral flags) 0o666)
130     c_close fd
131   return ()
132
133 #if defined(mingw32_TARGET_OS) || defined(__MINGW32__)
134 closeFd :: Bool -> CInt -> IO CInt
135 closeFd isStream fd 
136   | isStream  = c_closesocket fd
137   | otherwise = c_close fd
138
139 foreign import stdcall unsafe "HsBase.h closesocket"
140    c_closesocket :: CInt -> IO CInt
141 #endif
142
143 fdGetMode :: Int -> IO IOMode
144 fdGetMode fd = do
145 #if defined(mingw32_TARGET_OS) || defined(__MINGW32__)
146     -- XXX: this code is *BROKEN*, _setmode only deals with O_TEXT/O_BINARY
147     flags1 <- throwErrnoIfMinus1Retry "fdGetMode" 
148                 (c__setmode (fromIntegral fd) (fromIntegral o_WRONLY))
149     flags  <- throwErrnoIfMinus1Retry "fdGetMode" 
150                 (c__setmode (fromIntegral fd) (fromIntegral flags1))
151 #else
152     flags <- throwErrnoIfMinus1Retry "fdGetMode" 
153                 (c_fcntl_read (fromIntegral 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 :: Int -> IO Bool
172 fdIsTTY fd = c_isatty (fromIntegral fd) >>= return.toBool
173
174 #if defined(HTYPE_TCFLAG_T)
175
176 setEcho :: Int -> Bool -> IO ()
177 setEcho fd on = do
178   tcSetAttr fd $ \ p_tios -> do
179     c_lflag <- c_lflag p_tios :: IO CTcflag
180     let new_c_lflag
181          | on        = c_lflag .|. fromIntegral const_echo
182          | otherwise = c_lflag .&. complement (fromIntegral const_echo)
183     poke_c_lflag p_tios (new_c_lflag :: CTcflag)
184
185 getEcho :: Int -> IO Bool
186 getEcho fd = do
187   tcSetAttr fd $ \ p_tios -> do
188     c_lflag <- c_lflag p_tios :: IO CTcflag
189     return ((c_lflag .&. fromIntegral const_echo) /= 0)
190
191 setCooked :: Int -> Bool -> IO ()
192 setCooked fd cooked = 
193   tcSetAttr fd $ \ p_tios -> do
194
195     -- turn on/off ICANON
196     c_lflag <- c_lflag p_tios :: IO CTcflag
197     let new_c_lflag | cooked    = c_lflag .|. (fromIntegral const_icanon)
198                     | otherwise = c_lflag .&. complement (fromIntegral const_icanon)
199     poke_c_lflag p_tios (new_c_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 (fromIntegral 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 (fromIntegral 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 :: Int -> IO (Ptr CTermios)
245
246 foreign import ccall unsafe "HsBase.h __hscore_set_saved_termios"
247    set_saved_termios :: Int -> (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 :: Int -> Bool -> IO ()
261 setCooked fd cooked = do
262   x <- set_console_buffering (fromIntegral fd) (if cooked then 1 else 0)
263   if (x /= 0)
264    then ioException (ioe_unk_error "setCooked" "failed to set buffering")
265    else return ()
266
267 ioe_unk_error loc msg 
268  = IOError Nothing OtherError loc msg Nothing
269
270 -- Note: echoing goes hand in hand with enabling 'line input' / raw-ness
271 -- for Win32 consoles, hence setEcho ends up being the inverse of setCooked.
272 setEcho :: Int -> Bool -> IO ()
273 setEcho fd on = do
274   x <- set_console_echo (fromIntegral fd) (if on then 1 else 0)
275   if (x /= 0)
276    then ioException (ioe_unk_error "setEcho" "failed to set echoing")
277    else return ()
278
279 getEcho :: Int -> IO Bool
280 getEcho fd = do
281   r <- get_console_echo (fromIntegral fd)
282   if (r == (-1))
283    then ioException (ioe_unk_error "getEcho" "failed to get echoing")
284    else return (r == 1)
285
286 foreign import ccall unsafe "consUtils.h set_console_buffering__"
287    set_console_buffering :: CInt -> CInt -> IO CInt
288
289 foreign import ccall unsafe "consUtils.h set_console_echo__"
290    set_console_echo :: CInt -> CInt -> IO CInt
291
292 foreign import ccall unsafe "consUtils.h get_console_echo__"
293    get_console_echo :: CInt -> IO CInt
294
295 #endif
296
297 -- ---------------------------------------------------------------------------
298 -- Turning on non-blocking for a file descriptor
299
300 #if !defined(mingw32_TARGET_OS) && !defined(__MINGW32__)
301
302 setNonBlockingFD fd = do
303   flags <- throwErrnoIfMinus1Retry "setNonBlockingFD"
304                  (c_fcntl_read (fromIntegral fd) const_f_getfl)
305   -- An error when setting O_NONBLOCK isn't fatal: on some systems 
306   -- there are certain file handles on which this will fail (eg. /dev/null
307   -- on FreeBSD) so we throw away the return code from fcntl_write.
308   unless (testBit flags (fromIntegral o_NONBLOCK)) $ do
309     c_fcntl_write (fromIntegral fd) const_f_setfl (flags .|. o_NONBLOCK)
310     return ()
311 #else
312
313 -- bogus defns for win32
314 setNonBlockingFD fd = return ()
315
316 #endif
317
318 -- -----------------------------------------------------------------------------
319 -- foreign imports
320
321 foreign import ccall unsafe "HsBase.h access"
322    c_access :: CString -> CMode -> IO CInt
323
324 foreign import ccall unsafe "HsBase.h chmod"
325    c_chmod :: CString -> CMode -> IO CInt
326
327 foreign import ccall unsafe "HsBase.h chdir"
328    c_chdir :: CString -> IO CInt
329
330 foreign import ccall unsafe "HsBase.h close"
331    c_close :: CInt -> IO CInt
332
333 foreign import ccall unsafe "HsBase.h closedir" 
334    c_closedir :: Ptr CDir -> IO CInt
335
336 foreign import ccall unsafe "HsBase.h creat"
337    c_creat :: CString -> CMode -> IO CInt
338
339 foreign import ccall unsafe "HsBase.h dup"
340    c_dup :: CInt -> IO CInt
341
342 foreign import ccall unsafe "HsBase.h dup2"
343    c_dup2 :: CInt -> CInt -> IO CInt
344
345 foreign import ccall unsafe "HsBase.h __hscore_fstat"
346    c_fstat :: CInt -> Ptr CStat -> IO CInt
347
348 foreign import ccall unsafe "HsBase.h getcwd"
349    c_getcwd   :: Ptr CChar -> CInt -> IO (Ptr CChar)
350
351 foreign import ccall unsafe "HsBase.h isatty"
352    c_isatty :: CInt -> IO CInt
353
354 foreign import ccall unsafe "HsBase.h __hscore_lseek"
355    c_lseek :: CInt -> COff -> CInt -> IO COff
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 unlink"
391    c_unlink :: CString -> IO CInt
392
393 #if !defined(mingw32_TARGET_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 -> CInt -> 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 getpid"
407    c_getpid :: IO CPid
408
409 foreign import ccall unsafe "HsBase.h link"
410    c_link :: CString -> CString -> IO CInt
411
412 foreign import ccall unsafe "HsBase.h mkfifo"
413    c_mkfifo :: CString -> CMode -> IO CInt
414
415 foreign import ccall unsafe "HsBase.h pipe"
416    c_pipe :: Ptr CInt -> IO CInt
417
418 foreign import ccall unsafe "HsBase.h __hscore_sigemptyset"
419    c_sigemptyset :: Ptr CSigset -> IO CInt
420
421 foreign import ccall unsafe "HsBase.h __hscore_sigaddset"
422    c_sigaddset :: Ptr CSigset -> CInt -> IO CInt
423
424 foreign import ccall unsafe "HsBase.h sigprocmask"
425    c_sigprocmask :: CInt -> Ptr CSigset -> Ptr CSigset -> IO CInt
426
427 foreign import ccall unsafe "HsBase.h tcgetattr"
428    c_tcgetattr :: CInt -> Ptr CTermios -> IO CInt
429
430 foreign import ccall unsafe "HsBase.h tcsetattr"
431    c_tcsetattr :: CInt -> CInt -> Ptr CTermios -> IO CInt
432
433 foreign import ccall unsafe "HsBase.h utime"
434    c_utime :: CString -> Ptr CUtimbuf -> IO CMode
435
436 foreign import ccall unsafe "HsBase.h waitpid"
437    c_waitpid :: CPid -> Ptr CInt -> CInt -> IO CPid
438 #else
439 foreign import ccall unsafe "HsBase.h _setmode"
440    c__setmode :: CInt -> CInt -> IO CInt
441
442 --   /* Set "stdin" to have binary mode: */
443 --   result = _setmode( _fileno( stdin ), _O_BINARY );
444 --   if( result == -1 )
445 --      perror( "Cannot set mode" );
446 --   else
447 --      printf( "'stdin' successfully changed to binary mode\n" );
448 #endif
449
450 -- traversing directories
451 foreign import ccall unsafe "dirUtils.h __hscore_readdir"
452   readdir  :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt
453  
454 foreign import ccall unsafe "HsBase.h __hscore_free_dirent"
455   freeDirEnt  :: Ptr CDirent -> IO ()
456  
457 foreign import ccall unsafe "HsBase.h __hscore_end_of_dir"
458   end_of_dir :: CInt
459  
460 foreign import ccall unsafe "HsBase.h __hscore_d_name"
461   d_name :: Ptr CDirent -> IO CString
462
463 -- POSIX flags only:
464 foreign import ccall unsafe "HsBase.h __hscore_o_rdonly" o_RDONLY :: CInt
465 foreign import ccall unsafe "HsBase.h __hscore_o_wronly" o_WRONLY :: CInt
466 foreign import ccall unsafe "HsBase.h __hscore_o_rdwr"   o_RDWR   :: CInt
467 foreign import ccall unsafe "HsBase.h __hscore_o_append" o_APPEND :: CInt
468 foreign import ccall unsafe "HsBase.h __hscore_o_creat"  o_CREAT  :: CInt
469 foreign import ccall unsafe "HsBase.h __hscore_o_excl"   o_EXCL   :: CInt
470 foreign import ccall unsafe "HsBase.h __hscore_o_trunc"  o_TRUNC  :: CInt
471
472 -- non-POSIX flags.
473 foreign import ccall unsafe "HsBase.h __hscore_o_noctty"   o_NOCTTY   :: CInt
474 foreign import ccall unsafe "HsBase.h __hscore_o_nonblock" o_NONBLOCK :: CInt
475 foreign import ccall unsafe "HsBase.h __hscore_o_binary"   o_BINARY   :: CInt
476
477 foreign import ccall unsafe "HsBase.h __hscore_s_isreg"  s_isreg  :: CMode -> Bool
478 foreign import ccall unsafe "HsBase.h __hscore_s_ischr"  s_ischr  :: CMode -> Bool
479 foreign import ccall unsafe "HsBase.h __hscore_s_isblk"  s_isblk  :: CMode -> Bool
480 foreign import ccall unsafe "HsBase.h __hscore_s_isdir"  s_isdir  :: CMode -> Bool
481 foreign import ccall unsafe "HsBase.h __hscore_s_isfifo" s_isfifo :: CMode -> Bool
482
483 foreign import ccall unsafe "HsBase.h __hscore_sizeof_stat" sizeof_stat :: Int
484 foreign import ccall unsafe "HsBase.h __hscore_st_mtime" st_mtime :: Ptr CStat -> IO CTime
485 foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO COff
486 foreign import ccall unsafe "HsBase.h __hscore_st_mode" st_mode :: Ptr CStat -> IO CMode
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_TARGET_OS) && !defined(__MINGW32__)
509 foreign import ccall unsafe "HsBase.h __hscore_s_issock" s_issock :: CMode -> Bool
510 #else
511 s_issock :: CMode -> Bool
512 s_issock cmode = False
513 #endif