-
Notifications
You must be signed in to change notification settings - Fork 238
/
handler.rs
3336 lines (3064 loc) · 131 KB
/
handler.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
use std::cell::RefCell;
use std::ffi::{CStr, CString};
use std::fmt;
use std::io::{self, SeekFrom, Write};
use std::path::Path;
use std::ptr;
use std::slice;
use std::str;
use std::time::Duration;
use curl_sys;
use libc::{self, c_char, c_double, c_int, c_long, c_ulong, c_void, size_t};
use socket2::Socket;
use easy::form;
use easy::list;
use easy::windows;
use easy::{Form, List};
use panic;
use Error;
/// A trait for the various callbacks used by libcurl to invoke user code.
///
/// This trait represents all operations that libcurl can possibly invoke a
/// client for code during an HTTP transaction. Each callback has a default
/// "noop" implementation, the same as in libcurl. Types implementing this trait
/// may simply override the relevant functions to learn about the callbacks
/// they're interested in.
///
/// # Examples
///
/// ```
/// use curl::easy::{Easy2, Handler, WriteError};
///
/// struct Collector(Vec<u8>);
///
/// impl Handler for Collector {
/// fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
/// self.0.extend_from_slice(data);
/// Ok(data.len())
/// }
/// }
///
/// let mut easy = Easy2::new(Collector(Vec::new()));
/// easy.get(true).unwrap();
/// easy.url("https://www.rust-lang.org/").unwrap();
/// easy.perform().unwrap();
///
/// assert_eq!(easy.response_code().unwrap(), 200);
/// let contents = easy.get_ref();
/// println!("{}", String::from_utf8_lossy(&contents.0));
/// ```
pub trait Handler {
/// Callback invoked whenever curl has downloaded data for the application.
///
/// This callback function gets called by libcurl as soon as there is data
/// received that needs to be saved.
///
/// The callback function will be passed as much data as possible in all
/// invokes, but you must not make any assumptions. It may be one byte, it
/// may be thousands. If `show_header` is enabled, which makes header data
/// get passed to the write callback, you can get up to
/// `CURL_MAX_HTTP_HEADER` bytes of header data passed into it. This
/// usually means 100K.
///
/// This function may be called with zero bytes data if the transferred file
/// is empty.
///
/// The callback should return the number of bytes actually taken care of.
/// If that amount differs from the amount passed to your callback function,
/// it'll signal an error condition to the library. This will cause the
/// transfer to get aborted and the libcurl function used will return
/// an error with `is_write_error`.
///
/// If your callback function returns `Err(WriteError::Pause)` it will cause
/// this transfer to become paused. See `unpause_write` for further details.
///
/// By default data is sent into the void, and this corresponds to the
/// `CURLOPT_WRITEFUNCTION` and `CURLOPT_WRITEDATA` options.
fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
Ok(data.len())
}
/// Read callback for data uploads.
///
/// This callback function gets called by libcurl as soon as it needs to
/// read data in order to send it to the peer - like if you ask it to upload
/// or post data to the server.
///
/// Your function must then return the actual number of bytes that it stored
/// in that memory area. Returning 0 will signal end-of-file to the library
/// and cause it to stop the current transfer.
///
/// If you stop the current transfer by returning 0 "pre-maturely" (i.e
/// before the server expected it, like when you've said you will upload N
/// bytes and you upload less than N bytes), you may experience that the
/// server "hangs" waiting for the rest of the data that won't come.
///
/// The read callback may return `Err(ReadError::Abort)` to stop the
/// current operation immediately, resulting in a `is_aborted_by_callback`
/// error code from the transfer.
///
/// The callback can return `Err(ReadError::Pause)` to cause reading from
/// this connection to pause. See `unpause_read` for further details.
///
/// By default data not input, and this corresponds to the
/// `CURLOPT_READFUNCTION` and `CURLOPT_READDATA` options.
///
/// Note that the lifetime bound on this function is `'static`, but that
/// is often too restrictive. To use stack data consider calling the
/// `transfer` method and then using `read_function` to configure a
/// callback that can reference stack-local data.
fn read(&mut self, data: &mut [u8]) -> Result<usize, ReadError> {
drop(data);
Ok(0)
}
/// User callback for seeking in input stream.
///
/// This function gets called by libcurl to seek to a certain position in
/// the input stream and can be used to fast forward a file in a resumed
/// upload (instead of reading all uploaded bytes with the normal read
/// function/callback). It is also called to rewind a stream when data has
/// already been sent to the server and needs to be sent again. This may
/// happen when doing a HTTP PUT or POST with a multi-pass authentication
/// method, or when an existing HTTP connection is reused too late and the
/// server closes the connection.
///
/// The callback function must return `SeekResult::Ok` on success,
/// `SeekResult::Fail` to cause the upload operation to fail or
/// `SeekResult::CantSeek` to indicate that while the seek failed, libcurl
/// is free to work around the problem if possible. The latter can sometimes
/// be done by instead reading from the input or similar.
///
/// By default data this option is not set, and this corresponds to the
/// `CURLOPT_SEEKFUNCTION` and `CURLOPT_SEEKDATA` options.
fn seek(&mut self, whence: SeekFrom) -> SeekResult {
drop(whence);
SeekResult::CantSeek
}
/// Specify a debug callback
///
/// `debug_function` replaces the standard debug function used when
/// `verbose` is in effect. This callback receives debug information,
/// as specified in the type argument.
///
/// By default this option is not set and corresponds to the
/// `CURLOPT_DEBUGFUNCTION` and `CURLOPT_DEBUGDATA` options.
fn debug(&mut self, kind: InfoType, data: &[u8]) {
debug(kind, data)
}
/// Callback that receives header data
///
/// This function gets called by libcurl as soon as it has received header
/// data. The header callback will be called once for each header and only
/// complete header lines are passed on to the callback. Parsing headers is
/// very easy using this. If this callback returns `false` it'll signal an
/// error to the library. This will cause the transfer to get aborted and
/// the libcurl function in progress will return `is_write_error`.
///
/// A complete HTTP header that is passed to this function can be up to
/// CURL_MAX_HTTP_HEADER (100K) bytes.
///
/// It's important to note that the callback will be invoked for the headers
/// of all responses received after initiating a request and not just the
/// final response. This includes all responses which occur during
/// authentication negotiation. If you need to operate on only the headers
/// from the final response, you will need to collect headers in the
/// callback yourself and use HTTP status lines, for example, to delimit
/// response boundaries.
///
/// When a server sends a chunked encoded transfer, it may contain a
/// trailer. That trailer is identical to a HTTP header and if such a
/// trailer is received it is passed to the application using this callback
/// as well. There are several ways to detect it being a trailer and not an
/// ordinary header: 1) it comes after the response-body. 2) it comes after
/// the final header line (CR LF) 3) a Trailer: header among the regular
/// response-headers mention what header(s) to expect in the trailer.
///
/// For non-HTTP protocols like FTP, POP3, IMAP and SMTP this function will
/// get called with the server responses to the commands that libcurl sends.
///
/// By default this option is not set and corresponds to the
/// `CURLOPT_HEADERFUNCTION` and `CURLOPT_HEADERDATA` options.
fn header(&mut self, data: &[u8]) -> bool {
drop(data);
true
}
/// Callback to progress meter function
///
/// This function gets called by libcurl instead of its internal equivalent
/// with a frequent interval. While data is being transferred it will be
/// called very frequently, and during slow periods like when nothing is
/// being transferred it can slow down to about one call per second.
///
/// The callback gets told how much data libcurl will transfer and has
/// transferred, in number of bytes. The first argument is the total number
/// of bytes libcurl expects to download in this transfer. The second
/// argument is the number of bytes downloaded so far. The third argument is
/// the total number of bytes libcurl expects to upload in this transfer.
/// The fourth argument is the number of bytes uploaded so far.
///
/// Unknown/unused argument values passed to the callback will be set to
/// zero (like if you only download data, the upload size will remain 0).
/// Many times the callback will be called one or more times first, before
/// it knows the data sizes so a program must be made to handle that.
///
/// Returning `false` from this callback will cause libcurl to abort the
/// transfer and return `is_aborted_by_callback`.
///
/// If you transfer data with the multi interface, this function will not be
/// called during periods of idleness unless you call the appropriate
/// libcurl function that performs transfers.
///
/// `progress` must be set to `true` to make this function actually get
/// called.
///
/// By default this function calls an internal method and corresponds to
/// `CURLOPT_PROGRESSFUNCTION` and `CURLOPT_PROGRESSDATA`.
fn progress(&mut self, dltotal: f64, dlnow: f64, ultotal: f64, ulnow: f64) -> bool {
drop((dltotal, dlnow, ultotal, ulnow));
true
}
/// Callback to SSL context
///
/// This callback function gets called by libcurl just before the
/// initialization of an SSL connection after having processed all
/// other SSL related options to give a last chance to an
/// application to modify the behaviour of the SSL
/// initialization. The `ssl_ctx` parameter is actually a pointer
/// to the SSL library's SSL_CTX. If an error is returned from the
/// callback no attempt to establish a connection is made and the
/// perform operation will return the callback's error code.
///
/// This function will get called on all new connections made to a
/// server, during the SSL negotiation. The SSL_CTX pointer will
/// be a new one every time.
///
/// To use this properly, a non-trivial amount of knowledge of
/// your SSL library is necessary. For example, you can use this
/// function to call library-specific callbacks to add additional
/// validation code for certificates, and even to change the
/// actual URI of a HTTPS request.
///
/// By default this function calls an internal method and
/// corresponds to `CURLOPT_SSL_CTX_FUNCTION` and
/// `CURLOPT_SSL_CTX_DATA`.
///
/// Note that this callback is not guaranteed to be called, not all versions
/// of libcurl support calling this callback.
fn ssl_ctx(&mut self, cx: *mut c_void) -> Result<(), Error> {
// By default, if we're on an OpenSSL enabled libcurl and we're on
// Windows, add the system's certificate store to OpenSSL's certificate
// store.
ssl_ctx(cx)
}
/// Callback to open sockets for libcurl.
///
/// This callback function gets called by libcurl instead of the socket(2)
/// call. The callback function should return the newly created socket
/// or `None` in case no connection could be established or another
/// error was detected. Any additional `setsockopt(2)` calls can of course
/// be done on the socket at the user's discretion. A `None` return
/// value from the callback function will signal an unrecoverable error to
/// libcurl and it will return `is_couldnt_connect` from the function that
/// triggered this callback.
///
/// By default this function opens a standard socket and
/// corresponds to `CURLOPT_OPENSOCKETFUNCTION `.
fn open_socket(
&mut self,
family: c_int,
socktype: c_int,
protocol: c_int,
) -> Option<curl_sys::curl_socket_t> {
// Note that we override this to calling a function in `socket2` to
// ensure that we open all sockets with CLOEXEC. Otherwise if we rely on
// libcurl to open sockets it won't use CLOEXEC.
return Socket::new(family.into(), socktype.into(), Some(protocol.into()))
.ok()
.map(cvt);
#[cfg(unix)]
fn cvt(socket: Socket) -> curl_sys::curl_socket_t {
use std::os::unix::prelude::*;
socket.into_raw_fd()
}
#[cfg(windows)]
fn cvt(socket: Socket) -> curl_sys::curl_socket_t {
use std::os::windows::prelude::*;
socket.into_raw_socket()
}
}
}
pub fn debug(kind: InfoType, data: &[u8]) {
let out = io::stderr();
let prefix = match kind {
InfoType::Text => "*",
InfoType::HeaderIn => "<",
InfoType::HeaderOut => ">",
InfoType::DataIn | InfoType::SslDataIn => "{",
InfoType::DataOut | InfoType::SslDataOut => "}",
};
let mut out = out.lock();
drop(write!(out, "{} ", prefix));
match str::from_utf8(data) {
Ok(s) => drop(out.write_all(s.as_bytes())),
Err(_) => drop(writeln!(out, "({} bytes of data)", data.len())),
}
}
pub fn ssl_ctx(cx: *mut c_void) -> Result<(), Error> {
windows::add_certs_to_context(cx);
Ok(())
}
/// Raw bindings to a libcurl "easy session".
///
/// This type corresponds to the `CURL` type in libcurl, and is probably what
/// you want for just sending off a simple HTTP request and fetching a response.
/// Each easy handle can be thought of as a large builder before calling the
/// final `perform` function.
///
/// There are many many configuration options for each `Easy2` handle, and they
/// should all have their own documentation indicating what it affects and how
/// it interacts with other options. Some implementations of libcurl can use
/// this handle to interact with many different protocols, although by default
/// this crate only guarantees the HTTP/HTTPS protocols working.
///
/// Note that almost all methods on this structure which configure various
/// properties return a `Result`. This is largely used to detect whether the
/// underlying implementation of libcurl actually implements the option being
/// requested. If you're linked to a version of libcurl which doesn't support
/// the option, then an error will be returned. Some options also perform some
/// validation when they're set, and the error is returned through this vector.
///
/// Note that historically this library contained an `Easy` handle so this one's
/// called `Easy2`. The major difference between the `Easy` type is that an
/// `Easy2` structure uses a trait instead of closures for all of the callbacks
/// that curl can invoke. The `Easy` type is actually built on top of this
/// `Easy` type, and this `Easy2` type can be more flexible in some situations
/// due to the generic parameter.
///
/// There's not necessarily a right answer for which type is correct to use, but
/// as a general rule of thumb `Easy` is typically a reasonable choice for
/// synchronous I/O and `Easy2` is a good choice for asynchronous I/O.
///
/// # Examples
///
/// ```
/// use curl::easy::{Easy2, Handler, WriteError};
///
/// struct Collector(Vec<u8>);
///
/// impl Handler for Collector {
/// fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> {
/// self.0.extend_from_slice(data);
/// Ok(data.len())
/// }
/// }
///
/// let mut easy = Easy2::new(Collector(Vec::new()));
/// easy.get(true).unwrap();
/// easy.url("https://www.rust-lang.org/").unwrap();
/// easy.perform().unwrap();
///
/// assert_eq!(easy.response_code().unwrap(), 200);
/// let contents = easy.get_ref();
/// println!("{}", String::from_utf8_lossy(&contents.0));
/// ```
pub struct Easy2<H> {
inner: Box<Inner<H>>,
}
struct Inner<H> {
handle: *mut curl_sys::CURL,
header_list: Option<List>,
resolve_list: Option<List>,
connect_to_list: Option<List>,
form: Option<Form>,
error_buf: RefCell<Vec<u8>>,
handler: H,
}
unsafe impl<H: Send> Send for Inner<H> {}
/// Possible proxy types that libcurl currently understands.
#[non_exhaustive]
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy)]
pub enum ProxyType {
Http = curl_sys::CURLPROXY_HTTP as isize,
Http1 = curl_sys::CURLPROXY_HTTP_1_0 as isize,
Socks4 = curl_sys::CURLPROXY_SOCKS4 as isize,
Socks5 = curl_sys::CURLPROXY_SOCKS5 as isize,
Socks4a = curl_sys::CURLPROXY_SOCKS4A as isize,
Socks5Hostname = curl_sys::CURLPROXY_SOCKS5_HOSTNAME as isize,
}
/// Possible conditions for the `time_condition` method.
#[non_exhaustive]
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy)]
pub enum TimeCondition {
None = curl_sys::CURL_TIMECOND_NONE as isize,
IfModifiedSince = curl_sys::CURL_TIMECOND_IFMODSINCE as isize,
IfUnmodifiedSince = curl_sys::CURL_TIMECOND_IFUNMODSINCE as isize,
LastModified = curl_sys::CURL_TIMECOND_LASTMOD as isize,
}
/// Possible values to pass to the `ip_resolve` method.
#[non_exhaustive]
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy)]
pub enum IpResolve {
V4 = curl_sys::CURL_IPRESOLVE_V4 as isize,
V6 = curl_sys::CURL_IPRESOLVE_V6 as isize,
Any = curl_sys::CURL_IPRESOLVE_WHATEVER as isize,
}
/// Possible values to pass to the `http_version` method.
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum HttpVersion {
/// We don't care what http version to use, and we'd like the library to
/// choose the best possible for us.
Any = curl_sys::CURL_HTTP_VERSION_NONE as isize,
/// Please use HTTP 1.0 in the request
V10 = curl_sys::CURL_HTTP_VERSION_1_0 as isize,
/// Please use HTTP 1.1 in the request
V11 = curl_sys::CURL_HTTP_VERSION_1_1 as isize,
/// Please use HTTP 2 in the request
/// (Added in CURL 7.33.0)
V2 = curl_sys::CURL_HTTP_VERSION_2_0 as isize,
/// Use version 2 for HTTPS, version 1.1 for HTTP
/// (Added in CURL 7.47.0)
V2TLS = curl_sys::CURL_HTTP_VERSION_2TLS as isize,
/// Please use HTTP 2 without HTTP/1.1 Upgrade
/// (Added in CURL 7.49.0)
V2PriorKnowledge = curl_sys::CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE as isize,
/// Setting this value will make libcurl attempt to use HTTP/3 directly to
/// server given in the URL. Note that this cannot gracefully downgrade to
/// earlier HTTP version if the server doesn't support HTTP/3.
///
/// For more reliably upgrading to HTTP/3, set the preferred version to
/// something lower and let the server announce its HTTP/3 support via
/// Alt-Svc:.
///
/// (Added in CURL 7.66.0)
V3 = curl_sys::CURL_HTTP_VERSION_3 as isize,
}
/// Possible values to pass to the `ssl_version` and `ssl_min_max_version` method.
#[non_exhaustive]
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy)]
pub enum SslVersion {
Default = curl_sys::CURL_SSLVERSION_DEFAULT as isize,
Tlsv1 = curl_sys::CURL_SSLVERSION_TLSv1 as isize,
Sslv2 = curl_sys::CURL_SSLVERSION_SSLv2 as isize,
Sslv3 = curl_sys::CURL_SSLVERSION_SSLv3 as isize,
Tlsv10 = curl_sys::CURL_SSLVERSION_TLSv1_0 as isize,
Tlsv11 = curl_sys::CURL_SSLVERSION_TLSv1_1 as isize,
Tlsv12 = curl_sys::CURL_SSLVERSION_TLSv1_2 as isize,
Tlsv13 = curl_sys::CURL_SSLVERSION_TLSv1_3 as isize,
}
/// Possible return values from the `seek_function` callback.
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum SeekResult {
/// Indicates that the seek operation was a success
Ok = curl_sys::CURL_SEEKFUNC_OK as isize,
/// Indicates that the seek operation failed, and the entire request should
/// fail as a result.
Fail = curl_sys::CURL_SEEKFUNC_FAIL as isize,
/// Indicates that although the seek failed libcurl should attempt to keep
/// working if possible (for example "seek" through reading).
CantSeek = curl_sys::CURL_SEEKFUNC_CANTSEEK as isize,
}
/// Possible data chunks that can be witnessed as part of the `debug_function`
/// callback.
#[non_exhaustive]
#[derive(Debug, Clone, Copy)]
pub enum InfoType {
/// The data is informational text.
Text,
/// The data is header (or header-like) data received from the peer.
HeaderIn,
/// The data is header (or header-like) data sent to the peer.
HeaderOut,
/// The data is protocol data received from the peer.
DataIn,
/// The data is protocol data sent to the peer.
DataOut,
/// The data is SSL/TLS (binary) data received from the peer.
SslDataIn,
/// The data is SSL/TLS (binary) data sent to the peer.
SslDataOut,
}
/// Possible error codes that can be returned from the `read_function` callback.
#[non_exhaustive]
#[derive(Debug)]
pub enum ReadError {
/// Indicates that the connection should be aborted immediately
Abort,
/// Indicates that reading should be paused until `unpause` is called.
Pause,
}
/// Possible error codes that can be returned from the `write_function` callback.
#[non_exhaustive]
#[derive(Debug)]
pub enum WriteError {
/// Indicates that reading should be paused until `unpause` is called.
Pause,
}
/// Options for `.netrc` parsing.
#[derive(Debug, Clone, Copy)]
pub enum NetRc {
/// Ignoring `.netrc` file and use information from url
///
/// This option is default
Ignored = curl_sys::CURL_NETRC_IGNORED as isize,
/// The use of your `~/.netrc` file is optional, and information in the URL is to be
/// preferred. The file will be scanned for the host and user name (to find the password only)
/// or for the host only, to find the first user name and password after that machine, which
/// ever information is not specified in the URL.
Optional = curl_sys::CURL_NETRC_OPTIONAL as isize,
/// This value tells the library that use of the file is required, to ignore the information in
/// the URL, and to search the file for the host only.
Required = curl_sys::CURL_NETRC_REQUIRED as isize,
}
/// Structure which stores possible authentication methods to get passed to
/// `http_auth` and `proxy_auth`.
#[derive(Clone)]
pub struct Auth {
bits: c_long,
}
/// Structure which stores possible ssl options to pass to `ssl_options`.
#[derive(Clone)]
pub struct SslOpt {
bits: c_long,
}
impl<H: Handler> Easy2<H> {
/// Creates a new "easy" handle which is the core of almost all operations
/// in libcurl.
///
/// To use a handle, applications typically configure a number of options
/// followed by a call to `perform`. Options are preserved across calls to
/// `perform` and need to be reset manually (or via the `reset` method) if
/// this is not desired.
pub fn new(handler: H) -> Easy2<H> {
::init();
unsafe {
let handle = curl_sys::curl_easy_init();
assert!(!handle.is_null());
let mut ret = Easy2 {
inner: Box::new(Inner {
handle,
header_list: None,
resolve_list: None,
connect_to_list: None,
form: None,
error_buf: RefCell::new(vec![0; curl_sys::CURL_ERROR_SIZE]),
handler,
}),
};
ret.default_configure();
ret
}
}
/// Re-initializes this handle to the default values.
///
/// This puts the handle to the same state as it was in when it was just
/// created. This does, however, keep live connections, the session id
/// cache, the dns cache, and cookies.
pub fn reset(&mut self) {
unsafe {
curl_sys::curl_easy_reset(self.inner.handle);
}
self.default_configure();
}
fn default_configure(&mut self) {
self.setopt_ptr(
curl_sys::CURLOPT_ERRORBUFFER,
self.inner.error_buf.borrow().as_ptr() as *const _,
)
.expect("failed to set error buffer");
let _ = self.signal(false);
self.ssl_configure();
let ptr = &*self.inner as *const _ as *const _;
let cb: extern "C" fn(*mut c_char, size_t, size_t, *mut c_void) -> size_t = header_cb::<H>;
self.setopt_ptr(curl_sys::CURLOPT_HEADERFUNCTION, cb as *const _)
.expect("failed to set header callback");
self.setopt_ptr(curl_sys::CURLOPT_HEADERDATA, ptr)
.expect("failed to set header callback");
let cb: curl_sys::curl_write_callback = write_cb::<H>;
self.setopt_ptr(curl_sys::CURLOPT_WRITEFUNCTION, cb as *const _)
.expect("failed to set write callback");
self.setopt_ptr(curl_sys::CURLOPT_WRITEDATA, ptr)
.expect("failed to set write callback");
let cb: curl_sys::curl_read_callback = read_cb::<H>;
self.setopt_ptr(curl_sys::CURLOPT_READFUNCTION, cb as *const _)
.expect("failed to set read callback");
self.setopt_ptr(curl_sys::CURLOPT_READDATA, ptr)
.expect("failed to set read callback");
let cb: curl_sys::curl_seek_callback = seek_cb::<H>;
self.setopt_ptr(curl_sys::CURLOPT_SEEKFUNCTION, cb as *const _)
.expect("failed to set seek callback");
self.setopt_ptr(curl_sys::CURLOPT_SEEKDATA, ptr)
.expect("failed to set seek callback");
let cb: curl_sys::curl_progress_callback = progress_cb::<H>;
self.setopt_ptr(curl_sys::CURLOPT_PROGRESSFUNCTION, cb as *const _)
.expect("failed to set progress callback");
self.setopt_ptr(curl_sys::CURLOPT_PROGRESSDATA, ptr)
.expect("failed to set progress callback");
let cb: curl_sys::curl_debug_callback = debug_cb::<H>;
self.setopt_ptr(curl_sys::CURLOPT_DEBUGFUNCTION, cb as *const _)
.expect("failed to set debug callback");
self.setopt_ptr(curl_sys::CURLOPT_DEBUGDATA, ptr)
.expect("failed to set debug callback");
let cb: curl_sys::curl_ssl_ctx_callback = ssl_ctx_cb::<H>;
drop(self.setopt_ptr(curl_sys::CURLOPT_SSL_CTX_FUNCTION, cb as *const _));
drop(self.setopt_ptr(curl_sys::CURLOPT_SSL_CTX_DATA, ptr));
let cb: curl_sys::curl_opensocket_callback = opensocket_cb::<H>;
self.setopt_ptr(curl_sys::CURLOPT_OPENSOCKETFUNCTION, cb as *const _)
.expect("failed to set open socket callback");
self.setopt_ptr(curl_sys::CURLOPT_OPENSOCKETDATA, ptr)
.expect("failed to set open socket callback");
}
#[cfg(need_openssl_probe)]
fn ssl_configure(&mut self) {
let probe = ::openssl_probe::probe();
if let Some(ref path) = probe.cert_file {
let _ = self.cainfo(path);
}
if let Some(ref path) = probe.cert_dir {
let _ = self.capath(path);
}
}
#[cfg(not(need_openssl_probe))]
fn ssl_configure(&mut self) {}
}
impl<H> Easy2<H> {
// =========================================================================
// Behavior options
/// Configures this handle to have verbose output to help debug protocol
/// information.
///
/// By default output goes to stderr, but the `stderr` function on this type
/// can configure that. You can also use the `debug_function` method to get
/// all protocol data sent and received.
///
/// By default, this option is `false`.
pub fn verbose(&mut self, verbose: bool) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_VERBOSE, verbose as c_long)
}
/// Indicates whether header information is streamed to the output body of
/// this request.
///
/// This option is only relevant for protocols which have header metadata
/// (like http or ftp). It's not generally possible to extract headers
/// from the body if using this method, that use case should be intended for
/// the `header_function` method.
///
/// To set HTTP headers, use the `http_header` method.
///
/// By default, this option is `false` and corresponds to
/// `CURLOPT_HEADER`.
pub fn show_header(&mut self, show: bool) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_HEADER, show as c_long)
}
/// Indicates whether a progress meter will be shown for requests done with
/// this handle.
///
/// This will also prevent the `progress_function` from being called.
///
/// By default this option is `false` and corresponds to
/// `CURLOPT_NOPROGRESS`.
pub fn progress(&mut self, progress: bool) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_NOPROGRESS, (!progress) as c_long)
}
/// Inform libcurl whether or not it should install signal handlers or
/// attempt to use signals to perform library functions.
///
/// If this option is disabled then timeouts during name resolution will not
/// work unless libcurl is built against c-ares. Note that enabling this
/// option, however, may not cause libcurl to work with multiple threads.
///
/// By default this option is `false` and corresponds to `CURLOPT_NOSIGNAL`.
/// Note that this default is **different than libcurl** as it is intended
/// that this library is threadsafe by default. See the [libcurl docs] for
/// some more information.
///
/// [libcurl docs]: https://curl.haxx.se/libcurl/c/threadsafe.html
pub fn signal(&mut self, signal: bool) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_NOSIGNAL, (!signal) as c_long)
}
/// Indicates whether multiple files will be transferred based on the file
/// name pattern.
///
/// The last part of a filename uses fnmatch-like pattern matching.
///
/// By default this option is `false` and corresponds to
/// `CURLOPT_WILDCARDMATCH`.
pub fn wildcard_match(&mut self, m: bool) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_WILDCARDMATCH, m as c_long)
}
/// Provides the Unix domain socket which this handle will work with.
///
/// The string provided must be a path to a Unix domain socket encoded with
/// the format:
///
/// ```text
/// /path/file.sock
/// ```
///
/// By default this option is not set and corresponds to
/// [`CURLOPT_UNIX_SOCKET_PATH`](https://curl.haxx.se/libcurl/c/CURLOPT_UNIX_SOCKET_PATH.html).
pub fn unix_socket(&mut self, unix_domain_socket: &str) -> Result<(), Error> {
let socket = CString::new(unix_domain_socket)?;
self.setopt_str(curl_sys::CURLOPT_UNIX_SOCKET_PATH, &socket)
}
/// Provides the Unix domain socket which this handle will work with.
///
/// The string provided must be a path to a Unix domain socket encoded with
/// the format:
///
/// ```text
/// /path/file.sock
/// ```
///
/// This function is an alternative to [`Easy2::unix_socket`] that supports
/// non-UTF-8 paths and also supports disabling Unix sockets by setting the
/// option to `None`.
///
/// By default this option is not set and corresponds to
/// [`CURLOPT_UNIX_SOCKET_PATH`](https://curl.haxx.se/libcurl/c/CURLOPT_UNIX_SOCKET_PATH.html).
pub fn unix_socket_path<P: AsRef<Path>>(&mut self, path: Option<P>) -> Result<(), Error> {
if let Some(path) = path {
self.setopt_path(curl_sys::CURLOPT_UNIX_SOCKET_PATH, path.as_ref())
} else {
self.setopt_ptr(curl_sys::CURLOPT_UNIX_SOCKET_PATH, 0 as _)
}
}
// =========================================================================
// Internal accessors
/// Acquires a reference to the underlying handler for events.
pub fn get_ref(&self) -> &H {
&self.inner.handler
}
/// Acquires a reference to the underlying handler for events.
pub fn get_mut(&mut self) -> &mut H {
&mut self.inner.handler
}
// =========================================================================
// Error options
// TODO: error buffer and stderr
/// Indicates whether this library will fail on HTTP response codes >= 400.
///
/// This method is not fail-safe especially when authentication is involved.
///
/// By default this option is `false` and corresponds to
/// `CURLOPT_FAILONERROR`.
pub fn fail_on_error(&mut self, fail: bool) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_FAILONERROR, fail as c_long)
}
// =========================================================================
// Network options
/// Provides the URL which this handle will work with.
///
/// The string provided must be URL-encoded with the format:
///
/// ```text
/// scheme://host:port/path
/// ```
///
/// The syntax is not validated as part of this function and that is
/// deferred until later.
///
/// By default this option is not set and `perform` will not work until it
/// is set. This option corresponds to `CURLOPT_URL`.
pub fn url(&mut self, url: &str) -> Result<(), Error> {
let url = CString::new(url)?;
self.setopt_str(curl_sys::CURLOPT_URL, &url)
}
/// Configures the port number to connect to, instead of the one specified
/// in the URL or the default of the protocol.
pub fn port(&mut self, port: u16) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_PORT, port as c_long)
}
/// Connect to a specific host and port.
///
/// Each single string should be written using the format
/// `HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT` where `HOST` is the host of
/// the request, `PORT` is the port of the request, `CONNECT-TO-HOST` is the
/// host name to connect to, and `CONNECT-TO-PORT` is the port to connect
/// to.
///
/// The first string that matches the request's host and port is used.
///
/// By default, this option is empty and corresponds to
/// [`CURLOPT_CONNECT_TO`](https://curl.haxx.se/libcurl/c/CURLOPT_CONNECT_TO.html).
pub fn connect_to(&mut self, list: List) -> Result<(), Error> {
let ptr = list::raw(&list);
self.inner.connect_to_list = Some(list);
self.setopt_ptr(curl_sys::CURLOPT_CONNECT_TO, ptr as *const _)
}
// /// Indicates whether sequences of `/../` and `/./` will be squashed or not.
// ///
// /// By default this option is `false` and corresponds to
// /// `CURLOPT_PATH_AS_IS`.
// pub fn path_as_is(&mut self, as_is: bool) -> Result<(), Error> {
// }
/// Provide the URL of a proxy to use.
///
/// By default this option is not set and corresponds to `CURLOPT_PROXY`.
pub fn proxy(&mut self, url: &str) -> Result<(), Error> {
let url = CString::new(url)?;
self.setopt_str(curl_sys::CURLOPT_PROXY, &url)
}
/// Provide port number the proxy is listening on.
///
/// By default this option is not set (the default port for the proxy
/// protocol is used) and corresponds to `CURLOPT_PROXYPORT`.
pub fn proxy_port(&mut self, port: u16) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_PROXYPORT, port as c_long)
}
/// Set CA certificate to verify peer against for proxy.
///
/// By default this value is not set and corresponds to
/// `CURLOPT_PROXY_CAINFO`.
pub fn proxy_cainfo(&mut self, cainfo: &str) -> Result<(), Error> {
let cainfo = CString::new(cainfo)?;
self.setopt_str(curl_sys::CURLOPT_PROXY_CAINFO, &cainfo)
}
/// Specify a directory holding CA certificates for proxy.
///
/// The specified directory should hold multiple CA certificates to verify
/// the HTTPS proxy with. If libcurl is built against OpenSSL, the
/// certificate directory must be prepared using the OpenSSL `c_rehash`
/// utility.
///
/// By default this value is not set and corresponds to
/// `CURLOPT_PROXY_CAPATH`.
pub fn proxy_capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
self.setopt_path(curl_sys::CURLOPT_PROXY_CAPATH, path.as_ref())
}
/// Set client certificate for proxy.
///
/// By default this value is not set and corresponds to
/// `CURLOPT_PROXY_SSLCERT`.
pub fn proxy_sslcert(&mut self, sslcert: &str) -> Result<(), Error> {
let sslcert = CString::new(sslcert)?;
self.setopt_str(curl_sys::CURLOPT_PROXY_SSLCERT, &sslcert)
}
/// Set private key for HTTPS proxy.
///
/// By default this value is not set and corresponds to
/// `CURLOPT_PROXY_SSLKEY`.
pub fn proxy_sslkey(&mut self, sslkey: &str) -> Result<(), Error> {
let sslkey = CString::new(sslkey)?;
self.setopt_str(curl_sys::CURLOPT_PROXY_SSLKEY, &sslkey)
}
/// Indicates the type of proxy being used.
///
/// By default this option is `ProxyType::Http` and corresponds to
/// `CURLOPT_PROXYTYPE`.
pub fn proxy_type(&mut self, kind: ProxyType) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_PROXYTYPE, kind as c_long)
}
/// Provide a list of hosts that should not be proxied to.
///
/// This string is a comma-separated list of hosts which should not use the
/// proxy specified for connections. A single `*` character is also accepted
/// as a wildcard for all hosts.
///
/// By default this option is not set and corresponds to
/// `CURLOPT_NOPROXY`.
pub fn noproxy(&mut self, skip: &str) -> Result<(), Error> {
let skip = CString::new(skip)?;
self.setopt_str(curl_sys::CURLOPT_NOPROXY, &skip)
}
/// Inform curl whether it should tunnel all operations through the proxy.
///
/// This essentially means that a `CONNECT` is sent to the proxy for all
/// outbound requests.
///
/// By default this option is `false` and corresponds to
/// `CURLOPT_HTTPPROXYTUNNEL`.
pub fn http_proxy_tunnel(&mut self, tunnel: bool) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_HTTPPROXYTUNNEL, tunnel as c_long)
}
/// Tell curl which interface to bind to for an outgoing network interface.
///
/// The interface name, IP address, or host name can be specified here.
///
/// By default this option is not set and corresponds to
/// `CURLOPT_INTERFACE`.
pub fn interface(&mut self, interface: &str) -> Result<(), Error> {
let s = CString::new(interface)?;
self.setopt_str(curl_sys::CURLOPT_INTERFACE, &s)
}
/// Indicate which port should be bound to locally for this connection.
///
/// By default this option is 0 (any port) and corresponds to
/// `CURLOPT_LOCALPORT`.
pub fn set_local_port(&mut self, port: u16) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_LOCALPORT, port as c_long)
}
/// Indicates the number of attempts libcurl will perform to find a working
/// port number.
///
/// By default this option is 1 and corresponds to
/// `CURLOPT_LOCALPORTRANGE`.
pub fn local_port_range(&mut self, range: u16) -> Result<(), Error> {
self.setopt_long(curl_sys::CURLOPT_LOCALPORTRANGE, range as c_long)
}
/// Sets the DNS servers that wil be used.
///
/// Provide a comma separated list, for example: `8.8.8.8,8.8.4.4`.
///
/// By default this option is not set and the OS's DNS resolver is used.
/// This option can only be used if libcurl is linked against