]> git.lizzy.rs Git - rust.git/blob - src/librustrt/rtio.rs
7a91cca6265a0a782e29492eca9d0a69f7ed1e00
[rust.git] / src / librustrt / rtio.rs
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.
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 //! The EventLoop and internal synchronous I/O interface.
12
13 use core::prelude::*;
14 use alloc::owned::Box;
15 use collections::string::String;
16 use collections::vec::Vec;
17 use core::fmt;
18 use core::mem;
19 use libc::c_int;
20 use libc;
21
22 use c_str::CString;
23 use local::Local;
24 use task::Task;
25
26 pub trait EventLoop {
27     fn run(&mut self);
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>;
33
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;
37 }
38
39 pub trait Callback {
40     fn call(&mut self);
41 }
42
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.
50     fn fire(&mut self);
51 }
52
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
56     DontClose,
57     /// Synchronously close the handle, meaning that the task will block when
58     /// the handle is destroyed until it has been fully closed.
59     CloseSynchronously,
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
63     /// loop).
64     CloseAsynchronously,
65 }
66
67 /// Data needed to spawn a process. Serializes the `std::io::process::Command`
68 /// builder.
69 pub struct ProcessConfig<'a> {
70     /// Path to the program to run.
71     pub program: &'a CString,
72
73     /// Arguments to pass to the program (doesn't include the program itself).
74     pub args: &'a [CString],
75
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)]>,
79
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>,
83
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
86     /// written to.
87     pub stdin: StdioContainer,
88
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
91     /// collected.
92     pub stdout: StdioContainer,
93
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
96     /// collected.
97     pub stderr: StdioContainer,
98
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
104     /// `stderr` fields.
105     pub extra_io: &'a [StdioContainer],
106
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
110     /// fail.
111     pub uid: Option<uint>,
112
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>,
116
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.
119     pub detach: bool,
120 }
121
122 pub struct LocalIo<'a> {
123     factory: &'a mut IoFactory,
124 }
125
126 #[unsafe_destructor]
127 impl<'a> Drop for LocalIo<'a> {
128     fn drop(&mut self) {
129         // FIXME(pcwalton): Do nothing here for now, but eventually we may want
130         // something. For now this serves to make `LocalIo` noncopyable.
131     }
132 }
133
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
139         //
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).
148         //
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() {
152             Some(t) => t,
153             None => return None,
154         };
155         let ret = t.local_io().map(|t| {
156             unsafe { mem::transmute_copy(&t) }
157         });
158         Local::put(t);
159         return ret;
160     }
161
162     pub fn maybe_raise<T>(f: |io: &mut IoFactory| -> IoResult<T>)
163         -> IoResult<T>
164     {
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 {
170                 code: ERROR as uint,
171                 extra: 0,
172                 detail: None,
173             }),
174         }
175     }
176
177     pub fn new<'a>(io: &'a mut IoFactory) -> LocalIo<'a> {
178         LocalIo { factory: io }
179     }
180
181     /// Returns the underlying I/O factory as a trait reference.
182     #[inline]
183     pub fn get<'a>(&'a mut self) -> &'a mut IoFactory {
184         let f: &'a mut IoFactory = self.factory;
185         f
186     }
187 }
188
189 pub trait IoFactory {
190     // networking
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>>;
204
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) ->
220         IoResult<()>;
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) ->
225         IoResult<()>;
226
227     // misc
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>>;
238 }
239
240 pub trait RtioTcpListener : RtioSocket {
241     fn listen(~self) -> IoResult<Box<RtioTcpAcceptor + Send>>;
242 }
243
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>);
249 }
250
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>);
265 }
266
267 pub trait RtioSocket {
268     fn socket_name(&mut self) -> IoResult<SocketAddr>;
269 }
270
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<()>;
274
275     fn join_multicast(&mut self, multi: IpAddr) -> IoResult<()>;
276     fn leave_multicast(&mut self, multi: IpAddr) -> IoResult<()>;
277
278     fn loop_multicast_locally(&mut self) -> IoResult<()>;
279     fn dont_loop_multicast_locally(&mut self) -> IoResult<()>;
280
281     fn multicast_time_to_live(&mut self, ttl: int) -> IoResult<()>;
282     fn time_to_live(&mut self, ttl: int) -> IoResult<()>;
283
284     fn hear_broadcasts(&mut self) -> IoResult<()>;
285     fn ignore_broadcasts(&mut self) -> IoResult<()>;
286
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>);
291 }
292
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>);
297 }
298
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>;
310 }
311
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>);
317 }
318
319 pub trait RtioPipe {
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>;
323
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>);
329 }
330
331 pub trait RtioUnixListener {
332     fn listen(~self) -> IoResult<Box<RtioUnixAcceptor + Send>>;
333 }
334
335 pub trait RtioUnixAcceptor {
336     fn accept(&mut self) -> IoResult<Box<RtioPipe + Send>>;
337     fn set_timeout(&mut self, timeout: Option<u64>);
338 }
339
340 pub trait RtioTTY {
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;
346 }
347
348 pub trait PausableIdleCallback {
349     fn pause(&mut self);
350     fn resume(&mut self);
351 }
352
353 pub trait RtioSignal {}
354
355 pub struct IoError {
356     pub code: uint,
357     pub extra: uint,
358     pub detail: Option<String>,
359 }
360
361 pub type IoResult<T> = Result<T, IoError>;
362
363 #[deriving(PartialEq, Eq)]
364 pub enum IpAddr {
365     Ipv4Addr(u8, u8, u8, u8),
366     Ipv6Addr(u16, u16, u16, u16, u16, u16, u16, u16),
367 }
368
369 impl fmt::Show for IpAddr {
370     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
371         match *self {
372             Ipv4Addr(a, b, c, d) => write!(fmt, "{}.{}.{}.{}", a, b, c, d),
373             Ipv6Addr(a, b, c, d, e, f, g, h) => {
374                 write!(fmt,
375                        "{:04x}:{:04x}:{:04x}:{:04x}:{:04x}:{:04x}:{:04x}:{:04x}",
376                        a, b, c, d, e, f, g, h)
377             }
378         }
379     }
380 }
381
382 #[deriving(PartialEq, Eq)]
383 pub struct SocketAddr {
384     pub ip: IpAddr,
385     pub port: u16,
386 }
387
388 pub enum StdioContainer {
389     Ignored,
390     InheritFd(i32),
391     CreatePipe(bool, bool),
392 }
393
394 pub enum ProcessExit {
395     ExitStatus(int),
396     ExitSignal(int),
397 }
398
399 pub enum FileMode {
400     Open,
401     Append,
402     Truncate,
403 }
404
405 pub enum FileAccess {
406     Read,
407     Write,
408     ReadWrite,
409 }
410
411 pub struct FileStat {
412     pub size: u64,
413     pub kind: u64,
414     pub perm: u64,
415     pub created: u64,
416     pub modified: u64,
417     pub accessed: u64,
418     pub device: u64,
419     pub inode: u64,
420     pub rdev: u64,
421     pub nlink: u64,
422     pub uid: u64,
423     pub gid: u64,
424     pub blksize: u64,
425     pub blocks: u64,
426     pub flags: u64,
427     pub gen: u64,
428 }
429
430 pub enum SeekStyle {
431     SeekSet,
432     SeekEnd,
433     SeekCur,
434 }
435
436 pub struct AddrinfoHint {
437     pub family: uint,
438     pub socktype: uint,
439     pub protocol: uint,
440     pub flags: uint,
441 }
442
443 pub struct AddrinfoInfo {
444     pub address: SocketAddr,
445     pub family: uint,
446     pub socktype: uint,
447     pub protocol: uint,
448     pub flags: uint,
449 }