[project @ 2005-01-13 11:15:17 by ross]
[ghc-base.git] / System / Posix / Internals.hs
1 {-# OPTIONS_GHC -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 #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 #ifdef __GLASGOW_HASKELL__
37 import GHC.Base
38 import GHC.Num
39 import GHC.Real
40 import GHC.IOBase
41 #else
42 import System.IO
43 #endif
44
45 #ifdef __HUGS__
46 import Hugs.Prelude (IOException(..), IOErrorType(..))
47
48 {-# CFILES cbits/PrelIOUtils.c cbits/dirUtils.c cbits/consUtils.c #-}
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 #if defined(mingw32_TARGET_OS) || defined(__MINGW32__)
122 closeFd :: Bool -> CInt -> IO CInt
123 closeFd isStream fd 
124   | isStream  = c_closesocket fd
125   | otherwise = c_close fd
126
127 foreign import stdcall unsafe "HsBase.h closesocket"
128    c_closesocket :: CInt -> IO CInt
129 #endif
130
131 fdGetMode :: Int -> IO IOMode
132 fdGetMode fd = do
133 #if defined(mingw32_TARGET_OS) || defined(__MINGW32__)
134     -- XXX: this code is *BROKEN*, _setmode only deals with O_TEXT/O_BINARY
135     flags1 <- throwErrnoIfMinus1Retry "fdGetMode" 
136                 (c__setmode (fromIntegral fd) (fromIntegral o_WRONLY))
137     flags  <- throwErrnoIfMinus1Retry "fdGetMode" 
138                 (c__setmode (fromIntegral fd) (fromIntegral flags1))
139 #else
140     flags <- throwErrnoIfMinus1Retry "fdGetMode" 
141                 (c_fcntl_read (fromIntegral fd) const_f_getfl)
142 #endif
143     let
144        wH  = (flags .&. o_WRONLY) /= 0
145        aH  = (flags .&. o_APPEND) /= 0
146        rwH = (flags .&. o_RDWR) /= 0
147
148        mode
149          | wH && aH  = AppendMode
150          | wH        = WriteMode
151          | rwH       = ReadWriteMode
152          | otherwise = ReadMode
153           
154     return mode
155
156 -- ---------------------------------------------------------------------------
157 -- Terminal-related stuff
158
159 fdIsTTY :: Int -> IO Bool
160 fdIsTTY fd = c_isatty (fromIntegral fd) >>= return.toBool
161
162 #if defined(HTYPE_TCFLAG_T)
163
164 setEcho :: Int -> Bool -> IO ()
165 setEcho fd on = do
166   tcSetAttr fd $ \ p_tios -> do
167     c_lflag <- c_lflag p_tios :: IO CTcflag
168     let new_c_lflag
169          | on        = c_lflag .|. fromIntegral const_echo
170          | otherwise = c_lflag .&. complement (fromIntegral const_echo)
171     poke_c_lflag p_tios (new_c_lflag :: CTcflag)
172
173 getEcho :: Int -> IO Bool
174 getEcho fd = do
175   tcSetAttr fd $ \ p_tios -> do
176     c_lflag <- c_lflag p_tios :: IO CTcflag
177     return ((c_lflag .&. fromIntegral const_echo) /= 0)
178
179 setCooked :: Int -> Bool -> IO ()
180 setCooked fd cooked = 
181   tcSetAttr fd $ \ p_tios -> do
182
183     -- turn on/off ICANON
184     c_lflag <- c_lflag p_tios :: IO CTcflag
185     let new_c_lflag | cooked    = c_lflag .|. (fromIntegral const_icanon)
186                     | otherwise = c_lflag .&. complement (fromIntegral const_icanon)
187     poke_c_lflag p_tios (new_c_lflag :: CTcflag)
188
189     -- set VMIN & VTIME to 1/0 respectively
190     when (not cooked) $ do
191             c_cc <- ptr_c_cc p_tios
192             let vmin  = (c_cc `plusPtr` (fromIntegral const_vmin))  :: Ptr Word8
193                 vtime = (c_cc `plusPtr` (fromIntegral const_vtime)) :: Ptr Word8
194             poke vmin  1
195             poke vtime 0
196
197 tcSetAttr :: FD -> (Ptr CTermios -> IO a) -> IO a
198 tcSetAttr fd fun = do
199      allocaBytes sizeof_termios  $ \p_tios -> do
200         throwErrnoIfMinus1Retry "tcSetAttr"
201            (c_tcgetattr (fromIntegral fd) p_tios)
202
203 #ifdef __GLASGOW_HASKELL__
204         -- Save a copy of termios, if this is a standard file descriptor.
205         -- These terminal settings are restored in hs_exit().
206         when (fd <= 2) $ do
207           p <- get_saved_termios fd
208           when (p == nullPtr) $ do
209              saved_tios <- mallocBytes sizeof_termios
210              copyBytes saved_tios p_tios sizeof_termios
211              set_saved_termios fd saved_tios
212 #endif
213
214         -- tcsetattr() when invoked by a background process causes the process
215         -- to be sent SIGTTOU regardless of whether the process has TOSTOP set
216         -- in its terminal flags (try it...).  This function provides a
217         -- wrapper which temporarily blocks SIGTTOU around the call, making it
218         -- transparent.
219         allocaBytes sizeof_sigset_t $ \ p_sigset -> do
220         allocaBytes sizeof_sigset_t $ \ p_old_sigset -> do
221              c_sigemptyset p_sigset
222              c_sigaddset   p_sigset const_sigttou
223              c_sigprocmask const_sig_block p_sigset p_old_sigset
224              r <- fun p_tios  -- do the business
225              throwErrnoIfMinus1Retry_ "tcSetAttr" $
226                  c_tcsetattr (fromIntegral fd) const_tcsanow p_tios
227              c_sigprocmask const_sig_setmask p_old_sigset nullPtr
228              return r
229
230 #ifdef __GLASGOW_HASKELL__
231 foreign import ccall unsafe "HsBase.h __hscore_get_saved_termios"
232    get_saved_termios :: Int -> IO (Ptr CTermios)
233
234 foreign import ccall unsafe "HsBase.h __hscore_set_saved_termios"
235    set_saved_termios :: Int -> (Ptr CTermios) -> IO ()
236 #endif
237
238 #else
239
240 -- 'raw' mode for Win32 means turn off 'line input' (=> buffering and
241 -- character translation for the console.) The Win32 API for doing
242 -- this is GetConsoleMode(), which also requires echoing to be disabled
243 -- when turning off 'line input' processing. Notice that turning off
244 -- 'line input' implies enter/return is reported as '\r' (and it won't
245 -- report that character until another character is input..odd.) This
246 -- latter feature doesn't sit too well with IO actions like IO.hGetLine..
247 -- consider yourself warned.
248 setCooked :: Int -> Bool -> IO ()
249 setCooked fd cooked = do
250   x <- set_console_buffering (fromIntegral fd) (if cooked then 1 else 0)
251   if (x /= 0)
252    then ioError (ioe_unk_error "setCooked" "failed to set buffering")
253    else return ()
254
255 ioe_unk_error loc msg 
256  = IOError Nothing OtherError loc msg Nothing
257
258 -- Note: echoing goes hand in hand with enabling 'line input' / raw-ness
259 -- for Win32 consoles, hence setEcho ends up being the inverse of setCooked.
260 setEcho :: Int -> Bool -> IO ()
261 setEcho fd on = do
262   x <- set_console_echo (fromIntegral fd) (if on then 1 else 0)
263   if (x /= 0)
264    then ioError (ioe_unk_error "setEcho" "failed to set echoing")
265    else return ()
266
267 getEcho :: Int -> IO Bool
268 getEcho fd = do
269   r <- get_console_echo (fromIntegral fd)
270   if (r == (-1))
271    then ioError (ioe_unk_error "getEcho" "failed to get echoing")
272    else return (r == 1)
273
274 foreign import ccall unsafe "consUtils.h set_console_buffering__"
275    set_console_buffering :: CInt -> CInt -> IO CInt
276
277 foreign import ccall unsafe "consUtils.h set_console_echo__"
278    set_console_echo :: CInt -> CInt -> IO CInt
279
280 foreign import ccall unsafe "consUtils.h get_console_echo__"
281    get_console_echo :: CInt -> IO CInt
282
283 #endif
284
285 -- ---------------------------------------------------------------------------
286 -- Turning on non-blocking for a file descriptor
287
288 #if !defined(mingw32_TARGET_OS) && !defined(__MINGW32__)
289
290 setNonBlockingFD fd = do
291   flags <- throwErrnoIfMinus1Retry "setNonBlockingFD"
292                  (c_fcntl_read (fromIntegral fd) const_f_getfl)
293   -- An error when setting O_NONBLOCK isn't fatal: on some systems 
294   -- there are certain file handles on which this will fail (eg. /dev/null
295   -- on FreeBSD) so we throw away the return code from fcntl_write.
296   unless (testBit flags (fromIntegral o_NONBLOCK)) $ do
297     c_fcntl_write (fromIntegral fd) const_f_setfl (flags .|. o_NONBLOCK)
298     return ()
299 #else
300
301 -- bogus defns for win32
302 setNonBlockingFD fd = return ()
303
304 #endif
305
306 -- -----------------------------------------------------------------------------
307 -- foreign imports
308
309 foreign import ccall unsafe "HsBase.h access"
310    c_access :: CString -> CMode -> IO CInt
311
312 foreign import ccall unsafe "HsBase.h chmod"
313    c_chmod :: CString -> CMode -> IO CInt
314
315 foreign import ccall unsafe "HsBase.h chdir"
316    c_chdir :: CString -> IO CInt
317
318 foreign import ccall unsafe "HsBase.h close"
319    c_close :: CInt -> IO CInt
320
321 foreign import ccall unsafe "HsBase.h closedir" 
322    c_closedir :: Ptr CDir -> IO CInt
323
324 foreign import ccall unsafe "HsBase.h creat"
325    c_creat :: CString -> CMode -> IO CInt
326
327 foreign import ccall unsafe "HsBase.h dup"
328    c_dup :: CInt -> IO CInt
329
330 foreign import ccall unsafe "HsBase.h dup2"
331    c_dup2 :: CInt -> CInt -> IO CInt
332
333 foreign import ccall unsafe "HsBase.h __hscore_fstat"
334    c_fstat :: CInt -> Ptr CStat -> IO CInt
335
336 foreign import ccall unsafe "HsBase.h getcwd"
337    c_getcwd   :: Ptr CChar -> CInt -> IO (Ptr CChar)
338
339 foreign import ccall unsafe "HsBase.h isatty"
340    c_isatty :: CInt -> IO CInt
341
342 foreign import ccall unsafe "HsBase.h __hscore_lseek"
343    c_lseek :: CInt -> COff -> CInt -> IO COff
344
345 foreign import ccall unsafe "HsBase.h __hscore_lstat"
346    lstat :: CString -> Ptr CStat -> IO CInt
347
348 foreign import ccall unsafe "HsBase.h __hscore_open"
349    c_open :: CString -> CInt -> CMode -> IO CInt
350
351 foreign import ccall unsafe "HsBase.h opendir" 
352    c_opendir :: CString  -> IO (Ptr CDir)
353
354 foreign import ccall unsafe "HsBase.h __hscore_mkdir"
355    mkdir :: CString -> CInt -> IO CInt
356
357 foreign import ccall unsafe "HsBase.h read" 
358    c_read :: CInt -> Ptr CChar -> CSize -> IO CSsize
359
360 foreign import ccall unsafe "dirUtils.h __hscore_renameFile"
361    c_rename :: CString -> CString -> IO CInt
362                      
363 foreign import ccall unsafe "HsBase.h rewinddir"
364    c_rewinddir :: Ptr CDir -> IO ()
365
366 foreign import ccall unsafe "HsBase.h rmdir"
367    c_rmdir :: CString -> IO CInt
368
369 foreign import ccall unsafe "HsBase.h __hscore_stat"
370    c_stat :: CString -> Ptr CStat -> IO CInt
371
372 foreign import ccall unsafe "HsBase.h umask"
373    c_umask :: CMode -> IO CMode
374
375 foreign import ccall unsafe "HsBase.h write" 
376    c_write :: CInt -> Ptr CChar -> CSize -> IO CSsize
377
378 foreign import ccall unsafe "HsBase.h __hscore_ftruncate"
379    c_ftruncate :: CInt -> COff -> IO CInt
380
381 foreign import ccall unsafe "HsBase.h unlink"
382    c_unlink :: CString -> IO CInt
383
384 foreign import ccall unsafe "HsBase.h getpid"
385    c_getpid :: IO CPid
386
387 #if !defined(mingw32_TARGET_OS) && !defined(__MINGW32__)
388 foreign import ccall unsafe "HsBase.h fcntl"
389    c_fcntl_read  :: CInt -> CInt -> IO CInt
390
391 foreign import ccall unsafe "HsBase.h fcntl"
392    c_fcntl_write :: CInt -> CInt -> CInt -> IO CInt
393
394 foreign import ccall unsafe "HsBase.h fcntl"
395    c_fcntl_lock  :: CInt -> CInt -> Ptr CFLock -> IO CInt
396
397 foreign import ccall unsafe "HsBase.h fork"
398    c_fork :: IO CPid 
399
400 foreign import ccall unsafe "HsBase.h link"
401    c_link :: CString -> CString -> IO CInt
402
403 foreign import ccall unsafe "HsBase.h mkfifo"
404    c_mkfifo :: CString -> CMode -> IO CInt
405
406 foreign import ccall unsafe "HsBase.h pipe"
407    c_pipe :: Ptr CInt -> IO CInt
408
409 foreign import ccall unsafe "HsBase.h __hscore_sigemptyset"
410    c_sigemptyset :: Ptr CSigset -> IO CInt
411
412 foreign import ccall unsafe "HsBase.h __hscore_sigaddset"
413    c_sigaddset :: Ptr CSigset -> CInt -> IO CInt
414
415 foreign import ccall unsafe "HsBase.h sigprocmask"
416    c_sigprocmask :: CInt -> Ptr CSigset -> Ptr CSigset -> IO CInt
417
418 foreign import ccall unsafe "HsBase.h tcgetattr"
419    c_tcgetattr :: CInt -> Ptr CTermios -> IO CInt
420
421 foreign import ccall unsafe "HsBase.h tcsetattr"
422    c_tcsetattr :: CInt -> CInt -> Ptr CTermios -> IO CInt
423
424 foreign import ccall unsafe "HsBase.h utime"
425    c_utime :: CString -> Ptr CUtimbuf -> IO CMode
426
427 foreign import ccall unsafe "HsBase.h waitpid"
428    c_waitpid :: CPid -> Ptr CInt -> CInt -> IO CPid
429 #else
430 foreign import ccall unsafe "HsBase.h _setmode"
431    c__setmode :: CInt -> CInt -> IO CInt
432
433 --   /* Set "stdin" to have binary mode: */
434 --   result = _setmode( _fileno( stdin ), _O_BINARY );
435 --   if( result == -1 )
436 --      perror( "Cannot set mode" );
437 --   else
438 --      printf( "'stdin' successfully changed to binary mode\n" );
439 #endif
440
441 -- traversing directories
442 foreign import ccall unsafe "dirUtils.h __hscore_readdir"
443   readdir  :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt
444  
445 foreign import ccall unsafe "HsBase.h __hscore_free_dirent"
446   freeDirEnt  :: Ptr CDirent -> IO ()
447  
448 foreign import ccall unsafe "HsBase.h __hscore_end_of_dir"
449   end_of_dir :: CInt
450  
451 foreign import ccall unsafe "HsBase.h __hscore_d_name"
452   d_name :: Ptr CDirent -> IO CString
453
454 -- POSIX flags only:
455 foreign import ccall unsafe "HsBase.h __hscore_o_rdonly" o_RDONLY :: CInt
456 foreign import ccall unsafe "HsBase.h __hscore_o_wronly" o_WRONLY :: CInt
457 foreign import ccall unsafe "HsBase.h __hscore_o_rdwr"   o_RDWR   :: CInt
458 foreign import ccall unsafe "HsBase.h __hscore_o_append" o_APPEND :: CInt
459 foreign import ccall unsafe "HsBase.h __hscore_o_creat"  o_CREAT  :: CInt
460 foreign import ccall unsafe "HsBase.h __hscore_o_excl"   o_EXCL   :: CInt
461 foreign import ccall unsafe "HsBase.h __hscore_o_trunc"  o_TRUNC  :: CInt
462
463 -- non-POSIX flags.
464 foreign import ccall unsafe "HsBase.h __hscore_o_noctty"   o_NOCTTY   :: CInt
465 foreign import ccall unsafe "HsBase.h __hscore_o_nonblock" o_NONBLOCK :: CInt
466 foreign import ccall unsafe "HsBase.h __hscore_o_binary"   o_BINARY   :: CInt
467
468 foreign import ccall unsafe "HsBase.h __hscore_s_isreg"  s_isreg  :: CMode -> Bool
469 foreign import ccall unsafe "HsBase.h __hscore_s_ischr"  s_ischr  :: CMode -> Bool
470 foreign import ccall unsafe "HsBase.h __hscore_s_isblk"  s_isblk  :: CMode -> Bool
471 foreign import ccall unsafe "HsBase.h __hscore_s_isdir"  s_isdir  :: CMode -> Bool
472 foreign import ccall unsafe "HsBase.h __hscore_s_isfifo" s_isfifo :: CMode -> Bool
473
474 foreign import ccall unsafe "HsBase.h __hscore_sizeof_stat" sizeof_stat :: Int
475 foreign import ccall unsafe "HsBase.h __hscore_st_mtime" st_mtime :: Ptr CStat -> IO CTime
476 foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO COff
477 foreign import ccall unsafe "HsBase.h __hscore_st_mode" st_mode :: Ptr CStat -> IO CMode
478
479 foreign import ccall unsafe "HsBase.h __hscore_echo"         const_echo :: CInt
480 foreign import ccall unsafe "HsBase.h __hscore_tcsanow"      const_tcsanow :: CInt
481 foreign import ccall unsafe "HsBase.h __hscore_icanon"       const_icanon :: CInt
482 foreign import ccall unsafe "HsBase.h __hscore_vmin"         const_vmin   :: CInt
483 foreign import ccall unsafe "HsBase.h __hscore_vtime"        const_vtime  :: CInt
484 foreign import ccall unsafe "HsBase.h __hscore_sigttou"      const_sigttou :: CInt
485 foreign import ccall unsafe "HsBase.h __hscore_sig_block"    const_sig_block :: CInt
486 foreign import ccall unsafe "HsBase.h __hscore_sig_setmask"  const_sig_setmask :: CInt
487 foreign import ccall unsafe "HsBase.h __hscore_f_getfl"      const_f_getfl :: CInt
488 foreign import ccall unsafe "HsBase.h __hscore_f_setfl"      const_f_setfl :: CInt
489
490 #if defined(HTYPE_TCFLAG_T)
491 foreign import ccall unsafe "HsBase.h __hscore_sizeof_termios"  sizeof_termios :: Int
492 foreign import ccall unsafe "HsBase.h __hscore_sizeof_sigset_t" sizeof_sigset_t :: Int
493
494 foreign import ccall unsafe "HsBase.h __hscore_lflag" c_lflag :: Ptr CTermios -> IO CTcflag
495 foreign import ccall unsafe "HsBase.h __hscore_poke_lflag" poke_c_lflag :: Ptr CTermios -> CTcflag -> IO ()
496 foreign import ccall unsafe "HsBase.h __hscore_ptr_c_cc" ptr_c_cc  :: Ptr CTermios -> IO (Ptr Word8)
497 #endif
498
499 #if !defined(mingw32_TARGET_OS) && !defined(__MINGW32__)
500 foreign import ccall unsafe "HsBase.h __hscore_s_issock" s_issock :: CMode -> Bool
501 #else
502 s_issock :: CMode -> Bool
503 s_issock cmode = False
504 #endif