1 // Copyright 2013 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.
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.
11 //! The EventLoop and internal synchronous I/O interface.
14 use alloc::owned::Box;
15 use collections::string::String;
16 use collections::vec::Vec;
28 fn callback(&mut self, arg: proc(): Send);
29 fn pausable_idle_callback(&mut self, Box<Callback + Send>)
30 -> Box<PausableIdleCallback + Send>;
31 fn remote_callback(&mut self, Box<Callback + Send>)
32 -> Box<RemoteCallback + Send>;
34 /// The asynchronous I/O services. Not all event loops may provide one.
35 fn io<'a>(&'a mut self) -> Option<&'a mut IoFactory>;
36 fn has_active_io(&self) -> bool;
43 pub trait RemoteCallback {
44 /// Trigger the remote callback. Note that the number of times the
45 /// callback is run is not guaranteed. All that is guaranteed is
46 /// that, after calling 'fire', the callback will be called at
47 /// least once, but multiple callbacks may be coalesced and
48 /// callbacks may be called more often requested. Destruction also
49 /// triggers the callback.
53 /// Description of what to do when a file handle is closed
54 pub enum CloseBehavior {
55 /// Do not close this handle when the object is destroyed
57 /// Synchronously close the handle, meaning that the task will block when
58 /// the handle is destroyed until it has been fully closed.
60 /// Asynchronously closes a handle, meaning that the task will *not* block
61 /// when the handle is destroyed, but the handle will still get deallocated
62 /// and cleaned up (but this will happen asynchronously on the local event
67 /// Data needed to spawn a process. Serializes the `std::io::process::Command`
69 pub struct ProcessConfig<'a> {
70 /// Path to the program to run.
71 pub program: &'a CString,
73 /// Arguments to pass to the program (doesn't include the program itself).
74 pub args: &'a [CString],
76 /// Optional environment to specify for the program. If this is None, then
77 /// it will inherit the current process's environment.
78 pub env: Option<&'a [(&'a CString, &'a CString)]>,
80 /// Optional working directory for the new process. If this is None, then
81 /// the current directory of the running process is inherited.
82 pub cwd: Option<&'a CString>,
84 /// Configuration for the child process's stdin handle (file descriptor 0).
85 /// This field defaults to `CreatePipe(true, false)` so the input can be
87 pub stdin: StdioContainer,
89 /// Configuration for the child process's stdout handle (file descriptor 1).
90 /// This field defaults to `CreatePipe(false, true)` so the output can be
92 pub stdout: StdioContainer,
94 /// Configuration for the child process's stdout handle (file descriptor 2).
95 /// This field defaults to `CreatePipe(false, true)` so the output can be
97 pub stderr: StdioContainer,
99 /// Any number of streams/file descriptors/pipes may be attached to this
100 /// process. This list enumerates the file descriptors and such for the
101 /// process to be spawned, and the file descriptors inherited will start at
102 /// 3 and go to the length of this array. The first three file descriptors
103 /// (stdin/stdout/stderr) are configured with the `stdin`, `stdout`, and
105 pub extra_io: &'a [StdioContainer],
107 /// Sets the child process's user id. This translates to a `setuid` call in
108 /// the child process. Setting this value on windows will cause the spawn to
109 /// fail. Failure in the `setuid` call on unix will also cause the spawn to
111 pub uid: Option<uint>,
113 /// Similar to `uid`, but sets the group id of the child process. This has
114 /// the same semantics as the `uid` field.
115 pub gid: Option<uint>,
117 /// If true, the child process is spawned in a detached state. On unix, this
118 /// means that the child is the leader of a new process group.
122 pub struct LocalIo<'a> {
123 factory: &'a mut IoFactory,
127 impl<'a> Drop for LocalIo<'a> {
129 // FIXME(pcwalton): Do nothing here for now, but eventually we may want
130 // something. For now this serves to make `LocalIo` noncopyable.
134 impl<'a> LocalIo<'a> {
135 /// Returns the local I/O: either the local scheduler's I/O services or
136 /// the native I/O services.
137 pub fn borrow() -> Option<LocalIo> {
138 // FIXME(#11053): bad
140 // This is currently very unsafely implemented. We don't actually
141 // *take* the local I/O so there's a very real possibility that we
142 // can have two borrows at once. Currently there is not a clear way
143 // to actually borrow the local I/O factory safely because even if
144 // ownership were transferred down to the functions that the I/O
145 // factory implements it's just too much of a pain to know when to
146 // relinquish ownership back into the local task (but that would be
147 // the safe way of implementing this function).
149 // In order to get around this, we just transmute a copy out of the task
150 // in order to have what is likely a static lifetime (bad).
151 let mut t: Box<Task> = match Local::try_take() {
155 let ret = t.local_io().map(|t| {
156 unsafe { mem::transmute_copy(&t) }
162 pub fn maybe_raise<T>(f: |io: &mut IoFactory| -> IoResult<T>)
165 #[cfg(unix)] use ERROR = libc::EINVAL;
166 #[cfg(windows)] use ERROR = libc::ERROR_CALL_NOT_IMPLEMENTED;
167 match LocalIo::borrow() {
168 Some(mut io) => f(io.get()),
169 None => Err(IoError {
177 pub fn new<'a>(io: &'a mut IoFactory) -> LocalIo<'a> {
178 LocalIo { factory: io }
181 /// Returns the underlying I/O factory as a trait reference.
183 pub fn get<'a>(&'a mut self) -> &'a mut IoFactory {
184 let f: &'a mut IoFactory = self.factory;
189 pub trait IoFactory {
191 fn tcp_connect(&mut self, addr: SocketAddr,
192 timeout: Option<u64>) -> IoResult<Box<RtioTcpStream + Send>>;
193 fn tcp_bind(&mut self, addr: SocketAddr)
194 -> IoResult<Box<RtioTcpListener + Send>>;
195 fn udp_bind(&mut self, addr: SocketAddr)
196 -> IoResult<Box<RtioUdpSocket + Send>>;
197 fn unix_bind(&mut self, path: &CString)
198 -> IoResult<Box<RtioUnixListener + Send>>;
199 fn unix_connect(&mut self, path: &CString,
200 timeout: Option<u64>) -> IoResult<Box<RtioPipe + Send>>;
201 fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
202 hint: Option<AddrinfoHint>)
203 -> IoResult<Vec<AddrinfoInfo>>;
205 // filesystem operations
206 fn fs_from_raw_fd(&mut self, fd: c_int, close: CloseBehavior)
207 -> Box<RtioFileStream + Send>;
208 fn fs_open(&mut self, path: &CString, fm: FileMode, fa: FileAccess)
209 -> IoResult<Box<RtioFileStream + Send>>;
210 fn fs_unlink(&mut self, path: &CString) -> IoResult<()>;
211 fn fs_stat(&mut self, path: &CString) -> IoResult<FileStat>;
212 fn fs_mkdir(&mut self, path: &CString, mode: uint) -> IoResult<()>;
213 fn fs_chmod(&mut self, path: &CString, mode: uint) -> IoResult<()>;
214 fn fs_rmdir(&mut self, path: &CString) -> IoResult<()>;
215 fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()>;
216 fn fs_readdir(&mut self, path: &CString, flags: c_int) ->
217 IoResult<Vec<CString>>;
218 fn fs_lstat(&mut self, path: &CString) -> IoResult<FileStat>;
219 fn fs_chown(&mut self, path: &CString, uid: int, gid: int) ->
221 fn fs_readlink(&mut self, path: &CString) -> IoResult<CString>;
222 fn fs_symlink(&mut self, src: &CString, dst: &CString) -> IoResult<()>;
223 fn fs_link(&mut self, src: &CString, dst: &CString) -> IoResult<()>;
224 fn fs_utime(&mut self, src: &CString, atime: u64, mtime: u64) ->
228 fn timer_init(&mut self) -> IoResult<Box<RtioTimer + Send>>;
229 fn spawn(&mut self, cfg: ProcessConfig)
230 -> IoResult<(Box<RtioProcess + Send>,
231 Vec<Option<Box<RtioPipe + Send>>>)>;
232 fn kill(&mut self, pid: libc::pid_t, signal: int) -> IoResult<()>;
233 fn pipe_open(&mut self, fd: c_int) -> IoResult<Box<RtioPipe + Send>>;
234 fn tty_open(&mut self, fd: c_int, readable: bool)
235 -> IoResult<Box<RtioTTY + Send>>;
236 fn signal(&mut self, signal: int, cb: Box<Callback + Send>)
237 -> IoResult<Box<RtioSignal + Send>>;
240 pub trait RtioTcpListener : RtioSocket {
241 fn listen(~self) -> IoResult<Box<RtioTcpAcceptor + Send>>;
244 pub trait RtioTcpAcceptor : RtioSocket {
245 fn accept(&mut self) -> IoResult<Box<RtioTcpStream + Send>>;
246 fn accept_simultaneously(&mut self) -> IoResult<()>;
247 fn dont_accept_simultaneously(&mut self) -> IoResult<()>;
248 fn set_timeout(&mut self, timeout: Option<u64>);
251 pub trait RtioTcpStream : RtioSocket {
252 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
253 fn write(&mut self, buf: &[u8]) -> IoResult<()>;
254 fn peer_name(&mut self) -> IoResult<SocketAddr>;
255 fn control_congestion(&mut self) -> IoResult<()>;
256 fn nodelay(&mut self) -> IoResult<()>;
257 fn keepalive(&mut self, delay_in_seconds: uint) -> IoResult<()>;
258 fn letdie(&mut self) -> IoResult<()>;
259 fn clone(&self) -> Box<RtioTcpStream + Send>;
260 fn close_write(&mut self) -> IoResult<()>;
261 fn close_read(&mut self) -> IoResult<()>;
262 fn set_timeout(&mut self, timeout_ms: Option<u64>);
263 fn set_read_timeout(&mut self, timeout_ms: Option<u64>);
264 fn set_write_timeout(&mut self, timeout_ms: Option<u64>);
267 pub trait RtioSocket {
268 fn socket_name(&mut self) -> IoResult<SocketAddr>;
271 pub trait RtioUdpSocket : RtioSocket {
272 fn recv_from(&mut self, buf: &mut [u8]) -> IoResult<(uint, SocketAddr)>;
273 fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()>;
275 fn join_multicast(&mut self, multi: IpAddr) -> IoResult<()>;
276 fn leave_multicast(&mut self, multi: IpAddr) -> IoResult<()>;
278 fn loop_multicast_locally(&mut self) -> IoResult<()>;
279 fn dont_loop_multicast_locally(&mut self) -> IoResult<()>;
281 fn multicast_time_to_live(&mut self, ttl: int) -> IoResult<()>;
282 fn time_to_live(&mut self, ttl: int) -> IoResult<()>;
284 fn hear_broadcasts(&mut self) -> IoResult<()>;
285 fn ignore_broadcasts(&mut self) -> IoResult<()>;
287 fn clone(&self) -> Box<RtioUdpSocket + Send>;
288 fn set_timeout(&mut self, timeout_ms: Option<u64>);
289 fn set_read_timeout(&mut self, timeout_ms: Option<u64>);
290 fn set_write_timeout(&mut self, timeout_ms: Option<u64>);
293 pub trait RtioTimer {
294 fn sleep(&mut self, msecs: u64);
295 fn oneshot(&mut self, msecs: u64, cb: Box<Callback + Send>);
296 fn period(&mut self, msecs: u64, cb: Box<Callback + Send>);
299 pub trait RtioFileStream {
300 fn read(&mut self, buf: &mut [u8]) -> IoResult<int>;
301 fn write(&mut self, buf: &[u8]) -> IoResult<()>;
302 fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int>;
303 fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()>;
304 fn seek(&mut self, pos: i64, whence: SeekStyle) -> IoResult<u64>;
305 fn tell(&self) -> IoResult<u64>;
306 fn fsync(&mut self) -> IoResult<()>;
307 fn datasync(&mut self) -> IoResult<()>;
308 fn truncate(&mut self, offset: i64) -> IoResult<()>;
309 fn fstat(&mut self) -> IoResult<FileStat>;
312 pub trait RtioProcess {
313 fn id(&self) -> libc::pid_t;
314 fn kill(&mut self, signal: int) -> IoResult<()>;
315 fn wait(&mut self) -> IoResult<ProcessExit>;
316 fn set_timeout(&mut self, timeout: Option<u64>);
320 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
321 fn write(&mut self, buf: &[u8]) -> IoResult<()>;
322 fn clone(&self) -> Box<RtioPipe + Send>;
324 fn close_write(&mut self) -> IoResult<()>;
325 fn close_read(&mut self) -> IoResult<()>;
326 fn set_timeout(&mut self, timeout_ms: Option<u64>);
327 fn set_read_timeout(&mut self, timeout_ms: Option<u64>);
328 fn set_write_timeout(&mut self, timeout_ms: Option<u64>);
331 pub trait RtioUnixListener {
332 fn listen(~self) -> IoResult<Box<RtioUnixAcceptor + Send>>;
335 pub trait RtioUnixAcceptor {
336 fn accept(&mut self) -> IoResult<Box<RtioPipe + Send>>;
337 fn set_timeout(&mut self, timeout: Option<u64>);
341 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
342 fn write(&mut self, buf: &[u8]) -> IoResult<()>;
343 fn set_raw(&mut self, raw: bool) -> IoResult<()>;
344 fn get_winsize(&mut self) -> IoResult<(int, int)>;
345 fn isatty(&self) -> bool;
348 pub trait PausableIdleCallback {
350 fn resume(&mut self);
353 pub trait RtioSignal {}
358 pub detail: Option<String>,
361 pub type IoResult<T> = Result<T, IoError>;
363 #[deriving(PartialEq, Eq)]
365 Ipv4Addr(u8, u8, u8, u8),
366 Ipv6Addr(u16, u16, u16, u16, u16, u16, u16, u16),
369 impl fmt::Show for IpAddr {
370 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
372 Ipv4Addr(a, b, c, d) => write!(fmt, "{}.{}.{}.{}", a, b, c, d),
373 Ipv6Addr(a, b, c, d, e, f, g, h) => {
375 "{:04x}:{:04x}:{:04x}:{:04x}:{:04x}:{:04x}:{:04x}:{:04x}",
376 a, b, c, d, e, f, g, h)
382 #[deriving(PartialEq, Eq)]
383 pub struct SocketAddr {
388 pub enum StdioContainer {
391 CreatePipe(bool, bool),
394 pub enum ProcessExit {
405 pub enum FileAccess {
411 pub struct FileStat {
436 pub struct AddrinfoHint {
443 pub struct AddrinfoInfo {
444 pub address: SocketAddr,