forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnet_tcp.rs
1973 lines (1871 loc) · 72 KB
/
net_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 2012-2013 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.
//! High-level interface to libuv's TCP functionality
// FIXME #4425: Need FFI fixes
use future;
use future_spawn = future::spawn;
use ip = net_ip;
use uv;
use uv::iotask;
use uv::iotask::IoTask;
use core::io;
use core::libc::size_t;
use core::libc;
use core::comm::{stream, Port, SharedChan};
use core::ptr;
use core::result::{Result};
use core::result;
use core::uint;
use core::vec;
pub mod rustrt {
use core::libc;
#[nolink]
pub extern {
unsafe fn rust_uv_current_kernel_malloc(size: libc::c_uint)
-> *libc::c_void;
unsafe fn rust_uv_current_kernel_free(mem: *libc::c_void);
unsafe fn rust_uv_helper_uv_tcp_t_size() -> libc::c_uint;
}
}
/**
* Encapsulates an open TCP/IP connection through libuv
*
* `TcpSocket` is non-copyable/sendable and automagically handles closing the
* underlying libuv data structures when it goes out of scope. This is the
* data structure that is used for read/write operations over a TCP stream.
*/
pub struct TcpSocket {
socket_data: @TcpSocketData,
}
#[unsafe_destructor]
impl Drop for TcpSocket {
fn finalize(&self) {
tear_down_socket_data(self.socket_data)
}
}
pub fn TcpSocket(socket_data: @TcpSocketData) -> TcpSocket {
TcpSocket {
socket_data: socket_data
}
}
/**
* A buffered wrapper for `net::tcp::TcpSocket`
*
* It is created with a call to `net::tcp::socket_buf()` and has impls that
* satisfy both the `io::Reader` and `io::Writer` traits.
*/
pub struct TcpSocketBuf {
data: @TcpBufferedSocketData,
mut end_of_stream: bool
}
pub fn TcpSocketBuf(data: @TcpBufferedSocketData) -> TcpSocketBuf {
TcpSocketBuf {
data: data,
end_of_stream: false
}
}
/// Contains raw, string-based, error information returned from libuv
pub struct TcpErrData {
err_name: ~str,
err_msg: ~str,
}
/// Details returned as part of a `Result::Err` result from `tcp::listen`
pub enum TcpListenErrData {
/**
* Some unplanned-for error. The first and second fields correspond
* to libuv's `err_name` and `err_msg` fields, respectively.
*/
GenericListenErr(~str, ~str),
/**
* Failed to bind to the requested IP/Port, because it is already in use.
*
* # Possible Causes
*
* * Attempting to bind to a port already bound to another listener
*/
AddressInUse,
/**
* Request to bind to an IP/Port was denied by the system.
*
* # Possible Causes
*
* * Attemping to binding to an IP/Port as a non-Administrator
* on Windows Vista+
* * Attempting to bind, as a non-priv'd
* user, to 'privileged' ports (< 1024) on *nix
*/
AccessDenied
}
/// Details returned as part of a `Result::Err` result from `tcp::connect`
pub enum TcpConnectErrData {
/**
* Some unplanned-for error. The first and second fields correspond
* to libuv's `err_name` and `err_msg` fields, respectively.
*/
GenericConnectErr(~str, ~str),
/// Invalid IP or invalid port
ConnectionRefused
}
/**
* Initiate a client connection over TCP/IP
*
* # Arguments
*
* * `input_ip` - The IP address (versions 4 or 6) of the remote host
* * `port` - the unsigned integer of the desired remote host port
* * `iotask` - a `uv::iotask` that the tcp request will run on
*
* # Returns
*
* A `result` that, if the operation succeeds, contains a
* `net::net::TcpSocket` that can be used to send and receive data to/from
* the remote host. In the event of failure, a
* `net::tcp::TcpConnectErrData` instance will be returned
*/
pub fn connect(input_ip: ip::IpAddr, port: uint,
iotask: &IoTask)
-> result::Result<TcpSocket, TcpConnectErrData> {
unsafe {
let (result_po, result_ch) = stream::<ConnAttempt>();
let result_ch = SharedChan::new(result_ch);
let (closed_signal_po, closed_signal_ch) = stream::<()>();
let closed_signal_ch = SharedChan::new(closed_signal_ch);
let conn_data = ConnectReqData {
result_ch: result_ch,
closed_signal_ch: closed_signal_ch
};
let conn_data_ptr: *ConnectReqData = &conn_data;
let (reader_po, reader_ch) = stream::<Result<~[u8], TcpErrData>>();
let reader_ch = SharedChan::new(reader_ch);
let stream_handle_ptr = malloc_uv_tcp_t();
*(stream_handle_ptr as *mut uv::ll::uv_tcp_t) = uv::ll::tcp_t();
let socket_data = @TcpSocketData {
reader_po: @reader_po,
reader_ch: reader_ch,
stream_handle_ptr: stream_handle_ptr,
connect_req: uv::ll::connect_t(),
write_req: uv::ll::write_t(),
ipv6: match input_ip {
ip::Ipv4(_) => { false }
ip::Ipv6(_) => { true }
},
iotask: iotask.clone()
};
let socket_data_ptr: *TcpSocketData = &*socket_data;
// get an unsafe representation of our stream_handle_ptr that
// we can send into the interact cb to be handled in libuv..
debug!("stream_handle_ptr outside interact %?",
stream_handle_ptr);
do iotask::interact(iotask) |loop_ptr| {
unsafe {
debug!("in interact cb for tcp client connect..");
debug!("stream_handle_ptr in interact %?",
stream_handle_ptr);
match uv::ll::tcp_init( loop_ptr, stream_handle_ptr) {
0i32 => {
debug!("tcp_init successful");
debug!("dealing w/ ipv4 connection..");
let connect_req_ptr: *uv::ll::uv_connect_t =
&(*socket_data_ptr).connect_req;
let addr_str = ip::format_addr(&input_ip);
let connect_result = match input_ip {
ip::Ipv4(ref addr) => {
// have to "recreate" the
// sockaddr_in/6 since the ip_addr
// discards the port info.. should
// probably add an additional rust
// type that actually is closer to
// what the libuv API expects (ip str
// + port num)
debug!("addr: %?", addr);
let in_addr = uv::ll::ip4_addr(addr_str,
port as int);
uv::ll::tcp_connect(
connect_req_ptr,
stream_handle_ptr,
&in_addr,
tcp_connect_on_connect_cb)
}
ip::Ipv6(ref addr) => {
debug!("addr: %?", addr);
let in_addr = uv::ll::ip6_addr(addr_str,
port as int);
uv::ll::tcp_connect6(
connect_req_ptr,
stream_handle_ptr,
&in_addr,
tcp_connect_on_connect_cb)
}
};
match connect_result {
0i32 => {
debug!("tcp_connect successful: \
stream %x,
socket data %x",
stream_handle_ptr as uint,
socket_data_ptr as uint);
// reusable data that we'll have for the
// duration..
uv::ll::set_data_for_uv_handle(
stream_handle_ptr,
socket_data_ptr as
*libc::c_void);
// just so the connect_cb can send the
// outcome..
uv::ll::set_data_for_req(connect_req_ptr,
conn_data_ptr);
debug!("leaving tcp_connect interact cb...");
// let tcp_connect_on_connect_cb send on
// the result_ch, now..
}
_ => {
// immediate connect
// failure.. probably a garbage ip or
// somesuch
let err_data =
uv::ll::get_last_err_data(loop_ptr);
let result_ch = (*conn_data_ptr)
.result_ch.clone();
result_ch.send(ConnFailure(err_data));
uv::ll::set_data_for_uv_handle(
stream_handle_ptr,
conn_data_ptr);
uv::ll::close(stream_handle_ptr,
stream_error_close_cb);
}
}
}
_ => {
// failure to create a tcp handle
let err_data = uv::ll::get_last_err_data(loop_ptr);
let result_ch = (*conn_data_ptr).result_ch.clone();
result_ch.send(ConnFailure(err_data));
}
}
}
}
match result_po.recv() {
ConnSuccess => {
debug!("tcp::connect - received success on result_po");
result::Ok(TcpSocket(socket_data))
}
ConnFailure(ref err_data) => {
closed_signal_po.recv();
debug!("tcp::connect - received failure on result_po");
// still have to free the malloc'd stream handle..
rustrt::rust_uv_current_kernel_free(stream_handle_ptr
as *libc::c_void);
let tcp_conn_err = match err_data.err_name {
~"ECONNREFUSED" => ConnectionRefused,
_ => GenericConnectErr(err_data.err_name,
err_data.err_msg)
};
result::Err(tcp_conn_err)
}
}
}
}
/**
* Write binary data to a tcp stream; Blocks until operation completes
*
* # Arguments
*
* * sock - a `TcpSocket` to write to
* * raw_write_data - a vector of `~[u8]` that will be written to the stream.
* This value must remain valid for the duration of the `write` call
*
* # Returns
*
* A `Result` object with a `()` value as the `Ok` variant, or a
* `TcpErrData` value as the `Err` variant
*/
pub fn write(sock: &TcpSocket, raw_write_data: ~[u8])
-> result::Result<(), TcpErrData> {
let socket_data_ptr: *TcpSocketData = &*sock.socket_data;
write_common_impl(socket_data_ptr, raw_write_data)
}
/**
* Write binary data to tcp stream; Returns a `future::Future` value
* immediately
*
* # Safety
*
* This function can produce unsafe results if:
*
* 1. the call to `write_future` is made
* 2. the `future::Future` value returned is never resolved via
* `Future::get`
* 3. and then the `TcpSocket` passed in to `write_future` leaves
* scope and is destructed before the task that runs the libuv write
* operation completes.
*
* As such: If using `write_future`, always be sure to resolve the returned
* `Future` so as to ensure libuv doesn't try to access a released write
* handle. Otherwise, use the blocking `tcp::write` function instead.
*
* # Arguments
*
* * sock - a `TcpSocket` to write to
* * raw_write_data - a vector of `~[u8]` that will be written to the stream.
* This value must remain valid for the duration of the `write` call
*
* # Returns
*
* A `Future` value that, once the `write` operation completes, resolves to a
* `Result` object with a `nil` value as the `Ok` variant, or a `TcpErrData`
* value as the `Err` variant
*/
pub fn write_future(sock: &TcpSocket, raw_write_data: ~[u8])
-> future::Future<result::Result<(), TcpErrData>>
{
let socket_data_ptr: *TcpSocketData = &*sock.socket_data;
do future_spawn {
let data_copy = copy(raw_write_data);
write_common_impl(socket_data_ptr, data_copy)
}
}
/**
* Begin reading binary data from an open TCP connection; used with
* `read_stop`
*
* # Arguments
*
* * sock -- a `net::tcp::TcpSocket` for the connection to read from
*
* # Returns
*
* * A `Result` instance that will either contain a
* `core::comm::Port<Result<~[u8], TcpErrData>>` that the user can read
* (and * optionally, loop on) from until `read_stop` is called, or a
* `TcpErrData` record
*/
pub fn read_start(sock: &TcpSocket)
-> result::Result<@Port<result::Result<~[u8],
TcpErrData>>,
TcpErrData> {
let socket_data: *TcpSocketData = &*sock.socket_data;
read_start_common_impl(socket_data)
}
/**
* Stop reading from an open TCP connection; used with `read_start`
*
* # Arguments
*
* * `sock` - a `net::tcp::TcpSocket` that you wish to stop reading on
*/
pub fn read_stop(sock: &TcpSocket) -> result::Result<(), TcpErrData> {
let socket_data: *TcpSocketData = &*sock.socket_data;
read_stop_common_impl(socket_data)
}
/**
* Reads a single chunk of data from `TcpSocket`; block until data/error
* recv'd
*
* Does a blocking read operation for a single chunk of data from a
* `TcpSocket` until a data arrives or an error is received. The provided
* `timeout_msecs` value is used to raise an error if the timeout period
* passes without any data received.
*
* # Arguments
*
* * `sock` - a `net::tcp::TcpSocket` that you wish to read from
* * `timeout_msecs` - a `uint` value, in msecs, to wait before dropping the
* read attempt. Pass `0u` to wait indefinitely
*/
pub fn read(sock: &TcpSocket, timeout_msecs: uint)
-> result::Result<~[u8],TcpErrData> {
let socket_data: *TcpSocketData = &*sock.socket_data;
read_common_impl(socket_data, timeout_msecs)
}
/**
* Reads a single chunk of data; returns a `future::Future<~[u8]>`
* immediately
*
* Does a non-blocking read operation for a single chunk of data from a
* `TcpSocket` and immediately returns a `Future` value representing the
* result. When resolving the returned `Future`, it will block until data
* arrives or an error is received. The provided `timeout_msecs`
* value is used to raise an error if the timeout period passes without any
* data received.
*
* # Safety
*
* This function can produce unsafe results if the call to `read_future` is
* made, the `future::Future` value returned is never resolved via
* `Future::get`, and then the `TcpSocket` passed in to `read_future` leaves
* scope and is destructed before the task that runs the libuv read
* operation completes.
*
* As such: If using `read_future`, always be sure to resolve the returned
* `Future` so as to ensure libuv doesn't try to access a released read
* handle. Otherwise, use the blocking `tcp::read` function instead.
*
* # Arguments
*
* * `sock` - a `net::tcp::TcpSocket` that you wish to read from
* * `timeout_msecs` - a `uint` value, in msecs, to wait before dropping the
* read attempt. Pass `0u` to wait indefinitely
*/
fn read_future(sock: &TcpSocket, timeout_msecs: uint)
-> future::Future<result::Result<~[u8],TcpErrData>> {
let socket_data: *TcpSocketData = &*sock.socket_data;
do future_spawn {
read_common_impl(socket_data, timeout_msecs)
}
}
/**
* Bind an incoming client connection to a `net::tcp::TcpSocket`
*
* # Notes
*
* It is safe to call `net::tcp::accept` _only_ within the context of the
* `new_connect_cb` callback provided as the final argument to the
* `net::tcp::listen` function.
*
* The `new_conn` opaque value is provided _only_ as the first argument to the
* `new_connect_cb` provided as a part of `net::tcp::listen`.
* It can be safely sent to another task but it _must_ be
* used (via `net::tcp::accept`) before the `new_connect_cb` call it was
* provided to returns.
*
* This implies that a port/chan pair must be used to make sure that the
* `new_connect_cb` call blocks until an attempt to create a
* `net::tcp::TcpSocket` is completed.
*
* # Example
*
* Here, the `new_conn` is used in conjunction with `accept` from within
* a task spawned by the `new_connect_cb` passed into `listen`
*
* ~~~~~~~~~~~
* do net::tcp::listen(remote_ip, remote_port, backlog, iotask,
* // this callback is ran once after the connection is successfully
* // set up
* |kill_ch| {
* // pass the kill_ch to your main loop or wherever you want
* // to be able to externally kill the server from
* })
* // this callback is ran when a new connection arrives
* |new_conn, kill_ch| {
* let (cont_po, cont_ch) = comm::stream::<option::Option<TcpErrData>>();
* do task::spawn {
* let accept_result = net::tcp::accept(new_conn);
* match accept_result {
* Err(accept_error) => {
* cont_ch.send(Some(accept_error));
* // fail?
* },
* Ok(sock) => {
* cont_ch.send(None);
* // do work here
* }
* }
* };
* match cont_po.recv() {
* // shut down listen()
* Some(err_data) => kill_ch.send(Some(err_data)),
* // wait for next connection
* None => ()
* }
* };
* ~~~~~~~~~~~
*
* # Arguments
*
* * `new_conn` - an opaque value used to create a new `TcpSocket`
*
* # Returns
*
* On success, this function will return a `net::tcp::TcpSocket` as the
* `Ok` variant of a `Result`. The `net::tcp::TcpSocket` is anchored within
* the task that `accept` was called within for its lifetime. On failure,
* this function will return a `net::tcp::TcpErrData` record
* as the `Err` variant of a `Result`.
*/
pub fn accept(new_conn: TcpNewConnection)
-> result::Result<TcpSocket, TcpErrData> {
unsafe {
match new_conn{
NewTcpConn(server_handle_ptr) => {
let server_data_ptr = uv::ll::get_data_for_uv_handle(
server_handle_ptr) as *TcpListenFcData;
let (reader_po, reader_ch) = stream::<
Result<~[u8], TcpErrData>>();
let reader_ch = SharedChan::new(reader_ch);
let iotask = &(*server_data_ptr).iotask;
let stream_handle_ptr = malloc_uv_tcp_t();
*(stream_handle_ptr as *mut uv::ll::uv_tcp_t) =
uv::ll::tcp_t();
let client_socket_data: @TcpSocketData = @TcpSocketData {
reader_po: @reader_po,
reader_ch: reader_ch,
stream_handle_ptr : stream_handle_ptr,
connect_req : uv::ll::connect_t(),
write_req : uv::ll::write_t(),
ipv6: (*server_data_ptr).ipv6,
iotask : iotask.clone()
};
let client_socket_data_ptr: *TcpSocketData =
&*client_socket_data;
let client_stream_handle_ptr =
(*client_socket_data_ptr).stream_handle_ptr;
let (result_po, result_ch) = stream::<Option<TcpErrData>>();
let result_ch = SharedChan::new(result_ch);
// UNSAFE LIBUV INTERACTION BEGIN
// .. normally this happens within the context of
// a call to uv::hl::interact.. but we're breaking
// the rules here because this always has to be
// called within the context of a listen() new_connect_cb
// callback (or it will likely fail and drown your cat)
debug!("in interact cb for tcp::accept");
let loop_ptr = uv::ll::get_loop_for_uv_handle(
server_handle_ptr);
match uv::ll::tcp_init(loop_ptr, client_stream_handle_ptr) {
0i32 => {
debug!("uv_tcp_init successful for \
client stream");
match uv::ll::accept(
server_handle_ptr as *libc::c_void,
client_stream_handle_ptr as *libc::c_void) {
0i32 => {
debug!("successfully accepted client \
connection: \
stream %x, \
socket data %x",
client_stream_handle_ptr as uint,
client_socket_data_ptr as uint);
uv::ll::set_data_for_uv_handle(
client_stream_handle_ptr,
client_socket_data_ptr
as *libc::c_void);
let ptr = uv::ll::get_data_for_uv_handle(
client_stream_handle_ptr);
debug!("ptrs: %x %x",
client_socket_data_ptr as uint,
ptr as uint);
result_ch.send(None);
}
_ => {
debug!("failed to accept client conn");
result_ch.send(Some(
uv::ll::get_last_err_data(
loop_ptr).to_tcp_err()));
}
}
}
_ => {
debug!("failed to accept client stream");
result_ch.send(Some(
uv::ll::get_last_err_data(
loop_ptr).to_tcp_err()));
}
}
// UNSAFE LIBUV INTERACTION END
match result_po.recv() {
Some(copy err_data) => result::Err(err_data),
None => result::Ok(TcpSocket(client_socket_data))
}
}
}
}
}
/**
* Bind to a given IP/port and listen for new connections
*
* # Arguments
*
* * `host_ip` - a `net::ip::IpAddr` representing a unique IP
* (versions 4 or 6)
* * `port` - a uint representing the port to listen on
* * `backlog` - a uint representing the number of incoming connections
* to cache in memory
* * `hl_loop` - a `uv_iotask::IoTask` that the tcp request will run on
* * `on_establish_cb` - a callback that is evaluated if/when the listener
* is successfully established. it takes no parameters
* * `new_connect_cb` - a callback to be evaluated, on the libuv thread,
* whenever a client attempts to conect on the provided ip/port. the
* callback's arguments are:
* * `new_conn` - an opaque type that can be passed to
* `net::tcp::accept` in order to be converted to a `TcpSocket`.
* * `kill_ch` - channel of type `core::comm::Chan<Option<tcp_err_data>>`.
* this channel can be used to send a message to cause `listen` to begin
* closing the underlying libuv data structures.
*
* # returns
*
* a `Result` instance containing empty data of type `()` on a
* successful/normal shutdown, and a `TcpListenErrData` enum in the event
* of listen exiting because of an error
*/
pub fn listen(host_ip: ip::IpAddr, port: uint, backlog: uint,
iotask: &IoTask,
on_establish_cb: ~fn(SharedChan<Option<TcpErrData>>),
new_connect_cb: ~fn(TcpNewConnection,
SharedChan<Option<TcpErrData>>))
-> result::Result<(), TcpListenErrData> {
do listen_common(host_ip, port, backlog, iotask,
on_establish_cb)
// on_connect_cb
|handle| {
unsafe {
let server_data_ptr = uv::ll::get_data_for_uv_handle(handle)
as *TcpListenFcData;
let new_conn = NewTcpConn(handle);
let kill_ch = (*server_data_ptr).kill_ch.clone();
new_connect_cb(new_conn, kill_ch);
}
}
}
fn listen_common(host_ip: ip::IpAddr,
port: uint,
backlog: uint,
iotask: &IoTask,
on_establish_cb: ~fn(SharedChan<Option<TcpErrData>>),
on_connect_cb: ~fn(*uv::ll::uv_tcp_t))
-> result::Result<(), TcpListenErrData> {
let (stream_closed_po, stream_closed_ch) = stream::<()>();
let stream_closed_ch = SharedChan::new(stream_closed_ch);
let (kill_po, kill_ch) = stream::<Option<TcpErrData>>();
let kill_ch = SharedChan::new(kill_ch);
let server_stream = uv::ll::tcp_t();
let server_stream_ptr: *uv::ll::uv_tcp_t = &server_stream;
let server_data: TcpListenFcData = TcpListenFcData {
server_stream_ptr: server_stream_ptr,
stream_closed_ch: stream_closed_ch,
kill_ch: kill_ch.clone(),
on_connect_cb: on_connect_cb,
iotask: iotask.clone(),
ipv6: match &host_ip {
&ip::Ipv4(_) => { false }
&ip::Ipv6(_) => { true }
},
mut active: true
};
let server_data_ptr: *TcpListenFcData = &server_data;
let (setup_po, setup_ch) = stream();
// this is to address a compiler warning about
// an implicit copy.. it seems that double nested
// will defeat a move sigil, as is done to the host_ip
// arg above.. this same pattern works w/o complaint in
// tcp::connect (because the iotask::interact cb isn't
// nested within a core::comm::listen block)
let loc_ip = copy(host_ip);
do iotask::interact(iotask) |loop_ptr| {
unsafe {
match uv::ll::tcp_init(loop_ptr, server_stream_ptr) {
0i32 => {
uv::ll::set_data_for_uv_handle(
server_stream_ptr,
server_data_ptr);
let addr_str = ip::format_addr(&loc_ip);
let bind_result = match loc_ip {
ip::Ipv4(ref addr) => {
debug!("addr: %?", addr);
let in_addr = uv::ll::ip4_addr(
addr_str,
port as int);
uv::ll::tcp_bind(server_stream_ptr, &in_addr)
}
ip::Ipv6(ref addr) => {
debug!("addr: %?", addr);
let in_addr = uv::ll::ip6_addr(
addr_str,
port as int);
uv::ll::tcp_bind6(server_stream_ptr, &in_addr)
}
};
match bind_result {
0i32 => {
match uv::ll::listen(
server_stream_ptr,
backlog as libc::c_int,
tcp_lfc_on_connection_cb) {
0i32 => setup_ch.send(None),
_ => {
debug!(
"failure to uv_tcp_init");
let err_data =
uv::ll::get_last_err_data(
loop_ptr);
setup_ch.send(Some(err_data));
}
}
}
_ => {
debug!("failure to uv_tcp_bind");
let err_data = uv::ll::get_last_err_data(
loop_ptr);
setup_ch.send(Some(err_data));
}
}
}
_ => {
debug!("failure to uv_tcp_bind");
let err_data = uv::ll::get_last_err_data(
loop_ptr);
setup_ch.send(Some(err_data));
}
}
}
}
let setup_result = setup_po.recv();
match setup_result {
Some(ref err_data) => {
do iotask::interact(iotask) |loop_ptr| {
unsafe {
debug!(
"tcp::listen post-kill recv hl interact %?",
loop_ptr);
(*server_data_ptr).active = false;
uv::ll::close(server_stream_ptr, tcp_lfc_close_cb);
}
};
stream_closed_po.recv();
match err_data.err_name {
~"EACCES" => {
debug!("Got EACCES error");
result::Err(AccessDenied)
}
~"EADDRINUSE" => {
debug!("Got EADDRINUSE error");
result::Err(AddressInUse)
}
_ => {
debug!("Got '%s' '%s' libuv error",
err_data.err_name, err_data.err_msg);
result::Err(
GenericListenErr(err_data.err_name,
err_data.err_msg))
}
}
}
None => {
on_establish_cb(kill_ch.clone());
let kill_result = kill_po.recv();
do iotask::interact(iotask) |loop_ptr| {
unsafe {
debug!(
"tcp::listen post-kill recv hl interact %?",
loop_ptr);
(*server_data_ptr).active = false;
uv::ll::close(server_stream_ptr, tcp_lfc_close_cb);
}
};
stream_closed_po.recv();
match kill_result {
// some failure post bind/listen
Some(ref err_data) => result::Err(GenericListenErr(
err_data.err_name,
err_data.err_msg)),
// clean exit
None => result::Ok(())
}
}
}
}
/**
* Convert a `net::tcp::TcpSocket` to a `net::tcp::TcpSocketBuf`.
*
* This function takes ownership of a `net::tcp::TcpSocket`, returning it
* stored within a buffered wrapper, which can be converted to a `io::Reader`
* or `io::Writer`
*
* # Arguments
*
* * `sock` -- a `net::tcp::TcpSocket` that you want to buffer
*
* # Returns
*
* A buffered wrapper that you can cast as an `io::Reader` or `io::Writer`
*/
pub fn socket_buf(sock: TcpSocket) -> TcpSocketBuf {
TcpSocketBuf(@TcpBufferedSocketData {
sock: sock, mut buf: ~[], buf_off: 0
})
}
/// Convenience methods extending `net::tcp::TcpSocket`
pub impl TcpSocket {
pub fn read_start(&self) -> result::Result<@Port<
result::Result<~[u8], TcpErrData>>, TcpErrData> {
read_start(self)
}
pub fn read_stop(&self) ->
result::Result<(), TcpErrData> {
read_stop(self)
}
fn read(&self, timeout_msecs: uint) ->
result::Result<~[u8], TcpErrData> {
read(self, timeout_msecs)
}
fn read_future(&self, timeout_msecs: uint) ->
future::Future<result::Result<~[u8], TcpErrData>> {
read_future(self, timeout_msecs)
}
pub fn write(&self, raw_write_data: ~[u8])
-> result::Result<(), TcpErrData> {
write(self, raw_write_data)
}
pub fn write_future(&self, raw_write_data: ~[u8])
-> future::Future<result::Result<(), TcpErrData>> {
write_future(self, raw_write_data)
}
pub fn get_peer_addr(&self) -> ip::IpAddr {
unsafe {
if self.socket_data.ipv6 {
let addr = uv::ll::ip6_addr("", 0);
uv::ll::tcp_getpeername6(self.socket_data.stream_handle_ptr,
&addr);
ip::Ipv6(addr)
} else {
let addr = uv::ll::ip4_addr("", 0);
uv::ll::tcp_getpeername(self.socket_data.stream_handle_ptr,
&addr);
ip::Ipv4(addr)
}
}
}
}
/// Implementation of `io::Reader` trait for a buffered `net::tcp::TcpSocket`
impl io::Reader for TcpSocketBuf {
fn read(&self, buf: &mut [u8], len: uint) -> uint {
if len == 0 { return 0 }
let mut count: uint = 0;
loop {
assert!(count < len);
// If possible, copy up to `len` bytes from the internal
// `data.buf` into `buf`
let nbuffered = vec::uniq_len(&const self.data.buf) -
self.data.buf_off;
let needed = len - count;
if nbuffered > 0 {
unsafe {
let ncopy = uint::min(nbuffered, needed);
let dst = ptr::mut_offset(
vec::raw::to_mut_ptr(buf), count);
let src = ptr::const_offset(
vec::raw::to_const_ptr(self.data.buf),
self.data.buf_off);
ptr::copy_memory(dst, src, ncopy);
self.data.buf_off += ncopy;
count += ncopy;
}
}
assert!(count <= len);
if count == len {
break;
}
// We copied all the bytes we had in the internal buffer into
// the result buffer, but the caller wants more bytes, so we
// need to read in data from the socket. Note that the internal
// buffer is of no use anymore as we read all bytes from it,
// so we can throw it away.
let read_result = read(&self.data.sock, 0u);
if read_result.is_err() {
let err_data = read_result.get_err();
if err_data.err_name == ~"EOF" {
self.end_of_stream = true;
break;
} else {
debug!("ERROR sock_buf as io::reader.read err %? %?",
err_data.err_name, err_data.err_msg);
// As we have already copied data into result buffer,
// we cannot simply return 0 here. Instead the error
// should show up in a later call to read().
break;
}
}
else {
self.data.buf = result::unwrap(read_result);
self.data.buf_off = 0;
}
}
count
}
fn read_byte(&self) -> int {
loop {
if vec::uniq_len(&const self.data.buf) > self.data.buf_off {
let c = self.data.buf[self.data.buf_off];
self.data.buf_off += 1;
return c as int
}
let read_result = read(&self.data.sock, 0u);
if read_result.is_err() {
let err_data = read_result.get_err();
if err_data.err_name == ~"EOF" {
self.end_of_stream = true;
return -1
} else {
debug!("ERROR sock_buf as io::reader.read err %? %?",
err_data.err_name, err_data.err_msg);
fail!()
}
}
else {
self.data.buf = result::unwrap(read_result);
self.data.buf_off = 0;
}
}
}
fn eof(&self) -> bool {
self.end_of_stream
}
fn seek(&self, dist: int, seek: io::SeekStyle) {
debug!("tcp_socket_buf seek stub %? %?", dist, seek);
// noop
}
fn tell(&self) -> uint {
0u // noop
}
}
/// Implementation of `io::Reader` trait for a buffered `net::tcp::TcpSocket`
impl io::Writer for TcpSocketBuf {
pub fn write(&self, data: &const [u8]) {
unsafe {
let socket_data_ptr: *TcpSocketData =
&(*((*(self.data)).sock).socket_data);
let w_result = write_common_impl(socket_data_ptr,
vec::slice(data,
0,
data.len()).to_vec());
if w_result.is_err() {
let err_data = w_result.get_err();
debug!(
"ERROR sock_buf as io::writer.writer err: %? %?",
err_data.err_name, err_data.err_msg);
}
}
}
fn seek(&self, dist: int, seek: io::SeekStyle) {
debug!("tcp_socket_buf seek stub %? %?", dist, seek);
// noop
}
fn tell(&self) -> uint {
0u
}
fn flush(&self) -> int {
0
}
fn get_type(&self) -> io::WriterType {
io::File
}
}