]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/mod.rs
664a6a1e70c767b1b3b1f17d6a4b48782642f462
[rust.git] / src / libstd / sys / unix / mod.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(missing_docs)]
12 #![allow(non_camel_case_types)]
13 #![allow(unused_imports)]
14 #![allow(dead_code)]
15 #![allow(unused_unsafe)]
16 #![allow(unused_mut)]
17
18 extern crate libc;
19
20 use num;
21 use num::{Int, SignedInt};
22 use prelude::*;
23 use io::{mod, IoResult, IoError};
24 use sys_common::mkerr_libc;
25
26 macro_rules! helper_init( (static $name:ident: Helper<$m:ty>) => (
27     static $name: Helper<$m> = Helper {
28         lock: ::rustrt::mutex::NATIVE_MUTEX_INIT,
29         chan: ::cell::UnsafeCell { value: 0 as *mut Sender<$m> },
30         signal: ::cell::UnsafeCell { value: 0 },
31         initialized: ::cell::UnsafeCell { value: false },
32     };
33 ) )
34
35 pub mod c;
36 pub mod fs;
37 pub mod os;
38 pub mod tcp;
39 pub mod udp;
40 pub mod pipe;
41 pub mod helper_signal;
42 pub mod process;
43 pub mod timer;
44 pub mod tty;
45
46 pub mod addrinfo {
47     pub use sys_common::net::get_host_addresses;
48 }
49
50 // FIXME: move these to c module
51 pub type sock_t = self::fs::fd_t;
52 pub type wrlen = libc::size_t;
53 pub type msglen_t = libc::size_t;
54 pub unsafe fn close_sock(sock: sock_t) { let _ = libc::close(sock); }
55
56 pub fn last_error() -> IoError {
57     decode_error_detailed(os::errno() as i32)
58 }
59
60 pub fn last_net_error() -> IoError {
61     last_error()
62 }
63
64 extern "system" {
65     fn gai_strerror(errcode: libc::c_int) -> *const libc::c_char;
66 }
67
68 pub fn last_gai_error(s: libc::c_int) -> IoError {
69     use c_str::CString;
70
71     let mut err = decode_error(s);
72     err.detail = Some(unsafe {
73         CString::new(gai_strerror(s), false).as_str().unwrap().to_string()
74     });
75     err
76 }
77
78 /// Convert an `errno` value into a high-level error variant and description.
79 pub fn decode_error(errno: i32) -> IoError {
80     // FIXME: this should probably be a bit more descriptive...
81     let (kind, desc) = match errno {
82         libc::EOF => (io::EndOfFile, "end of file"),
83         libc::ECONNREFUSED => (io::ConnectionRefused, "connection refused"),
84         libc::ECONNRESET => (io::ConnectionReset, "connection reset"),
85         libc::EPERM | libc::EACCES =>
86             (io::PermissionDenied, "permission denied"),
87         libc::EPIPE => (io::BrokenPipe, "broken pipe"),
88         libc::ENOTCONN => (io::NotConnected, "not connected"),
89         libc::ECONNABORTED => (io::ConnectionAborted, "connection aborted"),
90         libc::EADDRNOTAVAIL => (io::ConnectionRefused, "address not available"),
91         libc::EADDRINUSE => (io::ConnectionRefused, "address in use"),
92         libc::ENOENT => (io::FileNotFound, "no such file or directory"),
93         libc::EISDIR => (io::InvalidInput, "illegal operation on a directory"),
94         libc::ENOSYS => (io::IoUnavailable, "function not implemented"),
95         libc::EINVAL => (io::InvalidInput, "invalid argument"),
96         libc::ENOTTY =>
97             (io::MismatchedFileTypeForOperation,
98              "file descriptor is not a TTY"),
99         libc::ETIMEDOUT => (io::TimedOut, "operation timed out"),
100         libc::ECANCELED => (io::TimedOut, "operation aborted"),
101
102         // These two constants can have the same value on some systems,
103         // but different values on others, so we can't use a match
104         // clause
105         x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
106             (io::ResourceUnavailable, "resource temporarily unavailable"),
107
108         _ => (io::OtherIoError, "unknown error")
109     };
110     IoError { kind: kind, desc: desc, detail: None }
111 }
112
113 pub fn decode_error_detailed(errno: i32) -> IoError {
114     let mut err = decode_error(errno);
115     err.detail = Some(os::error_string(errno));
116     err
117 }
118
119 #[inline]
120 pub fn retry<T: SignedInt> (f: || -> T) -> T {
121     let one: T = Int::one();
122     loop {
123         let n = f();
124         if n == -one && os::errno() == libc::EINTR as int { }
125         else { return n }
126     }
127 }
128
129 pub fn ms_to_timeval(ms: u64) -> libc::timeval {
130     libc::timeval {
131         tv_sec: (ms / 1000) as libc::time_t,
132         tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t,
133     }
134 }
135
136 pub fn wouldblock() -> bool {
137     let err = os::errno();
138     err == libc::EWOULDBLOCK as int || err == libc::EAGAIN as int
139 }
140
141 pub fn set_nonblocking(fd: sock_t, nb: bool) -> IoResult<()> {
142     let set = nb as libc::c_int;
143     mkerr_libc(retry(|| unsafe { c::ioctl(fd, c::FIONBIO, &set) }))
144 }
145
146 // nothing needed on unix platforms
147 pub fn init_net() {}