ff07615077707e4495140246487fc0078e99f884
[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 "config.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 #-}
48 #endif
49
50 -- ---------------------------------------------------------------------------
51 -- Types
52
53 type CDir       = ()
54 type CDirent    = ()
55 type CFLock     = ()
56 type CGroup     = ()
57 type CLconv     = ()
58 type CPasswd    = ()
59 type CSigaction = ()
60 type CSigset    = ()
61 type CStat      = ()
62 type CTermios   = ()
63 type CTm        = ()
64 type CTms       = ()
65 type CUtimbuf   = ()
66 type CUtsname   = ()
67
68 #ifndef __GLASGOW_HASKELL__
69 type FD = Int
70 #endif
71
72 -- ---------------------------------------------------------------------------
73 -- stat()-related stuff
74
75 fdFileSize :: Int -> IO Integer
76 fdFileSize fd = 
77   allocaBytes sizeof_stat $ \ p_stat -> do
78     throwErrnoIfMinus1Retry "fileSize" $
79         c_fstat (fromIntegral fd) p_stat
80     c_mode <- st_mode p_stat :: IO CMode 
81     if not (s_isreg c_mode)
82         then return (-1)
83         else do
84     c_size <- st_size p_stat :: IO COff
85     return (fromIntegral c_size)
86
87 data FDType  = Directory | Stream | RegularFile
88                deriving (Eq)
89
90 fileType :: FilePath -> IO FDType
91 fileType file =
92   allocaBytes sizeof_stat $ \ p_stat -> do
93   withCString file $ \p_file -> do
94     throwErrnoIfMinus1Retry "fileType" $
95       c_stat p_file p_stat
96     statGetType p_stat
97
98 -- NOTE: On Win32 platforms, this will only work with file descriptors
99 -- referring to file handles. i.e., it'll fail for socket FDs.
100 fdType :: Int -> IO FDType
101 fdType fd = 
102   allocaBytes sizeof_stat $ \ p_stat -> do
103     throwErrnoIfMinus1Retry "fdType" $
104         c_fstat (fromIntegral fd) p_stat
105     statGetType p_stat
106
107 statGetType p_stat = do
108   c_mode <- st_mode p_stat :: IO CMode
109   case () of
110       _ | s_isdir c_mode        -> return Directory
111         | s_isfifo c_mode || s_issock c_mode || s_ischr  c_mode
112                                 -> return Stream
113         | s_isreg c_mode        -> return RegularFile
114         | otherwise             -> ioError ioe_unknownfiletype
115     
116
117 ioe_unknownfiletype = IOError Nothing UnsupportedOperation "fdType"
118                         "unknown file type" Nothing
119
120 -- It isn't clear whether ftruncate is POSIX or not (I've read several
121 -- manpages and they seem to conflict), so we truncate using open/2.
122 fileTruncate :: FilePath -> IO ()
123 fileTruncate file = do
124   let flags = o_WRONLY .|. o_TRUNC
125   withCString file $ \file_cstr -> do
126     fd <- fromIntegral `liftM`
127             throwErrnoIfMinus1Retry "fileTruncate"
128                 (c_open file_cstr (fromIntegral flags) 0o666)
129     c_close fd
130   return ()
131
132 #ifdef mingw32_TARGET_OS
133 closeFd :: Bool -> CInt -> IO CInt
134 closeFd isStream fd 
135   | isStream  = c_closesocket fd
136   | otherwise = c_close fd
137
138 foreign import stdcall unsafe "HsBase.h closesocket"
139    c_closesocket :: CInt -> IO CInt
140 #endif
141
142 fdGetMode :: Int -> IO IOMode
143 fdGetMode fd = do
144 #ifdef mingw32_TARGET_OS
145     flags1 <- throwErrnoIfMinus1Retry "fdGetMode" 
146                 (c__setmode (fromIntegral fd) (fromIntegral o_WRONLY))
147     flags  <- throwErrnoIfMinus1Retry "fdGetMode" 
148                 (c__setmode (fromIntegral fd) (fromIntegral flags1))
149 #else
150     flags <- throwErrnoIfMinus1Retry "fdGetMode" 
151                 (c_fcntl_read (fromIntegral fd) const_f_getfl)
152 #endif
153     let
154        wH  = (flags .&. o_WRONLY) /= 0
155        aH  = (flags .&. o_APPEND) /= 0
156        rwH = (flags .&. o_RDWR) /= 0
157
158        mode
159          | wH && aH  = AppendMode
160          | wH        = WriteMode
161          | rwH       = ReadWriteMode
162          | otherwise = ReadMode
163           
164     return mode
165
166 -- ---------------------------------------------------------------------------
167 -- Terminal-related stuff
168
169 fdIsTTY :: Int -> IO Bool
170 fdIsTTY fd = c_isatty (fromIntegral fd) >>= return.toBool
171
172 #ifndef mingw32_TARGET_OS
173
174 setEcho :: Int -> Bool -> IO ()
175 setEcho fd on = do
176   tcSetAttr fd $ \ p_tios -> do
177     c_lflag <- c_lflag p_tios :: IO CTcflag
178     let new_c_lflag
179          | on        = c_lflag .|. fromIntegral const_echo
180          | otherwise = c_lflag .&. complement (fromIntegral const_echo)
181     poke_c_lflag p_tios (new_c_lflag :: CTcflag)
182
183 getEcho :: Int -> IO Bool
184 getEcho fd = do
185   tcSetAttr fd $ \ p_tios -> do
186     c_lflag <- c_lflag p_tios :: IO CTcflag
187     return ((c_lflag .&. fromIntegral const_echo) /= 0)
188
189 setCooked :: Int -> Bool -> IO ()
190 setCooked fd cooked = 
191   tcSetAttr fd $ \ p_tios -> do
192
193     -- turn on/off ICANON
194     c_lflag <- c_lflag p_tios :: IO CTcflag
195     let new_c_lflag | cooked    = c_lflag .|. (fromIntegral const_icanon)
196                     | otherwise = c_lflag .&. complement (fromIntegral const_icanon)
197     poke_c_lflag p_tios (new_c_lflag :: CTcflag)
198
199     -- set VMIN & VTIME to 1/0 respectively
200     when (not cooked) $ do
201             c_cc <- ptr_c_cc p_tios
202             let vmin  = (c_cc `plusPtr` (fromIntegral const_vmin))  :: Ptr Word8
203                 vtime = (c_cc `plusPtr` (fromIntegral const_vtime)) :: Ptr Word8
204             poke vmin  1
205             poke vtime 0
206
207 tcSetAttr :: FD -> (Ptr CTermios -> IO a) -> IO a
208 tcSetAttr fd fun = do
209      allocaBytes sizeof_termios  $ \p_tios -> do
210         throwErrnoIfMinus1Retry "tcSetAttr"
211            (c_tcgetattr (fromIntegral fd) p_tios)
212
213         -- Save a copy of termios, if this is a standard file descriptor.
214         -- These terminal settings are restored in hs_exit().
215         when (fd <= 2) $ do
216           p <- peekElemOff saved_termios fd
217           when (p == nullPtr) $ do
218              saved_tios <- mallocBytes sizeof_termios
219              copyBytes saved_tios p_tios sizeof_termios
220              pokeElemOff saved_termios fd saved_tios
221
222         -- tcsetattr() when invoked by a background process causes the process
223         -- to be sent SIGTTOU regardless of whether the process has TOSTOP set
224         -- in its terminal flags (try it...).  This function provides a
225         -- wrapper which temporarily blocks SIGTTOU around the call, making it
226         -- transparent.
227         allocaBytes sizeof_sigset_t $ \ p_sigset -> do
228         allocaBytes sizeof_sigset_t $ \ p_old_sigset -> do
229              c_sigemptyset p_sigset
230              c_sigaddset   p_sigset const_sigttou
231              c_sigprocmask const_sig_block p_sigset p_old_sigset
232              r <- fun p_tios  -- do the business
233              throwErrnoIfMinus1Retry_ "tcSetAttr" $
234                  c_tcsetattr (fromIntegral fd) const_tcsanow p_tios
235              c_sigprocmask const_sig_setmask p_old_sigset nullPtr
236              return r
237
238 foreign import ccall "&saved_termios" saved_termios :: Ptr (Ptr CTermios)
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 ioException (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 ioException (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 ioException (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 #ifndef mingw32_TARGET_OS
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   c_fcntl_write (fromIntegral fd) const_f_setfl (flags .|. o_NONBLOCK)
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 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 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 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 "HsBase.h readdir" 
361    c_readdir :: Ptr CDir -> IO (Ptr CDirent)
362
363 foreign import ccall unsafe "dirUtils.h __hscore_renameFile"
364    c_rename :: CString -> CString -> IO CInt
365                      
366 foreign import ccall unsafe "HsBase.h rewinddir"
367    c_rewinddir :: Ptr CDir -> IO ()
368
369 foreign import ccall unsafe "HsBase.h rmdir"
370    c_rmdir :: CString -> IO CInt
371
372 foreign import ccall unsafe "HsBase.h stat"
373    c_stat :: CString -> Ptr CStat -> IO CInt
374
375 foreign import ccall unsafe "HsBase.h umask"
376    c_umask :: CMode -> IO CMode
377
378 foreign import ccall unsafe "HsBase.h write" 
379    c_write :: CInt -> Ptr CChar -> CSize -> IO CSsize
380
381 foreign import ccall unsafe "HsBase.h unlink"
382    c_unlink :: CString -> IO CInt
383
384 #ifndef mingw32_TARGET_OS
385 foreign import ccall unsafe "HsBase.h fcntl"
386    c_fcntl_read  :: CInt -> CInt -> IO CInt
387
388 foreign import ccall unsafe "HsBase.h fcntl"
389    c_fcntl_write :: CInt -> CInt -> CInt -> IO CInt
390
391 foreign import ccall unsafe "HsBase.h fcntl"
392    c_fcntl_lock  :: CInt -> CInt -> Ptr CFLock -> IO CInt
393
394 foreign import ccall unsafe "HsBase.h fork"
395    c_fork :: IO CPid 
396
397 foreign import ccall unsafe "HsBase.h getpid"
398    c_getpid :: 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 #ifndef mingw32_TARGET_OS
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 #ifndef mingw32_TARGET_OS
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