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