[project @ 2005-07-26 11:00:42 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 | RawDevice
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          -- Q: map char devices to RawDevice too?
116         | s_isblk c_mode        -> return RawDevice
117         | otherwise             -> ioError ioe_unknownfiletype
118     
119
120 ioe_unknownfiletype = IOError Nothing UnsupportedOperation "fdType"
121                         "unknown file type" Nothing
122
123 #if __GLASGOW_HASKELL__ && (defined(mingw32_HOST_OS) || defined(__MINGW32__))
124 closeFd :: Bool -> CInt -> IO CInt
125 closeFd isStream fd 
126   | isStream  = c_closesocket fd
127   | otherwise = c_close fd
128
129 foreign import stdcall unsafe "HsBase.h closesocket"
130    c_closesocket :: CInt -> IO CInt
131 #endif
132
133 fdGetMode :: Int -> IO IOMode
134 fdGetMode fd = do
135 #if defined(mingw32_HOST_OS) || defined(__MINGW32__)
136     -- XXX: this code is *BROKEN*, _setmode only deals with O_TEXT/O_BINARY
137     flags1 <- throwErrnoIfMinus1Retry "fdGetMode" 
138                 (c__setmode (fromIntegral fd) (fromIntegral o_WRONLY))
139     flags  <- throwErrnoIfMinus1Retry "fdGetMode" 
140                 (c__setmode (fromIntegral fd) (fromIntegral flags1))
141 #else
142     flags <- throwErrnoIfMinus1Retry "fdGetMode" 
143                 (c_fcntl_read (fromIntegral fd) const_f_getfl)
144 #endif
145     let
146        wH  = (flags .&. o_WRONLY) /= 0
147        aH  = (flags .&. o_APPEND) /= 0
148        rwH = (flags .&. o_RDWR) /= 0
149
150        mode
151          | wH && aH  = AppendMode
152          | wH        = WriteMode
153          | rwH       = ReadWriteMode
154          | otherwise = ReadMode
155           
156     return mode
157
158 -- ---------------------------------------------------------------------------
159 -- Terminal-related stuff
160
161 fdIsTTY :: Int -> IO Bool
162 fdIsTTY fd = c_isatty (fromIntegral fd) >>= return.toBool
163
164 #if defined(HTYPE_TCFLAG_T)
165
166 setEcho :: Int -> Bool -> IO ()
167 setEcho fd on = do
168   tcSetAttr fd $ \ p_tios -> do
169     c_lflag <- c_lflag p_tios :: IO CTcflag
170     let new_c_lflag
171          | on        = c_lflag .|. fromIntegral const_echo
172          | otherwise = c_lflag .&. complement (fromIntegral const_echo)
173     poke_c_lflag p_tios (new_c_lflag :: CTcflag)
174
175 getEcho :: Int -> IO Bool
176 getEcho fd = do
177   tcSetAttr fd $ \ p_tios -> do
178     c_lflag <- c_lflag p_tios :: IO CTcflag
179     return ((c_lflag .&. fromIntegral const_echo) /= 0)
180
181 setCooked :: Int -> Bool -> IO ()
182 setCooked fd cooked = 
183   tcSetAttr fd $ \ p_tios -> do
184
185     -- turn on/off ICANON
186     c_lflag <- c_lflag p_tios :: IO CTcflag
187     let new_c_lflag | cooked    = c_lflag .|. (fromIntegral const_icanon)
188                     | otherwise = c_lflag .&. complement (fromIntegral const_icanon)
189     poke_c_lflag p_tios (new_c_lflag :: CTcflag)
190
191     -- set VMIN & VTIME to 1/0 respectively
192     when (not cooked) $ do
193             c_cc <- ptr_c_cc p_tios
194             let vmin  = (c_cc `plusPtr` (fromIntegral const_vmin))  :: Ptr Word8
195                 vtime = (c_cc `plusPtr` (fromIntegral const_vtime)) :: Ptr Word8
196             poke vmin  1
197             poke vtime 0
198
199 tcSetAttr :: FD -> (Ptr CTermios -> IO a) -> IO a
200 tcSetAttr fd fun = do
201      allocaBytes sizeof_termios  $ \p_tios -> do
202         throwErrnoIfMinus1Retry "tcSetAttr"
203            (c_tcgetattr (fromIntegral fd) p_tios)
204
205 #ifdef __GLASGOW_HASKELL__
206         -- Save a copy of termios, if this is a standard file descriptor.
207         -- These terminal settings are restored in hs_exit().
208         when (fd <= 2) $ do
209           p <- get_saved_termios fd
210           when (p == nullPtr) $ do
211              saved_tios <- mallocBytes sizeof_termios
212              copyBytes saved_tios p_tios sizeof_termios
213              set_saved_termios fd saved_tios
214 #endif
215
216         -- tcsetattr() when invoked by a background process causes the process
217         -- to be sent SIGTTOU regardless of whether the process has TOSTOP set
218         -- in its terminal flags (try it...).  This function provides a
219         -- wrapper which temporarily blocks SIGTTOU around the call, making it
220         -- transparent.
221         allocaBytes sizeof_sigset_t $ \ p_sigset -> do
222         allocaBytes sizeof_sigset_t $ \ p_old_sigset -> do
223              c_sigemptyset p_sigset
224              c_sigaddset   p_sigset const_sigttou
225              c_sigprocmask const_sig_block p_sigset p_old_sigset
226              r <- fun p_tios  -- do the business
227              throwErrnoIfMinus1Retry_ "tcSetAttr" $
228                  c_tcsetattr (fromIntegral fd) const_tcsanow p_tios
229              c_sigprocmask const_sig_setmask p_old_sigset nullPtr
230              return r
231
232 #ifdef __GLASGOW_HASKELL__
233 foreign import ccall unsafe "HsBase.h __hscore_get_saved_termios"
234    get_saved_termios :: Int -> IO (Ptr CTermios)
235
236 foreign import ccall unsafe "HsBase.h __hscore_set_saved_termios"
237    set_saved_termios :: Int -> (Ptr CTermios) -> IO ()
238 #endif
239
240 #else
241
242 -- 'raw' mode for Win32 means turn off 'line input' (=> buffering and
243 -- character translation for the console.) The Win32 API for doing
244 -- this is GetConsoleMode(), which also requires echoing to be disabled
245 -- when turning off 'line input' processing. Notice that turning off
246 -- 'line input' implies enter/return is reported as '\r' (and it won't
247 -- report that character until another character is input..odd.) This
248 -- latter feature doesn't sit too well with IO actions like IO.hGetLine..
249 -- consider yourself warned.
250 setCooked :: Int -> Bool -> IO ()
251 setCooked fd cooked = do
252   x <- set_console_buffering (fromIntegral fd) (if cooked then 1 else 0)
253   if (x /= 0)
254    then ioError (ioe_unk_error "setCooked" "failed to set buffering")
255    else return ()
256
257 ioe_unk_error loc msg 
258  = IOError Nothing OtherError loc msg Nothing
259
260 -- Note: echoing goes hand in hand with enabling 'line input' / raw-ness
261 -- for Win32 consoles, hence setEcho ends up being the inverse of setCooked.
262 setEcho :: Int -> Bool -> IO ()
263 setEcho fd on = do
264   x <- set_console_echo (fromIntegral fd) (if on then 1 else 0)
265   if (x /= 0)
266    then ioError (ioe_unk_error "setEcho" "failed to set echoing")
267    else return ()
268
269 getEcho :: Int -> IO Bool
270 getEcho fd = do
271   r <- get_console_echo (fromIntegral fd)
272   if (r == (-1))
273    then ioError (ioe_unk_error "getEcho" "failed to get echoing")
274    else return (r == 1)
275
276 foreign import ccall unsafe "consUtils.h set_console_buffering__"
277    set_console_buffering :: CInt -> CInt -> IO CInt
278
279 foreign import ccall unsafe "consUtils.h set_console_echo__"
280    set_console_echo :: CInt -> CInt -> IO CInt
281
282 foreign import ccall unsafe "consUtils.h get_console_echo__"
283    get_console_echo :: CInt -> IO CInt
284
285 #endif
286
287 -- ---------------------------------------------------------------------------
288 -- Turning on non-blocking for a file descriptor
289
290 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
291
292 setNonBlockingFD fd = do
293   flags <- throwErrnoIfMinus1Retry "setNonBlockingFD"
294                  (c_fcntl_read (fromIntegral fd) const_f_getfl)
295   -- An error when setting O_NONBLOCK isn't fatal: on some systems 
296   -- there are certain file handles on which this will fail (eg. /dev/null
297   -- on FreeBSD) so we throw away the return code from fcntl_write.
298   unless (testBit flags (fromIntegral o_NONBLOCK)) $ do
299     c_fcntl_write (fromIntegral fd) const_f_setfl (flags .|. o_NONBLOCK)
300     return ()
301 #else
302
303 -- bogus defns for win32
304 setNonBlockingFD fd = return ()
305
306 #endif
307
308 -- -----------------------------------------------------------------------------
309 -- foreign imports
310
311 foreign import ccall unsafe "HsBase.h access"
312    c_access :: CString -> CMode -> IO CInt
313
314 foreign import ccall unsafe "HsBase.h chmod"
315    c_chmod :: CString -> CMode -> IO CInt
316
317 foreign import ccall unsafe "HsBase.h chdir"
318    c_chdir :: CString -> IO CInt
319
320 foreign import ccall unsafe "HsBase.h close"
321    c_close :: CInt -> IO CInt
322
323 foreign import ccall unsafe "HsBase.h closedir" 
324    c_closedir :: Ptr CDir -> IO CInt
325
326 foreign import ccall unsafe "HsBase.h creat"
327    c_creat :: CString -> CMode -> IO CInt
328
329 foreign import ccall unsafe "HsBase.h dup"
330    c_dup :: CInt -> IO CInt
331
332 foreign import ccall unsafe "HsBase.h dup2"
333    c_dup2 :: CInt -> CInt -> IO CInt
334
335 foreign import ccall unsafe "HsBase.h __hscore_fstat"
336    c_fstat :: CInt -> Ptr CStat -> IO CInt
337
338 foreign import ccall unsafe "HsBase.h getcwd"
339    c_getcwd   :: Ptr CChar -> CInt -> IO (Ptr CChar)
340
341 foreign import ccall unsafe "HsBase.h isatty"
342    c_isatty :: CInt -> IO CInt
343
344 foreign import ccall unsafe "HsBase.h __hscore_lseek"
345    c_lseek :: CInt -> COff -> CInt -> IO COff
346
347 foreign import ccall unsafe "HsBase.h __hscore_lstat"
348    lstat :: CString -> Ptr CStat -> IO CInt
349
350 foreign import ccall unsafe "HsBase.h __hscore_open"
351    c_open :: CString -> CInt -> CMode -> IO CInt
352
353 foreign import ccall unsafe "HsBase.h opendir" 
354    c_opendir :: CString  -> IO (Ptr CDir)
355
356 foreign import ccall unsafe "HsBase.h __hscore_mkdir"
357    mkdir :: CString -> CInt -> IO CInt
358
359 foreign import ccall unsafe "HsBase.h read" 
360    c_read :: CInt -> Ptr CChar -> CSize -> IO CSsize
361
362 foreign import ccall unsafe "dirUtils.h __hscore_renameFile"
363    c_rename :: CString -> CString -> IO CInt
364                      
365 foreign import ccall unsafe "HsBase.h rewinddir"
366    c_rewinddir :: Ptr CDir -> IO ()
367
368 foreign import ccall unsafe "HsBase.h rmdir"
369    c_rmdir :: CString -> IO CInt
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 -> CInt -> 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 CMode
428
429 foreign import ccall unsafe "HsBase.h waitpid"
430    c_waitpid :: CPid -> Ptr CInt -> CInt -> IO CPid
431 #else
432 foreign import ccall unsafe "HsBase.h _setmode"
433    c__setmode :: CInt -> CInt -> IO CInt
434
435 --   /* Set "stdin" to have binary mode: */
436 --   result = _setmode( _fileno( stdin ), _O_BINARY );
437 --   if( result == -1 )
438 --      perror( "Cannot set mode" );
439 --   else
440 --      printf( "'stdin' successfully changed to binary mode\n" );
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"  s_isreg  :: CMode -> Bool
471 foreign import ccall unsafe "HsBase.h __hscore_s_ischr"  s_ischr  :: CMode -> Bool
472 foreign import ccall unsafe "HsBase.h __hscore_s_isblk"  s_isblk  :: CMode -> Bool
473 foreign import ccall unsafe "HsBase.h __hscore_s_isdir"  s_isdir  :: CMode -> Bool
474 foreign import ccall unsafe "HsBase.h __hscore_s_isfifo" s_isfifo :: CMode -> Bool
475
476 foreign import ccall unsafe "HsBase.h __hscore_sizeof_stat" sizeof_stat :: Int
477 foreign import ccall unsafe "HsBase.h __hscore_st_mtime" st_mtime :: Ptr CStat -> IO CTime
478 foreign import ccall unsafe "HsBase.h __hscore_st_size" st_size :: Ptr CStat -> IO COff
479 foreign import ccall unsafe "HsBase.h __hscore_st_mode" st_mode :: Ptr CStat -> IO CMode
480
481 foreign import ccall unsafe "HsBase.h __hscore_echo"         const_echo :: CInt
482 foreign import ccall unsafe "HsBase.h __hscore_tcsanow"      const_tcsanow :: CInt
483 foreign import ccall unsafe "HsBase.h __hscore_icanon"       const_icanon :: CInt
484 foreign import ccall unsafe "HsBase.h __hscore_vmin"         const_vmin   :: CInt
485 foreign import ccall unsafe "HsBase.h __hscore_vtime"        const_vtime  :: CInt
486 foreign import ccall unsafe "HsBase.h __hscore_sigttou"      const_sigttou :: CInt
487 foreign import ccall unsafe "HsBase.h __hscore_sig_block"    const_sig_block :: CInt
488 foreign import ccall unsafe "HsBase.h __hscore_sig_setmask"  const_sig_setmask :: CInt
489 foreign import ccall unsafe "HsBase.h __hscore_f_getfl"      const_f_getfl :: CInt
490 foreign import ccall unsafe "HsBase.h __hscore_f_setfl"      const_f_setfl :: CInt
491
492 #if defined(HTYPE_TCFLAG_T)
493 foreign import ccall unsafe "HsBase.h __hscore_sizeof_termios"  sizeof_termios :: Int
494 foreign import ccall unsafe "HsBase.h __hscore_sizeof_sigset_t" sizeof_sigset_t :: Int
495
496 foreign import ccall unsafe "HsBase.h __hscore_lflag" c_lflag :: Ptr CTermios -> IO CTcflag
497 foreign import ccall unsafe "HsBase.h __hscore_poke_lflag" poke_c_lflag :: Ptr CTermios -> CTcflag -> IO ()
498 foreign import ccall unsafe "HsBase.h __hscore_ptr_c_cc" ptr_c_cc  :: Ptr CTermios -> IO (Ptr Word8)
499 #endif
500
501 #if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
502 foreign import ccall unsafe "HsBase.h __hscore_s_issock" s_issock :: CMode -> Bool
503 #else
504 s_issock :: CMode -> Bool
505 s_issock cmode = False
506 #endif