-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathtcp.rs
1363 lines (1212 loc) · 44.6 KB
/
tcp.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! TCP network connections
//!
//! This module contains the ability to open a TCP stream to a socket address,
//! as well as creating a socket server to accept incoming connections. The
//! destination and binding addresses can either be an IPv4 or IPv6 address.
//!
//! A TCP connection implements the `Reader` and `Writer` traits, while the TCP
//! listener (socket server) implements the `Listener` and `Acceptor` traits.
use clone::Clone;
use io::IoResult;
use iter::Iterator;
use slice::ImmutableVector;
use result::{Ok,Err};
use io::net::addrinfo::get_host_addresses;
use io::net::ip::SocketAddr;
use io::{IoError, ConnectionFailed, InvalidInput};
use io::{Reader, Writer, Listener, Acceptor};
use from_str::FromStr;
use kinds::Send;
use option::{None, Some, Option};
use owned::Box;
use rt::rtio::{IoFactory, LocalIo, RtioSocket, RtioTcpListener};
use rt::rtio::{RtioTcpAcceptor, RtioTcpStream};
use rt::rtio;
/// A structure which represents a TCP stream between a local socket and a
/// remote socket.
///
/// # Example
///
/// ```no_run
/// # #![allow(unused_must_use)]
/// use std::io::TcpStream;
///
/// let mut stream = TcpStream::connect("127.0.0.1", 34254);
///
/// stream.write([1]);
/// let mut buf = [0];
/// stream.read(buf);
/// drop(stream); // close the connection
/// ```
pub struct TcpStream {
obj: Box<RtioTcpStream + Send>,
}
impl TcpStream {
fn new(s: Box<RtioTcpStream + Send>) -> TcpStream {
TcpStream { obj: s }
}
/// Open a TCP connection to a remote host by hostname or IP address.
///
/// `host` can be a hostname or IP address string. If no error is
/// encountered, then `Ok(stream)` is returned.
pub fn connect(host: &str, port: u16) -> IoResult<TcpStream> {
let addresses = match FromStr::from_str(host) {
Some(addr) => vec!(addr),
None => try!(get_host_addresses(host))
};
let mut err = IoError {
kind: ConnectionFailed,
desc: "no addresses found for hostname",
detail: None
};
for addr in addresses.iter() {
let addr = rtio::SocketAddr{ ip: super::to_rtio(*addr), port: port };
let result = LocalIo::maybe_raise(|io| {
io.tcp_connect(addr, None).map(TcpStream::new)
});
match result {
Ok(stream) => {
return Ok(stream)
}
Err(connect_err) => {
err = IoError::from_rtio_error(connect_err)
}
}
}
Err(err)
}
/// Creates a TCP connection to a remote socket address, timing out after
/// the specified number of milliseconds.
///
/// This is the same as the `connect` method, except that if the timeout
/// specified (in milliseconds) elapses before a connection is made an error
/// will be returned. The error's kind will be `TimedOut`.
///
/// Note that the `addr` argument may one day be split into a separate host
/// and port, similar to the API seen in `connect`.
#[experimental = "the timeout argument may eventually change types"]
pub fn connect_timeout(addr: SocketAddr,
timeout_ms: u64) -> IoResult<TcpStream> {
let SocketAddr { ip, port } = addr;
let addr = rtio::SocketAddr { ip: super::to_rtio(ip), port: port };
LocalIo::maybe_raise(|io| {
io.tcp_connect(addr, Some(timeout_ms)).map(TcpStream::new)
}).map_err(IoError::from_rtio_error)
}
/// Returns the socket address of the remote peer of this TCP connection.
pub fn peer_name(&mut self) -> IoResult<SocketAddr> {
match self.obj.peer_name() {
Ok(rtio::SocketAddr { ip, port }) => {
Ok(SocketAddr { ip: super::from_rtio(ip), port: port })
}
Err(e) => Err(IoError::from_rtio_error(e)),
}
}
/// Returns the socket address of the local half of this TCP connection.
pub fn socket_name(&mut self) -> IoResult<SocketAddr> {
match self.obj.socket_name() {
Ok(rtio::SocketAddr { ip, port }) => {
Ok(SocketAddr { ip: super::from_rtio(ip), port: port })
}
Err(e) => Err(IoError::from_rtio_error(e)),
}
}
/// Sets the nodelay flag on this connection to the boolean specified
#[experimental]
pub fn set_nodelay(&mut self, nodelay: bool) -> IoResult<()> {
if nodelay {
self.obj.nodelay()
} else {
self.obj.control_congestion()
}.map_err(IoError::from_rtio_error)
}
/// Sets the keepalive timeout to the timeout specified.
///
/// If the value specified is `None`, then the keepalive flag is cleared on
/// this connection. Otherwise, the keepalive timeout will be set to the
/// specified time, in seconds.
#[experimental]
pub fn set_keepalive(&mut self, delay_in_seconds: Option<uint>) -> IoResult<()> {
match delay_in_seconds {
Some(i) => self.obj.keepalive(i),
None => self.obj.letdie(),
}.map_err(IoError::from_rtio_error)
}
/// Closes the reading half of this connection.
///
/// This method will close the reading portion of this connection, causing
/// all pending and future reads to immediately return with an error.
///
/// # Example
///
/// ```no_run
/// # #![allow(unused_must_use)]
/// use std::io::timer;
/// use std::io::TcpStream;
///
/// let mut stream = TcpStream::connect("127.0.0.1", 34254).unwrap();
/// let stream2 = stream.clone();
///
/// spawn(proc() {
/// // close this stream after one second
/// timer::sleep(1000);
/// let mut stream = stream2;
/// stream.close_read();
/// });
///
/// // wait for some data, will get canceled after one second
/// let mut buf = [0];
/// stream.read(buf);
/// ```
///
/// Note that this method affects all cloned handles associated with this
/// stream, not just this one handle.
pub fn close_read(&mut self) -> IoResult<()> {
self.obj.close_read().map_err(IoError::from_rtio_error)
}
/// Closes the writing half of this connection.
///
/// This method will close the writing portion of this connection, causing
/// all future writes to immediately return with an error.
///
/// Note that this method affects all cloned handles associated with this
/// stream, not just this one handle.
pub fn close_write(&mut self) -> IoResult<()> {
self.obj.close_write().map_err(IoError::from_rtio_error)
}
/// Sets a timeout, in milliseconds, for blocking operations on this stream.
///
/// This function will set a timeout for all blocking operations (including
/// reads and writes) on this stream. The timeout specified is a relative
/// time, in milliseconds, into the future after which point operations will
/// time out. This means that the timeout must be reset periodically to keep
/// it from expiring. Specifying a value of `None` will clear the timeout
/// for this stream.
///
/// The timeout on this stream is local to this stream only. Setting a
/// timeout does not affect any other cloned instances of this stream, nor
/// does the timeout propagated to cloned handles of this stream. Setting
/// this timeout will override any specific read or write timeouts
/// previously set for this stream.
///
/// For clarification on the semantics of interrupting a read and a write,
/// take a look at `set_read_timeout` and `set_write_timeout`.
#[experimental = "the timeout argument may change in type and value"]
pub fn set_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_timeout(timeout_ms)
}
/// Sets the timeout for read operations on this stream.
///
/// See documentation in `set_timeout` for the semantics of this read time.
/// This will overwrite any previous read timeout set through either this
/// function or `set_timeout`.
///
/// # Errors
///
/// When this timeout expires, if there is no pending read operation, no
/// action is taken. Otherwise, the read operation will be scheduled to
/// promptly return. If a timeout error is returned, then no data was read
/// during the timeout period.
#[experimental = "the timeout argument may change in type and value"]
pub fn set_read_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_read_timeout(timeout_ms)
}
/// Sets the timeout for write operations on this stream.
///
/// See documentation in `set_timeout` for the semantics of this write time.
/// This will overwrite any previous write timeout set through either this
/// function or `set_timeout`.
///
/// # Errors
///
/// When this timeout expires, if there is no pending write operation, no
/// action is taken. Otherwise, the pending write operation will be
/// scheduled to promptly return. The actual state of the underlying stream
/// is not specified.
///
/// The write operation may return an error of type `ShortWrite` which
/// indicates that the object is known to have written an exact number of
/// bytes successfully during the timeout period, and the remaining bytes
/// were never written.
///
/// If the write operation returns `TimedOut`, then it the timeout primitive
/// does not know how many bytes were written as part of the timeout
/// operation. It may be the case that bytes continue to be written in an
/// asynchronous fashion after the call to write returns.
#[experimental = "the timeout argument may change in type and value"]
pub fn set_write_timeout(&mut self, timeout_ms: Option<u64>) {
self.obj.set_write_timeout(timeout_ms)
}
}
impl Clone for TcpStream {
/// Creates a new handle to this TCP stream, allowing for simultaneous reads
/// and writes of this connection.
///
/// The underlying TCP stream will not be closed until all handles to the
/// stream have been deallocated. All handles will also follow the same
/// stream, but two concurrent reads will not receive the same data.
/// Instead, the first read will receive the first packet received, and the
/// second read will receive the second packet.
fn clone(&self) -> TcpStream {
TcpStream { obj: self.obj.clone() }
}
}
impl Reader for TcpStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
self.obj.read(buf).map_err(IoError::from_rtio_error)
}
}
impl Writer for TcpStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
self.obj.write(buf).map_err(IoError::from_rtio_error)
}
}
/// A structure representing a socket server. This listener is used to create a
/// `TcpAcceptor` which can be used to accept sockets on a local port.
///
/// # Example
///
/// ```rust
/// # fn main() { }
/// # fn foo() {
/// # #![allow(dead_code)]
/// use std::io::{TcpListener, TcpStream};
/// use std::io::{Acceptor, Listener};
///
/// let listener = TcpListener::bind("127.0.0.1", 80);
///
/// // bind the listener to the specified address
/// let mut acceptor = listener.listen();
///
/// fn handle_client(mut stream: TcpStream) {
/// // ...
/// # &mut stream; // silence unused mutability/variable warning
/// }
/// // accept connections and process them, spawning a new tasks for each one
/// for stream in acceptor.incoming() {
/// match stream {
/// Err(e) => { /* connection failed */ }
/// Ok(stream) => spawn(proc() {
/// // connection succeeded
/// handle_client(stream)
/// })
/// }
/// }
///
/// // close the socket server
/// drop(acceptor);
/// # }
/// ```
pub struct TcpListener {
obj: Box<RtioTcpListener + Send>,
}
impl TcpListener {
/// Creates a new `TcpListener` which will be bound to the specified IP
/// and port. This listener is not ready for accepting connections,
/// `listen` must be called on it before that's possible.
///
/// Binding with a port number of 0 will request that the OS assigns a port
/// to this listener. The port allocated can be queried via the
/// `socket_name` function.
pub fn bind(addr: &str, port: u16) -> IoResult<TcpListener> {
match FromStr::from_str(addr) {
Some(ip) => {
let addr = rtio::SocketAddr{
ip: super::to_rtio(ip),
port: port,
};
LocalIo::maybe_raise(|io| {
io.tcp_bind(addr).map(|l| TcpListener { obj: l })
}).map_err(IoError::from_rtio_error)
}
None => {
Err(IoError{
kind: InvalidInput,
desc: "invalid IP address specified",
detail: None
})
}
}
}
/// Returns the local socket address of this listener.
pub fn socket_name(&mut self) -> IoResult<SocketAddr> {
match self.obj.socket_name() {
Ok(rtio::SocketAddr { ip, port }) => {
Ok(SocketAddr { ip: super::from_rtio(ip), port: port })
}
Err(e) => Err(IoError::from_rtio_error(e)),
}
}
}
impl Listener<TcpStream, TcpAcceptor> for TcpListener {
fn listen(self) -> IoResult<TcpAcceptor> {
match self.obj.listen() {
Ok(acceptor) => Ok(TcpAcceptor { obj: acceptor }),
Err(e) => Err(IoError::from_rtio_error(e)),
}
}
}
/// The accepting half of a TCP socket server. This structure is created through
/// a `TcpListener`'s `listen` method, and this object can be used to accept new
/// `TcpStream` instances.
pub struct TcpAcceptor {
obj: Box<RtioTcpAcceptor + Send>,
}
impl TcpAcceptor {
/// Prevents blocking on all future accepts after `ms` milliseconds have
/// elapsed.
///
/// This function is used to set a deadline after which this acceptor will
/// time out accepting any connections. The argument is the relative
/// distance, in milliseconds, to a point in the future after which all
/// accepts will fail.
///
/// If the argument specified is `None`, then any previously registered
/// timeout is cleared.
///
/// A timeout of `0` can be used to "poll" this acceptor to see if it has
/// any pending connections. All pending connections will be accepted,
/// regardless of whether the timeout has expired or not (the accept will
/// not block in this case).
///
/// # Example
///
/// ```no_run
/// # #![allow(experimental)]
/// use std::io::TcpListener;
/// use std::io::{Listener, Acceptor, TimedOut};
///
/// let mut a = TcpListener::bind("127.0.0.1", 8482).listen().unwrap();
///
/// // After 100ms have passed, all accepts will fail
/// a.set_timeout(Some(100));
///
/// match a.accept() {
/// Ok(..) => println!("accepted a socket"),
/// Err(ref e) if e.kind == TimedOut => { println!("timed out!"); }
/// Err(e) => println!("err: {}", e),
/// }
///
/// // Reset the timeout and try again
/// a.set_timeout(Some(100));
/// let socket = a.accept();
///
/// // Clear the timeout and block indefinitely waiting for a connection
/// a.set_timeout(None);
/// let socket = a.accept();
/// ```
#[experimental = "the type of the argument and name of this function are \
subject to change"]
pub fn set_timeout(&mut self, ms: Option<u64>) { self.obj.set_timeout(ms); }
}
impl Acceptor<TcpStream> for TcpAcceptor {
fn accept(&mut self) -> IoResult<TcpStream> {
match self.obj.accept(){
Ok(s) => Ok(TcpStream::new(s)),
Err(e) => Err(IoError::from_rtio_error(e)),
}
}
}
#[cfg(test)]
#[allow(experimental)]
mod test {
use super::*;
use io::net::ip::SocketAddr;
use io::*;
use prelude::*;
// FIXME #11530 this fails on android because tests are run as root
iotest!(fn bind_error() {
match TcpListener::bind("0.0.0.0", 1) {
Ok(..) => fail!(),
Err(e) => assert_eq!(e.kind, PermissionDenied),
}
} #[ignore(cfg(windows))] #[ignore(cfg(target_os = "android"))])
iotest!(fn connect_error() {
match TcpStream::connect("0.0.0.0", 1) {
Ok(..) => fail!(),
Err(e) => assert_eq!(e.kind, ConnectionRefused),
}
})
iotest!(fn listen_ip4_localhost() {
let socket_addr = next_test_ip4();
let ip_str = socket_addr.ip.to_str();
let port = socket_addr.port;
let listener = TcpListener::bind(ip_str.as_slice(), port);
let mut acceptor = listener.listen();
spawn(proc() {
let mut stream = TcpStream::connect("localhost", port);
stream.write([144]).unwrap();
});
let mut stream = acceptor.accept();
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == 144);
})
iotest!(fn connect_localhost() {
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut stream = TcpStream::connect("localhost", addr.port);
stream.write([64]).unwrap();
});
let mut stream = acceptor.accept();
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == 64);
})
iotest!(fn connect_ip4_loopback() {
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut stream = TcpStream::connect("127.0.0.1", addr.port);
stream.write([44]).unwrap();
});
let mut stream = acceptor.accept();
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == 44);
})
iotest!(fn connect_ip6_loopback() {
let addr = next_test_ip6();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut stream = TcpStream::connect("::1", addr.port);
stream.write([66]).unwrap();
});
let mut stream = acceptor.accept();
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == 66);
})
iotest!(fn smoke_test_ip4() {
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut stream = TcpStream::connect(ip_str.as_slice(), port);
stream.write([99]).unwrap();
});
let mut stream = acceptor.accept();
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == 99);
})
iotest!(fn smoke_test_ip6() {
let addr = next_test_ip6();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut stream = TcpStream::connect(ip_str.as_slice(), port);
stream.write([99]).unwrap();
});
let mut stream = acceptor.accept();
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == 99);
})
iotest!(fn read_eof_ip4() {
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let _stream = TcpStream::connect(ip_str.as_slice(), port);
// Close
});
let mut stream = acceptor.accept();
let mut buf = [0];
let nread = stream.read(buf);
assert!(nread.is_err());
})
iotest!(fn read_eof_ip6() {
let addr = next_test_ip6();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let _stream = TcpStream::connect(ip_str.as_slice(), port);
// Close
});
let mut stream = acceptor.accept();
let mut buf = [0];
let nread = stream.read(buf);
assert!(nread.is_err());
})
iotest!(fn read_eof_twice_ip4() {
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let _stream = TcpStream::connect(ip_str.as_slice(), port);
// Close
});
let mut stream = acceptor.accept();
let mut buf = [0];
let nread = stream.read(buf);
assert!(nread.is_err());
match stream.read(buf) {
Ok(..) => fail!(),
Err(ref e) => {
assert!(e.kind == NotConnected || e.kind == EndOfFile,
"unknown kind: {:?}", e.kind);
}
}
})
iotest!(fn read_eof_twice_ip6() {
let addr = next_test_ip6();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let _stream = TcpStream::connect(ip_str.as_slice(), port);
// Close
});
let mut stream = acceptor.accept();
let mut buf = [0];
let nread = stream.read(buf);
assert!(nread.is_err());
match stream.read(buf) {
Ok(..) => fail!(),
Err(ref e) => {
assert!(e.kind == NotConnected || e.kind == EndOfFile,
"unknown kind: {:?}", e.kind);
}
}
})
iotest!(fn write_close_ip4() {
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let _stream = TcpStream::connect(ip_str.as_slice(), port);
// Close
});
let mut stream = acceptor.accept();
let buf = [0];
loop {
match stream.write(buf) {
Ok(..) => {}
Err(e) => {
assert!(e.kind == ConnectionReset ||
e.kind == BrokenPipe ||
e.kind == ConnectionAborted,
"unknown error: {:?}", e);
break;
}
}
}
})
iotest!(fn write_close_ip6() {
let addr = next_test_ip6();
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let _stream = TcpStream::connect(ip_str.as_slice(), port);
// Close
});
let mut stream = acceptor.accept();
let buf = [0];
loop {
match stream.write(buf) {
Ok(..) => {}
Err(e) => {
assert!(e.kind == ConnectionReset ||
e.kind == BrokenPipe ||
e.kind == ConnectionAborted,
"unknown error: {:?}", e);
break;
}
}
}
})
iotest!(fn multiple_connect_serial_ip4() {
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
let max = 10u;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
for _ in range(0, max) {
let mut stream = TcpStream::connect(ip_str.as_slice(), port);
stream.write([99]).unwrap();
}
});
for ref mut stream in acceptor.incoming().take(max) {
let mut buf = [0];
stream.read(buf).unwrap();
assert_eq!(buf[0], 99);
}
})
iotest!(fn multiple_connect_serial_ip6() {
let addr = next_test_ip6();
let ip_str = addr.ip.to_str();
let port = addr.port;
let max = 10u;
let mut acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
for _ in range(0, max) {
let mut stream = TcpStream::connect(ip_str.as_slice(), port);
stream.write([99]).unwrap();
}
});
for ref mut stream in acceptor.incoming().take(max) {
let mut buf = [0];
stream.read(buf).unwrap();
assert_eq!(buf[0], 99);
}
})
iotest!(fn multiple_connect_interleaved_greedy_schedule_ip4() {
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
static MAX: int = 10;
let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut acceptor = acceptor;
for (i, stream) in acceptor.incoming().enumerate().take(MAX as uint) {
// Start another task to handle the connection
spawn(proc() {
let mut stream = stream;
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == i as u8);
debug!("read");
});
}
});
connect(0, addr);
fn connect(i: int, addr: SocketAddr) {
let ip_str = addr.ip.to_str();
let port = addr.port;
if i == MAX { return }
spawn(proc() {
debug!("connecting");
let mut stream = TcpStream::connect(ip_str.as_slice(), port);
// Connect again before writing
connect(i + 1, addr);
debug!("writing");
stream.write([i as u8]).unwrap();
});
}
})
iotest!(fn multiple_connect_interleaved_greedy_schedule_ip6() {
let addr = next_test_ip6();
let ip_str = addr.ip.to_str();
let port = addr.port;
static MAX: int = 10;
let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut acceptor = acceptor;
for (i, stream) in acceptor.incoming().enumerate().take(MAX as uint) {
// Start another task to handle the connection
spawn(proc() {
let mut stream = stream;
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == i as u8);
debug!("read");
});
}
});
connect(0, addr);
fn connect(i: int, addr: SocketAddr) {
let ip_str = addr.ip.to_str();
let port = addr.port;
if i == MAX { return }
spawn(proc() {
debug!("connecting");
let mut stream = TcpStream::connect(ip_str.as_slice(), port);
// Connect again before writing
connect(i + 1, addr);
debug!("writing");
stream.write([i as u8]).unwrap();
});
}
})
iotest!(fn multiple_connect_interleaved_lazy_schedule_ip4() {
static MAX: int = 10;
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut acceptor = acceptor;
for stream in acceptor.incoming().take(MAX as uint) {
// Start another task to handle the connection
spawn(proc() {
let mut stream = stream;
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == 99);
debug!("read");
});
}
});
connect(0, addr);
fn connect(i: int, addr: SocketAddr) {
let ip_str = addr.ip.to_str();
let port = addr.port;
if i == MAX { return }
spawn(proc() {
debug!("connecting");
let mut stream = TcpStream::connect(ip_str.as_slice(), port);
// Connect again before writing
connect(i + 1, addr);
debug!("writing");
stream.write([99]).unwrap();
});
}
})
iotest!(fn multiple_connect_interleaved_lazy_schedule_ip6() {
static MAX: int = 10;
let addr = next_test_ip6();
let ip_str = addr.ip.to_str();
let port = addr.port;
let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut acceptor = acceptor;
for stream in acceptor.incoming().take(MAX as uint) {
// Start another task to handle the connection
spawn(proc() {
let mut stream = stream;
let mut buf = [0];
stream.read(buf).unwrap();
assert!(buf[0] == 99);
debug!("read");
});
}
});
connect(0, addr);
fn connect(i: int, addr: SocketAddr) {
let ip_str = addr.ip.to_str();
let port = addr.port;
if i == MAX { return }
spawn(proc() {
debug!("connecting");
let mut stream = TcpStream::connect(ip_str.as_slice(), port);
// Connect again before writing
connect(i + 1, addr);
debug!("writing");
stream.write([99]).unwrap();
});
}
})
pub fn socket_name(addr: SocketAddr) {
let ip_str = addr.ip.to_str();
let port = addr.port;
let mut listener = TcpListener::bind(ip_str.as_slice(), port).unwrap();
// Make sure socket_name gives
// us the socket we binded to.
let so_name = listener.socket_name();
assert!(so_name.is_ok());
assert_eq!(addr, so_name.unwrap());
}
pub fn peer_name(addr: SocketAddr) {
let ip_str = addr.ip.to_str();
let port = addr.port;
let acceptor = TcpListener::bind(ip_str.as_slice(), port).listen();
spawn(proc() {
let mut acceptor = acceptor;
acceptor.accept().unwrap();
});
let stream = TcpStream::connect(ip_str.as_slice(), port);
assert!(stream.is_ok());
let mut stream = stream.unwrap();
// Make sure peer_name gives us the
// address/port of the peer we've
// connected to.
let peer_name = stream.peer_name();
assert!(peer_name.is_ok());
assert_eq!(addr, peer_name.unwrap());
}
iotest!(fn socket_and_peer_name_ip4() {
peer_name(next_test_ip4());
socket_name(next_test_ip4());
})
iotest!(fn socket_and_peer_name_ip6() {
// FIXME: peer name is not consistent
//peer_name(next_test_ip6());
socket_name(next_test_ip6());
})
iotest!(fn partial_read() {
let addr = next_test_ip4();
let port = addr.port;
let (tx, rx) = channel();
spawn(proc() {
let ip_str = addr.ip.to_str();
let mut srv = TcpListener::bind(ip_str.as_slice(), port).listen().unwrap();
tx.send(());
let mut cl = srv.accept().unwrap();
cl.write([10]).unwrap();
let mut b = [0];
cl.read(b).unwrap();
tx.send(());
});
rx.recv();
let ip_str = addr.ip.to_str();
let mut c = TcpStream::connect(ip_str.as_slice(), port).unwrap();
let mut b = [0, ..10];
assert_eq!(c.read(b), Ok(1));
c.write([1]).unwrap();
rx.recv();
})
iotest!(fn double_bind() {
let addr = next_test_ip4();
let ip_str = addr.ip.to_str();
let port = addr.port;
let listener = TcpListener::bind(ip_str.as_slice(), port).unwrap().listen();
assert!(listener.is_ok());
match TcpListener::bind(ip_str.as_slice(), port).listen() {
Ok(..) => fail!(),
Err(e) => {
assert!(e.kind == ConnectionRefused || e.kind == OtherIoError,
"unknown error: {} {}", e, e.kind);
}
}
})
iotest!(fn fast_rebind() {
let addr = next_test_ip4();
let port = addr.port;
let (tx, rx) = channel();
spawn(proc() {
let ip_str = addr.ip.to_str();
rx.recv();
let _stream = TcpStream::connect(ip_str.as_slice(), port).unwrap();
// Close