diff options
Diffstat (limited to 'vendor/curl')
37 files changed, 11771 insertions, 0 deletions
diff --git a/vendor/curl/.cargo-checksum.json b/vendor/curl/.cargo-checksum.json new file mode 100644 index 000000000..5a650a726 --- /dev/null +++ b/vendor/curl/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"b962b6d0432e37be8d33021aeb1d669b49e0873ff0b56cda44d5a6239d160bfd","Cargo.toml":"98d3050d21376857208565b9d1530d11a7b3f0de0ddb2041a4bc5a6bf31cb386","LICENSE":"f96def8cba2793fb8582fd12ca6d4dc0ef4ee239e8c3f80e809ec43648da6199","README.md":"a47d8409247540d29003509655a4276e7698da8d01073e09f71584e75a73e835","build.rs":"e67a610bb4fe4987f8e7cf0d94c3beb3b70b10a3c24c3c0a606cc4f475a5a2ca","ci/Dockerfile-centos7":"101be5e39036dddbf1d782f5402eebfb17895ea824f459e26fb7967ff6278ca9","ci/Dockerfile-linux32":"e04764084af5d2c09eee38e015305d5e0cdd0f125b870c36e7069d4c5f5919fe","ci/Dockerfile-linux64":"4a59f30fb905e4b9de15094d3dfaa5bc2cce62db6961e6d204de31cbbb436b9a","ci/Dockerfile-linux64-curl":"cf7f6db3940e9dbf4c159daeab741beab34ee37d5a89bc4d7a654032666014df","ci/Dockerfile-mingw":"7fb3093158bbea457b5a6827f337be42b541ea97de851a80e4732b5346b76f05","ci/Dockerfile-musl":"03afb1b28326566a1ee70a66ad0dc5216e6601e642bfbdf120b6403f42786d2a","ci/run.sh":"11fcde0f23450705e1de16eb1fd81fb55ae85883ebb0ea9c659cc289686c54cf","examples/aws_sigv4.rs":"e9238c488f3c9eef6de2bdf737fcfe58b77108f54a5af5001e5f8e7999ec0c7d","examples/doh.rs":"86384fad0a498551498ac0cc2e2afdf0c658321980b8510c088b7f27322ac264","examples/https.rs":"3ef0d44d5d84626df2387c264f3e39c5c7d5e53b8de44a95257cc023dbd4bbac","examples/multi-dl.rs":"82d832cdda8c79c05c387657cdeb540e186251e73dfad575d99e3b13db115c97","examples/ssl_cert_blob.rs":"37cfee0cd85be74be0d08d72737e1328f6b6c3982c8e23f64a37a9500fb858a2","examples/ssl_proxy.rs":"16f97b2cd5211a99b5fbc61ee60f6b80e1f54ecd14117ef7f3ab9c7e651326d2","src/easy/form.rs":"4f3545d1489728b62e04d1d3e29b8cf4777e0f114e4da0f65dad3a90eef1f863","src/easy/handle.rs":"4ba54605ead1b018837de12249afa5d9b3f6ad34f75aede2e28afd238688a33a","src/easy/handler.rs":"223b2d39e34718398d69f816b6da6e6bfc9018965a1204e3017d46ac9d5e0c7a","src/easy/list.rs":"e2ae7f76fc940d3ab69d601905591118b5b711c51dde2028ff62013e1a4d25bc","src/easy/mod.rs":"e3526f22cdfe67460c31834d0ee98b91708e09f757a9868c0e9113439308d2aa","src/easy/windows.rs":"b2fd777ee9e7e68c731673a14bf3bd40ea7d640bfe361fd304408c8dc4311275","src/error.rs":"7666642113c4718cf4387955144bec213179958adfe4447bf0f9b341cf6873c2","src/lib.rs":"c030a8193b14e5050e179ff2a915dd7eb10002166b390383248aac19d618326d","src/multi.rs":"933847b107ab090252a9730671ee3aea485580ddc7b526cd7a1e60a8b12c60ef","src/panic.rs":"add8b1808f445852a858de38a1cda075bb038ffe5e5cef49e7f3e39de97403ba","src/version.rs":"76eb93d915967f35b4ed86979cc6f891a7cdc6e09a0b1615aa5aa4f2859ce662","tests/atexit.rs":"7843e7ba37fe718bca16e603d38e146afb25c1eaa9ab99df703a216cf12bf135","tests/easy.rs":"d86ef516c29a6fc5aec460b2df0f00f3d157bc5e7b187fc2fd7d4054f79d9853","tests/formdata":"5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03","tests/multi.rs":"7672e4f0cc26b31598898323c1a90fb2eea886ea65cb6488936cf6f7ea763ca0","tests/post.rs":"f78325ac6ab251f5cacff660a278e7c20c21f2960ce9036090b0ef513bccfe0b","tests/protocols.rs":"708b37c6d967236f9c626d01e87d0441b6e31dd8a830e1f5fcd614b77ea77e5a","tests/server/mod.rs":"283e1d906659d3942ed55b86f05bbd0ad592f0dfffff0d5c68ef805b380b4d06"},"package":"509bd11746c7ac09ebd19f0b17782eae80aadee26237658a6b4808afb5c11a22"}
\ No newline at end of file diff --git a/vendor/curl/Cargo.lock b/vendor/curl/Cargo.lock new file mode 100644 index 000000000..3c0ccde9f --- /dev/null +++ b/vendor/curl/Cargo.lock @@ -0,0 +1,652 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "anyhow" +version = "1.0.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb07d2053ccdbe10e2af2995a2f116c1330396493dc1269f6a91d0ae82e19704" + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bumpalo" +version = "3.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37ccbd214614c6783386c1af30caf03192f17891059cecc394b4fb119e363de3" + +[[package]] +name = "cc" +version = "1.0.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "cmake" +version = "0.1.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8ad8cef104ac57b68b89df3208164d228503abbdce70f6880ffa3d970e7443a" +dependencies = [ + "cc", +] + +[[package]] +name = "curl" +version = "0.4.44" +dependencies = [ + "anyhow", + "curl-sys", + "libc", + "mio", + "mio-extras", + "openssl-probe", + "openssl-sys", + "schannel", + "socket2", + "winapi 0.3.9", +] + +[[package]] +name = "curl-sys" +version = "0.4.56+curl-7.83.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6093e169dd4de29e468fa649fbae11cdcd5551c81fe5bf1b0677adad7ef3d26f" +dependencies = [ + "cc", + "libc", + "libnghttp2-sys", + "libz-sys", + "openssl-sys", + "pkg-config", + "rustls-ffi", + "vcpkg", + "winapi 0.3.9", +] + +[[package]] +name = "fuchsia-zircon" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +dependencies = [ + "bitflags", + "fuchsia-zircon-sys", +] + +[[package]] +name = "fuchsia-zircon-sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" + +[[package]] +name = "iovec" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e" +dependencies = [ + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3fac17f7123a73ca62df411b1bf727ccc805daa070338fda671c86dac1bdc27" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "kernel32-sys" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "libc" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" + +[[package]] +name = "libnghttp2-sys" +version = "0.1.7+1.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57ed28aba195b38d5ff02b9170cbff627e336a20925e43b4945390401c5dc93f" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "libz-sys" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf" +dependencies = [ + "cc", + "cmake", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if 1.0.0", +] + +[[package]] +name = "mio" +version = "0.6.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4afd66f5b91bf2a3bc13fad0e21caedac168ca4c707504e75585648ae80e4cc4" +dependencies = [ + "cfg-if 0.1.10", + "fuchsia-zircon", + "fuchsia-zircon-sys", + "iovec", + "kernel32-sys", + "libc", + "log", + "miow", + "net2", + "slab", + "winapi 0.2.8", +] + +[[package]] +name = "mio-extras" +version = "2.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52403fe290012ce777c4626790c8951324a2b9e3316b3143779c72b029742f19" +dependencies = [ + "lazycell", + "log", + "mio", + "slab", +] + +[[package]] +name = "miow" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebd808424166322d4a38da87083bfddd3ac4c131334ed55856112eb06d46944d" +dependencies = [ + "kernel32-sys", + "net2", + "winapi 0.2.8", + "ws2_32-sys", +] + +[[package]] +name = "net2" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "391630d12b68002ae1e25e8f974306474966550ad82dac6886fb8910c19568ae" +dependencies = [ + "cfg-if 0.1.10", + "libc", + "winapi 0.3.9", +] + +[[package]] +name = "num_enum" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf5395665662ef45796a4ff5486c5d41d29e0c09640af4c5f17fd94ee2c119c9" +dependencies = [ + "num_enum_derive", +] + +[[package]] +name = "num_enum_derive" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0498641e53dd6ac1a4f22547548caa6864cc4933784319cd1775271c5a46ce" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "once_cell" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18a6dbe30758c9f83eb00cbea4ac95966305f5a7772f3f42ebfc7fc7eddbd8e1" + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-src" +version = "111.22.0+1.1.1q" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f31f0d509d1c1ae9cada2f9539ff8f37933831fd5098879e482aa687d659853" +dependencies = [ + "cc", +] + +[[package]] +name = "openssl-sys" +version = "0.9.75" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5f9bd0c2710541a3cda73d6f9ac4f1b240de4ae261065d309dbe73d9dceb42f" +dependencies = [ + "autocfg", + "cc", + "libc", + "openssl-src", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "pkg-config" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" + +[[package]] +name = "proc-macro-crate" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17d47ce914bf4de440332250b0edd23ce48c005f59fab39d3335866b114f11a" +dependencies = [ + "thiserror", + "toml", +] + +[[package]] +name = "proc-macro2" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd96a1e8ed2596c337f8eae5f24924ec83f5ad5ab21ea8e455d3566c69fbcaf7" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin", + "untrusted", + "web-sys", + "winapi 0.3.9", +] + +[[package]] +name = "rustls" +version = "0.20.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aab8ee6c7097ed6057f43c187a62418d0c05a4bd5f18b3571db50ee0f9ce033" +dependencies = [ + "log", + "ring", + "sct", + "webpki", +] + +[[package]] +name = "rustls-ffi" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da52707cca59e6eef8a78f3ad8d04024254a168ed1b41eb4dfa9616eace781a" +dependencies = [ + "libc", + "log", + "num_enum", + "rustls", + "rustls-pemfile", + "sct", + "webpki", +] + +[[package]] +name = "rustls-pemfile" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eebeaeb360c87bfb72e84abdb3447159c0eaececf1bef2aecd65a8be949d1c9" +dependencies = [ + "base64", +] + +[[package]] +name = "schannel" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d6731146462ea25d9244b2ed5fd1d716d25c52e4d54aa4fb0f3c4e9854dbe2" +dependencies = [ + "lazy_static", + "windows-sys", +] + +[[package]] +name = "sct" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "serde" +version = "1.0.140" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc855a42c7967b7c369eb5860f7164ef1f6f81c20c7cc1141f2a604e18723b03" + +[[package]] +name = "slab" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" +dependencies = [ + "autocfg", +] + +[[package]] +name = "socket2" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0" +dependencies = [ + "libc", + "winapi 0.3.9", +] + +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + +[[package]] +name = "syn" +version = "1.0.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "toml" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +dependencies = [ + "serde", +] + +[[package]] +name = "unicode-ident" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15c61ba63f9235225a22310255a29b806b907c9b8c964bcbd0a2c70f3f2deea7" + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "wasm-bindgen" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c53b543413a17a202f4be280a7e5c62a1c69345f5de525ee64f8cfdbc954994" +dependencies = [ + "cfg-if 1.0.0", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5491a68ab4500fa6b4d726bd67408630c3dbe9c4fe7bda16d5c82a1fd8c7340a" +dependencies = [ + "bumpalo", + "lazy_static", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c441e177922bc58f1e12c022624b6216378e5febc2f0533e41ba443d505b80aa" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d94ac45fcf608c1f45ef53e748d35660f168490c10b23704c7779ab8f5c3048" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a89911bd99e5f3659ec4acf9c4d93b0a90fe4a2a11f15328472058edc5261be" + +[[package]] +name = "web-sys" +version = "0.3.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fed94beee57daf8dd7d51f2b15dc2bcde92d7a72304cdf662a4371008b71b90" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "winapi" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-build" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" +dependencies = [ + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" + +[[package]] +name = "windows_i686_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" + +[[package]] +name = "windows_i686_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" + +[[package]] +name = "ws2_32-sys" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] diff --git a/vendor/curl/Cargo.toml b/vendor/curl/Cargo.toml new file mode 100644 index 000000000..bfb59f457 --- /dev/null +++ b/vendor/curl/Cargo.toml @@ -0,0 +1,124 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "curl" +version = "0.4.44" +authors = ["Alex Crichton <alex@alexcrichton.com>"] +autotests = true +description = "Rust bindings to libcurl for making HTTP requests" +homepage = "https://github.com/alexcrichton/curl-rust" +documentation = "https://docs.rs/curl" +readme = "README.md" +categories = [ + "api-bindings", + "web-programming::http-client", +] +license = "MIT" +repository = "https://github.com/alexcrichton/curl-rust" + +[[example]] +name = "https" +path = "examples/https.rs" + +[[example]] +name = "ssl_proxy" +path = "examples/ssl_proxy.rs" +required-features = ["ssl"] + +[[example]] +name = "ssl_cert_blob" +path = "examples/ssl_cert_blob.rs" +required-features = ["ssl"] + +[[example]] +name = "aws_sigv4" +path = "examples/aws_sigv4.rs" +required-features = [ + "static-curl", + "ssl", +] + +[[example]] +name = "multi-dl" +path = "examples/multi-dl.rs" +required-features = ["ssl"] + +[[test]] +name = "atexit" +harness = false + +[dependencies.curl-sys] +version = "0.4.56" +default-features = false + +[dependencies.libc] +version = "0.2.42" + +[dependencies.socket2] +version = "0.4.0" + +[dev-dependencies.anyhow] +version = "1.0.31" + +[dev-dependencies.mio] +version = "0.6" + +[dev-dependencies.mio-extras] +version = "2.0.3" + +[features] +default = ["ssl"] +force-system-lib-on-osx = ["curl-sys/force-system-lib-on-osx"] +http2 = ["curl-sys/http2"] +mesalink = ["curl-sys/mesalink"] +ntlm = ["curl-sys/ntlm"] +poll_7_68_0 = ["curl-sys/poll_7_68_0"] +protocol-ftp = ["curl-sys/protocol-ftp"] +rustls = ["curl-sys/rustls"] +spnego = ["curl-sys/spnego"] +ssl = [ + "openssl-sys", + "openssl-probe", + "curl-sys/ssl", +] +static-curl = ["curl-sys/static-curl"] +static-ssl = ["curl-sys/static-ssl"] +upkeep_7_62_0 = ["curl-sys/upkeep_7_62_0"] +zlib-ng-compat = [ + "curl-sys/zlib-ng-compat", + "static-curl", +] + +[target."cfg(all(unix, not(target_os = \"macos\")))".dependencies.openssl-probe] +version = "0.1.2" +optional = true + +[target."cfg(all(unix, not(target_os = \"macos\")))".dependencies.openssl-sys] +version = "0.9.43" +optional = true + +[target."cfg(target_env = \"msvc\")".dependencies.schannel] +version = "0.1.13" + +[target."cfg(target_env = \"msvc\")".dependencies.winapi] +version = "0.3" +features = [ + "libloaderapi", + "wincrypt", +] + +[badges.appveyor] +repository = "alexcrichton/curl-rust" + +[badges.travis-ci] +repository = "alexcrichton/curl-rust" diff --git a/vendor/curl/LICENSE b/vendor/curl/LICENSE new file mode 100644 index 000000000..5f5e4b09d --- /dev/null +++ b/vendor/curl/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Carl Lerche + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/curl/README.md b/vendor/curl/README.md new file mode 100644 index 000000000..27ab5e1ae --- /dev/null +++ b/vendor/curl/README.md @@ -0,0 +1,174 @@ +# curl-rust + +[libcurl] bindings for Rust + +[![Latest Version](https://img.shields.io/crates/v/curl.svg)](https://crates.io/crates/curl) +[![Documentation](https://docs.rs/curl/badge.svg)](https://docs.rs/curl) +[![License](https://img.shields.io/github/license/alexcrichton/curl-rust.svg)](LICENSE) +[![Build](https://github.com/alexcrichton/curl-rust/workflows/CI/badge.svg)](https://github.com/alexcrichton/curl-rust/actions) + +## Quick Start + +```rust +use std::io::{stdout, Write}; + +use curl::easy::Easy; + +// Print a web page onto stdout +fn main() { + let mut easy = Easy::new(); + easy.url("https://www.rust-lang.org/").unwrap(); + easy.write_function(|data| { + stdout().write_all(data).unwrap(); + Ok(data.len()) + }).unwrap(); + easy.perform().unwrap(); + + println!("{}", easy.response_code().unwrap()); +} +``` + +```rust +use curl::easy::Easy; + +// Capture output into a local `Vec`. +fn main() { + let mut dst = Vec::new(); + let mut easy = Easy::new(); + easy.url("https://www.rust-lang.org/").unwrap(); + + let mut transfer = easy.transfer(); + transfer.write_function(|data| { + dst.extend_from_slice(data); + Ok(data.len()) + }).unwrap(); + transfer.perform().unwrap(); +} +``` + +## Post / Put requests + +The `put` and `post` methods on `Easy` can configure the method of the HTTP +request, and then `read_function` can be used to specify how data is filled in. +This interface works particularly well with types that implement `Read`. + +```rust,no_run +use std::io::Read; +use curl::easy::Easy; + +fn main() { + let mut data = "this is the body".as_bytes(); + + let mut easy = Easy::new(); + easy.url("http://www.example.com/upload").unwrap(); + easy.post(true).unwrap(); + easy.post_field_size(data.len() as u64).unwrap(); + + let mut transfer = easy.transfer(); + transfer.read_function(|buf| { + Ok(data.read(buf).unwrap_or(0)) + }).unwrap(); + transfer.perform().unwrap(); +} +``` + +## Custom headers + +Custom headers can be specified as part of the request: + +```rust,no_run +use curl::easy::{Easy, List}; + +fn main() { + let mut easy = Easy::new(); + easy.url("http://www.example.com").unwrap(); + + let mut list = List::new(); + list.append("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==").unwrap(); + easy.http_headers(list).unwrap(); + easy.perform().unwrap(); +} +``` + +## Keep alive + +The handle can be re-used across multiple requests. Curl will attempt to +keep the connections alive. + +```rust,no_run +use curl::easy::Easy; + +fn main() { + let mut handle = Easy::new(); + + handle.url("http://www.example.com/foo").unwrap(); + handle.perform().unwrap(); + + handle.url("http://www.example.com/bar").unwrap(); + handle.perform().unwrap(); +} +``` + +## Multiple requests + +The libcurl library provides support for sending multiple requests +simultaneously through the "multi" interface. This is currently bound in the +`multi` module of this crate and provides the ability to execute multiple +transfers simultaneously. For more information, see that module. + +## Building + +By default, this crate will attempt to dynamically link to the system-wide +libcurl and the system-wide SSL library. Some of this behavior can be customized +with various Cargo features: + +- `ssl`: Enable SSL/TLS support using the platform-default TLS backend. On Windows this is [Schannel], on macOS [Secure Transport], and [OpenSSL] (or equivalent) on all other platforms. Enabled by default. +- `rustls` Enable SSL/TLS support via [Rustls], a well-received alternative TLS backend written in Rust. Rustls is always statically linked. Disabled by default. + + Note that Rustls support is experimental within Curl itself and may have significant bugs, so we don't offer any sort of stability guarantee with this feature. +- `http2`: Enable HTTP/2 support via libnghttp2. Disabled by default. +- `static-curl`: Use a bundled libcurl version and statically link to it. Disabled by default. +- `static-ssl`: Use a bundled OpenSSL version and statically link to it. Only applies on platforms that use OpenSSL. Disabled by default. +- `spnego`: Enable SPNEGO support. Disabled by default. +- `upkeep_7_62_0`: Enable curl_easy_upkeep() support, introduced in curl 7.62.0. Disabled by default. +- `poll_7_68_0`: Enable curl_multi_poll()/curl_multi_wakeup() support, requires curl 7.68.0 or later. Disabled by default. +- `ntlm`: Enable NTLM support in curl. Disabled by default. + +## Version Support + +The bindings have been developed using curl version 7.24.0. They should +work with any newer version of curl and possibly with older versions, +but this has not been tested. + +## Troubleshooting + +### Curl built against the NSS SSL library + +If you encounter the following error message: + +``` + [77] Problem with the SSL CA cert (path? access rights?) +``` + +That means most likely, that curl was linked against `libcurl-nss.so` due to +installed libcurl NSS development files, and that the required library +`libnsspem.so` is missing. See also the curl man page: "If curl is built +against the NSS SSL library, the NSS PEM PKCS#11 module (`libnsspem.so`) needs to be available for this option to work properly." + +In order to avoid this failure you can either + + * install the missing library (e.g. Debian: `nss-plugin-pem`), or + * remove the libcurl NSS development files (e.g. Debian: `libcurl4-nss-dev`) and + rebuild curl-rust. + +## License + +The `curl-rust` crate is licensed under the MIT license, see [`LICENSE`](LICENSE) for more +details. + + +[libcurl]: https://curl.haxx.se/libcurl/ +[OpenSSL]: https://www.openssl.org/ +[Rustls]: https://github.com/ctz/rustls +[Schannel]: https://docs.microsoft.com/en-us/windows/win32/com/schannel +[Secure Transport]: https://developer.apple.com/documentation/security/secure_transport diff --git a/vendor/curl/build.rs b/vendor/curl/build.rs new file mode 100644 index 000000000..11539d433 --- /dev/null +++ b/vendor/curl/build.rs @@ -0,0 +1,23 @@ +use std::env; + +fn main() { + // OpenSSL >= 1.1.0 can be initialized concurrently and is initialized correctly by libcurl. + // <= 1.0.2 need locking callbacks, which are provided by openssl_sys::init(). + let use_openssl = match env::var("DEP_OPENSSL_VERSION_NUMBER") { + Ok(version) => { + let version = u64::from_str_radix(&version, 16).unwrap(); + if version < 0x1_01_00_00_0 { + println!("cargo:rustc-cfg=need_openssl_init"); + } + true + } + Err(_) => false, + }; + + if use_openssl { + // The system libcurl should have the default certificate paths configured. + if env::var_os("DEP_CURL_STATIC").is_some() { + println!("cargo:rustc-cfg=need_openssl_probe"); + } + } +} diff --git a/vendor/curl/ci/Dockerfile-centos7 b/vendor/curl/ci/Dockerfile-centos7 new file mode 100644 index 000000000..3af7dbbd3 --- /dev/null +++ b/vendor/curl/ci/Dockerfile-centos7 @@ -0,0 +1,7 @@ +FROM centos:7 + +RUN yum update -y +RUN yum install -y \ + gcc ca-certificates make \ + openssl-devel \ + pkgconfig diff --git a/vendor/curl/ci/Dockerfile-linux32 b/vendor/curl/ci/Dockerfile-linux32 new file mode 100644 index 000000000..4d55dcf04 --- /dev/null +++ b/vendor/curl/ci/Dockerfile-linux32 @@ -0,0 +1,14 @@ +FROM ubuntu:16.04 + +RUN dpkg --add-architecture i386 && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + gcc-multilib \ + ca-certificates \ + make \ + libc6-dev \ + libssl-dev:i386 \ + pkg-config + +ENV PKG_CONFIG=i686-linux-gnu-pkg-config \ + PKG_CONFIG_ALLOW_CROSS=1 diff --git a/vendor/curl/ci/Dockerfile-linux64 b/vendor/curl/ci/Dockerfile-linux64 new file mode 100644 index 000000000..0acd1223a --- /dev/null +++ b/vendor/curl/ci/Dockerfile-linux64 @@ -0,0 +1,7 @@ +FROM ubuntu:16.04 + +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + gcc ca-certificates make libc6-dev \ + libssl-dev \ + pkg-config diff --git a/vendor/curl/ci/Dockerfile-linux64-curl b/vendor/curl/ci/Dockerfile-linux64-curl new file mode 100644 index 000000000..dd58df136 --- /dev/null +++ b/vendor/curl/ci/Dockerfile-linux64-curl @@ -0,0 +1,6 @@ +FROM ubuntu:16.04 + +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + gcc ca-certificates make libc6-dev \ + libssl-dev libcurl4-openssl-dev pkg-config diff --git a/vendor/curl/ci/Dockerfile-mingw b/vendor/curl/ci/Dockerfile-mingw new file mode 100644 index 000000000..ee5926c8d --- /dev/null +++ b/vendor/curl/ci/Dockerfile-mingw @@ -0,0 +1,6 @@ +FROM ubuntu:16.04 + +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + gcc ca-certificates make libc6-dev \ + gcc-mingw-w64-x86-64 libz-mingw-w64-dev diff --git a/vendor/curl/ci/Dockerfile-musl b/vendor/curl/ci/Dockerfile-musl new file mode 100644 index 000000000..47d211fdf --- /dev/null +++ b/vendor/curl/ci/Dockerfile-musl @@ -0,0 +1,18 @@ +FROM ubuntu:16.04 + +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + gcc ca-certificates make libc6-dev curl \ + musl-tools + +RUN \ + curl https://www.openssl.org/source/old/1.0.2/openssl-1.0.2g.tar.gz | tar xzf - && \ + cd openssl-1.0.2g && \ + CC=musl-gcc ./Configure --prefix=/openssl no-dso linux-x86_64 -fPIC && \ + make -j10 && \ + make install && \ + cd .. && \ + rm -rf openssl-1.0.2g + +ENV OPENSSL_STATIC=1 \ + OPENSSL_DIR=/openssl diff --git a/vendor/curl/ci/run.sh b/vendor/curl/ci/run.sh new file mode 100755 index 000000000..6c2dae399 --- /dev/null +++ b/vendor/curl/ci/run.sh @@ -0,0 +1,26 @@ +#!/bin/sh + +set -ex + +cargo test --target $TARGET --no-run +# First test with no extra protocols enabled. +cargo test --target $TARGET --no-run --features static-curl +# Then with rustls TLS backend. +cargo test --target $TARGET --no-run --features rustls,static-curl +# Then with all extra protocols enabled. +cargo test --target $TARGET --no-run --features static-curl,protocol-ftp,ntlm +if [ -z "$NO_RUN" ]; then + cargo test --target $TARGET + cargo test --target $TARGET --features static-curl + cargo test --target $TARGET --features static-curl,protocol-ftp + + # Note that `-Clink-dead-code` is passed here to suppress `--gc-sections` to + # help confirm that we're compiling everything necessary for curl itself. + RUSTFLAGS=-Clink-dead-code \ + cargo run --manifest-path systest/Cargo.toml --target $TARGET + RUSTFLAGS=-Clink-dead-code \ + cargo run --manifest-path systest/Cargo.toml --target $TARGET --features curl-sys/static-curl,curl-sys/protocol-ftp + + cargo doc --no-deps --target $TARGET + cargo doc --no-deps -p curl-sys --target $TARGET +fi diff --git a/vendor/curl/examples/aws_sigv4.rs b/vendor/curl/examples/aws_sigv4.rs new file mode 100644 index 000000000..1a2661a70 --- /dev/null +++ b/vendor/curl/examples/aws_sigv4.rs @@ -0,0 +1,14 @@ +use anyhow::Result; + +use curl::easy::Easy; + +fn main() -> Result<()> { + let mut handle = Easy::new(); + handle.verbose(true)?; + handle.url("https://ec2.us-east-1.amazonaws.com/?Action=DescribeRegions&Version=2013-10-15")?; + handle.aws_sigv4("aws:amz")?; + handle.username("myAccessKeyId")?; + handle.password("mySecretAccessKey")?; + handle.perform()?; + Ok(()) +} diff --git a/vendor/curl/examples/doh.rs b/vendor/curl/examples/doh.rs new file mode 100644 index 000000000..77ebe385c --- /dev/null +++ b/vendor/curl/examples/doh.rs @@ -0,0 +1,17 @@ +use curl::easy::Easy; +use std::io::{stdout, Write}; + +fn main() -> Result<(), curl::Error> { + let mut curl = Easy::new(); + + curl.url("https://example.com")?; + curl.doh_url(Some("https://cloudflare-dns.com/dns-query"))?; + curl.write_function(|data| { + stdout().write_all(data).unwrap(); + Ok(data.len()) + })?; + + curl.perform()?; + + Ok(()) +} diff --git a/vendor/curl/examples/https.rs b/vendor/curl/examples/https.rs new file mode 100644 index 000000000..2c34c4817 --- /dev/null +++ b/vendor/curl/examples/https.rs @@ -0,0 +1,23 @@ +//! Simple HTTPS GET +//! +//! This example is a Rust adaptation of the [C example of the same +//! name](https://curl.se/libcurl/c/https.html). + +extern crate curl; + +use curl::easy::Easy; +use std::io::{stdout, Write}; + +fn main() -> Result<(), curl::Error> { + let mut curl = Easy::new(); + + curl.url("https://example.com/")?; + curl.write_function(|data| { + stdout().write_all(data).unwrap(); + Ok(data.len()) + })?; + + curl.perform()?; + + Ok(()) +} diff --git a/vendor/curl/examples/multi-dl.rs b/vendor/curl/examples/multi-dl.rs new file mode 100644 index 000000000..5a6861082 --- /dev/null +++ b/vendor/curl/examples/multi-dl.rs @@ -0,0 +1,88 @@ +use std::collections::HashMap; +use std::time::Duration; + +use anyhow::Result; + +use curl::easy::{Easy2, Handler, WriteError}; +use curl::multi::{Easy2Handle, Multi}; + +const URLS: &[&str] = &[ + "https://www.microsoft.com", + "https://www.google.com", + "https://www.amazon.com", + "https://www.apple.com", +]; + +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()) + } +} + +fn download(multi: &mut Multi, token: usize, url: &str) -> Result<Easy2Handle<Collector>> { + let version = curl::Version::get(); + let mut request = Easy2::new(Collector(Vec::new())); + request.url(&url)?; + request.useragent(&format!("curl/{}", version.version()))?; + + let mut handle = multi.add2(request)?; + handle.set_token(token)?; + Ok(handle) +} + +fn main() -> Result<()> { + let mut multi = Multi::new(); + let mut handles = URLS + .iter() + .enumerate() + .map(|(token, url)| Ok((token, download(&mut multi, token, url)?))) + .collect::<Result<HashMap<_, _>>>()?; + + let mut still_alive = true; + while still_alive { + // We still need to process the last messages when + // `Multi::perform` returns "0". + if multi.perform()? == 0 { + still_alive = false; + } + + multi.messages(|message| { + let token = message.token().expect("failed to get the token"); + let handle = handles + .get_mut(&token) + .expect("the download value should exist in the HashMap"); + + match message + .result_for2(&handle) + .expect("token mismatch with the `EasyHandle`") + { + Ok(()) => { + let http_status = handle + .response_code() + .expect("HTTP request finished without status code"); + + println!( + "R: Transfer succeeded (Status: {}) {} (Download length: {})", + http_status, + URLS[token], + handle.get_ref().0.len() + ); + } + Err(error) => { + println!("E: {} - <{}>", error, URLS[token]); + } + } + }); + + if still_alive { + // The sleeping time could be reduced to allow other processing. + // For instance, a thread could check a condition signalling the + // thread shutdown. + multi.wait(&mut [], Duration::from_secs(60))?; + } + } + + Ok(()) +} diff --git a/vendor/curl/examples/ssl_cert_blob.rs b/vendor/curl/examples/ssl_cert_blob.rs new file mode 100644 index 000000000..b6933bdd8 --- /dev/null +++ b/vendor/curl/examples/ssl_cert_blob.rs @@ -0,0 +1,42 @@ +use std::env; +use std::fs::File; +use std::io::{stdout, Read, Write}; +use std::path::Path; + +use anyhow::{bail, Result}; +use curl::easy::Easy; + +fn read_file(path: impl AsRef<Path>) -> Result<Vec<u8>> { + let mut f = File::open(path)?; + let mut buf = Vec::new(); + f.read_to_end(&mut buf)?; + Ok(buf) +} + +fn main() -> Result<()> { + let argv = env::args().collect::<Vec<_>>(); + if argv.len() < 4 { + bail!("usage: ssl_cert_blob URL CERT KEY"); + } + let url = &argv[1]; + let cert_path = &argv[2]; + let key_path = &argv[3]; + + let mut handle = Easy::new(); + + handle.url(url)?; + handle.verbose(true)?; + handle.write_function(|data| { + stdout().write_all(data).unwrap(); + Ok(data.len()) + })?; + + let cert_blob = read_file(cert_path)?; + let key_blob = read_file(key_path)?; + + handle.ssl_cert_blob(&cert_blob)?; + handle.ssl_key_blob(&key_blob)?; + + handle.perform()?; + Ok(()) +} diff --git a/vendor/curl/examples/ssl_proxy.rs b/vendor/curl/examples/ssl_proxy.rs new file mode 100644 index 000000000..1884d6880 --- /dev/null +++ b/vendor/curl/examples/ssl_proxy.rs @@ -0,0 +1,27 @@ +use anyhow::Result; + +fn main() -> Result<()> { + let mut handle = curl::easy::Easy::new(); + + let proxy_url = "https://fwdproxy"; + let proxy_port = 8082; + let cainfo = "/var/credentials/root/ca.pem"; + let sslcert = "/var/credentials/user/x509.pem"; + let sslkey = "/var/credentials/user/x509.pem"; + + handle.connect_timeout(std::time::Duration::from_secs(5))?; + handle.connect_only(true)?; + handle.verbose(true)?; + handle.url("https://www.google.com")?; + + handle.proxy(proxy_url)?; + handle.proxy_port(proxy_port)?; + handle.proxy_cainfo(cainfo)?; + handle.proxy_sslcert(sslcert)?; + handle.proxy_sslkey(sslkey)?; + println!("ssl proxy setup done"); + + handle.perform()?; + println!("connected done"); + Ok(()) +} diff --git a/vendor/curl/src/easy/form.rs b/vendor/curl/src/easy/form.rs new file mode 100644 index 000000000..83f8031e3 --- /dev/null +++ b/vendor/curl/src/easy/form.rs @@ -0,0 +1,376 @@ +use std::ffi::CString; +use std::fmt; +use std::path::Path; +use std::ptr; + +use crate::easy::{list, List}; +use crate::FormError; +use curl_sys; + +/// Multipart/formdata for an HTTP POST request. +/// +/// This structure is built up and then passed to the `Easy::httppost` method to +/// be sent off with a request. +pub struct Form { + head: *mut curl_sys::curl_httppost, + tail: *mut curl_sys::curl_httppost, + headers: Vec<List>, + buffers: Vec<Vec<u8>>, + strings: Vec<CString>, +} + +/// One part in a multipart upload, added to a `Form`. +pub struct Part<'form, 'data> { + form: &'form mut Form, + name: &'data str, + array: Vec<curl_sys::curl_forms>, + error: Option<FormError>, +} + +pub fn raw(form: &Form) -> *mut curl_sys::curl_httppost { + form.head +} + +impl Form { + /// Creates a new blank form ready for the addition of new data. + pub fn new() -> Form { + Form { + head: ptr::null_mut(), + tail: ptr::null_mut(), + headers: Vec::new(), + buffers: Vec::new(), + strings: Vec::new(), + } + } + + /// Prepares adding a new part to this `Form` + /// + /// Note that the part is not actually added to the form until the `add` + /// method is called on `Part`, which may or may not fail. + pub fn part<'a, 'data>(&'a mut self, name: &'data str) -> Part<'a, 'data> { + Part { + error: None, + form: self, + name, + array: vec![curl_sys::curl_forms { + option: curl_sys::CURLFORM_END, + value: ptr::null_mut(), + }], + } + } +} + +impl fmt::Debug for Form { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // TODO: fill this out more + f.debug_struct("Form").field("fields", &"...").finish() + } +} + +impl Drop for Form { + fn drop(&mut self) { + unsafe { + curl_sys::curl_formfree(self.head); + } + } +} + +impl<'form, 'data> Part<'form, 'data> { + /// A pointer to the contents of this part, the actual data to send away. + pub fn contents(&mut self, contents: &'data [u8]) -> &mut Self { + let pos = self.array.len() - 1; + + // curl has an oddity where if the length if 0 it will call strlen + // on the value. This means that if someone wants to add empty form + // contents we need to make sure the buffer contains a null byte. + let ptr = if contents.is_empty() { + b"\x00" + } else { + contents + } + .as_ptr(); + + self.array.insert( + pos, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_COPYCONTENTS, + value: ptr as *mut _, + }, + ); + self.array.insert( + pos + 1, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_CONTENTSLENGTH, + value: contents.len() as *mut _, + }, + ); + self + } + + /// Causes this file to be read and its contents used as data in this part + /// + /// This part does not automatically become a file upload part simply + /// because its data was read from a file. + /// + /// # Errors + /// + /// If the filename has any internal nul bytes or if on Windows it does not + /// contain a unicode filename then the `add` function will eventually + /// return an error. + pub fn file_content<P>(&mut self, file: P) -> &mut Self + where + P: AsRef<Path>, + { + self._file_content(file.as_ref()) + } + + fn _file_content(&mut self, file: &Path) -> &mut Self { + if let Some(bytes) = self.path2cstr(file) { + let pos = self.array.len() - 1; + self.array.insert( + pos, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_FILECONTENT, + value: bytes.as_ptr() as *mut _, + }, + ); + self.form.strings.push(bytes); + } + self + } + + /// Makes this part a file upload part of the given file. + /// + /// Sets the filename field to the basename of the provided file name, and + /// it reads the contents of the file and passes them as data and sets the + /// content type if the given file matches one of the internally known file + /// extensions. + /// + /// The given upload file must exist entirely on the filesystem before the + /// upload is started because libcurl needs to read the size of it + /// beforehand. + /// + /// Multiple files can be uploaded by calling this method multiple times and + /// content types can also be configured for each file (by calling that + /// next). + /// + /// # Errors + /// + /// If the filename has any internal nul bytes or if on Windows it does not + /// contain a unicode filename then this function will cause `add` to return + /// an error when called. + pub fn file<P: ?Sized>(&mut self, file: &'data P) -> &mut Self + where + P: AsRef<Path>, + { + self._file(file.as_ref()) + } + + fn _file(&mut self, file: &'data Path) -> &mut Self { + if let Some(bytes) = self.path2cstr(file) { + let pos = self.array.len() - 1; + self.array.insert( + pos, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_FILE, + value: bytes.as_ptr() as *mut _, + }, + ); + self.form.strings.push(bytes); + } + self + } + + /// Used in combination with `Part::file`, provides the content-type for + /// this part, possibly instead of choosing an internal one. + /// + /// # Panics + /// + /// This function will panic if `content_type` contains an internal nul + /// byte. + pub fn content_type(&mut self, content_type: &'data str) -> &mut Self { + if let Some(bytes) = self.bytes2cstr(content_type.as_bytes()) { + let pos = self.array.len() - 1; + self.array.insert( + pos, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_CONTENTTYPE, + value: bytes.as_ptr() as *mut _, + }, + ); + self.form.strings.push(bytes); + } + self + } + + /// Used in combination with `Part::file`, provides the filename for + /// this part instead of the actual one. + /// + /// # Errors + /// + /// If `name` contains an internal nul byte, or if on Windows the path is + /// not valid unicode then this function will return an error when `add` is + /// called. + pub fn filename<P: ?Sized>(&mut self, name: &'data P) -> &mut Self + where + P: AsRef<Path>, + { + self._filename(name.as_ref()) + } + + fn _filename(&mut self, name: &'data Path) -> &mut Self { + if let Some(bytes) = self.path2cstr(name) { + let pos = self.array.len() - 1; + self.array.insert( + pos, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_FILENAME, + value: bytes.as_ptr() as *mut _, + }, + ); + self.form.strings.push(bytes); + } + self + } + + /// This is used to provide a custom file upload part without using the + /// `file` method above. + /// + /// The first parameter is for the filename field and the second is the + /// in-memory contents. + /// + /// # Errors + /// + /// If `name` contains an internal nul byte, or if on Windows the path is + /// not valid unicode then this function will return an error when `add` is + /// called. + pub fn buffer<P: ?Sized>(&mut self, name: &'data P, data: Vec<u8>) -> &mut Self + where + P: AsRef<Path>, + { + self._buffer(name.as_ref(), data) + } + + fn _buffer(&mut self, name: &'data Path, mut data: Vec<u8>) -> &mut Self { + if let Some(bytes) = self.path2cstr(name) { + // If `CURLFORM_BUFFERLENGTH` is set to `0`, libcurl will instead do a strlen() on the + // contents to figure out the size so we need to make sure the buffer is actually + // zero terminated. + let length = data.len(); + if length == 0 { + data.push(0); + } + + let pos = self.array.len() - 1; + self.array.insert( + pos, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_BUFFER, + value: bytes.as_ptr() as *mut _, + }, + ); + self.form.strings.push(bytes); + self.array.insert( + pos + 1, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_BUFFERPTR, + value: data.as_ptr() as *mut _, + }, + ); + self.array.insert( + pos + 2, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_BUFFERLENGTH, + value: length as *mut _, + }, + ); + self.form.buffers.push(data); + } + self + } + + /// Specifies extra headers for the form POST section. + /// + /// Appends the list of headers to those libcurl automatically generates. + pub fn content_header(&mut self, headers: List) -> &mut Self { + let pos = self.array.len() - 1; + self.array.insert( + pos, + curl_sys::curl_forms { + option: curl_sys::CURLFORM_CONTENTHEADER, + value: list::raw(&headers) as *mut _, + }, + ); + self.form.headers.push(headers); + self + } + + /// Attempts to add this part to the `Form` that it was created from. + /// + /// If any error happens while adding, that error is returned, otherwise + /// `Ok(())` is returned. + pub fn add(&mut self) -> Result<(), FormError> { + if let Some(err) = self.error.clone() { + return Err(err); + } + let rc = unsafe { + curl_sys::curl_formadd( + &mut self.form.head, + &mut self.form.tail, + curl_sys::CURLFORM_COPYNAME, + self.name.as_ptr(), + curl_sys::CURLFORM_NAMELENGTH, + self.name.len(), + curl_sys::CURLFORM_ARRAY, + self.array.as_ptr(), + curl_sys::CURLFORM_END, + ) + }; + if rc == curl_sys::CURL_FORMADD_OK { + Ok(()) + } else { + Err(FormError::new(rc)) + } + } + + #[cfg(unix)] + fn path2cstr(&mut self, p: &Path) -> Option<CString> { + use std::os::unix::prelude::*; + self.bytes2cstr(p.as_os_str().as_bytes()) + } + + #[cfg(windows)] + fn path2cstr(&mut self, p: &Path) -> Option<CString> { + match p.to_str() { + Some(bytes) => self.bytes2cstr(bytes.as_bytes()), + None if self.error.is_none() => { + // TODO: better error code + self.error = Some(FormError::new(curl_sys::CURL_FORMADD_INCOMPLETE)); + None + } + None => None, + } + } + + fn bytes2cstr(&mut self, bytes: &[u8]) -> Option<CString> { + match CString::new(bytes) { + Ok(c) => Some(c), + Err(..) if self.error.is_none() => { + // TODO: better error code + self.error = Some(FormError::new(curl_sys::CURL_FORMADD_INCOMPLETE)); + None + } + Err(..) => None, + } + } +} + +impl<'form, 'data> fmt::Debug for Part<'form, 'data> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // TODO: fill this out more + f.debug_struct("Part") + .field("name", &self.name) + .field("form", &self.form) + .finish() + } +} diff --git a/vendor/curl/src/easy/handle.rs b/vendor/curl/src/easy/handle.rs new file mode 100644 index 000000000..fb18e0270 --- /dev/null +++ b/vendor/curl/src/easy/handle.rs @@ -0,0 +1,1694 @@ +use std::cell::Cell; +use std::fmt; +use std::io::SeekFrom; +use std::path::Path; +use std::ptr; +use std::str; +use std::time::Duration; + +use curl_sys; +use libc::c_void; + +use crate::easy::handler::{self, InfoType, ReadError, SeekResult, WriteError}; +use crate::easy::handler::{Auth, NetRc, ProxyType, SslOpt}; +use crate::easy::handler::{HttpVersion, IpResolve, SslVersion, TimeCondition}; +use crate::easy::{Easy2, Handler}; +use crate::easy::{Form, List}; +use crate::Error; + +/// Raw bindings to a libcurl "easy session". +/// +/// This type is the same as the `Easy2` type in this library except that it +/// does not contain a type parameter. Callbacks from curl are all controlled +/// via closures on this `Easy` type, and this type namely has a `transfer` +/// method as well for ergonomic management of these callbacks. +/// +/// 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 +/// +/// Creating a handle which can be used later +/// +/// ``` +/// use curl::easy::Easy; +/// +/// let handle = Easy::new(); +/// ``` +/// +/// Send an HTTP request, writing the response to stdout. +/// +/// ``` +/// use std::io::{stdout, Write}; +/// +/// use curl::easy::Easy; +/// +/// let mut handle = Easy::new(); +/// handle.url("https://www.rust-lang.org/").unwrap(); +/// handle.write_function(|data| { +/// stdout().write_all(data).unwrap(); +/// Ok(data.len()) +/// }).unwrap(); +/// handle.perform().unwrap(); +/// ``` +/// +/// Collect all output of an HTTP request to a vector. +/// +/// ``` +/// use curl::easy::Easy; +/// +/// let mut data = Vec::new(); +/// let mut handle = Easy::new(); +/// handle.url("https://www.rust-lang.org/").unwrap(); +/// { +/// let mut transfer = handle.transfer(); +/// transfer.write_function(|new_data| { +/// data.extend_from_slice(new_data); +/// Ok(new_data.len()) +/// }).unwrap(); +/// transfer.perform().unwrap(); +/// } +/// println!("{:?}", data); +/// ``` +/// +/// More examples of various properties of an HTTP request can be found on the +/// specific methods as well. +#[derive(Debug)] +pub struct Easy { + inner: Easy2<EasyData>, +} + +/// A scoped transfer of information which borrows an `Easy` and allows +/// referencing stack-local data of the lifetime `'data`. +/// +/// Usage of `Easy` requires the `'static` and `Send` bounds on all callbacks +/// registered, but that's not often wanted if all you need is to collect a +/// bunch of data in memory to a vector, for example. The `Transfer` structure, +/// created by the `Easy::transfer` method, is used for this sort of request. +/// +/// The callbacks attached to a `Transfer` are only active for that one transfer +/// object, and they allow to elide both the `Send` and `'static` bounds to +/// close over stack-local information. +pub struct Transfer<'easy, 'data> { + easy: &'easy mut Easy, + data: Box<Callbacks<'data>>, +} + +pub struct EasyData { + running: Cell<bool>, + owned: Callbacks<'static>, + borrowed: Cell<*mut Callbacks<'static>>, +} + +unsafe impl Send for EasyData {} + +#[derive(Default)] +struct Callbacks<'a> { + write: Option<Box<dyn FnMut(&[u8]) -> Result<usize, WriteError> + 'a>>, + read: Option<Box<dyn FnMut(&mut [u8]) -> Result<usize, ReadError> + 'a>>, + seek: Option<Box<dyn FnMut(SeekFrom) -> SeekResult + 'a>>, + debug: Option<Box<dyn FnMut(InfoType, &[u8]) + 'a>>, + header: Option<Box<dyn FnMut(&[u8]) -> bool + 'a>>, + progress: Option<Box<dyn FnMut(f64, f64, f64, f64) -> bool + 'a>>, + ssl_ctx: Option<Box<dyn FnMut(*mut c_void) -> Result<(), Error> + 'a>>, +} + +impl Easy { + /// 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() -> Easy { + Easy { + inner: Easy2::new(EasyData { + running: Cell::new(false), + owned: Callbacks::default(), + borrowed: Cell::new(ptr::null_mut()), + }), + } + } + + // ========================================================================= + // Behavior options + + /// Same as [`Easy2::verbose`](struct.Easy2.html#method.verbose) + pub fn verbose(&mut self, verbose: bool) -> Result<(), Error> { + self.inner.verbose(verbose) + } + + /// Same as [`Easy2::show_header`](struct.Easy2.html#method.show_header) + pub fn show_header(&mut self, show: bool) -> Result<(), Error> { + self.inner.show_header(show) + } + + /// Same as [`Easy2::progress`](struct.Easy2.html#method.progress) + pub fn progress(&mut self, progress: bool) -> Result<(), Error> { + self.inner.progress(progress) + } + + /// Same as [`Easy2::signal`](struct.Easy2.html#method.signal) + pub fn signal(&mut self, signal: bool) -> Result<(), Error> { + self.inner.signal(signal) + } + + /// Same as [`Easy2::wildcard_match`](struct.Easy2.html#method.wildcard_match) + pub fn wildcard_match(&mut self, m: bool) -> Result<(), Error> { + self.inner.wildcard_match(m) + } + + /// Same as [`Easy2::unix_socket`](struct.Easy2.html#method.unix_socket) + pub fn unix_socket(&mut self, unix_domain_socket: &str) -> Result<(), Error> { + self.inner.unix_socket(unix_domain_socket) + } + + /// Same as [`Easy2::unix_socket_path`](struct.Easy2.html#method.unix_socket_path) + pub fn unix_socket_path<P: AsRef<Path>>(&mut self, path: Option<P>) -> Result<(), Error> { + self.inner.unix_socket_path(path) + } + + // ========================================================================= + // Callback options + + /// Set callback for writing received data. + /// + /// 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. + /// + /// 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 `write_function` to configure a + /// callback that can reference stack-local data. + /// + /// # Examples + /// + /// ``` + /// use std::io::{stdout, Write}; + /// use curl::easy::Easy; + /// + /// let mut handle = Easy::new(); + /// handle.url("https://www.rust-lang.org/").unwrap(); + /// handle.write_function(|data| { + /// Ok(stdout().write(data).unwrap()) + /// }).unwrap(); + /// handle.perform().unwrap(); + /// ``` + /// + /// Writing to a stack-local buffer + /// + /// ``` + /// use std::io::{stdout, Write}; + /// use curl::easy::Easy; + /// + /// let mut buf = Vec::new(); + /// let mut handle = Easy::new(); + /// handle.url("https://www.rust-lang.org/").unwrap(); + /// + /// let mut transfer = handle.transfer(); + /// transfer.write_function(|data| { + /// buf.extend_from_slice(data); + /// Ok(data.len()) + /// }).unwrap(); + /// transfer.perform().unwrap(); + /// ``` + pub fn write_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(&[u8]) -> Result<usize, WriteError> + Send + 'static, + { + self.inner.get_mut().owned.write = Some(Box::new(f)); + Ok(()) + } + + /// 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. + /// + /// # Examples + /// + /// Read input from stdin + /// + /// ```no_run + /// use std::io::{stdin, Read}; + /// use curl::easy::Easy; + /// + /// let mut handle = Easy::new(); + /// handle.url("https://example.com/login").unwrap(); + /// handle.read_function(|into| { + /// Ok(stdin().read(into).unwrap()) + /// }).unwrap(); + /// handle.post(true).unwrap(); + /// handle.perform().unwrap(); + /// ``` + /// + /// Reading from stack-local data: + /// + /// ```no_run + /// use std::io::{stdin, Read}; + /// use curl::easy::Easy; + /// + /// let mut data_to_upload = &b"foobar"[..]; + /// let mut handle = Easy::new(); + /// handle.url("https://example.com/login").unwrap(); + /// handle.post(true).unwrap(); + /// + /// let mut transfer = handle.transfer(); + /// transfer.read_function(|into| { + /// Ok(data_to_upload.read(into).unwrap()) + /// }).unwrap(); + /// transfer.perform().unwrap(); + /// ``` + pub fn read_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(&mut [u8]) -> Result<usize, ReadError> + Send + 'static, + { + self.inner.get_mut().owned.read = Some(Box::new(f)); + Ok(()) + } + + /// 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. + /// + /// 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 `seek_function` to configure a + /// callback that can reference stack-local data. + pub fn seek_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(SeekFrom) -> SeekResult + Send + 'static, + { + self.inner.get_mut().owned.seek = Some(Box::new(f)); + Ok(()) + } + + /// 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`. + /// + /// 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 `progress_function` to configure a + /// callback that can reference stack-local data. + pub fn progress_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(f64, f64, f64, f64) -> bool + Send + 'static, + { + self.inner.get_mut().owned.progress = Some(Box::new(f)); + Ok(()) + } + + /// 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 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 `progress_function` to configure a + /// callback that can reference stack-local data. + pub fn ssl_ctx_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(*mut c_void) -> Result<(), Error> + Send + 'static, + { + self.inner.get_mut().owned.ssl_ctx = Some(Box::new(f)); + Ok(()) + } + + /// 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. + /// + /// 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 `debug_function` to configure a + /// callback that can reference stack-local data. + pub fn debug_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(InfoType, &[u8]) + Send + 'static, + { + self.inner.get_mut().owned.debug = Some(Box::new(f)); + Ok(()) + } + + /// 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. + /// + /// 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 `header_function` to configure a + /// callback that can reference stack-local data. + /// + /// # Examples + /// + /// ``` + /// use std::str; + /// + /// use curl::easy::Easy; + /// + /// let mut handle = Easy::new(); + /// handle.url("https://www.rust-lang.org/").unwrap(); + /// handle.header_function(|header| { + /// print!("header: {}", str::from_utf8(header).unwrap()); + /// true + /// }).unwrap(); + /// handle.perform().unwrap(); + /// ``` + /// + /// Collecting headers to a stack local vector + /// + /// ``` + /// use std::str; + /// + /// use curl::easy::Easy; + /// + /// let mut headers = Vec::new(); + /// let mut handle = Easy::new(); + /// handle.url("https://www.rust-lang.org/").unwrap(); + /// + /// { + /// let mut transfer = handle.transfer(); + /// transfer.header_function(|header| { + /// headers.push(str::from_utf8(header).unwrap().to_string()); + /// true + /// }).unwrap(); + /// transfer.perform().unwrap(); + /// } + /// + /// println!("{:?}", headers); + /// ``` + pub fn header_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(&[u8]) -> bool + Send + 'static, + { + self.inner.get_mut().owned.header = Some(Box::new(f)); + Ok(()) + } + + // ========================================================================= + // Error options + + // TODO: error buffer and stderr + + /// Same as [`Easy2::fail_on_error`](struct.Easy2.html#method.fail_on_error) + pub fn fail_on_error(&mut self, fail: bool) -> Result<(), Error> { + self.inner.fail_on_error(fail) + } + + // ========================================================================= + // Network options + + /// Same as [`Easy2::url`](struct.Easy2.html#method.url) + pub fn url(&mut self, url: &str) -> Result<(), Error> { + self.inner.url(url) + } + + /// Same as [`Easy2::port`](struct.Easy2.html#method.port) + pub fn port(&mut self, port: u16) -> Result<(), Error> { + self.inner.port(port) + } + + /// Same as [`Easy2::connect_to`](struct.Easy2.html#method.connect_to) + pub fn connect_to(&mut self, list: List) -> Result<(), Error> { + self.inner.connect_to(list) + } + + /// Same as [`Easy2::path_as_is`](struct.Easy2.html#method.path_as_is) + pub fn path_as_is(&mut self, as_is: bool) -> Result<(), Error> { + self.inner.path_as_is(as_is) + } + + /// Same as [`Easy2::proxy`](struct.Easy2.html#method.proxy) + pub fn proxy(&mut self, url: &str) -> Result<(), Error> { + self.inner.proxy(url) + } + + /// Same as [`Easy2::proxy_port`](struct.Easy2.html#method.proxy_port) + pub fn proxy_port(&mut self, port: u16) -> Result<(), Error> { + self.inner.proxy_port(port) + } + + /// Same as [`Easy2::proxy_cainfo`](struct.Easy2.html#method.proxy_cainfo) + pub fn proxy_cainfo(&mut self, cainfo: &str) -> Result<(), Error> { + self.inner.proxy_cainfo(cainfo) + } + + /// Same as [`Easy2::proxy_capath`](struct.Easy2.html#method.proxy_capath) + pub fn proxy_capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.inner.proxy_capath(path) + } + + /// Same as [`Easy2::proxy_sslcert`](struct.Easy2.html#method.proxy_sslcert) + pub fn proxy_sslcert(&mut self, sslcert: &str) -> Result<(), Error> { + self.inner.proxy_sslcert(sslcert) + } + + /// Same as [`Easy2::proxy_sslcert_type`](struct.Easy2.html#method.proxy_sslcert_type) + pub fn proxy_sslcert_type(&mut self, kind: &str) -> Result<(), Error> { + self.inner.proxy_sslcert_type(kind) + } + + /// Same as [`Easy2::proxy_sslcert_blob`](struct.Easy2.html#method.proxy_sslcert_blob) + pub fn proxy_sslcert_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.inner.proxy_sslcert_blob(blob) + } + + /// Same as [`Easy2::proxy_sslkey`](struct.Easy2.html#method.proxy_sslkey) + pub fn proxy_sslkey(&mut self, sslkey: &str) -> Result<(), Error> { + self.inner.proxy_sslkey(sslkey) + } + + /// Same as [`Easy2::proxy_sslkey_type`](struct.Easy2.html#method.proxy_sslkey_type) + pub fn proxy_sslkey_type(&mut self, kind: &str) -> Result<(), Error> { + self.inner.proxy_sslkey_type(kind) + } + + /// Same as [`Easy2::proxy_sslkey_blob`](struct.Easy2.html#method.proxy_sslkey_blob) + pub fn proxy_sslkey_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.inner.proxy_sslkey_blob(blob) + } + + /// Same as [`Easy2::proxy_key_password`](struct.Easy2.html#method.proxy_key_password) + pub fn proxy_key_password(&mut self, password: &str) -> Result<(), Error> { + self.inner.proxy_key_password(password) + } + + /// Same as [`Easy2::proxy_type`](struct.Easy2.html#method.proxy_type) + pub fn proxy_type(&mut self, kind: ProxyType) -> Result<(), Error> { + self.inner.proxy_type(kind) + } + + /// Same as [`Easy2::noproxy`](struct.Easy2.html#method.noproxy) + pub fn noproxy(&mut self, skip: &str) -> Result<(), Error> { + self.inner.noproxy(skip) + } + + /// Same as [`Easy2::http_proxy_tunnel`](struct.Easy2.html#method.http_proxy_tunnel) + pub fn http_proxy_tunnel(&mut self, tunnel: bool) -> Result<(), Error> { + self.inner.http_proxy_tunnel(tunnel) + } + + /// Same as [`Easy2::interface`](struct.Easy2.html#method.interface) + pub fn interface(&mut self, interface: &str) -> Result<(), Error> { + self.inner.interface(interface) + } + + /// Same as [`Easy2::set_local_port`](struct.Easy2.html#method.set_local_port) + pub fn set_local_port(&mut self, port: u16) -> Result<(), Error> { + self.inner.set_local_port(port) + } + + /// Same as [`Easy2::local_port_range`](struct.Easy2.html#method.local_port_range) + pub fn local_port_range(&mut self, range: u16) -> Result<(), Error> { + self.inner.local_port_range(range) + } + + /// Same as [`Easy2::dns_servers`](struct.Easy2.html#method.dns_servers) + pub fn dns_servers(&mut self, servers: &str) -> Result<(), Error> { + self.inner.dns_servers(servers) + } + + /// Same as [`Easy2::dns_cache_timeout`](struct.Easy2.html#method.dns_cache_timeout) + pub fn dns_cache_timeout(&mut self, dur: Duration) -> Result<(), Error> { + self.inner.dns_cache_timeout(dur) + } + + /// Same as [`Easy2::doh_url`](struct.Easy2.html#method.doh_url) + pub fn doh_url(&mut self, url: Option<&str>) -> Result<(), Error> { + self.inner.doh_url(url) + } + + /// Same as [`Easy2::doh_ssl_verify_peer`](struct.Easy2.html#method.doh_ssl_verify_peer) + pub fn doh_ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error> { + self.inner.doh_ssl_verify_peer(verify) + } + + /// Same as [`Easy2::doh_ssl_verify_host`](struct.Easy2.html#method.doh_ssl_verify_host) + pub fn doh_ssl_verify_host(&mut self, verify: bool) -> Result<(), Error> { + self.inner.doh_ssl_verify_host(verify) + } + + /// Same as [`Easy2::doh_ssl_verify_status`](struct.Easy2.html#method.doh_ssl_verify_status) + pub fn doh_ssl_verify_status(&mut self, verify: bool) -> Result<(), Error> { + self.inner.doh_ssl_verify_status(verify) + } + + /// Same as [`Easy2::buffer_size`](struct.Easy2.html#method.buffer_size) + pub fn buffer_size(&mut self, size: usize) -> Result<(), Error> { + self.inner.buffer_size(size) + } + + /// Same as [`Easy2::upload_buffer_size`](struct.Easy2.html#method.upload_buffer_size) + pub fn upload_buffer_size(&mut self, size: usize) -> Result<(), Error> { + self.inner.upload_buffer_size(size) + } + + /// Same as [`Easy2::tcp_nodelay`](struct.Easy2.html#method.tcp_nodelay) + pub fn tcp_nodelay(&mut self, enable: bool) -> Result<(), Error> { + self.inner.tcp_nodelay(enable) + } + + /// Same as [`Easy2::tcp_keepalive`](struct.Easy2.html#method.tcp_keepalive) + pub fn tcp_keepalive(&mut self, enable: bool) -> Result<(), Error> { + self.inner.tcp_keepalive(enable) + } + + /// Same as [`Easy2::tcp_keepintvl`](struct.Easy2.html#method.tcp_keepalive) + pub fn tcp_keepintvl(&mut self, dur: Duration) -> Result<(), Error> { + self.inner.tcp_keepintvl(dur) + } + + /// Same as [`Easy2::tcp_keepidle`](struct.Easy2.html#method.tcp_keepidle) + pub fn tcp_keepidle(&mut self, dur: Duration) -> Result<(), Error> { + self.inner.tcp_keepidle(dur) + } + + /// Same as [`Easy2::address_scope`](struct.Easy2.html#method.address_scope) + pub fn address_scope(&mut self, scope: u32) -> Result<(), Error> { + self.inner.address_scope(scope) + } + + // ========================================================================= + // Names and passwords + + /// Same as [`Easy2::username`](struct.Easy2.html#method.username) + pub fn username(&mut self, user: &str) -> Result<(), Error> { + self.inner.username(user) + } + + /// Same as [`Easy2::password`](struct.Easy2.html#method.password) + pub fn password(&mut self, pass: &str) -> Result<(), Error> { + self.inner.password(pass) + } + + /// Same as [`Easy2::http_auth`](struct.Easy2.html#method.http_auth) + pub fn http_auth(&mut self, auth: &Auth) -> Result<(), Error> { + self.inner.http_auth(auth) + } + + /// Same as [`Easy2::aws_sigv4`](struct.Easy2.html#method.aws_sigv4) + pub fn aws_sigv4(&mut self, param: &str) -> Result<(), Error> { + self.inner.aws_sigv4(param) + } + + /// Same as [`Easy2::proxy_username`](struct.Easy2.html#method.proxy_username) + pub fn proxy_username(&mut self, user: &str) -> Result<(), Error> { + self.inner.proxy_username(user) + } + + /// Same as [`Easy2::proxy_password`](struct.Easy2.html#method.proxy_password) + pub fn proxy_password(&mut self, pass: &str) -> Result<(), Error> { + self.inner.proxy_password(pass) + } + + /// Same as [`Easy2::proxy_auth`](struct.Easy2.html#method.proxy_auth) + pub fn proxy_auth(&mut self, auth: &Auth) -> Result<(), Error> { + self.inner.proxy_auth(auth) + } + + /// Same as [`Easy2::netrc`](struct.Easy2.html#method.netrc) + pub fn netrc(&mut self, netrc: NetRc) -> Result<(), Error> { + self.inner.netrc(netrc) + } + + // ========================================================================= + // HTTP Options + + /// Same as [`Easy2::autoreferer`](struct.Easy2.html#method.autoreferer) + pub fn autoreferer(&mut self, enable: bool) -> Result<(), Error> { + self.inner.autoreferer(enable) + } + + /// Same as [`Easy2::accept_encoding`](struct.Easy2.html#method.accept_encoding) + pub fn accept_encoding(&mut self, encoding: &str) -> Result<(), Error> { + self.inner.accept_encoding(encoding) + } + + /// Same as [`Easy2::transfer_encoding`](struct.Easy2.html#method.transfer_encoding) + pub fn transfer_encoding(&mut self, enable: bool) -> Result<(), Error> { + self.inner.transfer_encoding(enable) + } + + /// Same as [`Easy2::follow_location`](struct.Easy2.html#method.follow_location) + pub fn follow_location(&mut self, enable: bool) -> Result<(), Error> { + self.inner.follow_location(enable) + } + + /// Same as [`Easy2::unrestricted_auth`](struct.Easy2.html#method.unrestricted_auth) + pub fn unrestricted_auth(&mut self, enable: bool) -> Result<(), Error> { + self.inner.unrestricted_auth(enable) + } + + /// Same as [`Easy2::max_redirections`](struct.Easy2.html#method.max_redirections) + pub fn max_redirections(&mut self, max: u32) -> Result<(), Error> { + self.inner.max_redirections(max) + } + + /// Same as [`Easy2::put`](struct.Easy2.html#method.put) + pub fn put(&mut self, enable: bool) -> Result<(), Error> { + self.inner.put(enable) + } + + /// Same as [`Easy2::post`](struct.Easy2.html#method.post) + pub fn post(&mut self, enable: bool) -> Result<(), Error> { + self.inner.post(enable) + } + + /// Same as [`Easy2::post_field_copy`](struct.Easy2.html#method.post_field_copy) + pub fn post_fields_copy(&mut self, data: &[u8]) -> Result<(), Error> { + self.inner.post_fields_copy(data) + } + + /// Same as [`Easy2::post_field_size`](struct.Easy2.html#method.post_field_size) + pub fn post_field_size(&mut self, size: u64) -> Result<(), Error> { + self.inner.post_field_size(size) + } + + /// Same as [`Easy2::httppost`](struct.Easy2.html#method.httppost) + pub fn httppost(&mut self, form: Form) -> Result<(), Error> { + self.inner.httppost(form) + } + + /// Same as [`Easy2::referer`](struct.Easy2.html#method.referer) + pub fn referer(&mut self, referer: &str) -> Result<(), Error> { + self.inner.referer(referer) + } + + /// Same as [`Easy2::useragent`](struct.Easy2.html#method.useragent) + pub fn useragent(&mut self, useragent: &str) -> Result<(), Error> { + self.inner.useragent(useragent) + } + + /// Same as [`Easy2::http_headers`](struct.Easy2.html#method.http_headers) + pub fn http_headers(&mut self, list: List) -> Result<(), Error> { + self.inner.http_headers(list) + } + + /// Same as [`Easy2::cookie`](struct.Easy2.html#method.cookie) + pub fn cookie(&mut self, cookie: &str) -> Result<(), Error> { + self.inner.cookie(cookie) + } + + /// Same as [`Easy2::cookie_file`](struct.Easy2.html#method.cookie_file) + pub fn cookie_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> { + self.inner.cookie_file(file) + } + + /// Same as [`Easy2::cookie_jar`](struct.Easy2.html#method.cookie_jar) + pub fn cookie_jar<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> { + self.inner.cookie_jar(file) + } + + /// Same as [`Easy2::cookie_session`](struct.Easy2.html#method.cookie_session) + pub fn cookie_session(&mut self, session: bool) -> Result<(), Error> { + self.inner.cookie_session(session) + } + + /// Same as [`Easy2::cookie_list`](struct.Easy2.html#method.cookie_list) + pub fn cookie_list(&mut self, cookie: &str) -> Result<(), Error> { + self.inner.cookie_list(cookie) + } + + /// Same as [`Easy2::get`](struct.Easy2.html#method.get) + pub fn get(&mut self, enable: bool) -> Result<(), Error> { + self.inner.get(enable) + } + + /// Same as [`Easy2::ignore_content_length`](struct.Easy2.html#method.ignore_content_length) + pub fn ignore_content_length(&mut self, ignore: bool) -> Result<(), Error> { + self.inner.ignore_content_length(ignore) + } + + /// Same as [`Easy2::http_content_decoding`](struct.Easy2.html#method.http_content_decoding) + pub fn http_content_decoding(&mut self, enable: bool) -> Result<(), Error> { + self.inner.http_content_decoding(enable) + } + + /// Same as [`Easy2::http_transfer_decoding`](struct.Easy2.html#method.http_transfer_decoding) + pub fn http_transfer_decoding(&mut self, enable: bool) -> Result<(), Error> { + self.inner.http_transfer_decoding(enable) + } + + // ========================================================================= + // Protocol Options + + /// Same as [`Easy2::range`](struct.Easy2.html#method.range) + pub fn range(&mut self, range: &str) -> Result<(), Error> { + self.inner.range(range) + } + + /// Same as [`Easy2::resume_from`](struct.Easy2.html#method.resume_from) + pub fn resume_from(&mut self, from: u64) -> Result<(), Error> { + self.inner.resume_from(from) + } + + /// Same as [`Easy2::custom_request`](struct.Easy2.html#method.custom_request) + pub fn custom_request(&mut self, request: &str) -> Result<(), Error> { + self.inner.custom_request(request) + } + + /// Same as [`Easy2::fetch_filetime`](struct.Easy2.html#method.fetch_filetime) + pub fn fetch_filetime(&mut self, fetch: bool) -> Result<(), Error> { + self.inner.fetch_filetime(fetch) + } + + /// Same as [`Easy2::nobody`](struct.Easy2.html#method.nobody) + pub fn nobody(&mut self, enable: bool) -> Result<(), Error> { + self.inner.nobody(enable) + } + + /// Same as [`Easy2::in_filesize`](struct.Easy2.html#method.in_filesize) + pub fn in_filesize(&mut self, size: u64) -> Result<(), Error> { + self.inner.in_filesize(size) + } + + /// Same as [`Easy2::upload`](struct.Easy2.html#method.upload) + pub fn upload(&mut self, enable: bool) -> Result<(), Error> { + self.inner.upload(enable) + } + + /// Same as [`Easy2::max_filesize`](struct.Easy2.html#method.max_filesize) + pub fn max_filesize(&mut self, size: u64) -> Result<(), Error> { + self.inner.max_filesize(size) + } + + /// Same as [`Easy2::time_condition`](struct.Easy2.html#method.time_condition) + pub fn time_condition(&mut self, cond: TimeCondition) -> Result<(), Error> { + self.inner.time_condition(cond) + } + + /// Same as [`Easy2::time_value`](struct.Easy2.html#method.time_value) + pub fn time_value(&mut self, val: i64) -> Result<(), Error> { + self.inner.time_value(val) + } + + // ========================================================================= + // Connection Options + + /// Same as [`Easy2::timeout`](struct.Easy2.html#method.timeout) + pub fn timeout(&mut self, timeout: Duration) -> Result<(), Error> { + self.inner.timeout(timeout) + } + + /// Same as [`Easy2::low_speed_limit`](struct.Easy2.html#method.low_speed_limit) + pub fn low_speed_limit(&mut self, limit: u32) -> Result<(), Error> { + self.inner.low_speed_limit(limit) + } + + /// Same as [`Easy2::low_speed_time`](struct.Easy2.html#method.low_speed_time) + pub fn low_speed_time(&mut self, dur: Duration) -> Result<(), Error> { + self.inner.low_speed_time(dur) + } + + /// Same as [`Easy2::max_send_speed`](struct.Easy2.html#method.max_send_speed) + pub fn max_send_speed(&mut self, speed: u64) -> Result<(), Error> { + self.inner.max_send_speed(speed) + } + + /// Same as [`Easy2::max_recv_speed`](struct.Easy2.html#method.max_recv_speed) + pub fn max_recv_speed(&mut self, speed: u64) -> Result<(), Error> { + self.inner.max_recv_speed(speed) + } + + /// Same as [`Easy2::max_connects`](struct.Easy2.html#method.max_connects) + pub fn max_connects(&mut self, max: u32) -> Result<(), Error> { + self.inner.max_connects(max) + } + + /// Same as [`Easy2::maxage_conn`](struct.Easy2.html#method.maxage_conn) + pub fn maxage_conn(&mut self, max_age: Duration) -> Result<(), Error> { + self.inner.maxage_conn(max_age) + } + + /// Same as [`Easy2::fresh_connect`](struct.Easy2.html#method.fresh_connect) + pub fn fresh_connect(&mut self, enable: bool) -> Result<(), Error> { + self.inner.fresh_connect(enable) + } + + /// Same as [`Easy2::forbid_reuse`](struct.Easy2.html#method.forbid_reuse) + pub fn forbid_reuse(&mut self, enable: bool) -> Result<(), Error> { + self.inner.forbid_reuse(enable) + } + + /// Same as [`Easy2::connect_timeout`](struct.Easy2.html#method.connect_timeout) + pub fn connect_timeout(&mut self, timeout: Duration) -> Result<(), Error> { + self.inner.connect_timeout(timeout) + } + + /// Same as [`Easy2::ip_resolve`](struct.Easy2.html#method.ip_resolve) + pub fn ip_resolve(&mut self, resolve: IpResolve) -> Result<(), Error> { + self.inner.ip_resolve(resolve) + } + + /// Same as [`Easy2::resolve`](struct.Easy2.html#method.resolve) + pub fn resolve(&mut self, list: List) -> Result<(), Error> { + self.inner.resolve(list) + } + + /// Same as [`Easy2::connect_only`](struct.Easy2.html#method.connect_only) + pub fn connect_only(&mut self, enable: bool) -> Result<(), Error> { + self.inner.connect_only(enable) + } + + // ========================================================================= + // SSL/Security Options + + /// Same as [`Easy2::ssl_cert`](struct.Easy2.html#method.ssl_cert) + pub fn ssl_cert<P: AsRef<Path>>(&mut self, cert: P) -> Result<(), Error> { + self.inner.ssl_cert(cert) + } + + /// Same as [`Easy2::ssl_cert_blob`](struct.Easy2.html#method.ssl_cert_blob) + pub fn ssl_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.inner.ssl_cert_blob(blob) + } + + /// Same as [`Easy2::ssl_cert_type`](struct.Easy2.html#method.ssl_cert_type) + pub fn ssl_cert_type(&mut self, kind: &str) -> Result<(), Error> { + self.inner.ssl_cert_type(kind) + } + + /// Same as [`Easy2::ssl_key`](struct.Easy2.html#method.ssl_key) + pub fn ssl_key<P: AsRef<Path>>(&mut self, key: P) -> Result<(), Error> { + self.inner.ssl_key(key) + } + + /// Same as [`Easy2::ssl_key_blob`](struct.Easy2.html#method.ssl_key_blob) + pub fn ssl_key_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.inner.ssl_key_blob(blob) + } + + /// Same as [`Easy2::ssl_key_type`](struct.Easy2.html#method.ssl_key_type) + pub fn ssl_key_type(&mut self, kind: &str) -> Result<(), Error> { + self.inner.ssl_key_type(kind) + } + + /// Same as [`Easy2::key_password`](struct.Easy2.html#method.key_password) + pub fn key_password(&mut self, password: &str) -> Result<(), Error> { + self.inner.key_password(password) + } + + /// Same as [`Easy2::ssl_cainfo_blob`](struct.Easy2.html#method.ssl_cainfo_blob) + pub fn ssl_cainfo_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.inner.ssl_cainfo_blob(blob) + } + + /// Same as [`Easy2::proxy_ssl_cainfo_blob`](struct.Easy2.html#method.proxy_ssl_cainfo_blob) + pub fn proxy_ssl_cainfo_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.inner.proxy_ssl_cainfo_blob(blob) + } + + /// Same as [`Easy2::ssl_engine`](struct.Easy2.html#method.ssl_engine) + pub fn ssl_engine(&mut self, engine: &str) -> Result<(), Error> { + self.inner.ssl_engine(engine) + } + + /// Same as [`Easy2::ssl_engine_default`](struct.Easy2.html#method.ssl_engine_default) + pub fn ssl_engine_default(&mut self, enable: bool) -> Result<(), Error> { + self.inner.ssl_engine_default(enable) + } + + /// Same as [`Easy2::http_version`](struct.Easy2.html#method.http_version) + pub fn http_version(&mut self, version: HttpVersion) -> Result<(), Error> { + self.inner.http_version(version) + } + + /// Same as [`Easy2::ssl_version`](struct.Easy2.html#method.ssl_version) + pub fn ssl_version(&mut self, version: SslVersion) -> Result<(), Error> { + self.inner.ssl_version(version) + } + + /// Same as [`Easy2::proxy_ssl_version`](struct.Easy2.html#method.proxy_ssl_version) + pub fn proxy_ssl_version(&mut self, version: SslVersion) -> Result<(), Error> { + self.inner.proxy_ssl_version(version) + } + + /// Same as [`Easy2::ssl_min_max_version`](struct.Easy2.html#method.ssl_min_max_version) + pub fn ssl_min_max_version( + &mut self, + min_version: SslVersion, + max_version: SslVersion, + ) -> Result<(), Error> { + self.inner.ssl_min_max_version(min_version, max_version) + } + + /// Same as [`Easy2::proxy_ssl_min_max_version`](struct.Easy2.html#method.proxy_ssl_min_max_version) + pub fn proxy_ssl_min_max_version( + &mut self, + min_version: SslVersion, + max_version: SslVersion, + ) -> Result<(), Error> { + self.inner + .proxy_ssl_min_max_version(min_version, max_version) + } + + /// Same as [`Easy2::ssl_verify_host`](struct.Easy2.html#method.ssl_verify_host) + pub fn ssl_verify_host(&mut self, verify: bool) -> Result<(), Error> { + self.inner.ssl_verify_host(verify) + } + + /// Same as [`Easy2::proxy_ssl_verify_host`](struct.Easy2.html#method.proxy_ssl_verify_host) + pub fn proxy_ssl_verify_host(&mut self, verify: bool) -> Result<(), Error> { + self.inner.proxy_ssl_verify_host(verify) + } + + /// Same as [`Easy2::ssl_verify_peer`](struct.Easy2.html#method.ssl_verify_peer) + pub fn ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error> { + self.inner.ssl_verify_peer(verify) + } + + /// Same as [`Easy2::proxy_ssl_verify_peer`](struct.Easy2.html#method.proxy_ssl_verify_peer) + pub fn proxy_ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error> { + self.inner.proxy_ssl_verify_peer(verify) + } + + /// Same as [`Easy2::cainfo`](struct.Easy2.html#method.cainfo) + pub fn cainfo<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.inner.cainfo(path) + } + + /// Same as [`Easy2::issuer_cert`](struct.Easy2.html#method.issuer_cert) + pub fn issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.inner.issuer_cert(path) + } + + /// Same as [`Easy2::proxy_issuer_cert`](struct.Easy2.html#method.proxy_issuer_cert) + pub fn proxy_issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.inner.proxy_issuer_cert(path) + } + + /// Same as [`Easy2::issuer_cert_blob`](struct.Easy2.html#method.issuer_cert_blob) + pub fn issuer_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.inner.issuer_cert_blob(blob) + } + + /// Same as [`Easy2::proxy_issuer_cert_blob`](struct.Easy2.html#method.proxy_issuer_cert_blob) + pub fn proxy_issuer_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.inner.proxy_issuer_cert_blob(blob) + } + + /// Same as [`Easy2::capath`](struct.Easy2.html#method.capath) + pub fn capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.inner.capath(path) + } + + /// Same as [`Easy2::crlfile`](struct.Easy2.html#method.crlfile) + pub fn crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.inner.crlfile(path) + } + + /// Same as [`Easy2::proxy_crlfile`](struct.Easy2.html#method.proxy_crlfile) + pub fn proxy_crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.inner.proxy_crlfile(path) + } + + /// Same as [`Easy2::certinfo`](struct.Easy2.html#method.certinfo) + pub fn certinfo(&mut self, enable: bool) -> Result<(), Error> { + self.inner.certinfo(enable) + } + + /// Same as [`Easy2::random_file`](struct.Easy2.html#method.random_file) + pub fn random_file<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> { + self.inner.random_file(p) + } + + /// Same as [`Easy2::egd_socket`](struct.Easy2.html#method.egd_socket) + pub fn egd_socket<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> { + self.inner.egd_socket(p) + } + + /// Same as [`Easy2::ssl_cipher_list`](struct.Easy2.html#method.ssl_cipher_list) + pub fn ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error> { + self.inner.ssl_cipher_list(ciphers) + } + + /// Same as [`Easy2::proxy_ssl_cipher_list`](struct.Easy2.html#method.proxy_ssl_cipher_list) + pub fn proxy_ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error> { + self.inner.proxy_ssl_cipher_list(ciphers) + } + + /// Same as [`Easy2::ssl_sessionid_cache`](struct.Easy2.html#method.ssl_sessionid_cache) + pub fn ssl_sessionid_cache(&mut self, enable: bool) -> Result<(), Error> { + self.inner.ssl_sessionid_cache(enable) + } + + /// Same as [`Easy2::ssl_options`](struct.Easy2.html#method.ssl_options) + pub fn ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> { + self.inner.ssl_options(bits) + } + + /// Same as [`Easy2::proxy_ssl_options`](struct.Easy2.html#method.proxy_ssl_options) + pub fn proxy_ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> { + self.inner.proxy_ssl_options(bits) + } + + /// Same as [`Easy2::pinned_public_key`](struct.Easy2.html#method.pinned_public_key) + pub fn pinned_public_key(&mut self, pubkey: &str) -> Result<(), Error> { + self.inner.pinned_public_key(pubkey) + } + + // ========================================================================= + // getters + + /// Same as [`Easy2::time_condition_unmet`](struct.Easy2.html#method.time_condition_unmet) + pub fn time_condition_unmet(&mut self) -> Result<bool, Error> { + self.inner.time_condition_unmet() + } + + /// Same as [`Easy2::effective_url`](struct.Easy2.html#method.effective_url) + pub fn effective_url(&mut self) -> Result<Option<&str>, Error> { + self.inner.effective_url() + } + + /// Same as [`Easy2::effective_url_bytes`](struct.Easy2.html#method.effective_url_bytes) + pub fn effective_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> { + self.inner.effective_url_bytes() + } + + /// Same as [`Easy2::response_code`](struct.Easy2.html#method.response_code) + pub fn response_code(&mut self) -> Result<u32, Error> { + self.inner.response_code() + } + + /// Same as [`Easy2::http_connectcode`](struct.Easy2.html#method.http_connectcode) + pub fn http_connectcode(&mut self) -> Result<u32, Error> { + self.inner.http_connectcode() + } + + /// Same as [`Easy2::filetime`](struct.Easy2.html#method.filetime) + pub fn filetime(&mut self) -> Result<Option<i64>, Error> { + self.inner.filetime() + } + + /// Same as [`Easy2::download_size`](struct.Easy2.html#method.download_size) + pub fn download_size(&mut self) -> Result<f64, Error> { + self.inner.download_size() + } + + /// Same as [`Easy2::upload_size`](struct.Easy2.html#method.upload_size) + pub fn upload_size(&mut self) -> Result<f64, Error> { + self.inner.upload_size() + } + + /// Same as [`Easy2::content_length_download`](struct.Easy2.html#method.content_length_download) + pub fn content_length_download(&mut self) -> Result<f64, Error> { + self.inner.content_length_download() + } + + /// Same as [`Easy2::total_time`](struct.Easy2.html#method.total_time) + pub fn total_time(&mut self) -> Result<Duration, Error> { + self.inner.total_time() + } + + /// Same as [`Easy2::namelookup_time`](struct.Easy2.html#method.namelookup_time) + pub fn namelookup_time(&mut self) -> Result<Duration, Error> { + self.inner.namelookup_time() + } + + /// Same as [`Easy2::connect_time`](struct.Easy2.html#method.connect_time) + pub fn connect_time(&mut self) -> Result<Duration, Error> { + self.inner.connect_time() + } + + /// Same as [`Easy2::appconnect_time`](struct.Easy2.html#method.appconnect_time) + pub fn appconnect_time(&mut self) -> Result<Duration, Error> { + self.inner.appconnect_time() + } + + /// Same as [`Easy2::pretransfer_time`](struct.Easy2.html#method.pretransfer_time) + pub fn pretransfer_time(&mut self) -> Result<Duration, Error> { + self.inner.pretransfer_time() + } + + /// Same as [`Easy2::starttransfer_time`](struct.Easy2.html#method.starttransfer_time) + pub fn starttransfer_time(&mut self) -> Result<Duration, Error> { + self.inner.starttransfer_time() + } + + /// Same as [`Easy2::redirect_time`](struct.Easy2.html#method.redirect_time) + pub fn redirect_time(&mut self) -> Result<Duration, Error> { + self.inner.redirect_time() + } + + /// Same as [`Easy2::redirect_count`](struct.Easy2.html#method.redirect_count) + pub fn redirect_count(&mut self) -> Result<u32, Error> { + self.inner.redirect_count() + } + + /// Same as [`Easy2::redirect_url`](struct.Easy2.html#method.redirect_url) + pub fn redirect_url(&mut self) -> Result<Option<&str>, Error> { + self.inner.redirect_url() + } + + /// Same as [`Easy2::redirect_url_bytes`](struct.Easy2.html#method.redirect_url_bytes) + pub fn redirect_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> { + self.inner.redirect_url_bytes() + } + + /// Same as [`Easy2::header_size`](struct.Easy2.html#method.header_size) + pub fn header_size(&mut self) -> Result<u64, Error> { + self.inner.header_size() + } + + /// Same as [`Easy2::request_size`](struct.Easy2.html#method.request_size) + pub fn request_size(&mut self) -> Result<u64, Error> { + self.inner.request_size() + } + + /// Same as [`Easy2::content_type`](struct.Easy2.html#method.content_type) + pub fn content_type(&mut self) -> Result<Option<&str>, Error> { + self.inner.content_type() + } + + /// Same as [`Easy2::content_type_bytes`](struct.Easy2.html#method.content_type_bytes) + pub fn content_type_bytes(&mut self) -> Result<Option<&[u8]>, Error> { + self.inner.content_type_bytes() + } + + /// Same as [`Easy2::os_errno`](struct.Easy2.html#method.os_errno) + pub fn os_errno(&mut self) -> Result<i32, Error> { + self.inner.os_errno() + } + + /// Same as [`Easy2::primary_ip`](struct.Easy2.html#method.primary_ip) + pub fn primary_ip(&mut self) -> Result<Option<&str>, Error> { + self.inner.primary_ip() + } + + /// Same as [`Easy2::primary_port`](struct.Easy2.html#method.primary_port) + pub fn primary_port(&mut self) -> Result<u16, Error> { + self.inner.primary_port() + } + + /// Same as [`Easy2::local_ip`](struct.Easy2.html#method.local_ip) + pub fn local_ip(&mut self) -> Result<Option<&str>, Error> { + self.inner.local_ip() + } + + /// Same as [`Easy2::local_port`](struct.Easy2.html#method.local_port) + pub fn local_port(&mut self) -> Result<u16, Error> { + self.inner.local_port() + } + + /// Same as [`Easy2::cookies`](struct.Easy2.html#method.cookies) + pub fn cookies(&mut self) -> Result<List, Error> { + self.inner.cookies() + } + + /// Same as [`Easy2::pipewait`](struct.Easy2.html#method.pipewait) + pub fn pipewait(&mut self, wait: bool) -> Result<(), Error> { + self.inner.pipewait(wait) + } + + /// Same as [`Easy2::http_09_allowed`](struct.Easy2.html#method.http_09_allowed) + pub fn http_09_allowed(&mut self, allow: bool) -> Result<(), Error> { + self.inner.http_09_allowed(allow) + } + + // ========================================================================= + // Other methods + + /// Same as [`Easy2::perform`](struct.Easy2.html#method.perform) + pub fn perform(&self) -> Result<(), Error> { + assert!(self.inner.get_ref().borrowed.get().is_null()); + self.do_perform() + } + + fn do_perform(&self) -> Result<(), Error> { + // We don't allow recursive invocations of `perform` because we're + // invoking `FnMut`closures behind a `&self` pointer. This flag acts as + // our own `RefCell` borrow flag sorta. + if self.inner.get_ref().running.get() { + return Err(Error::new(curl_sys::CURLE_FAILED_INIT)); + } + + self.inner.get_ref().running.set(true); + struct Reset<'a>(&'a Cell<bool>); + impl<'a> Drop for Reset<'a> { + fn drop(&mut self) { + self.0.set(false); + } + } + let _reset = Reset(&self.inner.get_ref().running); + + self.inner.perform() + } + + /// Creates a new scoped transfer which can be used to set callbacks and + /// data which only live for the scope of the returned object. + /// + /// An `Easy` handle is often reused between different requests to cache + /// connections to servers, but often the lifetime of the data as part of + /// each transfer is unique. This function serves as an ability to share an + /// `Easy` across many transfers while ergonomically using possibly + /// stack-local data as part of each transfer. + /// + /// Configuration can be set on the `Easy` and then a `Transfer` can be + /// created to set scoped configuration (like callbacks). Finally, the + /// `perform` method on the `Transfer` function can be used. + /// + /// When the `Transfer` option is dropped then all configuration set on the + /// transfer itself will be reset. + pub fn transfer<'data, 'easy>(&'easy mut self) -> Transfer<'easy, 'data> { + assert!(!self.inner.get_ref().running.get()); + Transfer { + data: Box::new(Callbacks::default()), + easy: self, + } + } + + /// Same as [`Easy2::upkeep`](struct.Easy2.html#method.upkeep) + #[cfg(feature = "upkeep_7_62_0")] + pub fn upkeep(&self) -> Result<(), Error> { + self.inner.upkeep() + } + + /// Same as [`Easy2::unpause_read`](struct.Easy2.html#method.unpause_read) + pub fn unpause_read(&self) -> Result<(), Error> { + self.inner.unpause_read() + } + + /// Same as [`Easy2::unpause_write`](struct.Easy2.html#method.unpause_write) + pub fn unpause_write(&self) -> Result<(), Error> { + self.inner.unpause_write() + } + + /// Same as [`Easy2::url_encode`](struct.Easy2.html#method.url_encode) + pub fn url_encode(&mut self, s: &[u8]) -> String { + self.inner.url_encode(s) + } + + /// Same as [`Easy2::url_decode`](struct.Easy2.html#method.url_decode) + pub fn url_decode(&mut self, s: &str) -> Vec<u8> { + self.inner.url_decode(s) + } + + /// Same as [`Easy2::reset`](struct.Easy2.html#method.reset) + pub fn reset(&mut self) { + self.inner.reset() + } + + /// Same as [`Easy2::recv`](struct.Easy2.html#method.recv) + pub fn recv(&mut self, data: &mut [u8]) -> Result<usize, Error> { + self.inner.recv(data) + } + + /// Same as [`Easy2::send`](struct.Easy2.html#method.send) + pub fn send(&mut self, data: &[u8]) -> Result<usize, Error> { + self.inner.send(data) + } + + /// Same as [`Easy2::raw`](struct.Easy2.html#method.raw) + pub fn raw(&self) -> *mut curl_sys::CURL { + self.inner.raw() + } + + /// Same as [`Easy2::take_error_buf`](struct.Easy2.html#method.take_error_buf) + pub fn take_error_buf(&self) -> Option<String> { + self.inner.take_error_buf() + } +} + +impl EasyData { + /// An unsafe function to get the appropriate callback field. + /// + /// We can have callbacks configured from one of two different sources. + /// We could either have a callback from the `borrowed` field, callbacks on + /// an ephemeral `Transfer`, or the `owned` field which are `'static` + /// callbacks that live for the lifetime of this `EasyData`. + /// + /// The first set of callbacks are unsafe to access because they're actually + /// owned elsewhere and we're just aliasing. Additionally they don't + /// technically live long enough for us to access them, so they're hidden + /// behind unsafe pointers and casts. + /// + /// This function returns `&'a mut T` but that's actually somewhat of a lie. + /// The value should **not be stored to** nor should it be used for the full + /// lifetime of `'a`, but rather immediately in the local scope. + /// + /// Basically this is just intended to acquire a callback, invoke it, and + /// then stop. Nothing else. Super unsafe. + unsafe fn callback<'a, T, F>(&'a mut self, f: F) -> Option<&'a mut T> + where + F: for<'b> Fn(&'b mut Callbacks<'static>) -> &'b mut Option<T>, + { + let ptr = self.borrowed.get(); + if !ptr.is_null() { + let val = f(&mut *ptr); + if val.is_some() { + return val.as_mut(); + } + } + f(&mut self.owned).as_mut() + } +} + +impl Handler for EasyData { + fn write(&mut self, data: &[u8]) -> Result<usize, WriteError> { + unsafe { + match self.callback(|s| &mut s.write) { + Some(write) => write(data), + None => Ok(data.len()), + } + } + } + + fn read(&mut self, data: &mut [u8]) -> Result<usize, ReadError> { + unsafe { + match self.callback(|s| &mut s.read) { + Some(read) => read(data), + None => Ok(0), + } + } + } + + fn seek(&mut self, whence: SeekFrom) -> SeekResult { + unsafe { + match self.callback(|s| &mut s.seek) { + Some(seek) => seek(whence), + None => SeekResult::CantSeek, + } + } + } + + fn debug(&mut self, kind: InfoType, data: &[u8]) { + unsafe { + match self.callback(|s| &mut s.debug) { + Some(debug) => debug(kind, data), + None => handler::debug(kind, data), + } + } + } + + fn header(&mut self, data: &[u8]) -> bool { + unsafe { + match self.callback(|s| &mut s.header) { + Some(header) => header(data), + None => true, + } + } + } + + fn progress(&mut self, dltotal: f64, dlnow: f64, ultotal: f64, ulnow: f64) -> bool { + unsafe { + match self.callback(|s| &mut s.progress) { + Some(progress) => progress(dltotal, dlnow, ultotal, ulnow), + None => true, + } + } + } + + fn ssl_ctx(&mut self, cx: *mut c_void) -> Result<(), Error> { + unsafe { + match self.callback(|s| &mut s.ssl_ctx) { + Some(ssl_ctx) => ssl_ctx(cx), + None => handler::ssl_ctx(cx), + } + } + } +} + +impl fmt::Debug for EasyData { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "callbacks ...".fmt(f) + } +} + +impl<'easy, 'data> Transfer<'easy, 'data> { + /// Same as `Easy::write_function`, just takes a non `'static` lifetime + /// corresponding to the lifetime of this transfer. + pub fn write_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(&[u8]) -> Result<usize, WriteError> + 'data, + { + self.data.write = Some(Box::new(f)); + Ok(()) + } + + /// Same as `Easy::read_function`, just takes a non `'static` lifetime + /// corresponding to the lifetime of this transfer. + pub fn read_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(&mut [u8]) -> Result<usize, ReadError> + 'data, + { + self.data.read = Some(Box::new(f)); + Ok(()) + } + + /// Same as `Easy::seek_function`, just takes a non `'static` lifetime + /// corresponding to the lifetime of this transfer. + pub fn seek_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(SeekFrom) -> SeekResult + 'data, + { + self.data.seek = Some(Box::new(f)); + Ok(()) + } + + /// Same as `Easy::progress_function`, just takes a non `'static` lifetime + /// corresponding to the lifetime of this transfer. + pub fn progress_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(f64, f64, f64, f64) -> bool + 'data, + { + self.data.progress = Some(Box::new(f)); + Ok(()) + } + + /// Same as `Easy::ssl_ctx_function`, just takes a non `'static` + /// lifetime corresponding to the lifetime of this transfer. + pub fn ssl_ctx_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(*mut c_void) -> Result<(), Error> + Send + 'data, + { + self.data.ssl_ctx = Some(Box::new(f)); + Ok(()) + } + + /// Same as `Easy::debug_function`, just takes a non `'static` lifetime + /// corresponding to the lifetime of this transfer. + pub fn debug_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(InfoType, &[u8]) + 'data, + { + self.data.debug = Some(Box::new(f)); + Ok(()) + } + + /// Same as `Easy::header_function`, just takes a non `'static` lifetime + /// corresponding to the lifetime of this transfer. + pub fn header_function<F>(&mut self, f: F) -> Result<(), Error> + where + F: FnMut(&[u8]) -> bool + 'data, + { + self.data.header = Some(Box::new(f)); + Ok(()) + } + + /// Same as `Easy::perform`. + pub fn perform(&self) -> Result<(), Error> { + let inner = self.easy.inner.get_ref(); + + // Note that we're casting a `&self` pointer to a `*mut`, and then + // during the invocation of this call we're going to invoke `FnMut` + // closures that we ourselves own. + // + // This should be ok, however, because `do_perform` checks for recursive + // invocations of `perform` and disallows them. Our type also isn't + // `Sync`. + inner.borrowed.set(&*self.data as *const _ as *mut _); + + // Make sure to reset everything back to the way it was before when + // we're done. + struct Reset<'a>(&'a Cell<*mut Callbacks<'static>>); + impl<'a> Drop for Reset<'a> { + fn drop(&mut self) { + self.0.set(ptr::null_mut()); + } + } + let _reset = Reset(&inner.borrowed); + + self.easy.do_perform() + } + + /// Same as `Easy::upkeep` + #[cfg(feature = "upkeep_7_62_0")] + pub fn upkeep(&self) -> Result<(), Error> { + self.easy.upkeep() + } + + /// Same as `Easy::unpause_read`. + pub fn unpause_read(&self) -> Result<(), Error> { + self.easy.unpause_read() + } + + /// Same as `Easy::unpause_write` + pub fn unpause_write(&self) -> Result<(), Error> { + self.easy.unpause_write() + } +} + +impl<'easy, 'data> fmt::Debug for Transfer<'easy, 'data> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Transfer") + .field("easy", &self.easy) + .finish() + } +} + +impl<'easy, 'data> Drop for Transfer<'easy, 'data> { + fn drop(&mut self) { + // Extra double check to make sure we don't leak a pointer to ourselves. + assert!(self.easy.inner.get_ref().borrowed.get().is_null()); + } +} diff --git a/vendor/curl/src/easy/handler.rs b/vendor/curl/src/easy/handler.rs new file mode 100644 index 000000000..b90a968d3 --- /dev/null +++ b/vendor/curl/src/easy/handler.rs @@ -0,0 +1,3850 @@ +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 crate::easy::form; +use crate::easy::list; +use crate::easy::windows; +use crate::easy::{Form, List}; +use crate::panic; +use crate::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> { + crate::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) { + use std::sync::Once; + + static mut PROBE: Option<::openssl_probe::ProbeResult> = None; + static INIT: Once = Once::new(); + + // Probe for certificate stores the first time an easy handle is created, + // and re-use the results for subsequent handles. + INIT.call_once(|| unsafe { + PROBE = Some(::openssl_probe::probe()); + }); + let probe = unsafe { PROBE.as_ref().unwrap() }; + + 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> { + self.setopt_long(curl_sys::CURLOPT_PATH_AS_IS, as_is as c_long) + } + + /// 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) + } + + /// Specify type of the client SSL certificate for HTTPS proxy. + /// + /// The string should be the format of your certificate. Supported formats + /// are "PEM" and "DER", except with Secure Transport. OpenSSL (versions + /// 0.9.3 and later) and Secure Transport (on iOS 5 or later, or OS X 10.7 + /// or later) also support "P12" for PKCS#12-encoded files. + /// + /// By default this option is "PEM" and corresponds to + /// `CURLOPT_PROXY_SSLCERTTYPE`. + pub fn proxy_sslcert_type(&mut self, kind: &str) -> Result<(), Error> { + let kind = CString::new(kind)?; + self.setopt_str(curl_sys::CURLOPT_PROXY_SSLCERTTYPE, &kind) + } + + /// Set the client certificate for the proxy using an in-memory blob. + /// + /// The specified byte buffer should contain the binary content of the + /// certificate, which will be copied into the handle. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_SSLCERT_BLOB`. + pub fn proxy_sslcert_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.setopt_blob(curl_sys::CURLOPT_PROXY_SSLCERT_BLOB, blob) + } + + /// 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) + } + + /// Set type of the private key file for HTTPS proxy. + /// + /// The string should be the format of your private key. Supported formats + /// are "PEM", "DER" and "ENG". + /// + /// The format "ENG" enables you to load the private key from a crypto + /// engine. In this case `ssl_key` is used as an identifier passed to + /// the engine. You have to set the crypto engine with `ssl_engine`. + /// "DER" format key file currently does not work because of a bug in + /// OpenSSL. + /// + /// By default this option is "PEM" and corresponds to + /// `CURLOPT_PROXY_SSLKEYTYPE`. + pub fn proxy_sslkey_type(&mut self, kind: &str) -> Result<(), Error> { + let kind = CString::new(kind)?; + self.setopt_str(curl_sys::CURLOPT_PROXY_SSLKEYTYPE, &kind) + } + + /// Set the private key for the proxy using an in-memory blob. + /// + /// The specified byte buffer should contain the binary content of the + /// private key, which will be copied into the handle. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_SSLKEY_BLOB`. + pub fn proxy_sslkey_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.setopt_blob(curl_sys::CURLOPT_PROXY_SSLKEY_BLOB, blob) + } + + /// Set passphrase to private key for HTTPS proxy. + /// + /// This will be used as the password required to use the `ssl_key`. + /// You never needed a pass phrase to load a certificate but you need one to + /// load your private key. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_KEYPASSWD`. + pub fn proxy_key_password(&mut self, password: &str) -> Result<(), Error> { + let password = CString::new(password)?; + self.setopt_str(curl_sys::CURLOPT_PROXY_KEYPASSWD, &password) + } + + /// 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 + /// [c-ares](https://c-ares.haxx.se), otherwise setting it will return + /// an error. + pub fn dns_servers(&mut self, servers: &str) -> Result<(), Error> { + let s = CString::new(servers)?; + self.setopt_str(curl_sys::CURLOPT_DNS_SERVERS, &s) + } + + /// Sets the timeout of how long name resolves will be kept in memory. + /// + /// This is distinct from DNS TTL options and is entirely speculative. + /// + /// By default this option is 60s and corresponds to + /// `CURLOPT_DNS_CACHE_TIMEOUT`. + pub fn dns_cache_timeout(&mut self, dur: Duration) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_DNS_CACHE_TIMEOUT, dur.as_secs() as c_long) + } + + /// Provide the DNS-over-HTTPS URL. + /// + /// The parameter must be URL-encoded in the following format: + /// `https://host:port/path`. It **must** specify a HTTPS URL. + /// + /// libcurl does not validate the syntax or use this variable until the + /// transfer is issued. Even if you set a crazy value here, this method will + /// still return [`Ok`]. + /// + /// curl sends `POST` requests to the given DNS-over-HTTPS URL. + /// + /// To find the DoH server itself, which might be specified using a name, + /// libcurl will use the default name lookup function. You can bootstrap + /// that by providing the address for the DoH server with + /// [`Easy2::resolve`]. + /// + /// Disable DoH use again by setting this option to [`None`]. + /// + /// By default this option is not set and corresponds to `CURLOPT_DOH_URL`. + pub fn doh_url(&mut self, url: Option<&str>) -> Result<(), Error> { + if let Some(url) = url { + let url = CString::new(url)?; + self.setopt_str(curl_sys::CURLOPT_DOH_URL, &url) + } else { + self.setopt_ptr(curl_sys::CURLOPT_DOH_URL, ptr::null()) + } + } + + /// This option tells curl to verify the authenticity of the DoH + /// (DNS-over-HTTPS) server's certificate. A value of `true` means curl + /// verifies; `false` means it does not. + /// + /// This option is the DoH equivalent of [`Easy2::ssl_verify_peer`] and only + /// affects requests to the DoH server. + /// + /// When negotiating a TLS or SSL connection, the server sends a certificate + /// indicating its identity. Curl verifies whether the certificate is + /// authentic, i.e. that you can trust that the server is who the + /// certificate says it is. This trust is based on a chain of digital + /// signatures, rooted in certification authority (CA) certificates you + /// supply. curl uses a default bundle of CA certificates (the path for that + /// is determined at build time) and you can specify alternate certificates + /// with the [`Easy2::cainfo`] option or the [`Easy2::capath`] option. + /// + /// When `doh_ssl_verify_peer` is enabled, and the verification fails to + /// prove that the certificate is authentic, the connection fails. When the + /// option is zero, the peer certificate verification succeeds regardless. + /// + /// Authenticating the certificate is not enough to be sure about the + /// server. You typically also want to ensure that the server is the server + /// you mean to be talking to. Use [`Easy2::doh_ssl_verify_host`] for that. + /// The check that the host name in the certificate is valid for the host + /// name you are connecting to is done independently of the + /// `doh_ssl_verify_peer` option. + /// + /// **WARNING:** disabling verification of the certificate allows bad guys + /// to man-in-the-middle the communication without you knowing it. Disabling + /// verification makes the communication insecure. Just having encryption on + /// a transfer is not enough as you cannot be sure that you are + /// communicating with the correct end-point. + /// + /// By default this option is set to `true` and corresponds to + /// `CURLOPT_DOH_SSL_VERIFYPEER`. + pub fn doh_ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_DOH_SSL_VERIFYPEER, verify.into()) + } + + /// Tells curl to verify the DoH (DNS-over-HTTPS) server's certificate name + /// fields against the host name. + /// + /// This option is the DoH equivalent of [`Easy2::ssl_verify_host`] and only + /// affects requests to the DoH server. + /// + /// When `doh_ssl_verify_host` is `true`, the SSL certificate provided by + /// the DoH server must indicate that the server name is the same as the + /// server name to which you meant to connect to, or the connection fails. + /// + /// Curl considers the DoH server the intended one when the Common Name + /// field or a Subject Alternate Name field in the certificate matches the + /// host name in the DoH URL to which you told Curl to connect. + /// + /// When the verify value is set to `false`, the connection succeeds + /// regardless of the names used in the certificate. Use that ability with + /// caution! + /// + /// See also [`Easy2::doh_ssl_verify_peer`] to verify the digital signature + /// of the DoH server certificate. If libcurl is built against NSS and + /// [`Easy2::doh_ssl_verify_peer`] is `false`, `doh_ssl_verify_host` is also + /// set to `false` and cannot be overridden. + /// + /// By default this option is set to `true` and corresponds to + /// `CURLOPT_DOH_SSL_VERIFYHOST`. + pub fn doh_ssl_verify_host(&mut self, verify: bool) -> Result<(), Error> { + self.setopt_long( + curl_sys::CURLOPT_DOH_SSL_VERIFYHOST, + if verify { 2 } else { 0 }, + ) + } + + /// Pass a long as parameter set to 1 to enable or 0 to disable. + /// + /// This option determines whether libcurl verifies the status of the DoH + /// (DNS-over-HTTPS) server cert using the "Certificate Status Request" TLS + /// extension (aka. OCSP stapling). + /// + /// This option is the DoH equivalent of CURLOPT_SSL_VERIFYSTATUS and only + /// affects requests to the DoH server. + /// + /// Note that if this option is enabled but the server does not support the + /// TLS extension, the verification will fail. + /// + /// By default this option is set to `false` and corresponds to + /// `CURLOPT_DOH_SSL_VERIFYSTATUS`. + pub fn doh_ssl_verify_status(&mut self, verify: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_DOH_SSL_VERIFYSTATUS, verify.into()) + } + + /// Specify the preferred receive buffer size, in bytes. + /// + /// This is treated as a request, not an order, and the main point of this + /// is that the write callback may get called more often with smaller + /// chunks. + /// + /// By default this option is the maximum write size and corresopnds to + /// `CURLOPT_BUFFERSIZE`. + pub fn buffer_size(&mut self, size: usize) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_BUFFERSIZE, size as c_long) + } + + /// Specify the preferred send buffer size, in bytes. + /// + /// This is treated as a request, not an order, and the main point of this + /// is that the read callback may get called more often with smaller + /// chunks. + /// + /// The upload buffer size is by default 64 kilobytes. + pub fn upload_buffer_size(&mut self, size: usize) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_UPLOAD_BUFFERSIZE, size as c_long) + } + + // /// Enable or disable TCP Fast Open + // /// + // /// By default this options defaults to `false` and corresponds to + // /// `CURLOPT_TCP_FASTOPEN` + // pub fn fast_open(&mut self, enable: bool) -> Result<(), Error> { + // } + + /// Configures whether the TCP_NODELAY option is set, or Nagle's algorithm + /// is disabled. + /// + /// The purpose of Nagle's algorithm is to minimize the number of small + /// packet's on the network, and disabling this may be less efficient in + /// some situations. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_TCP_NODELAY`. + pub fn tcp_nodelay(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_TCP_NODELAY, enable as c_long) + } + + /// Configures whether TCP keepalive probes will be sent. + /// + /// The delay and frequency of these probes is controlled by `tcp_keepidle` + /// and `tcp_keepintvl`. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_TCP_KEEPALIVE`. + pub fn tcp_keepalive(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_TCP_KEEPALIVE, enable as c_long) + } + + /// Configures the TCP keepalive idle time wait. + /// + /// This is the delay, after which the connection is idle, keepalive probes + /// will be sent. Not all operating systems support this. + /// + /// By default this corresponds to `CURLOPT_TCP_KEEPIDLE`. + pub fn tcp_keepidle(&mut self, amt: Duration) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_TCP_KEEPIDLE, amt.as_secs() as c_long) + } + + /// Configures the delay between keepalive probes. + /// + /// By default this corresponds to `CURLOPT_TCP_KEEPINTVL`. + pub fn tcp_keepintvl(&mut self, amt: Duration) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_TCP_KEEPINTVL, amt.as_secs() as c_long) + } + + /// Configures the scope for local IPv6 addresses. + /// + /// Sets the scope_id value to use when connecting to IPv6 or link-local + /// addresses. + /// + /// By default this value is 0 and corresponds to `CURLOPT_ADDRESS_SCOPE` + pub fn address_scope(&mut self, scope: u32) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_ADDRESS_SCOPE, scope as c_long) + } + + // ========================================================================= + // Names and passwords + + /// Configures the username to pass as authentication for this connection. + /// + /// By default this value is not set and corresponds to `CURLOPT_USERNAME`. + pub fn username(&mut self, user: &str) -> Result<(), Error> { + let user = CString::new(user)?; + self.setopt_str(curl_sys::CURLOPT_USERNAME, &user) + } + + /// Configures the password to pass as authentication for this connection. + /// + /// By default this value is not set and corresponds to `CURLOPT_PASSWORD`. + pub fn password(&mut self, pass: &str) -> Result<(), Error> { + let pass = CString::new(pass)?; + self.setopt_str(curl_sys::CURLOPT_PASSWORD, &pass) + } + + /// Set HTTP server authentication methods to try + /// + /// If more than one method is set, libcurl will first query the site to see + /// which authentication methods it supports and then pick the best one you + /// allow it to use. For some methods, this will induce an extra network + /// round-trip. Set the actual name and password with the `password` and + /// `username` methods. + /// + /// For authentication with a proxy, see `proxy_auth`. + /// + /// By default this value is basic and corresponds to `CURLOPT_HTTPAUTH`. + pub fn http_auth(&mut self, auth: &Auth) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_HTTPAUTH, auth.bits) + } + + /// Provides AWS V4 signature authentication on HTTP(S) header. + /// + /// `param` is used to create outgoing authentication headers. + /// Its format is `provider1[:provider2[:region[:service]]]`. + /// `provider1,\ provider2"` are used for generating auth parameters + /// such as "Algorithm", "date", "request type" and "signed headers". + /// `region` is the geographic area of a resources collection. It is + /// extracted from the host name specified in the URL if omitted. + /// `service` is a function provided by a cloud. It is extracted + /// from the host name specified in the URL if omitted. + /// + /// Example with "Test:Try", when curl will do the algorithm, it will + /// generate "TEST-HMAC-SHA256" for "Algorithm", "x-try-date" and + /// "X-Try-Date" for "date", "test4_request" for "request type", and + /// "SignedHeaders=content-type;host;x-try-date" for "signed headers". + /// If you use just "test", instead of "test:try", test will be use + /// for every strings generated. + /// + /// This is a special auth type that can't be combined with the others. + /// It will override the other auth types you might have set. + /// + /// By default this is not set and corresponds to `CURLOPT_AWS_SIGV4`. + pub fn aws_sigv4(&mut self, param: &str) -> Result<(), Error> { + let param = CString::new(param)?; + self.setopt_str(curl_sys::CURLOPT_AWS_SIGV4, ¶m) + } + + /// Configures the proxy username to pass as authentication for this + /// connection. + /// + /// By default this value is not set and corresponds to + /// `CURLOPT_PROXYUSERNAME`. + pub fn proxy_username(&mut self, user: &str) -> Result<(), Error> { + let user = CString::new(user)?; + self.setopt_str(curl_sys::CURLOPT_PROXYUSERNAME, &user) + } + + /// Configures the proxy password to pass as authentication for this + /// connection. + /// + /// By default this value is not set and corresponds to + /// `CURLOPT_PROXYPASSWORD`. + pub fn proxy_password(&mut self, pass: &str) -> Result<(), Error> { + let pass = CString::new(pass)?; + self.setopt_str(curl_sys::CURLOPT_PROXYPASSWORD, &pass) + } + + /// Set HTTP proxy authentication methods to try + /// + /// If more than one method is set, libcurl will first query the site to see + /// which authentication methods it supports and then pick the best one you + /// allow it to use. For some methods, this will induce an extra network + /// round-trip. Set the actual name and password with the `proxy_password` + /// and `proxy_username` methods. + /// + /// By default this value is basic and corresponds to `CURLOPT_PROXYAUTH`. + pub fn proxy_auth(&mut self, auth: &Auth) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_PROXYAUTH, auth.bits) + } + + /// Enable .netrc parsing + /// + /// By default the .netrc file is ignored and corresponds to `CURL_NETRC_IGNORED`. + pub fn netrc(&mut self, netrc: NetRc) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_NETRC, netrc as c_long) + } + + // ========================================================================= + // HTTP Options + + /// Indicates whether the referer header is automatically updated + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_AUTOREFERER`. + pub fn autoreferer(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_AUTOREFERER, enable as c_long) + } + + /// Enables automatic decompression of HTTP downloads. + /// + /// Sets the contents of the Accept-Encoding header sent in an HTTP request. + /// This enables decoding of a response with Content-Encoding. + /// + /// Currently supported encoding are `identity`, `zlib`, and `gzip`. A + /// zero-length string passed in will send all accepted encodings. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_ACCEPT_ENCODING`. + pub fn accept_encoding(&mut self, encoding: &str) -> Result<(), Error> { + let encoding = CString::new(encoding)?; + self.setopt_str(curl_sys::CURLOPT_ACCEPT_ENCODING, &encoding) + } + + /// Request the HTTP Transfer Encoding. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_TRANSFER_ENCODING`. + pub fn transfer_encoding(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_TRANSFER_ENCODING, enable as c_long) + } + + /// Follow HTTP 3xx redirects. + /// + /// Indicates whether any `Location` headers in the response should get + /// followed. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_FOLLOWLOCATION`. + pub fn follow_location(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_FOLLOWLOCATION, enable as c_long) + } + + /// Send credentials to hosts other than the first as well. + /// + /// Sends username/password credentials even when the host changes as part + /// of a redirect. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_UNRESTRICTED_AUTH`. + pub fn unrestricted_auth(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_UNRESTRICTED_AUTH, enable as c_long) + } + + /// Set the maximum number of redirects allowed. + /// + /// A value of 0 will refuse any redirect. + /// + /// By default this option is `-1` (unlimited) and corresponds to + /// `CURLOPT_MAXREDIRS`. + pub fn max_redirections(&mut self, max: u32) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_MAXREDIRS, max as c_long) + } + + // TODO: post_redirections + + /// Make an HTTP PUT request. + /// + /// By default this option is `false` and corresponds to `CURLOPT_PUT`. + pub fn put(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_PUT, enable as c_long) + } + + /// Make an HTTP POST request. + /// + /// This will also make the library use the + /// `Content-Type: application/x-www-form-urlencoded` header. + /// + /// POST data can be specified through `post_fields` or by specifying a read + /// function. + /// + /// By default this option is `false` and corresponds to `CURLOPT_POST`. + pub fn post(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_POST, enable as c_long) + } + + /// Configures the data that will be uploaded as part of a POST. + /// + /// Note that the data is copied into this handle and if that's not desired + /// then the read callbacks can be used instead. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_COPYPOSTFIELDS`. + pub fn post_fields_copy(&mut self, data: &[u8]) -> Result<(), Error> { + // Set the length before the pointer so libcurl knows how much to read + self.post_field_size(data.len() as u64)?; + self.setopt_ptr(curl_sys::CURLOPT_COPYPOSTFIELDS, data.as_ptr() as *const _) + } + + /// Configures the size of data that's going to be uploaded as part of a + /// POST operation. + /// + /// This is called automatically as part of `post_fields` and should only + /// be called if data is being provided in a read callback (and even then + /// it's optional). + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_POSTFIELDSIZE_LARGE`. + pub fn post_field_size(&mut self, size: u64) -> Result<(), Error> { + // Clear anything previous to ensure we don't read past a buffer + self.setopt_ptr(curl_sys::CURLOPT_POSTFIELDS, ptr::null())?; + self.setopt_off_t( + curl_sys::CURLOPT_POSTFIELDSIZE_LARGE, + size as curl_sys::curl_off_t, + ) + } + + /// Tells libcurl you want a multipart/formdata HTTP POST to be made and you + /// instruct what data to pass on to the server in the `form` argument. + /// + /// By default this option is set to null and corresponds to + /// `CURLOPT_HTTPPOST`. + pub fn httppost(&mut self, form: Form) -> Result<(), Error> { + self.setopt_ptr(curl_sys::CURLOPT_HTTPPOST, form::raw(&form) as *const _)?; + self.inner.form = Some(form); + Ok(()) + } + + /// Sets the HTTP referer header + /// + /// By default this option is not set and corresponds to `CURLOPT_REFERER`. + pub fn referer(&mut self, referer: &str) -> Result<(), Error> { + let referer = CString::new(referer)?; + self.setopt_str(curl_sys::CURLOPT_REFERER, &referer) + } + + /// Sets the HTTP user-agent header + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_USERAGENT`. + pub fn useragent(&mut self, useragent: &str) -> Result<(), Error> { + let useragent = CString::new(useragent)?; + self.setopt_str(curl_sys::CURLOPT_USERAGENT, &useragent) + } + + /// Add some headers to this HTTP request. + /// + /// If you add a header that is otherwise used internally, the value here + /// takes precedence. If a header is added with no content (like `Accept:`) + /// the internally the header will get disabled. To add a header with no + /// content, use the form `MyHeader;` (not the trailing semicolon). + /// + /// Headers must not be CRLF terminated. Many replaced headers have common + /// shortcuts which should be prefered. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_HTTPHEADER` + /// + /// # Examples + /// + /// ``` + /// use curl::easy::{Easy, List}; + /// + /// let mut list = List::new(); + /// list.append("Foo: bar").unwrap(); + /// list.append("Bar: baz").unwrap(); + /// + /// let mut handle = Easy::new(); + /// handle.url("https://www.rust-lang.org/").unwrap(); + /// handle.http_headers(list).unwrap(); + /// handle.perform().unwrap(); + /// ``` + pub fn http_headers(&mut self, list: List) -> Result<(), Error> { + let ptr = list::raw(&list); + self.inner.header_list = Some(list); + self.setopt_ptr(curl_sys::CURLOPT_HTTPHEADER, ptr as *const _) + } + + // /// Add some headers to send to the HTTP proxy. + // /// + // /// This function is essentially the same as `http_headers`. + // /// + // /// By default this option is not set and corresponds to + // /// `CURLOPT_PROXYHEADER` + // pub fn proxy_headers(&mut self, list: &'a List) -> Result<(), Error> { + // self.setopt_ptr(curl_sys::CURLOPT_PROXYHEADER, list.raw as *const _) + // } + + /// Set the contents of the HTTP Cookie header. + /// + /// Pass a string of the form `name=contents` for one cookie value or + /// `name1=val1; name2=val2` for multiple values. + /// + /// Using this option multiple times will only make the latest string + /// override the previous ones. This option will not enable the cookie + /// engine, use `cookie_file` or `cookie_jar` to do that. + /// + /// By default this option is not set and corresponds to `CURLOPT_COOKIE`. + pub fn cookie(&mut self, cookie: &str) -> Result<(), Error> { + let cookie = CString::new(cookie)?; + self.setopt_str(curl_sys::CURLOPT_COOKIE, &cookie) + } + + /// Set the file name to read cookies from. + /// + /// The cookie data can be in either the old Netscape / Mozilla cookie data + /// format or just regular HTTP headers (Set-Cookie style) dumped to a file. + /// + /// This also enables the cookie engine, making libcurl parse and send + /// cookies on subsequent requests with this handle. + /// + /// Given an empty or non-existing file or by passing the empty string ("") + /// to this option, you can enable the cookie engine without reading any + /// initial cookies. + /// + /// If you use this option multiple times, you just add more files to read. + /// Subsequent files will add more cookies. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_COOKIEFILE`. + pub fn cookie_file<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_COOKIEFILE, file.as_ref()) + } + + /// Set the file name to store cookies to. + /// + /// This will make libcurl write all internally known cookies to the file + /// when this handle is dropped. If no cookies are known, no file will be + /// created. Specify "-" as filename to instead have the cookies written to + /// stdout. Using this option also enables cookies for this session, so if + /// you for example follow a location it will make matching cookies get sent + /// accordingly. + /// + /// Note that libcurl doesn't read any cookies from the cookie jar. If you + /// want to read cookies from a file, use `cookie_file`. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_COOKIEJAR`. + pub fn cookie_jar<P: AsRef<Path>>(&mut self, file: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_COOKIEJAR, file.as_ref()) + } + + /// Start a new cookie session + /// + /// Marks this as a new cookie "session". It will force libcurl to ignore + /// all cookies it is about to load that are "session cookies" from the + /// previous session. By default, libcurl always stores and loads all + /// cookies, independent if they are session cookies or not. Session cookies + /// are cookies without expiry date and they are meant to be alive and + /// existing for this "session" only. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_COOKIESESSION`. + pub fn cookie_session(&mut self, session: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_COOKIESESSION, session as c_long) + } + + /// Add to or manipulate cookies held in memory. + /// + /// Such a cookie can be either a single line in Netscape / Mozilla format + /// or just regular HTTP-style header (Set-Cookie: ...) format. This will + /// also enable the cookie engine. This adds that single cookie to the + /// internal cookie store. + /// + /// Exercise caution if you are using this option and multiple transfers may + /// occur. If you use the Set-Cookie format and don't specify a domain then + /// the cookie is sent for any domain (even after redirects are followed) + /// and cannot be modified by a server-set cookie. If a server sets a cookie + /// of the same name (or maybe you've imported one) then both will be sent + /// on a future transfer to that server, likely not what you intended. + /// address these issues set a domain in Set-Cookie or use the Netscape + /// format. + /// + /// Additionally, there are commands available that perform actions if you + /// pass in these exact strings: + /// + /// * "ALL" - erases all cookies held in memory + /// * "SESS" - erases all session cookies held in memory + /// * "FLUSH" - write all known cookies to the specified cookie jar + /// * "RELOAD" - reread all cookies from the cookie file + /// + /// By default this options corresponds to `CURLOPT_COOKIELIST` + pub fn cookie_list(&mut self, cookie: &str) -> Result<(), Error> { + let cookie = CString::new(cookie)?; + self.setopt_str(curl_sys::CURLOPT_COOKIELIST, &cookie) + } + + /// Ask for a HTTP GET request. + /// + /// By default this option is `false` and corresponds to `CURLOPT_HTTPGET`. + pub fn get(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_HTTPGET, enable as c_long) + } + + // /// Ask for a HTTP GET request. + // /// + // /// By default this option is `false` and corresponds to `CURLOPT_HTTPGET`. + // pub fn http_version(&mut self, vers: &str) -> Result<(), Error> { + // self.setopt_long(curl_sys::CURLOPT_HTTPGET, enable as c_long) + // } + + /// Ignore the content-length header. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_IGNORE_CONTENT_LENGTH`. + pub fn ignore_content_length(&mut self, ignore: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_IGNORE_CONTENT_LENGTH, ignore as c_long) + } + + /// Enable or disable HTTP content decoding. + /// + /// By default this option is `true` and corresponds to + /// `CURLOPT_HTTP_CONTENT_DECODING`. + pub fn http_content_decoding(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_HTTP_CONTENT_DECODING, enable as c_long) + } + + /// Enable or disable HTTP transfer decoding. + /// + /// By default this option is `true` and corresponds to + /// `CURLOPT_HTTP_TRANSFER_DECODING`. + pub fn http_transfer_decoding(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_HTTP_TRANSFER_DECODING, enable as c_long) + } + + // /// Timeout for the Expect: 100-continue response + // /// + // /// By default this option is 1s and corresponds to + // /// `CURLOPT_EXPECT_100_TIMEOUT_MS`. + // pub fn expect_100_timeout(&mut self, enable: bool) -> Result<(), Error> { + // self.setopt_long(curl_sys::CURLOPT_HTTP_TRANSFER_DECODING, + // enable as c_long) + // } + + // /// Wait for pipelining/multiplexing. + // /// + // /// Tells libcurl to prefer to wait for a connection to confirm or deny that + // /// it can do pipelining or multiplexing before continuing. + // /// + // /// When about to perform a new transfer that allows pipelining or + // /// multiplexing, libcurl will check for existing connections to re-use and + // /// pipeline on. If no such connection exists it will immediately continue + // /// and create a fresh new connection to use. + // /// + // /// By setting this option to `true` - having `pipeline` enabled for the + // /// multi handle this transfer is associated with - libcurl will instead + // /// wait for the connection to reveal if it is possible to + // /// pipeline/multiplex on before it continues. This enables libcurl to much + // /// better keep the number of connections to a minimum when using pipelining + // /// or multiplexing protocols. + // /// + // /// The effect thus becomes that with this option set, libcurl prefers to + // /// wait and re-use an existing connection for pipelining rather than the + // /// opposite: prefer to open a new connection rather than waiting. + // /// + // /// The waiting time is as long as it takes for the connection to get up and + // /// for libcurl to get the necessary response back that informs it about its + // /// protocol and support level. + // pub fn http_pipewait(&mut self, enable: bool) -> Result<(), Error> { + // } + + // ========================================================================= + // Protocol Options + + /// Indicates the range that this request should retrieve. + /// + /// The string provided should be of the form `N-M` where either `N` or `M` + /// can be left out. For HTTP transfers multiple ranges separated by commas + /// are also accepted. + /// + /// By default this option is not set and corresponds to `CURLOPT_RANGE`. + pub fn range(&mut self, range: &str) -> Result<(), Error> { + let range = CString::new(range)?; + self.setopt_str(curl_sys::CURLOPT_RANGE, &range) + } + + /// Set a point to resume transfer from + /// + /// Specify the offset in bytes you want the transfer to start from. + /// + /// By default this option is 0 and corresponds to + /// `CURLOPT_RESUME_FROM_LARGE`. + pub fn resume_from(&mut self, from: u64) -> Result<(), Error> { + self.setopt_off_t( + curl_sys::CURLOPT_RESUME_FROM_LARGE, + from as curl_sys::curl_off_t, + ) + } + + /// Set a custom request string + /// + /// Specifies that a custom request will be made (e.g. a custom HTTP + /// method). This does not change how libcurl performs internally, just + /// changes the string sent to the server. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_CUSTOMREQUEST`. + pub fn custom_request(&mut self, request: &str) -> Result<(), Error> { + let request = CString::new(request)?; + self.setopt_str(curl_sys::CURLOPT_CUSTOMREQUEST, &request) + } + + /// Get the modification time of the remote resource + /// + /// If true, libcurl will attempt to get the modification time of the + /// remote document in this operation. This requires that the remote server + /// sends the time or replies to a time querying command. The `filetime` + /// function can be used after a transfer to extract the received time (if + /// any). + /// + /// By default this option is `false` and corresponds to `CURLOPT_FILETIME` + pub fn fetch_filetime(&mut self, fetch: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_FILETIME, fetch as c_long) + } + + /// Indicate whether to download the request without getting the body + /// + /// This is useful, for example, for doing a HEAD request. + /// + /// By default this option is `false` and corresponds to `CURLOPT_NOBODY`. + pub fn nobody(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_NOBODY, enable as c_long) + } + + /// Set the size of the input file to send off. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_INFILESIZE_LARGE`. + pub fn in_filesize(&mut self, size: u64) -> Result<(), Error> { + self.setopt_off_t( + curl_sys::CURLOPT_INFILESIZE_LARGE, + size as curl_sys::curl_off_t, + ) + } + + /// Enable or disable data upload. + /// + /// This means that a PUT request will be made for HTTP and probably wants + /// to be combined with the read callback as well as the `in_filesize` + /// method. + /// + /// By default this option is `false` and corresponds to `CURLOPT_UPLOAD`. + pub fn upload(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_UPLOAD, enable as c_long) + } + + /// Configure the maximum file size to download. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_MAXFILESIZE_LARGE`. + pub fn max_filesize(&mut self, size: u64) -> Result<(), Error> { + self.setopt_off_t( + curl_sys::CURLOPT_MAXFILESIZE_LARGE, + size as curl_sys::curl_off_t, + ) + } + + /// Selects a condition for a time request. + /// + /// This value indicates how the `time_value` option is interpreted. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_TIMECONDITION`. + pub fn time_condition(&mut self, cond: TimeCondition) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_TIMECONDITION, cond as c_long) + } + + /// Sets the time value for a conditional request. + /// + /// The value here should be the number of seconds elapsed since January 1, + /// 1970. To pass how to interpret this value, use `time_condition`. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_TIMEVALUE`. + pub fn time_value(&mut self, val: i64) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_TIMEVALUE, val as c_long) + } + + // ========================================================================= + // Connection Options + + /// Set maximum time the request is allowed to take. + /// + /// Normally, name lookups can take a considerable time and limiting + /// operations to less than a few minutes risk aborting perfectly normal + /// operations. + /// + /// If libcurl is built to use the standard system name resolver, that + /// portion of the transfer will still use full-second resolution for + /// timeouts with a minimum timeout allowed of one second. + /// + /// In unix-like systems, this might cause signals to be used unless + /// `nosignal` is set. + /// + /// Since this puts a hard limit for how long a request is allowed to + /// take, it has limited use in dynamic use cases with varying transfer + /// times. You are then advised to explore `low_speed_limit`, + /// `low_speed_time` or using `progress_function` to implement your own + /// timeout logic. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_TIMEOUT_MS`. + pub fn timeout(&mut self, timeout: Duration) -> Result<(), Error> { + // TODO: checked arithmetic and casts + // TODO: use CURLOPT_TIMEOUT if the timeout is too great + let ms = timeout.as_secs() * 1000 + timeout.subsec_millis() as u64; + self.setopt_long(curl_sys::CURLOPT_TIMEOUT_MS, ms as c_long) + } + + /// Set the low speed limit in bytes per second. + /// + /// This specifies the average transfer speed in bytes per second that the + /// transfer should be below during `low_speed_time` for libcurl to consider + /// it to be too slow and abort. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_LOW_SPEED_LIMIT`. + pub fn low_speed_limit(&mut self, limit: u32) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_LOW_SPEED_LIMIT, limit as c_long) + } + + /// Set the low speed time period. + /// + /// Specifies the window of time for which if the transfer rate is below + /// `low_speed_limit` the request will be aborted. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_LOW_SPEED_TIME`. + pub fn low_speed_time(&mut self, dur: Duration) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_LOW_SPEED_TIME, dur.as_secs() as c_long) + } + + /// Rate limit data upload speed + /// + /// If an upload exceeds this speed (counted in bytes per second) on + /// cumulative average during the transfer, the transfer will pause to keep + /// the average rate less than or equal to the parameter value. + /// + /// By default this option is not set (unlimited speed) and corresponds to + /// `CURLOPT_MAX_SEND_SPEED_LARGE`. + pub fn max_send_speed(&mut self, speed: u64) -> Result<(), Error> { + self.setopt_off_t( + curl_sys::CURLOPT_MAX_SEND_SPEED_LARGE, + speed as curl_sys::curl_off_t, + ) + } + + /// Rate limit data download speed + /// + /// If a download exceeds this speed (counted in bytes per second) on + /// cumulative average during the transfer, the transfer will pause to keep + /// the average rate less than or equal to the parameter value. + /// + /// By default this option is not set (unlimited speed) and corresponds to + /// `CURLOPT_MAX_RECV_SPEED_LARGE`. + pub fn max_recv_speed(&mut self, speed: u64) -> Result<(), Error> { + self.setopt_off_t( + curl_sys::CURLOPT_MAX_RECV_SPEED_LARGE, + speed as curl_sys::curl_off_t, + ) + } + + /// Set the maximum connection cache size. + /// + /// The set amount will be the maximum number of simultaneously open + /// persistent connections that libcurl may cache in the pool associated + /// with this handle. The default is 5, and there isn't much point in + /// changing this value unless you are perfectly aware of how this works and + /// changes libcurl's behaviour. This concerns connections using any of the + /// protocols that support persistent connections. + /// + /// When reaching the maximum limit, curl closes the oldest one in the cache + /// to prevent increasing the number of open connections. + /// + /// By default this option is set to 5 and corresponds to + /// `CURLOPT_MAXCONNECTS` + pub fn max_connects(&mut self, max: u32) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_MAXCONNECTS, max as c_long) + } + + /// Set the maximum idle time allowed for a connection. + /// + /// This configuration sets the maximum time that a connection inside of the connection cache + /// can be reused. Any connection older than this value will be considered stale and will + /// be closed. + /// + /// By default, a value of 118 seconds is used. + pub fn maxage_conn(&mut self, max_age: Duration) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_MAXAGE_CONN, max_age.as_secs() as c_long) + } + + /// Force a new connection to be used. + /// + /// Makes the next transfer use a new (fresh) connection by force instead of + /// trying to re-use an existing one. This option should be used with + /// caution and only if you understand what it does as it may seriously + /// impact performance. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_FRESH_CONNECT`. + pub fn fresh_connect(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_FRESH_CONNECT, enable as c_long) + } + + /// Make connection get closed at once after use. + /// + /// Makes libcurl explicitly close the connection when done with the + /// transfer. Normally, libcurl keeps all connections alive when done with + /// one transfer in case a succeeding one follows that can re-use them. + /// This option should be used with caution and only if you understand what + /// it does as it can seriously impact performance. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_FORBID_REUSE`. + pub fn forbid_reuse(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_FORBID_REUSE, enable as c_long) + } + + /// Timeout for the connect phase + /// + /// This is the maximum time that you allow the connection phase to the + /// server to take. This only limits the connection phase, it has no impact + /// once it has connected. + /// + /// By default this value is 300 seconds and corresponds to + /// `CURLOPT_CONNECTTIMEOUT_MS`. + pub fn connect_timeout(&mut self, timeout: Duration) -> Result<(), Error> { + let ms = timeout.as_secs() * 1000 + timeout.subsec_millis() as u64; + self.setopt_long(curl_sys::CURLOPT_CONNECTTIMEOUT_MS, ms as c_long) + } + + /// Specify which IP protocol version to use + /// + /// Allows an application to select what kind of IP addresses to use when + /// resolving host names. This is only interesting when using host names + /// that resolve addresses using more than one version of IP. + /// + /// By default this value is "any" and corresponds to `CURLOPT_IPRESOLVE`. + pub fn ip_resolve(&mut self, resolve: IpResolve) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_IPRESOLVE, resolve as c_long) + } + + /// Specify custom host name to IP address resolves. + /// + /// Allows specifying hostname to IP mappins to use before trying the + /// system resolver. + /// + /// # Examples + /// + /// ```no_run + /// use curl::easy::{Easy, List}; + /// + /// let mut list = List::new(); + /// list.append("www.rust-lang.org:443:185.199.108.153").unwrap(); + /// + /// let mut handle = Easy::new(); + /// handle.url("https://www.rust-lang.org/").unwrap(); + /// handle.resolve(list).unwrap(); + /// handle.perform().unwrap(); + /// ``` + pub fn resolve(&mut self, list: List) -> Result<(), Error> { + let ptr = list::raw(&list); + self.inner.resolve_list = Some(list); + self.setopt_ptr(curl_sys::CURLOPT_RESOLVE, ptr as *const _) + } + + /// Configure whether to stop when connected to target server + /// + /// When enabled it tells the library to perform all the required proxy + /// authentication and connection setup, but no data transfer, and then + /// return. + /// + /// The option can be used to simply test a connection to a server. + /// + /// By default this value is `false` and corresponds to + /// `CURLOPT_CONNECT_ONLY`. + pub fn connect_only(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_CONNECT_ONLY, enable as c_long) + } + + // /// Set interface to speak DNS over. + // /// + // /// Set the name of the network interface that the DNS resolver should bind + // /// to. This must be an interface name (not an address). + // /// + // /// By default this option is not set and corresponds to + // /// `CURLOPT_DNS_INTERFACE`. + // pub fn dns_interface(&mut self, interface: &str) -> Result<(), Error> { + // let interface = CString::new(interface)?; + // self.setopt_str(curl_sys::CURLOPT_DNS_INTERFACE, &interface) + // } + // + // /// IPv4 address to bind DNS resolves to + // /// + // /// Set the local IPv4 address that the resolver should bind to. The + // /// argument should be of type char * and contain a single numerical IPv4 + // /// address as a string. + // /// + // /// By default this option is not set and corresponds to + // /// `CURLOPT_DNS_LOCAL_IP4`. + // pub fn dns_local_ip4(&mut self, ip: &str) -> Result<(), Error> { + // let ip = CString::new(ip)?; + // self.setopt_str(curl_sys::CURLOPT_DNS_LOCAL_IP4, &ip) + // } + // + // /// IPv6 address to bind DNS resolves to + // /// + // /// Set the local IPv6 address that the resolver should bind to. The + // /// argument should be of type char * and contain a single numerical IPv6 + // /// address as a string. + // /// + // /// By default this option is not set and corresponds to + // /// `CURLOPT_DNS_LOCAL_IP6`. + // pub fn dns_local_ip6(&mut self, ip: &str) -> Result<(), Error> { + // let ip = CString::new(ip)?; + // self.setopt_str(curl_sys::CURLOPT_DNS_LOCAL_IP6, &ip) + // } + // + // /// Set preferred DNS servers. + // /// + // /// Provides a list of DNS servers to be used instead of the system default. + // /// The format of the dns servers option is: + // /// + // /// ```text + // /// host[:port],[host[:port]]... + // /// ``` + // /// + // /// By default this option is not set and corresponds to + // /// `CURLOPT_DNS_SERVERS`. + // pub fn dns_servers(&mut self, servers: &str) -> Result<(), Error> { + // let servers = CString::new(servers)?; + // self.setopt_str(curl_sys::CURLOPT_DNS_SERVERS, &servers) + // } + + // ========================================================================= + // SSL/Security Options + + /// Sets the SSL client certificate. + /// + /// The string should be the file name of your client certificate. The + /// default format is "P12" on Secure Transport and "PEM" on other engines, + /// and can be changed with `ssl_cert_type`. + /// + /// With NSS or Secure Transport, this can also be the nickname of the + /// certificate you wish to authenticate with as it is named in the security + /// database. If you want to use a file from the current directory, please + /// precede it with "./" prefix, in order to avoid confusion with a + /// nickname. + /// + /// When using a client certificate, you most likely also need to provide a + /// private key with `ssl_key`. + /// + /// By default this option is not set and corresponds to `CURLOPT_SSLCERT`. + pub fn ssl_cert<P: AsRef<Path>>(&mut self, cert: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_SSLCERT, cert.as_ref()) + } + + /// Set the SSL client certificate using an in-memory blob. + /// + /// The specified byte buffer should contain the binary content of your + /// client certificate, which will be copied into the handle. The format of + /// the certificate can be specified with `ssl_cert_type`. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_SSLCERT_BLOB`. + pub fn ssl_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.setopt_blob(curl_sys::CURLOPT_SSLCERT_BLOB, blob) + } + + /// Specify type of the client SSL certificate. + /// + /// The string should be the format of your certificate. Supported formats + /// are "PEM" and "DER", except with Secure Transport. OpenSSL (versions + /// 0.9.3 and later) and Secure Transport (on iOS 5 or later, or OS X 10.7 + /// or later) also support "P12" for PKCS#12-encoded files. + /// + /// By default this option is "PEM" and corresponds to + /// `CURLOPT_SSLCERTTYPE`. + pub fn ssl_cert_type(&mut self, kind: &str) -> Result<(), Error> { + let kind = CString::new(kind)?; + self.setopt_str(curl_sys::CURLOPT_SSLCERTTYPE, &kind) + } + + /// Specify private keyfile for TLS and SSL client cert. + /// + /// The string should be the file name of your private key. The default + /// format is "PEM" and can be changed with `ssl_key_type`. + /// + /// (iOS and Mac OS X only) This option is ignored if curl was built against + /// Secure Transport. Secure Transport expects the private key to be already + /// present in the keychain or PKCS#12 file containing the certificate. + /// + /// By default this option is not set and corresponds to `CURLOPT_SSLKEY`. + pub fn ssl_key<P: AsRef<Path>>(&mut self, key: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_SSLKEY, key.as_ref()) + } + + /// Specify an SSL private key using an in-memory blob. + /// + /// The specified byte buffer should contain the binary content of your + /// private key, which will be copied into the handle. The format of + /// the private key can be specified with `ssl_key_type`. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_SSLKEY_BLOB`. + pub fn ssl_key_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.setopt_blob(curl_sys::CURLOPT_SSLKEY_BLOB, blob) + } + + /// Set type of the private key file. + /// + /// The string should be the format of your private key. Supported formats + /// are "PEM", "DER" and "ENG". + /// + /// The format "ENG" enables you to load the private key from a crypto + /// engine. In this case `ssl_key` is used as an identifier passed to + /// the engine. You have to set the crypto engine with `ssl_engine`. + /// "DER" format key file currently does not work because of a bug in + /// OpenSSL. + /// + /// By default this option is "PEM" and corresponds to + /// `CURLOPT_SSLKEYTYPE`. + pub fn ssl_key_type(&mut self, kind: &str) -> Result<(), Error> { + let kind = CString::new(kind)?; + self.setopt_str(curl_sys::CURLOPT_SSLKEYTYPE, &kind) + } + + /// Set passphrase to private key. + /// + /// This will be used as the password required to use the `ssl_key`. + /// You never needed a pass phrase to load a certificate but you need one to + /// load your private key. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_KEYPASSWD`. + pub fn key_password(&mut self, password: &str) -> Result<(), Error> { + let password = CString::new(password)?; + self.setopt_str(curl_sys::CURLOPT_KEYPASSWD, &password) + } + + /// Set the SSL Certificate Authorities using an in-memory blob. + /// + /// The specified byte buffer should contain the binary content of one + /// or more PEM-encoded CA certificates, which will be copied into + /// the handle. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_CAINFO_BLOB`. + pub fn ssl_cainfo_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.setopt_blob(curl_sys::CURLOPT_CAINFO_BLOB, blob) + } + + /// Set the SSL Certificate Authorities for HTTPS proxies using an in-memory + /// blob. + /// + /// The specified byte buffer should contain the binary content of one + /// or more PEM-encoded CA certificates, which will be copied into + /// the handle. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_CAINFO_BLOB`. + pub fn proxy_ssl_cainfo_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.setopt_blob(curl_sys::CURLOPT_PROXY_CAINFO_BLOB, blob) + } + + /// Set the SSL engine identifier. + /// + /// This will be used as the identifier for the crypto engine you want to + /// use for your private key. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_SSLENGINE`. + pub fn ssl_engine(&mut self, engine: &str) -> Result<(), Error> { + let engine = CString::new(engine)?; + self.setopt_str(curl_sys::CURLOPT_SSLENGINE, &engine) + } + + /// Make this handle's SSL engine the default. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_SSLENGINE_DEFAULT`. + pub fn ssl_engine_default(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_SSLENGINE_DEFAULT, enable as c_long) + } + + // /// Enable TLS false start. + // /// + // /// This option determines whether libcurl should use false start during the + // /// TLS handshake. False start is a mode where a TLS client will start + // /// sending application data before verifying the server's Finished message, + // /// thus saving a round trip when performing a full handshake. + // /// + // /// By default this option is not set and corresponds to + // /// `CURLOPT_SSL_FALSESTARTE`. + // pub fn ssl_false_start(&mut self, enable: bool) -> Result<(), Error> { + // self.setopt_long(curl_sys::CURLOPT_SSLENGINE_DEFAULT, enable as c_long) + // } + + /// Set preferred HTTP version. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_HTTP_VERSION`. + pub fn http_version(&mut self, version: HttpVersion) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_HTTP_VERSION, version as c_long) + } + + /// Set preferred TLS/SSL version. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_SSLVERSION`. + pub fn ssl_version(&mut self, version: SslVersion) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_SSLVERSION, version as c_long) + } + + /// Set preferred TLS/SSL version when connecting to an HTTPS proxy. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_SSLVERSION`. + pub fn proxy_ssl_version(&mut self, version: SslVersion) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_PROXY_SSLVERSION, version as c_long) + } + + /// Set preferred TLS/SSL version with minimum version and maximum version. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_SSLVERSION`. + pub fn ssl_min_max_version( + &mut self, + min_version: SslVersion, + max_version: SslVersion, + ) -> Result<(), Error> { + let version = (min_version as c_long) | ((max_version as c_long) << 16); + self.setopt_long(curl_sys::CURLOPT_SSLVERSION, version) + } + + /// Set preferred TLS/SSL version with minimum version and maximum version + /// when connecting to an HTTPS proxy. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_SSLVERSION`. + pub fn proxy_ssl_min_max_version( + &mut self, + min_version: SslVersion, + max_version: SslVersion, + ) -> Result<(), Error> { + let version = (min_version as c_long) | ((max_version as c_long) << 16); + self.setopt_long(curl_sys::CURLOPT_PROXY_SSLVERSION, version) + } + + /// Verify the certificate's name against host. + /// + /// This should be disabled with great caution! It basically disables the + /// security features of SSL if it is disabled. + /// + /// By default this option is set to `true` and corresponds to + /// `CURLOPT_SSL_VERIFYHOST`. + pub fn ssl_verify_host(&mut self, verify: bool) -> Result<(), Error> { + let val = if verify { 2 } else { 0 }; + self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYHOST, val) + } + + /// Verify the certificate's name against host for HTTPS proxy. + /// + /// This should be disabled with great caution! It basically disables the + /// security features of SSL if it is disabled. + /// + /// By default this option is set to `true` and corresponds to + /// `CURLOPT_PROXY_SSL_VERIFYHOST`. + pub fn proxy_ssl_verify_host(&mut self, verify: bool) -> Result<(), Error> { + let val = if verify { 2 } else { 0 }; + self.setopt_long(curl_sys::CURLOPT_PROXY_SSL_VERIFYHOST, val) + } + + /// Verify the peer's SSL certificate. + /// + /// This should be disabled with great caution! It basically disables the + /// security features of SSL if it is disabled. + /// + /// By default this option is set to `true` and corresponds to + /// `CURLOPT_SSL_VERIFYPEER`. + pub fn ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYPEER, verify as c_long) + } + + /// Verify the peer's SSL certificate for HTTPS proxy. + /// + /// This should be disabled with great caution! It basically disables the + /// security features of SSL if it is disabled. + /// + /// By default this option is set to `true` and corresponds to + /// `CURLOPT_PROXY_SSL_VERIFYPEER`. + pub fn proxy_ssl_verify_peer(&mut self, verify: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_PROXY_SSL_VERIFYPEER, verify as c_long) + } + + // /// Verify the certificate's status. + // /// + // /// This option determines whether libcurl verifies the status of the server + // /// cert using the "Certificate Status Request" TLS extension (aka. OCSP + // /// stapling). + // /// + // /// By default this option is set to `false` and corresponds to + // /// `CURLOPT_SSL_VERIFYSTATUS`. + // pub fn ssl_verify_status(&mut self, verify: bool) -> Result<(), Error> { + // self.setopt_long(curl_sys::CURLOPT_SSL_VERIFYSTATUS, verify as c_long) + // } + + /// Specify the path to Certificate Authority (CA) bundle + /// + /// The file referenced should hold one or more certificates to verify the + /// peer with. + /// + /// This option is by default set to the system path where libcurl's cacert + /// bundle is assumed to be stored, as established at build time. + /// + /// If curl is built against the NSS SSL library, the NSS PEM PKCS#11 module + /// (libnsspem.so) needs to be available for this option to work properly. + /// + /// By default this option is the system defaults, and corresponds to + /// `CURLOPT_CAINFO`. + pub fn cainfo<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_CAINFO, path.as_ref()) + } + + /// Set the issuer SSL certificate filename + /// + /// Specifies a file holding a CA certificate in PEM format. If the option + /// is set, an additional check against the peer certificate is performed to + /// verify the issuer is indeed the one associated with the certificate + /// provided by the option. This additional check is useful in multi-level + /// PKI where one needs to enforce that the peer certificate is from a + /// specific branch of the tree. + /// + /// This option makes sense only when used in combination with the + /// [`Easy2::ssl_verify_peer`] option. Otherwise, the result of the check is + /// not considered as failure. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_ISSUERCERT`. + pub fn issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_ISSUERCERT, path.as_ref()) + } + + /// Set the issuer SSL certificate filename for HTTPS proxies + /// + /// Specifies a file holding a CA certificate in PEM format. If the option + /// is set, an additional check against the peer certificate is performed to + /// verify the issuer is indeed the one associated with the certificate + /// provided by the option. This additional check is useful in multi-level + /// PKI where one needs to enforce that the peer certificate is from a + /// specific branch of the tree. + /// + /// This option makes sense only when used in combination with the + /// [`Easy2::proxy_ssl_verify_peer`] option. Otherwise, the result of the + /// check is not considered as failure. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_ISSUERCERT`. + pub fn proxy_issuer_cert<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_PROXY_ISSUERCERT, path.as_ref()) + } + + /// Set the issuer SSL certificate using an in-memory blob. + /// + /// The specified byte buffer should contain the binary content of a CA + /// certificate in the PEM format. The certificate will be copied into the + /// handle. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_ISSUERCERT_BLOB`. + pub fn issuer_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.setopt_blob(curl_sys::CURLOPT_ISSUERCERT_BLOB, blob) + } + + /// Set the issuer SSL certificate for HTTPS proxies using an in-memory blob. + /// + /// The specified byte buffer should contain the binary content of a CA + /// certificate in the PEM format. The certificate will be copied into the + /// handle. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_ISSUERCERT_BLOB`. + pub fn proxy_issuer_cert_blob(&mut self, blob: &[u8]) -> Result<(), Error> { + self.setopt_blob(curl_sys::CURLOPT_PROXY_ISSUERCERT_BLOB, blob) + } + + /// Specify directory holding CA certificates + /// + /// Names a directory holding multiple CA certificates to verify the peer + /// with. If libcurl is built against OpenSSL, the certificate directory + /// must be prepared using the openssl c_rehash utility. This makes sense + /// only when used in combination with the `ssl_verify_peer` option. + /// + /// By default this option is not set and corresponds to `CURLOPT_CAPATH`. + pub fn capath<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_CAPATH, path.as_ref()) + } + + /// Specify a Certificate Revocation List file + /// + /// Names a file with the concatenation of CRL (in PEM format) to use in the + /// certificate validation that occurs during the SSL exchange. + /// + /// When curl is built to use NSS or GnuTLS, there is no way to influence + /// the use of CRL passed to help in the verification process. When libcurl + /// is built with OpenSSL support, X509_V_FLAG_CRL_CHECK and + /// X509_V_FLAG_CRL_CHECK_ALL are both set, requiring CRL check against all + /// the elements of the certificate chain if a CRL file is passed. + /// + /// This option makes sense only when used in combination with the + /// [`Easy2::ssl_verify_peer`] option. + /// + /// A specific error code (`is_ssl_crl_badfile`) is defined with the + /// option. It is returned when the SSL exchange fails because the CRL file + /// cannot be loaded. A failure in certificate verification due to a + /// revocation information found in the CRL does not trigger this specific + /// error. + /// + /// By default this option is not set and corresponds to `CURLOPT_CRLFILE`. + pub fn crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_CRLFILE, path.as_ref()) + } + + /// Specify a Certificate Revocation List file to use when connecting to an + /// HTTPS proxy. + /// + /// Names a file with the concatenation of CRL (in PEM format) to use in the + /// certificate validation that occurs during the SSL exchange. + /// + /// When curl is built to use NSS or GnuTLS, there is no way to influence + /// the use of CRL passed to help in the verification process. When libcurl + /// is built with OpenSSL support, X509_V_FLAG_CRL_CHECK and + /// X509_V_FLAG_CRL_CHECK_ALL are both set, requiring CRL check against all + /// the elements of the certificate chain if a CRL file is passed. + /// + /// This option makes sense only when used in combination with the + /// [`Easy2::proxy_ssl_verify_peer`] option. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_CRLFILE`. + pub fn proxy_crlfile<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_PROXY_CRLFILE, path.as_ref()) + } + + /// Request SSL certificate information + /// + /// Enable libcurl's certificate chain info gatherer. With this enabled, + /// libcurl will extract lots of information and data about the certificates + /// in the certificate chain used in the SSL connection. + /// + /// By default this option is `false` and corresponds to + /// `CURLOPT_CERTINFO`. + pub fn certinfo(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_CERTINFO, enable as c_long) + } + + /// Set pinned public key. + /// + /// Pass a pointer to a zero terminated string as parameter. The string can + /// be the file name of your pinned public key. The file format expected is + /// "PEM" or "DER". The string can also be any number of base64 encoded + /// sha256 hashes preceded by "sha256//" and separated by ";" + /// + /// When negotiating a TLS or SSL connection, the server sends a certificate + /// indicating its identity. A public key is extracted from this certificate + /// and if it does not exactly match the public key provided to this option, + /// curl will abort the connection before sending or receiving any data. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PINNEDPUBLICKEY`. + pub fn pinned_public_key(&mut self, pubkey: &str) -> Result<(), Error> { + let key = CString::new(pubkey)?; + self.setopt_str(curl_sys::CURLOPT_PINNEDPUBLICKEY, &key) + } + + /// Specify a source for random data + /// + /// The file will be used to read from to seed the random engine for SSL and + /// more. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_RANDOM_FILE`. + pub fn random_file<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_RANDOM_FILE, p.as_ref()) + } + + /// Specify EGD socket path. + /// + /// Indicates the path name to the Entropy Gathering Daemon socket. It will + /// be used to seed the random engine for SSL. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_EGDSOCKET`. + pub fn egd_socket<P: AsRef<Path>>(&mut self, p: P) -> Result<(), Error> { + self.setopt_path(curl_sys::CURLOPT_EGDSOCKET, p.as_ref()) + } + + /// Specify ciphers to use for TLS. + /// + /// Holds the list of ciphers to use for the SSL connection. The list must + /// be syntactically correct, it consists of one or more cipher strings + /// separated by colons. Commas or spaces are also acceptable separators + /// but colons are normally used, !, - and + can be used as operators. + /// + /// For OpenSSL and GnuTLS valid examples of cipher lists include 'RC4-SHA', + /// ´SHA1+DES´, 'TLSv1' and 'DEFAULT'. The default list is normally set when + /// you compile OpenSSL. + /// + /// You'll find more details about cipher lists on this URL: + /// + /// https://www.openssl.org/docs/apps/ciphers.html + /// + /// For NSS, valid examples of cipher lists include 'rsa_rc4_128_md5', + /// ´rsa_aes_128_sha´, etc. With NSS you don't add/remove ciphers. If one + /// uses this option then all known ciphers are disabled and only those + /// passed in are enabled. + /// + /// You'll find more details about the NSS cipher lists on this URL: + /// + /// http://git.fedorahosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html#Directives + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_SSL_CIPHER_LIST`. + pub fn ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error> { + let ciphers = CString::new(ciphers)?; + self.setopt_str(curl_sys::CURLOPT_SSL_CIPHER_LIST, &ciphers) + } + + /// Specify ciphers to use for TLS for an HTTPS proxy. + /// + /// Holds the list of ciphers to use for the SSL connection. The list must + /// be syntactically correct, it consists of one or more cipher strings + /// separated by colons. Commas or spaces are also acceptable separators + /// but colons are normally used, !, - and + can be used as operators. + /// + /// For OpenSSL and GnuTLS valid examples of cipher lists include 'RC4-SHA', + /// ´SHA1+DES´, 'TLSv1' and 'DEFAULT'. The default list is normally set when + /// you compile OpenSSL. + /// + /// You'll find more details about cipher lists on this URL: + /// + /// https://www.openssl.org/docs/apps/ciphers.html + /// + /// For NSS, valid examples of cipher lists include 'rsa_rc4_128_md5', + /// ´rsa_aes_128_sha´, etc. With NSS you don't add/remove ciphers. If one + /// uses this option then all known ciphers are disabled and only those + /// passed in are enabled. + /// + /// You'll find more details about the NSS cipher lists on this URL: + /// + /// http://git.fedorahosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html#Directives + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_PROXY_SSL_CIPHER_LIST`. + pub fn proxy_ssl_cipher_list(&mut self, ciphers: &str) -> Result<(), Error> { + let ciphers = CString::new(ciphers)?; + self.setopt_str(curl_sys::CURLOPT_PROXY_SSL_CIPHER_LIST, &ciphers) + } + + /// Enable or disable use of the SSL session-ID cache + /// + /// By default all transfers are done using the cache enabled. While nothing + /// ever should get hurt by attempting to reuse SSL session-IDs, there seem + /// to be or have been broken SSL implementations in the wild that may + /// require you to disable this in order for you to succeed. + /// + /// This corresponds to the `CURLOPT_SSL_SESSIONID_CACHE` option. + pub fn ssl_sessionid_cache(&mut self, enable: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_SSL_SESSIONID_CACHE, enable as c_long) + } + + /// Set SSL behavior options + /// + /// Inform libcurl about SSL specific behaviors. + /// + /// This corresponds to the `CURLOPT_SSL_OPTIONS` option. + pub fn ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_SSL_OPTIONS, bits.bits) + } + + /// Set SSL behavior options for proxies + /// + /// Inform libcurl about SSL specific behaviors. + /// + /// This corresponds to the `CURLOPT_PROXY_SSL_OPTIONS` option. + pub fn proxy_ssl_options(&mut self, bits: &SslOpt) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_PROXY_SSL_OPTIONS, bits.bits) + } + + // /// Stores a private pointer-sized piece of data. + // /// + // /// This can be retrieved through the `private` function and otherwise + // /// libcurl does not tamper with this value. This corresponds to + // /// `CURLOPT_PRIVATE` and defaults to 0. + // pub fn set_private(&mut self, private: usize) -> Result<(), Error> { + // self.setopt_ptr(curl_sys::CURLOPT_PRIVATE, private as *const _) + // } + // + // /// Fetches this handle's private pointer-sized piece of data. + // /// + // /// This corresponds to `CURLINFO_PRIVATE` and defaults to 0. + // pub fn private(&mut self) -> Result<usize, Error> { + // self.getopt_ptr(curl_sys::CURLINFO_PRIVATE).map(|p| p as usize) + // } + + // ========================================================================= + // getters + + /// Set maximum time to wait for Expect 100 request before sending body. + /// + /// `curl` has internal heuristics that trigger the use of a `Expect` + /// header for large enough request bodies where the client first sends the + /// request header along with an `Expect: 100-continue` header. The server + /// is supposed to validate the headers and respond with a `100` response + /// status code after which `curl` will send the actual request body. + /// + /// However, if the server does not respond to the initial request + /// within `CURLOPT_EXPECT_100_TIMEOUT_MS` then `curl` will send the + /// request body anyways. + /// + /// The best-case scenario is where the request is invalid and the server + /// replies with a `417 Expectation Failed` without having to wait for or process + /// the request body at all. However, this behaviour can also lead to higher + /// total latency since in the best case, an additional server roundtrip is required + /// and in the worst case, the request is delayed by `CURLOPT_EXPECT_100_TIMEOUT_MS`. + /// + /// More info: https://curl.se/libcurl/c/CURLOPT_EXPECT_100_TIMEOUT_MS.html + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_EXPECT_100_TIMEOUT_MS`. + pub fn expect_100_timeout(&mut self, timeout: Duration) -> Result<(), Error> { + let ms = timeout.as_secs() * 1000 + timeout.subsec_millis() as u64; + self.setopt_long(curl_sys::CURLOPT_EXPECT_100_TIMEOUT_MS, ms as c_long) + } + + /// Get info on unmet time conditional + /// + /// Returns if the condition provided in the previous request didn't match + /// + //// This corresponds to `CURLINFO_CONDITION_UNMET` and may return an error if the + /// option is not supported + pub fn time_condition_unmet(&mut self) -> Result<bool, Error> { + self.getopt_long(curl_sys::CURLINFO_CONDITION_UNMET) + .map(|r| r != 0) + } + + /// Get the last used URL + /// + /// In cases when you've asked libcurl to follow redirects, it may + /// not be the same value you set with `url`. + /// + /// This methods corresponds to the `CURLINFO_EFFECTIVE_URL` option. + /// + /// Returns `Ok(None)` if no effective url is listed or `Err` if an error + /// happens or the underlying bytes aren't valid utf-8. + pub fn effective_url(&mut self) -> Result<Option<&str>, Error> { + self.getopt_str(curl_sys::CURLINFO_EFFECTIVE_URL) + } + + /// Get the last used URL, in bytes + /// + /// In cases when you've asked libcurl to follow redirects, it may + /// not be the same value you set with `url`. + /// + /// This methods corresponds to the `CURLINFO_EFFECTIVE_URL` option. + /// + /// Returns `Ok(None)` if no effective url is listed or `Err` if an error + /// happens or the underlying bytes aren't valid utf-8. + pub fn effective_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> { + self.getopt_bytes(curl_sys::CURLINFO_EFFECTIVE_URL) + } + + /// Get the last response code + /// + /// The stored value will be zero if no server response code has been + /// received. Note that a proxy's CONNECT response should be read with + /// `http_connectcode` and not this. + /// + /// Corresponds to `CURLINFO_RESPONSE_CODE` and returns an error if this + /// option is not supported. + pub fn response_code(&mut self) -> Result<u32, Error> { + self.getopt_long(curl_sys::CURLINFO_RESPONSE_CODE) + .map(|c| c as u32) + } + + /// Get the CONNECT response code + /// + /// Returns the last received HTTP proxy response code to a CONNECT request. + /// The returned value will be zero if no such response code was available. + /// + /// Corresponds to `CURLINFO_HTTP_CONNECTCODE` and returns an error if this + /// option is not supported. + pub fn http_connectcode(&mut self) -> Result<u32, Error> { + self.getopt_long(curl_sys::CURLINFO_HTTP_CONNECTCODE) + .map(|c| c as u32) + } + + /// Get the remote time of the retrieved document + /// + /// Returns the remote time of the retrieved document (in number of seconds + /// since 1 Jan 1970 in the GMT/UTC time zone). If you get `None`, it can be + /// because of many reasons (it might be unknown, the server might hide it + /// or the server doesn't support the command that tells document time etc) + /// and the time of the document is unknown. + /// + /// Note that you must tell the server to collect this information before + /// the transfer is made, by using the `filetime` method to + /// or you will unconditionally get a `None` back. + /// + /// This corresponds to `CURLINFO_FILETIME` and may return an error if the + /// option is not supported + pub fn filetime(&mut self) -> Result<Option<i64>, Error> { + self.getopt_long(curl_sys::CURLINFO_FILETIME).map(|r| { + if r == -1 { + None + } else { + Some(r as i64) + } + }) + } + + /// Get the number of downloaded bytes + /// + /// Returns the total amount of bytes that were downloaded. + /// The amount is only for the latest transfer and will be reset again for each new transfer. + /// This counts actual payload data, what's also commonly called body. + /// All meta and header data are excluded and will not be counted in this number. + /// + /// This corresponds to `CURLINFO_SIZE_DOWNLOAD` and may return an error if the + /// option is not supported + pub fn download_size(&mut self) -> Result<f64, Error> { + self.getopt_double(curl_sys::CURLINFO_SIZE_DOWNLOAD) + .map(|r| r as f64) + } + + /// Get the number of uploaded bytes + /// + /// Returns the total amount of bytes that were uploaded. + /// + /// This corresponds to `CURLINFO_SIZE_UPLOAD` and may return an error if the + /// option is not supported + pub fn upload_size(&mut self) -> Result<f64, Error> { + self.getopt_double(curl_sys::CURLINFO_SIZE_UPLOAD) + .map(|r| r as f64) + } + + /// Get the content-length of the download + /// + /// Returns the content-length of the download. + /// This is the value read from the Content-Length: field + /// + /// This corresponds to `CURLINFO_CONTENT_LENGTH_DOWNLOAD` and may return an error if the + /// option is not supported + pub fn content_length_download(&mut self) -> Result<f64, Error> { + self.getopt_double(curl_sys::CURLINFO_CONTENT_LENGTH_DOWNLOAD) + .map(|r| r as f64) + } + + /// Get total time of previous transfer + /// + /// Returns the total time for the previous transfer, + /// including name resolving, TCP connect etc. + /// + /// Corresponds to `CURLINFO_TOTAL_TIME` and may return an error if the + /// option isn't supported. + pub fn total_time(&mut self) -> Result<Duration, Error> { + self.getopt_double(curl_sys::CURLINFO_TOTAL_TIME) + .map(double_seconds_to_duration) + } + + /// Get the name lookup time + /// + /// Returns the total time from the start + /// until the name resolving was completed. + /// + /// Corresponds to `CURLINFO_NAMELOOKUP_TIME` and may return an error if the + /// option isn't supported. + pub fn namelookup_time(&mut self) -> Result<Duration, Error> { + self.getopt_double(curl_sys::CURLINFO_NAMELOOKUP_TIME) + .map(double_seconds_to_duration) + } + + /// Get the time until connect + /// + /// Returns the total time from the start + /// until the connection to the remote host (or proxy) was completed. + /// + /// Corresponds to `CURLINFO_CONNECT_TIME` and may return an error if the + /// option isn't supported. + pub fn connect_time(&mut self) -> Result<Duration, Error> { + self.getopt_double(curl_sys::CURLINFO_CONNECT_TIME) + .map(double_seconds_to_duration) + } + + /// Get the time until the SSL/SSH handshake is completed + /// + /// Returns the total time it took from the start until the SSL/SSH + /// connect/handshake to the remote host was completed. This time is most often + /// very near to the `pretransfer_time` time, except for cases such as + /// HTTP pipelining where the pretransfer time can be delayed due to waits in + /// line for the pipeline and more. + /// + /// Corresponds to `CURLINFO_APPCONNECT_TIME` and may return an error if the + /// option isn't supported. + pub fn appconnect_time(&mut self) -> Result<Duration, Error> { + self.getopt_double(curl_sys::CURLINFO_APPCONNECT_TIME) + .map(double_seconds_to_duration) + } + + /// Get the time until the file transfer start + /// + /// Returns the total time it took from the start until the file + /// transfer is just about to begin. This includes all pre-transfer commands + /// and negotiations that are specific to the particular protocol(s) involved. + /// It does not involve the sending of the protocol- specific request that + /// triggers a transfer. + /// + /// Corresponds to `CURLINFO_PRETRANSFER_TIME` and may return an error if the + /// option isn't supported. + pub fn pretransfer_time(&mut self) -> Result<Duration, Error> { + self.getopt_double(curl_sys::CURLINFO_PRETRANSFER_TIME) + .map(double_seconds_to_duration) + } + + /// Get the time until the first byte is received + /// + /// Returns the total time it took from the start until the first + /// byte is received by libcurl. This includes `pretransfer_time` and + /// also the time the server needs to calculate the result. + /// + /// Corresponds to `CURLINFO_STARTTRANSFER_TIME` and may return an error if the + /// option isn't supported. + pub fn starttransfer_time(&mut self) -> Result<Duration, Error> { + self.getopt_double(curl_sys::CURLINFO_STARTTRANSFER_TIME) + .map(double_seconds_to_duration) + } + + /// Get the time for all redirection steps + /// + /// Returns the total time it took for all redirection steps + /// include name lookup, connect, pretransfer and transfer before final + /// transaction was started. `redirect_time` contains the complete + /// execution time for multiple redirections. + /// + /// Corresponds to `CURLINFO_REDIRECT_TIME` and may return an error if the + /// option isn't supported. + pub fn redirect_time(&mut self) -> Result<Duration, Error> { + self.getopt_double(curl_sys::CURLINFO_REDIRECT_TIME) + .map(double_seconds_to_duration) + } + + /// Get the number of redirects + /// + /// Corresponds to `CURLINFO_REDIRECT_COUNT` and may return an error if the + /// option isn't supported. + pub fn redirect_count(&mut self) -> Result<u32, Error> { + self.getopt_long(curl_sys::CURLINFO_REDIRECT_COUNT) + .map(|c| c as u32) + } + + /// Get the URL a redirect would go to + /// + /// Returns the URL a redirect would take you to if you would enable + /// `follow_location`. This can come very handy if you think using the + /// built-in libcurl redirect logic isn't good enough for you but you would + /// still prefer to avoid implementing all the magic of figuring out the new + /// URL. + /// + /// Corresponds to `CURLINFO_REDIRECT_URL` and may return an error if the + /// url isn't valid utf-8 or an error happens. + pub fn redirect_url(&mut self) -> Result<Option<&str>, Error> { + self.getopt_str(curl_sys::CURLINFO_REDIRECT_URL) + } + + /// Get the URL a redirect would go to, in bytes + /// + /// Returns the URL a redirect would take you to if you would enable + /// `follow_location`. This can come very handy if you think using the + /// built-in libcurl redirect logic isn't good enough for you but you would + /// still prefer to avoid implementing all the magic of figuring out the new + /// URL. + /// + /// Corresponds to `CURLINFO_REDIRECT_URL` and may return an error. + pub fn redirect_url_bytes(&mut self) -> Result<Option<&[u8]>, Error> { + self.getopt_bytes(curl_sys::CURLINFO_REDIRECT_URL) + } + + /// Get size of retrieved headers + /// + /// Corresponds to `CURLINFO_HEADER_SIZE` and may return an error if the + /// option isn't supported. + pub fn header_size(&mut self) -> Result<u64, Error> { + self.getopt_long(curl_sys::CURLINFO_HEADER_SIZE) + .map(|c| c as u64) + } + + /// Get size of sent request. + /// + /// Corresponds to `CURLINFO_REQUEST_SIZE` and may return an error if the + /// option isn't supported. + pub fn request_size(&mut self) -> Result<u64, Error> { + self.getopt_long(curl_sys::CURLINFO_REQUEST_SIZE) + .map(|c| c as u64) + } + + /// Get Content-Type + /// + /// Returns the content-type of the downloaded object. This is the value + /// read from the Content-Type: field. If you get `None`, it means that the + /// server didn't send a valid Content-Type header or that the protocol + /// used doesn't support this. + /// + /// Corresponds to `CURLINFO_CONTENT_TYPE` and may return an error if the + /// option isn't supported. + pub fn content_type(&mut self) -> Result<Option<&str>, Error> { + self.getopt_str(curl_sys::CURLINFO_CONTENT_TYPE) + } + + /// Get Content-Type, in bytes + /// + /// Returns the content-type of the downloaded object. This is the value + /// read from the Content-Type: field. If you get `None`, it means that the + /// server didn't send a valid Content-Type header or that the protocol + /// used doesn't support this. + /// + /// Corresponds to `CURLINFO_CONTENT_TYPE` and may return an error if the + /// option isn't supported. + pub fn content_type_bytes(&mut self) -> Result<Option<&[u8]>, Error> { + self.getopt_bytes(curl_sys::CURLINFO_CONTENT_TYPE) + } + + /// Get errno number from last connect failure. + /// + /// Note that the value is only set on failure, it is not reset upon a + /// successful operation. The number is OS and system specific. + /// + /// Corresponds to `CURLINFO_OS_ERRNO` and may return an error if the + /// option isn't supported. + pub fn os_errno(&mut self) -> Result<i32, Error> { + self.getopt_long(curl_sys::CURLINFO_OS_ERRNO) + .map(|c| c as i32) + } + + /// Get IP address of last connection. + /// + /// Returns a string holding the IP address of the most recent connection + /// done with this curl handle. This string may be IPv6 when that is + /// enabled. + /// + /// Corresponds to `CURLINFO_PRIMARY_IP` and may return an error if the + /// option isn't supported. + pub fn primary_ip(&mut self) -> Result<Option<&str>, Error> { + self.getopt_str(curl_sys::CURLINFO_PRIMARY_IP) + } + + /// Get the latest destination port number + /// + /// Corresponds to `CURLINFO_PRIMARY_PORT` and may return an error if the + /// option isn't supported. + pub fn primary_port(&mut self) -> Result<u16, Error> { + self.getopt_long(curl_sys::CURLINFO_PRIMARY_PORT) + .map(|c| c as u16) + } + + /// Get local IP address of last connection + /// + /// Returns a string holding the IP address of the local end of most recent + /// connection done with this curl handle. This string may be IPv6 when that + /// is enabled. + /// + /// Corresponds to `CURLINFO_LOCAL_IP` and may return an error if the + /// option isn't supported. + pub fn local_ip(&mut self) -> Result<Option<&str>, Error> { + self.getopt_str(curl_sys::CURLINFO_LOCAL_IP) + } + + /// Get the latest local port number + /// + /// Corresponds to `CURLINFO_LOCAL_PORT` and may return an error if the + /// option isn't supported. + pub fn local_port(&mut self) -> Result<u16, Error> { + self.getopt_long(curl_sys::CURLINFO_LOCAL_PORT) + .map(|c| c as u16) + } + + /// Get all known cookies + /// + /// Returns a linked-list of all cookies cURL knows (expired ones, too). + /// + /// Corresponds to the `CURLINFO_COOKIELIST` option and may return an error + /// if the option isn't supported. + pub fn cookies(&mut self) -> Result<List, Error> { + unsafe { + let mut list = ptr::null_mut(); + let rc = curl_sys::curl_easy_getinfo( + self.inner.handle, + curl_sys::CURLINFO_COOKIELIST, + &mut list, + ); + self.cvt(rc)?; + Ok(list::from_raw(list)) + } + } + + /// Wait for pipelining/multiplexing + /// + /// Set wait to `true` to tell libcurl to prefer to wait for a connection to + /// confirm or deny that it can do pipelining or multiplexing before + /// continuing. + /// + /// When about to perform a new transfer that allows pipelining or + /// multiplexing, libcurl will check for existing connections to re-use and + /// pipeline on. If no such connection exists it will immediately continue + /// and create a fresh new connection to use. + /// + /// By setting this option to `true` - and having `pipelining(true, true)` + /// enabled for the multi handle this transfer is associated with - libcurl + /// will instead wait for the connection to reveal if it is possible to + /// pipeline/multiplex on before it continues. This enables libcurl to much + /// better keep the number of connections to a minimum when using pipelining + /// or multiplexing protocols. + /// + /// The effect thus becomes that with this option set, libcurl prefers to + /// wait and re-use an existing connection for pipelining rather than the + /// opposite: prefer to open a new connection rather than waiting. + /// + /// The waiting time is as long as it takes for the connection to get up and + /// for libcurl to get the necessary response back that informs it about its + /// protocol and support level. + /// + /// This corresponds to the `CURLOPT_PIPEWAIT` option. + pub fn pipewait(&mut self, wait: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_PIPEWAIT, wait as c_long) + } + + /// Allow HTTP/0.9 compliant responses + /// + /// Set allow to `true` to tell libcurl to allow HTTP/0.9 responses. A HTTP/0.9 + /// response is a server response entirely without headers and only a body. + /// + /// By default this option is not set and corresponds to + /// `CURLOPT_HTTP09_ALLOWED`. + pub fn http_09_allowed(&mut self, allow: bool) -> Result<(), Error> { + self.setopt_long(curl_sys::CURLOPT_HTTP09_ALLOWED, allow as c_long) + } + + // ========================================================================= + // Other methods + + /// After options have been set, this will perform the transfer described by + /// the options. + /// + /// This performs the request in a synchronous fashion. This can be used + /// multiple times for one easy handle and libcurl will attempt to re-use + /// the same connection for all transfers. + /// + /// This method will preserve all options configured in this handle for the + /// next request, and if that is not desired then the options can be + /// manually reset or the `reset` method can be called. + /// + /// Note that this method takes `&self`, which is quite important! This + /// allows applications to close over the handle in various callbacks to + /// call methods like `unpause_write` and `unpause_read` while a transfer is + /// in progress. + pub fn perform(&self) -> Result<(), Error> { + let ret = unsafe { self.cvt(curl_sys::curl_easy_perform(self.inner.handle)) }; + panic::propagate(); + ret + } + + /// Some protocols have "connection upkeep" mechanisms. These mechanisms + /// usually send some traffic on existing connections in order to keep them + /// alive; this can prevent connections from being closed due to overzealous + /// firewalls, for example. + /// + /// Currently the only protocol with a connection upkeep mechanism is + /// HTTP/2: when the connection upkeep interval is exceeded and upkeep() is + /// called, an HTTP/2 PING frame is sent on the connection. + #[cfg(feature = "upkeep_7_62_0")] + pub fn upkeep(&self) -> Result<(), Error> { + let ret = unsafe { self.cvt(curl_sys::curl_easy_upkeep(self.inner.handle)) }; + panic::propagate(); + return ret; + } + + /// Unpause reading on a connection. + /// + /// Using this function, you can explicitly unpause a connection that was + /// previously paused. + /// + /// A connection can be paused by letting the read or the write callbacks + /// return `ReadError::Pause` or `WriteError::Pause`. + /// + /// To unpause, you may for example call this from the progress callback + /// which gets called at least once per second, even if the connection is + /// paused. + /// + /// The chance is high that you will get your write callback called before + /// this function returns. + pub fn unpause_read(&self) -> Result<(), Error> { + unsafe { + let rc = curl_sys::curl_easy_pause(self.inner.handle, curl_sys::CURLPAUSE_RECV_CONT); + self.cvt(rc) + } + } + + /// Unpause writing on a connection. + /// + /// Using this function, you can explicitly unpause a connection that was + /// previously paused. + /// + /// A connection can be paused by letting the read or the write callbacks + /// return `ReadError::Pause` or `WriteError::Pause`. A write callback that + /// returns pause signals to the library that it couldn't take care of any + /// data at all, and that data will then be delivered again to the callback + /// when the writing is later unpaused. + /// + /// To unpause, you may for example call this from the progress callback + /// which gets called at least once per second, even if the connection is + /// paused. + pub fn unpause_write(&self) -> Result<(), Error> { + unsafe { + let rc = curl_sys::curl_easy_pause(self.inner.handle, curl_sys::CURLPAUSE_SEND_CONT); + self.cvt(rc) + } + } + + /// URL encodes a string `s` + pub fn url_encode(&mut self, s: &[u8]) -> String { + if s.is_empty() { + return String::new(); + } + unsafe { + let p = curl_sys::curl_easy_escape( + self.inner.handle, + s.as_ptr() as *const _, + s.len() as c_int, + ); + assert!(!p.is_null()); + let ret = str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap(); + let ret = String::from(ret); + curl_sys::curl_free(p as *mut _); + ret + } + } + + /// URL decodes a string `s`, returning `None` if it fails + pub fn url_decode(&mut self, s: &str) -> Vec<u8> { + if s.is_empty() { + return Vec::new(); + } + + // Work around https://curl.haxx.se/docs/adv_20130622.html, a bug where + // if the last few characters are a bad escape then curl will have a + // buffer overrun. + let mut iter = s.chars().rev(); + let orig_len = s.len(); + let mut data; + let mut s = s; + if iter.next() == Some('%') || iter.next() == Some('%') || iter.next() == Some('%') { + data = s.to_string(); + data.push(0u8 as char); + s = &data[..]; + } + unsafe { + let mut len = 0; + let p = curl_sys::curl_easy_unescape( + self.inner.handle, + s.as_ptr() as *const _, + orig_len as c_int, + &mut len, + ); + assert!(!p.is_null()); + let slice = slice::from_raw_parts(p as *const u8, len as usize); + let ret = slice.to_vec(); + curl_sys::curl_free(p as *mut _); + ret + } + } + + // TODO: I don't think this is safe, you can drop this which has all the + // callback data and then the next is use-after-free + // + // /// Attempts to clone this handle, returning a new session handle with the + // /// same options set for this handle. + // /// + // /// Internal state info and things like persistent connections ccannot be + // /// transferred. + // /// + // /// # Errors + // /// + // /// If a new handle could not be allocated or another error happens, `None` + // /// is returned. + // pub fn try_clone<'b>(&mut self) -> Option<Easy<'b>> { + // unsafe { + // let handle = curl_sys::curl_easy_duphandle(self.handle); + // if handle.is_null() { + // None + // } else { + // Some(Easy { + // handle: handle, + // data: blank_data(), + // _marker: marker::PhantomData, + // }) + // } + // } + // } + + /// Receives data from a connected socket. + /// + /// Only useful after a successful `perform` with the `connect_only` option + /// set as well. + pub fn recv(&mut self, data: &mut [u8]) -> Result<usize, Error> { + unsafe { + let mut n = 0; + let r = curl_sys::curl_easy_recv( + self.inner.handle, + data.as_mut_ptr() as *mut _, + data.len(), + &mut n, + ); + if r == curl_sys::CURLE_OK { + Ok(n) + } else { + Err(Error::new(r)) + } + } + } + + /// Sends data over the connected socket. + /// + /// Only useful after a successful `perform` with the `connect_only` option + /// set as well. + pub fn send(&mut self, data: &[u8]) -> Result<usize, Error> { + unsafe { + let mut n = 0; + let rc = curl_sys::curl_easy_send( + self.inner.handle, + data.as_ptr() as *const _, + data.len(), + &mut n, + ); + self.cvt(rc)?; + Ok(n) + } + } + + /// Get a pointer to the raw underlying CURL handle. + pub fn raw(&self) -> *mut curl_sys::CURL { + self.inner.handle + } + + #[cfg(unix)] + fn setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error> { + use std::os::unix::prelude::*; + let s = CString::new(val.as_os_str().as_bytes())?; + self.setopt_str(opt, &s) + } + + #[cfg(windows)] + fn setopt_path(&mut self, opt: curl_sys::CURLoption, val: &Path) -> Result<(), Error> { + match val.to_str() { + Some(s) => self.setopt_str(opt, &CString::new(s)?), + None => Err(Error::new(curl_sys::CURLE_CONV_FAILED)), + } + } + + fn setopt_long(&mut self, opt: curl_sys::CURLoption, val: c_long) -> Result<(), Error> { + unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, val)) } + } + + fn setopt_str(&mut self, opt: curl_sys::CURLoption, val: &CStr) -> Result<(), Error> { + self.setopt_ptr(opt, val.as_ptr()) + } + + fn setopt_ptr(&self, opt: curl_sys::CURLoption, val: *const c_char) -> Result<(), Error> { + unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, val)) } + } + + fn setopt_off_t( + &mut self, + opt: curl_sys::CURLoption, + val: curl_sys::curl_off_t, + ) -> Result<(), Error> { + unsafe { + let rc = curl_sys::curl_easy_setopt(self.inner.handle, opt, val); + self.cvt(rc) + } + } + + fn setopt_blob(&mut self, opt: curl_sys::CURLoption, val: &[u8]) -> Result<(), Error> { + let blob = curl_sys::curl_blob { + data: val.as_ptr() as *const c_void as *mut c_void, + len: val.len(), + flags: curl_sys::CURL_BLOB_COPY, + }; + let blob_ptr = &blob as *const curl_sys::curl_blob; + unsafe { self.cvt(curl_sys::curl_easy_setopt(self.inner.handle, opt, blob_ptr)) } + } + + fn getopt_bytes(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&[u8]>, Error> { + unsafe { + let p = self.getopt_ptr(opt)?; + if p.is_null() { + Ok(None) + } else { + Ok(Some(CStr::from_ptr(p).to_bytes())) + } + } + } + + fn getopt_ptr(&mut self, opt: curl_sys::CURLINFO) -> Result<*const c_char, Error> { + unsafe { + let mut p = ptr::null(); + let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p); + self.cvt(rc)?; + Ok(p) + } + } + + fn getopt_str(&mut self, opt: curl_sys::CURLINFO) -> Result<Option<&str>, Error> { + match self.getopt_bytes(opt) { + Ok(None) => Ok(None), + Err(e) => Err(e), + Ok(Some(bytes)) => match str::from_utf8(bytes) { + Ok(s) => Ok(Some(s)), + Err(_) => Err(Error::new(curl_sys::CURLE_CONV_FAILED)), + }, + } + } + + fn getopt_long(&mut self, opt: curl_sys::CURLINFO) -> Result<c_long, Error> { + unsafe { + let mut p = 0; + let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p); + self.cvt(rc)?; + Ok(p) + } + } + + fn getopt_double(&mut self, opt: curl_sys::CURLINFO) -> Result<c_double, Error> { + unsafe { + let mut p = 0 as c_double; + let rc = curl_sys::curl_easy_getinfo(self.inner.handle, opt, &mut p); + self.cvt(rc)?; + Ok(p) + } + } + + /// Returns the contents of the internal error buffer, if available. + /// + /// When an easy handle is created it configured the `CURLOPT_ERRORBUFFER` + /// parameter and instructs libcurl to store more error information into a + /// buffer for better error messages and better debugging. The contents of + /// that buffer are automatically coupled with all errors for methods on + /// this type, but if manually invoking APIs the contents will need to be + /// extracted with this method. + /// + /// Put another way, you probably don't need this, you're probably already + /// getting nice error messages! + /// + /// This function will clear the internal buffer, so this is an operation + /// that mutates the handle internally. + pub fn take_error_buf(&self) -> Option<String> { + let mut buf = self.inner.error_buf.borrow_mut(); + if buf[0] == 0 { + return None; + } + let pos = buf.iter().position(|i| *i == 0).unwrap_or(buf.len()); + let msg = String::from_utf8_lossy(&buf[..pos]).into_owned(); + buf[0] = 0; + Some(msg) + } + + fn cvt(&self, rc: curl_sys::CURLcode) -> Result<(), Error> { + if rc == curl_sys::CURLE_OK { + return Ok(()); + } + let mut err = Error::new(rc); + if let Some(msg) = self.take_error_buf() { + err.set_extra(msg); + } + Err(err) + } +} + +impl<H: fmt::Debug> fmt::Debug for Easy2<H> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Easy") + .field("handle", &self.inner.handle) + .field("handler", &self.inner.handler) + .finish() + } +} + +impl<H> Drop for Easy2<H> { + fn drop(&mut self) { + unsafe { + curl_sys::curl_easy_cleanup(self.inner.handle); + } + } +} + +extern "C" fn header_cb<H: Handler>( + buffer: *mut c_char, + size: size_t, + nitems: size_t, + userptr: *mut c_void, +) -> size_t { + let keep_going = panic::catch(|| unsafe { + let data = slice::from_raw_parts(buffer as *const u8, size * nitems); + (*(userptr as *mut Inner<H>)).handler.header(data) + }) + .unwrap_or(false); + if keep_going { + size * nitems + } else { + !0 + } +} + +extern "C" fn write_cb<H: Handler>( + ptr: *mut c_char, + size: size_t, + nmemb: size_t, + data: *mut c_void, +) -> size_t { + panic::catch(|| unsafe { + let input = slice::from_raw_parts(ptr as *const u8, size * nmemb); + match (*(data as *mut Inner<H>)).handler.write(input) { + Ok(s) => s, + Err(WriteError::Pause) => curl_sys::CURL_WRITEFUNC_PAUSE, + } + }) + .unwrap_or(!0) +} + +extern "C" fn read_cb<H: Handler>( + ptr: *mut c_char, + size: size_t, + nmemb: size_t, + data: *mut c_void, +) -> size_t { + panic::catch(|| unsafe { + let input = slice::from_raw_parts_mut(ptr as *mut u8, size * nmemb); + match (*(data as *mut Inner<H>)).handler.read(input) { + Ok(s) => s, + Err(ReadError::Pause) => curl_sys::CURL_READFUNC_PAUSE, + Err(ReadError::Abort) => curl_sys::CURL_READFUNC_ABORT, + } + }) + .unwrap_or(!0) +} + +extern "C" fn seek_cb<H: Handler>( + data: *mut c_void, + offset: curl_sys::curl_off_t, + origin: c_int, +) -> c_int { + panic::catch(|| unsafe { + let from = if origin == libc::SEEK_SET { + SeekFrom::Start(offset as u64) + } else { + panic!("unknown origin from libcurl: {}", origin); + }; + (*(data as *mut Inner<H>)).handler.seek(from) as c_int + }) + .unwrap_or(!0) +} + +extern "C" fn progress_cb<H: Handler>( + data: *mut c_void, + dltotal: c_double, + dlnow: c_double, + ultotal: c_double, + ulnow: c_double, +) -> c_int { + let keep_going = panic::catch(|| unsafe { + (*(data as *mut Inner<H>)) + .handler + .progress(dltotal, dlnow, ultotal, ulnow) + }) + .unwrap_or(false); + if keep_going { + 0 + } else { + 1 + } +} + +// TODO: expose `handle`? is that safe? +extern "C" fn debug_cb<H: Handler>( + _handle: *mut curl_sys::CURL, + kind: curl_sys::curl_infotype, + data: *mut c_char, + size: size_t, + userptr: *mut c_void, +) -> c_int { + panic::catch(|| unsafe { + let data = slice::from_raw_parts(data as *const u8, size); + let kind = match kind { + curl_sys::CURLINFO_TEXT => InfoType::Text, + curl_sys::CURLINFO_HEADER_IN => InfoType::HeaderIn, + curl_sys::CURLINFO_HEADER_OUT => InfoType::HeaderOut, + curl_sys::CURLINFO_DATA_IN => InfoType::DataIn, + curl_sys::CURLINFO_DATA_OUT => InfoType::DataOut, + curl_sys::CURLINFO_SSL_DATA_IN => InfoType::SslDataIn, + curl_sys::CURLINFO_SSL_DATA_OUT => InfoType::SslDataOut, + _ => return, + }; + (*(userptr as *mut Inner<H>)).handler.debug(kind, data) + }); + 0 +} + +extern "C" fn ssl_ctx_cb<H: Handler>( + _handle: *mut curl_sys::CURL, + ssl_ctx: *mut c_void, + data: *mut c_void, +) -> curl_sys::CURLcode { + let res = panic::catch(|| unsafe { + match (*(data as *mut Inner<H>)).handler.ssl_ctx(ssl_ctx) { + Ok(()) => curl_sys::CURLE_OK, + Err(e) => e.code(), + } + }); + // Default to a generic SSL error in case of panic. This + // shouldn't really matter since the error should be + // propagated later on but better safe than sorry... + res.unwrap_or(curl_sys::CURLE_SSL_CONNECT_ERROR) +} + +// TODO: expose `purpose` and `sockaddr` inside of `address` +extern "C" fn opensocket_cb<H: Handler>( + data: *mut c_void, + _purpose: curl_sys::curlsocktype, + address: *mut curl_sys::curl_sockaddr, +) -> curl_sys::curl_socket_t { + let res = panic::catch(|| unsafe { + (*(data as *mut Inner<H>)) + .handler + .open_socket((*address).family, (*address).socktype, (*address).protocol) + .unwrap_or(curl_sys::CURL_SOCKET_BAD) + }); + res.unwrap_or(curl_sys::CURL_SOCKET_BAD) +} + +fn double_seconds_to_duration(seconds: f64) -> Duration { + let whole_seconds = seconds.trunc() as u64; + let nanos = seconds.fract() * 1_000_000_000f64; + Duration::new(whole_seconds, nanos as u32) +} + +#[test] +fn double_seconds_to_duration_whole_second() { + let dur = double_seconds_to_duration(1.0); + assert_eq!(dur.as_secs(), 1); + assert_eq!(dur.subsec_nanos(), 0); +} + +#[test] +fn double_seconds_to_duration_sub_second1() { + let dur = double_seconds_to_duration(0.0); + assert_eq!(dur.as_secs(), 0); + assert_eq!(dur.subsec_nanos(), 0); +} + +#[test] +fn double_seconds_to_duration_sub_second2() { + let dur = double_seconds_to_duration(0.5); + assert_eq!(dur.as_secs(), 0); + assert_eq!(dur.subsec_nanos(), 500_000_000); +} + +impl Auth { + /// Creates a new set of authentications with no members. + /// + /// An `Auth` structure is used to configure which forms of authentication + /// are attempted when negotiating connections with servers. + pub fn new() -> Auth { + Auth { bits: 0 } + } + + /// HTTP Basic authentication. + /// + /// This is the default choice, and the only method that is in wide-spread + /// use and supported virtually everywhere. This sends the user name and + /// password over the network in plain text, easily captured by others. + pub fn basic(&mut self, on: bool) -> &mut Auth { + self.flag(curl_sys::CURLAUTH_BASIC, on) + } + + /// HTTP Digest authentication. + /// + /// Digest authentication is defined in RFC 2617 and is a more secure way to + /// do authentication over public networks than the regular old-fashioned + /// Basic method. + pub fn digest(&mut self, on: bool) -> &mut Auth { + self.flag(curl_sys::CURLAUTH_DIGEST, on) + } + + /// HTTP Digest authentication with an IE flavor. + /// + /// Digest authentication is defined in RFC 2617 and is a more secure way to + /// do authentication over public networks than the regular old-fashioned + /// Basic method. The IE flavor is simply that libcurl will use a special + /// "quirk" that IE is known to have used before version 7 and that some + /// servers require the client to use. + pub fn digest_ie(&mut self, on: bool) -> &mut Auth { + self.flag(curl_sys::CURLAUTH_DIGEST_IE, on) + } + + /// HTTP Negotiate (SPNEGO) authentication. + /// + /// Negotiate authentication is defined in RFC 4559 and is the most secure + /// way to perform authentication over HTTP. + /// + /// You need to build libcurl with a suitable GSS-API library or SSPI on + /// Windows for this to work. + pub fn gssnegotiate(&mut self, on: bool) -> &mut Auth { + self.flag(curl_sys::CURLAUTH_GSSNEGOTIATE, on) + } + + /// HTTP NTLM authentication. + /// + /// A proprietary protocol invented and used by Microsoft. It uses a + /// challenge-response and hash concept similar to Digest, to prevent the + /// password from being eavesdropped. + /// + /// You need to build libcurl with either OpenSSL, GnuTLS or NSS support for + /// this option to work, or build libcurl on Windows with SSPI support. + pub fn ntlm(&mut self, on: bool) -> &mut Auth { + self.flag(curl_sys::CURLAUTH_NTLM, on) + } + + /// NTLM delegating to winbind helper. + /// + /// Authentication is performed by a separate binary application that is + /// executed when needed. The name of the application is specified at + /// compile time but is typically /usr/bin/ntlm_auth + /// + /// Note that libcurl will fork when necessary to run the winbind + /// application and kill it when complete, calling waitpid() to await its + /// exit when done. On POSIX operating systems, killing the process will + /// cause a SIGCHLD signal to be raised (regardless of whether + /// CURLOPT_NOSIGNAL is set), which must be handled intelligently by the + /// application. In particular, the application must not unconditionally + /// call wait() in its SIGCHLD signal handler to avoid being subject to a + /// race condition. This behavior is subject to change in future versions of + /// libcurl. + /// + /// A proprietary protocol invented and used by Microsoft. It uses a + /// challenge-response and hash concept similar to Digest, to prevent the + /// password from being eavesdropped. + pub fn ntlm_wb(&mut self, on: bool) -> &mut Auth { + self.flag(curl_sys::CURLAUTH_NTLM_WB, on) + } + + /// HTTP AWS V4 signature authentication. + /// + /// This is a special auth type that can't be combined with the others. + /// It will override the other auth types you might have set. + /// + /// Enabling this auth type is the same as using "aws:amz" as param in + /// [`Easy2::aws_sigv4`](struct.Easy2.html#method.aws_sigv4) method. + pub fn aws_sigv4(&mut self, on: bool) -> &mut Auth { + self.flag(curl_sys::CURLAUTH_AWS_SIGV4, on) + } + + fn flag(&mut self, bit: c_ulong, on: bool) -> &mut Auth { + if on { + self.bits |= bit as c_long; + } else { + self.bits &= !bit as c_long; + } + self + } +} + +impl fmt::Debug for Auth { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let bits = self.bits as c_ulong; + f.debug_struct("Auth") + .field("basic", &(bits & curl_sys::CURLAUTH_BASIC != 0)) + .field("digest", &(bits & curl_sys::CURLAUTH_DIGEST != 0)) + .field("digest_ie", &(bits & curl_sys::CURLAUTH_DIGEST_IE != 0)) + .field( + "gssnegotiate", + &(bits & curl_sys::CURLAUTH_GSSNEGOTIATE != 0), + ) + .field("ntlm", &(bits & curl_sys::CURLAUTH_NTLM != 0)) + .field("ntlm_wb", &(bits & curl_sys::CURLAUTH_NTLM_WB != 0)) + .field("aws_sigv4", &(bits & curl_sys::CURLAUTH_AWS_SIGV4 != 0)) + .finish() + } +} + +impl SslOpt { + /// Creates a new set of SSL options. + pub fn new() -> SslOpt { + SslOpt { bits: 0 } + } + + /// Tells libcurl to disable certificate revocation checks for those SSL + /// backends where such behavior is present. + /// + /// Currently this option is only supported for WinSSL (the native Windows + /// SSL library), with an exception in the case of Windows' Untrusted + /// Publishers blacklist which it seems can't be bypassed. This option may + /// have broader support to accommodate other SSL backends in the future. + /// https://curl.haxx.se/docs/ssl-compared.html + pub fn no_revoke(&mut self, on: bool) -> &mut SslOpt { + self.flag(curl_sys::CURLSSLOPT_NO_REVOKE, on) + } + + /// Tells libcurl to not attempt to use any workarounds for a security flaw + /// in the SSL3 and TLS1.0 protocols. + /// + /// If this option isn't used or this bit is set to 0, the SSL layer libcurl + /// uses may use a work-around for this flaw although it might cause + /// interoperability problems with some (older) SSL implementations. + /// + /// > WARNING: avoiding this work-around lessens the security, and by + /// > setting this option to 1 you ask for exactly that. This option is only + /// > supported for DarwinSSL, NSS and OpenSSL. + pub fn allow_beast(&mut self, on: bool) -> &mut SslOpt { + self.flag(curl_sys::CURLSSLOPT_ALLOW_BEAST, on) + } + + fn flag(&mut self, bit: c_long, on: bool) -> &mut SslOpt { + if on { + self.bits |= bit as c_long; + } else { + self.bits &= !bit as c_long; + } + self + } +} + +impl fmt::Debug for SslOpt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("SslOpt") + .field( + "no_revoke", + &(self.bits & curl_sys::CURLSSLOPT_NO_REVOKE != 0), + ) + .field( + "allow_beast", + &(self.bits & curl_sys::CURLSSLOPT_ALLOW_BEAST != 0), + ) + .finish() + } +} diff --git a/vendor/curl/src/easy/list.rs b/vendor/curl/src/easy/list.rs new file mode 100644 index 000000000..ac5d4ef49 --- /dev/null +++ b/vendor/curl/src/easy/list.rs @@ -0,0 +1,103 @@ +use std::ffi::{CStr, CString}; +use std::fmt; +use std::ptr; + +use crate::Error; +use curl_sys; + +/// A linked list of a strings +pub struct List { + raw: *mut curl_sys::curl_slist, +} + +/// An iterator over `List` +#[derive(Clone)] +pub struct Iter<'a> { + _me: &'a List, + cur: *mut curl_sys::curl_slist, +} + +pub fn raw(list: &List) -> *mut curl_sys::curl_slist { + list.raw +} + +pub unsafe fn from_raw(raw: *mut curl_sys::curl_slist) -> List { + List { raw } +} + +unsafe impl Send for List {} + +impl List { + /// Creates a new empty list of strings. + pub fn new() -> List { + List { + raw: ptr::null_mut(), + } + } + + /// Appends some data into this list. + pub fn append(&mut self, data: &str) -> Result<(), Error> { + let data = CString::new(data)?; + unsafe { + let raw = curl_sys::curl_slist_append(self.raw, data.as_ptr()); + assert!(!raw.is_null()); + self.raw = raw; + Ok(()) + } + } + + /// Returns an iterator over the nodes in this list. + pub fn iter(&self) -> Iter { + Iter { + _me: self, + cur: self.raw, + } + } +} + +impl fmt::Debug for List { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_list() + .entries(self.iter().map(String::from_utf8_lossy)) + .finish() + } +} + +impl<'a> IntoIterator for &'a List { + type IntoIter = Iter<'a>; + type Item = &'a [u8]; + + fn into_iter(self) -> Iter<'a> { + self.iter() + } +} + +impl Drop for List { + fn drop(&mut self) { + unsafe { curl_sys::curl_slist_free_all(self.raw) } + } +} + +impl<'a> Iterator for Iter<'a> { + type Item = &'a [u8]; + + fn next(&mut self) -> Option<&'a [u8]> { + if self.cur.is_null() { + return None; + } + + unsafe { + let ret = Some(CStr::from_ptr((*self.cur).data).to_bytes()); + self.cur = (*self.cur).next; + ret + } + } +} + +impl<'a> fmt::Debug for Iter<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_list() + .entries(self.clone().map(String::from_utf8_lossy)) + .finish() + } +} diff --git a/vendor/curl/src/easy/mod.rs b/vendor/curl/src/easy/mod.rs new file mode 100644 index 000000000..988309946 --- /dev/null +++ b/vendor/curl/src/easy/mod.rs @@ -0,0 +1,22 @@ +//! Bindings to the "easy" libcurl API. +//! +//! This module contains some simple types like `Easy` and `List` which are just +//! wrappers around the corresponding libcurl types. There's also a few enums +//! scattered about for various options here and there. +//! +//! Most simple usage of libcurl will likely use the `Easy` structure here, and +//! you can find more docs about its usage on that struct. + +mod form; +mod handle; +mod handler; +mod list; +mod windows; + +pub use self::form::{Form, Part}; +pub use self::handle::{Easy, Transfer}; +pub use self::handler::{Auth, NetRc, ProxyType, SslOpt}; +pub use self::handler::{Easy2, Handler}; +pub use self::handler::{HttpVersion, IpResolve, SslVersion, TimeCondition}; +pub use self::handler::{InfoType, ReadError, SeekResult, WriteError}; +pub use self::list::{Iter, List}; diff --git a/vendor/curl/src/easy/windows.rs b/vendor/curl/src/easy/windows.rs new file mode 100644 index 000000000..cbf2817cf --- /dev/null +++ b/vendor/curl/src/easy/windows.rs @@ -0,0 +1,132 @@ +#![allow(non_camel_case_types, non_snake_case)] + +use libc::c_void; + +#[cfg(target_env = "msvc")] +mod win { + use schannel::cert_context::ValidUses; + use schannel::cert_store::CertStore; + use std::ffi::CString; + use std::mem; + use std::ptr; + use winapi::ctypes::*; + use winapi::um::libloaderapi::*; + use winapi::um::wincrypt::*; + + fn lookup(module: &str, symbol: &str) -> Option<*const c_void> { + unsafe { + let symbol = CString::new(symbol).unwrap(); + let mut mod_buf: Vec<u16> = module.encode_utf16().collect(); + mod_buf.push(0); + let handle = GetModuleHandleW(mod_buf.as_mut_ptr()); + let n = GetProcAddress(handle, symbol.as_ptr()); + if n == ptr::null_mut() { + None + } else { + Some(n as *const c_void) + } + } + } + + pub enum X509_STORE {} + pub enum X509 {} + pub enum SSL_CTX {} + + type d2i_X509_fn = unsafe extern "C" fn( + a: *mut *mut X509, + pp: *mut *const c_uchar, + length: c_long, + ) -> *mut X509; + type X509_free_fn = unsafe extern "C" fn(x: *mut X509); + type X509_STORE_add_cert_fn = + unsafe extern "C" fn(store: *mut X509_STORE, x: *mut X509) -> c_int; + type SSL_CTX_get_cert_store_fn = unsafe extern "C" fn(ctx: *const SSL_CTX) -> *mut X509_STORE; + + struct OpenSSL { + d2i_X509: d2i_X509_fn, + X509_free: X509_free_fn, + X509_STORE_add_cert: X509_STORE_add_cert_fn, + SSL_CTX_get_cert_store: SSL_CTX_get_cert_store_fn, + } + + unsafe fn lookup_functions(crypto_module: &str, ssl_module: &str) -> Option<OpenSSL> { + macro_rules! get { + ($(let $sym:ident in $module:expr;)*) => ($( + let $sym = match lookup($module, stringify!($sym)) { + Some(p) => p, + None => return None, + }; + )*) + } + get! { + let d2i_X509 in crypto_module; + let X509_free in crypto_module; + let X509_STORE_add_cert in crypto_module; + let SSL_CTX_get_cert_store in ssl_module; + } + Some(OpenSSL { + d2i_X509: mem::transmute(d2i_X509), + X509_free: mem::transmute(X509_free), + X509_STORE_add_cert: mem::transmute(X509_STORE_add_cert), + SSL_CTX_get_cert_store: mem::transmute(SSL_CTX_get_cert_store), + }) + } + + pub unsafe fn add_certs_to_context(ssl_ctx: *mut c_void) { + // check the runtime version of OpenSSL + let openssl = match crate::version::Version::get().ssl_version() { + Some(ssl_ver) if ssl_ver.starts_with("OpenSSL/1.1.0") => { + lookup_functions("libcrypto", "libssl") + } + Some(ssl_ver) if ssl_ver.starts_with("OpenSSL/1.0.2") => { + lookup_functions("libeay32", "ssleay32") + } + _ => return, + }; + let openssl = match openssl { + Some(s) => s, + None => return, + }; + + let openssl_store = (openssl.SSL_CTX_get_cert_store)(ssl_ctx as *const SSL_CTX); + let store = match CertStore::open_current_user("ROOT") { + Ok(s) => s, + Err(_) => return, + }; + + for cert in store.certs() { + let valid_uses = match cert.valid_uses() { + Ok(v) => v, + Err(_) => continue, + }; + + // check the extended key usage for the "Server Authentication" OID + match valid_uses { + ValidUses::All => {} + ValidUses::Oids(ref oids) => { + let oid = szOID_PKIX_KP_SERVER_AUTH.to_owned(); + if !oids.contains(&oid) { + continue; + } + } + } + + let der = cert.to_der(); + let x509 = (openssl.d2i_X509)(ptr::null_mut(), &mut der.as_ptr(), der.len() as c_long); + if !x509.is_null() { + (openssl.X509_STORE_add_cert)(openssl_store, x509); + (openssl.X509_free)(x509); + } + } + } +} + +#[cfg(target_env = "msvc")] +pub fn add_certs_to_context(ssl_ctx: *mut c_void) { + unsafe { + win::add_certs_to_context(ssl_ctx as *mut _); + } +} + +#[cfg(not(target_env = "msvc"))] +pub fn add_certs_to_context(_: *mut c_void) {} diff --git a/vendor/curl/src/error.rs b/vendor/curl/src/error.rs new file mode 100644 index 000000000..a138f75df --- /dev/null +++ b/vendor/curl/src/error.rs @@ -0,0 +1,617 @@ +use std::error; +use std::ffi::{self, CStr}; +use std::fmt; +use std::io; +use std::str; + +/// An error returned from various "easy" operations. +/// +/// This structure wraps a `CURLcode`. +#[derive(Clone, PartialEq)] +pub struct Error { + code: curl_sys::CURLcode, + extra: Option<Box<str>>, +} + +impl Error { + /// Creates a new error from the underlying code returned by libcurl. + pub fn new(code: curl_sys::CURLcode) -> Error { + Error { code, extra: None } + } + + /// Stores some extra information about this error inside this error. + /// + /// This is typically used with `take_error_buf` on the easy handles to + /// couple the extra `CURLOPT_ERRORBUFFER` information with an `Error` being + /// returned. + pub fn set_extra(&mut self, extra: String) { + self.extra = Some(extra.into()); + } + + /// Returns whether this error corresponds to CURLE_UNSUPPORTED_PROTOCOL. + pub fn is_unsupported_protocol(&self) -> bool { + self.code == curl_sys::CURLE_UNSUPPORTED_PROTOCOL + } + + /// Returns whether this error corresponds to CURLE_FAILED_INIT. + pub fn is_failed_init(&self) -> bool { + self.code == curl_sys::CURLE_FAILED_INIT + } + + /// Returns whether this error corresponds to CURLE_URL_MALFORMAT. + pub fn is_url_malformed(&self) -> bool { + self.code == curl_sys::CURLE_URL_MALFORMAT + } + + // /// Returns whether this error corresponds to CURLE_NOT_BUILT_IN. + // pub fn is_not_built_in(&self) -> bool { + // self.code == curl_sys::CURLE_NOT_BUILT_IN + // } + + /// Returns whether this error corresponds to CURLE_COULDNT_RESOLVE_PROXY. + pub fn is_couldnt_resolve_proxy(&self) -> bool { + self.code == curl_sys::CURLE_COULDNT_RESOLVE_PROXY + } + + /// Returns whether this error corresponds to CURLE_COULDNT_RESOLVE_HOST. + pub fn is_couldnt_resolve_host(&self) -> bool { + self.code == curl_sys::CURLE_COULDNT_RESOLVE_HOST + } + + /// Returns whether this error corresponds to CURLE_COULDNT_CONNECT. + pub fn is_couldnt_connect(&self) -> bool { + self.code == curl_sys::CURLE_COULDNT_CONNECT + } + + /// Returns whether this error corresponds to CURLE_REMOTE_ACCESS_DENIED. + pub fn is_remote_access_denied(&self) -> bool { + self.code == curl_sys::CURLE_REMOTE_ACCESS_DENIED + } + + /// Returns whether this error corresponds to CURLE_PARTIAL_FILE. + pub fn is_partial_file(&self) -> bool { + self.code == curl_sys::CURLE_PARTIAL_FILE + } + + /// Returns whether this error corresponds to CURLE_QUOTE_ERROR. + pub fn is_quote_error(&self) -> bool { + self.code == curl_sys::CURLE_QUOTE_ERROR + } + + /// Returns whether this error corresponds to CURLE_HTTP_RETURNED_ERROR. + pub fn is_http_returned_error(&self) -> bool { + self.code == curl_sys::CURLE_HTTP_RETURNED_ERROR + } + + /// Returns whether this error corresponds to CURLE_READ_ERROR. + pub fn is_read_error(&self) -> bool { + self.code == curl_sys::CURLE_READ_ERROR + } + + /// Returns whether this error corresponds to CURLE_WRITE_ERROR. + pub fn is_write_error(&self) -> bool { + self.code == curl_sys::CURLE_WRITE_ERROR + } + + /// Returns whether this error corresponds to CURLE_UPLOAD_FAILED. + pub fn is_upload_failed(&self) -> bool { + self.code == curl_sys::CURLE_UPLOAD_FAILED + } + + /// Returns whether this error corresponds to CURLE_OUT_OF_MEMORY. + pub fn is_out_of_memory(&self) -> bool { + self.code == curl_sys::CURLE_OUT_OF_MEMORY + } + + /// Returns whether this error corresponds to CURLE_OPERATION_TIMEDOUT. + pub fn is_operation_timedout(&self) -> bool { + self.code == curl_sys::CURLE_OPERATION_TIMEDOUT + } + + /// Returns whether this error corresponds to CURLE_RANGE_ERROR. + pub fn is_range_error(&self) -> bool { + self.code == curl_sys::CURLE_RANGE_ERROR + } + + /// Returns whether this error corresponds to CURLE_HTTP_POST_ERROR. + pub fn is_http_post_error(&self) -> bool { + self.code == curl_sys::CURLE_HTTP_POST_ERROR + } + + /// Returns whether this error corresponds to CURLE_SSL_CONNECT_ERROR. + pub fn is_ssl_connect_error(&self) -> bool { + self.code == curl_sys::CURLE_SSL_CONNECT_ERROR + } + + /// Returns whether this error corresponds to CURLE_BAD_DOWNLOAD_RESUME. + pub fn is_bad_download_resume(&self) -> bool { + self.code == curl_sys::CURLE_BAD_DOWNLOAD_RESUME + } + + /// Returns whether this error corresponds to CURLE_FILE_COULDNT_READ_FILE. + pub fn is_file_couldnt_read_file(&self) -> bool { + self.code == curl_sys::CURLE_FILE_COULDNT_READ_FILE + } + + /// Returns whether this error corresponds to CURLE_FUNCTION_NOT_FOUND. + pub fn is_function_not_found(&self) -> bool { + self.code == curl_sys::CURLE_FUNCTION_NOT_FOUND + } + + /// Returns whether this error corresponds to CURLE_ABORTED_BY_CALLBACK. + pub fn is_aborted_by_callback(&self) -> bool { + self.code == curl_sys::CURLE_ABORTED_BY_CALLBACK + } + + /// Returns whether this error corresponds to CURLE_BAD_FUNCTION_ARGUMENT. + pub fn is_bad_function_argument(&self) -> bool { + self.code == curl_sys::CURLE_BAD_FUNCTION_ARGUMENT + } + + /// Returns whether this error corresponds to CURLE_INTERFACE_FAILED. + pub fn is_interface_failed(&self) -> bool { + self.code == curl_sys::CURLE_INTERFACE_FAILED + } + + /// Returns whether this error corresponds to CURLE_TOO_MANY_REDIRECTS. + pub fn is_too_many_redirects(&self) -> bool { + self.code == curl_sys::CURLE_TOO_MANY_REDIRECTS + } + + /// Returns whether this error corresponds to CURLE_UNKNOWN_OPTION. + pub fn is_unknown_option(&self) -> bool { + self.code == curl_sys::CURLE_UNKNOWN_OPTION + } + + /// Returns whether this error corresponds to CURLE_PEER_FAILED_VERIFICATION. + pub fn is_peer_failed_verification(&self) -> bool { + self.code == curl_sys::CURLE_PEER_FAILED_VERIFICATION + } + + /// Returns whether this error corresponds to CURLE_GOT_NOTHING. + pub fn is_got_nothing(&self) -> bool { + self.code == curl_sys::CURLE_GOT_NOTHING + } + + /// Returns whether this error corresponds to CURLE_SSL_ENGINE_NOTFOUND. + pub fn is_ssl_engine_notfound(&self) -> bool { + self.code == curl_sys::CURLE_SSL_ENGINE_NOTFOUND + } + + /// Returns whether this error corresponds to CURLE_SSL_ENGINE_SETFAILED. + pub fn is_ssl_engine_setfailed(&self) -> bool { + self.code == curl_sys::CURLE_SSL_ENGINE_SETFAILED + } + + /// Returns whether this error corresponds to CURLE_SEND_ERROR. + pub fn is_send_error(&self) -> bool { + self.code == curl_sys::CURLE_SEND_ERROR + } + + /// Returns whether this error corresponds to CURLE_RECV_ERROR. + pub fn is_recv_error(&self) -> bool { + self.code == curl_sys::CURLE_RECV_ERROR + } + + /// Returns whether this error corresponds to CURLE_SSL_CERTPROBLEM. + pub fn is_ssl_certproblem(&self) -> bool { + self.code == curl_sys::CURLE_SSL_CERTPROBLEM + } + + /// Returns whether this error corresponds to CURLE_SSL_CIPHER. + pub fn is_ssl_cipher(&self) -> bool { + self.code == curl_sys::CURLE_SSL_CIPHER + } + + /// Returns whether this error corresponds to CURLE_SSL_CACERT. + pub fn is_ssl_cacert(&self) -> bool { + self.code == curl_sys::CURLE_SSL_CACERT + } + + /// Returns whether this error corresponds to CURLE_BAD_CONTENT_ENCODING. + pub fn is_bad_content_encoding(&self) -> bool { + self.code == curl_sys::CURLE_BAD_CONTENT_ENCODING + } + + /// Returns whether this error corresponds to CURLE_FILESIZE_EXCEEDED. + pub fn is_filesize_exceeded(&self) -> bool { + self.code == curl_sys::CURLE_FILESIZE_EXCEEDED + } + + /// Returns whether this error corresponds to CURLE_USE_SSL_FAILED. + pub fn is_use_ssl_failed(&self) -> bool { + self.code == curl_sys::CURLE_USE_SSL_FAILED + } + + /// Returns whether this error corresponds to CURLE_SEND_FAIL_REWIND. + pub fn is_send_fail_rewind(&self) -> bool { + self.code == curl_sys::CURLE_SEND_FAIL_REWIND + } + + /// Returns whether this error corresponds to CURLE_SSL_ENGINE_INITFAILED. + pub fn is_ssl_engine_initfailed(&self) -> bool { + self.code == curl_sys::CURLE_SSL_ENGINE_INITFAILED + } + + /// Returns whether this error corresponds to CURLE_LOGIN_DENIED. + pub fn is_login_denied(&self) -> bool { + self.code == curl_sys::CURLE_LOGIN_DENIED + } + + /// Returns whether this error corresponds to CURLE_CONV_FAILED. + pub fn is_conv_failed(&self) -> bool { + self.code == curl_sys::CURLE_CONV_FAILED + } + + /// Returns whether this error corresponds to CURLE_CONV_REQD. + pub fn is_conv_required(&self) -> bool { + self.code == curl_sys::CURLE_CONV_REQD + } + + /// Returns whether this error corresponds to CURLE_SSL_CACERT_BADFILE. + pub fn is_ssl_cacert_badfile(&self) -> bool { + self.code == curl_sys::CURLE_SSL_CACERT_BADFILE + } + + /// Returns whether this error corresponds to CURLE_SSL_CRL_BADFILE. + pub fn is_ssl_crl_badfile(&self) -> bool { + self.code == curl_sys::CURLE_SSL_CRL_BADFILE + } + + /// Returns whether this error corresponds to CURLE_SSL_SHUTDOWN_FAILED. + pub fn is_ssl_shutdown_failed(&self) -> bool { + self.code == curl_sys::CURLE_SSL_SHUTDOWN_FAILED + } + + /// Returns whether this error corresponds to CURLE_AGAIN. + pub fn is_again(&self) -> bool { + self.code == curl_sys::CURLE_AGAIN + } + + /// Returns whether this error corresponds to CURLE_SSL_ISSUER_ERROR. + pub fn is_ssl_issuer_error(&self) -> bool { + self.code == curl_sys::CURLE_SSL_ISSUER_ERROR + } + + /// Returns whether this error corresponds to CURLE_CHUNK_FAILED. + pub fn is_chunk_failed(&self) -> bool { + self.code == curl_sys::CURLE_CHUNK_FAILED + } + + /// Returns whether this error corresponds to CURLE_HTTP2. + pub fn is_http2_error(&self) -> bool { + self.code == curl_sys::CURLE_HTTP2 + } + + /// Returns whether this error corresponds to CURLE_HTTP2_STREAM. + pub fn is_http2_stream_error(&self) -> bool { + self.code == curl_sys::CURLE_HTTP2_STREAM + } + + // /// Returns whether this error corresponds to CURLE_NO_CONNECTION_AVAILABLE. + // pub fn is_no_connection_available(&self) -> bool { + // self.code == curl_sys::CURLE_NO_CONNECTION_AVAILABLE + // } + + /// Returns the value of the underlying error corresponding to libcurl. + pub fn code(&self) -> curl_sys::CURLcode { + self.code + } + + /// Returns the general description of this error code, using curl's + /// builtin `strerror`-like functionality. + pub fn description(&self) -> &str { + unsafe { + let s = curl_sys::curl_easy_strerror(self.code); + assert!(!s.is_null()); + str::from_utf8(CStr::from_ptr(s).to_bytes()).unwrap() + } + } + + /// Returns the extra description of this error, if any is available. + pub fn extra_description(&self) -> Option<&str> { + self.extra.as_deref() + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let desc = self.description(); + match self.extra { + Some(ref s) => write!(f, "[{}] {} ({})", self.code(), desc, s), + None => write!(f, "[{}] {}", self.code(), desc), + } + } +} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Error") + .field("description", &self.description()) + .field("code", &self.code) + .field("extra", &self.extra) + .finish() + } +} + +impl error::Error for Error {} + +/// An error returned from "share" operations. +/// +/// This structure wraps a `CURLSHcode`. +#[derive(Clone, PartialEq)] +pub struct ShareError { + code: curl_sys::CURLSHcode, +} + +impl ShareError { + /// Creates a new error from the underlying code returned by libcurl. + pub fn new(code: curl_sys::CURLSHcode) -> ShareError { + ShareError { code } + } + + /// Returns whether this error corresponds to CURLSHE_BAD_OPTION. + pub fn is_bad_option(&self) -> bool { + self.code == curl_sys::CURLSHE_BAD_OPTION + } + + /// Returns whether this error corresponds to CURLSHE_IN_USE. + pub fn is_in_use(&self) -> bool { + self.code == curl_sys::CURLSHE_IN_USE + } + + /// Returns whether this error corresponds to CURLSHE_INVALID. + pub fn is_invalid(&self) -> bool { + self.code == curl_sys::CURLSHE_INVALID + } + + /// Returns whether this error corresponds to CURLSHE_NOMEM. + pub fn is_nomem(&self) -> bool { + self.code == curl_sys::CURLSHE_NOMEM + } + + // /// Returns whether this error corresponds to CURLSHE_NOT_BUILT_IN. + // pub fn is_not_built_in(&self) -> bool { + // self.code == curl_sys::CURLSHE_NOT_BUILT_IN + // } + + /// Returns the value of the underlying error corresponding to libcurl. + pub fn code(&self) -> curl_sys::CURLSHcode { + self.code + } + + /// Returns curl's human-readable version of this error. + pub fn description(&self) -> &str { + unsafe { + let s = curl_sys::curl_share_strerror(self.code); + assert!(!s.is_null()); + str::from_utf8(CStr::from_ptr(s).to_bytes()).unwrap() + } + } +} + +impl fmt::Display for ShareError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.description().fmt(f) + } +} + +impl fmt::Debug for ShareError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "ShareError {{ description: {:?}, code: {} }}", + self.description(), + self.code + ) + } +} + +impl error::Error for ShareError {} + +/// An error from "multi" operations. +/// +/// THis structure wraps a `CURLMcode`. +#[derive(Clone, PartialEq)] +pub struct MultiError { + code: curl_sys::CURLMcode, +} + +impl MultiError { + /// Creates a new error from the underlying code returned by libcurl. + pub fn new(code: curl_sys::CURLMcode) -> MultiError { + MultiError { code } + } + + /// Returns whether this error corresponds to CURLM_BAD_HANDLE. + pub fn is_bad_handle(&self) -> bool { + self.code == curl_sys::CURLM_BAD_HANDLE + } + + /// Returns whether this error corresponds to CURLM_BAD_EASY_HANDLE. + pub fn is_bad_easy_handle(&self) -> bool { + self.code == curl_sys::CURLM_BAD_EASY_HANDLE + } + + /// Returns whether this error corresponds to CURLM_OUT_OF_MEMORY. + pub fn is_out_of_memory(&self) -> bool { + self.code == curl_sys::CURLM_OUT_OF_MEMORY + } + + /// Returns whether this error corresponds to CURLM_INTERNAL_ERROR. + pub fn is_internal_error(&self) -> bool { + self.code == curl_sys::CURLM_INTERNAL_ERROR + } + + /// Returns whether this error corresponds to CURLM_BAD_SOCKET. + pub fn is_bad_socket(&self) -> bool { + self.code == curl_sys::CURLM_BAD_SOCKET + } + + /// Returns whether this error corresponds to CURLM_UNKNOWN_OPTION. + pub fn is_unknown_option(&self) -> bool { + self.code == curl_sys::CURLM_UNKNOWN_OPTION + } + + /// Returns whether this error corresponds to CURLM_CALL_MULTI_PERFORM. + pub fn is_call_perform(&self) -> bool { + self.code == curl_sys::CURLM_CALL_MULTI_PERFORM + } + + // /// Returns whether this error corresponds to CURLM_ADDED_ALREADY. + // pub fn is_added_already(&self) -> bool { + // self.code == curl_sys::CURLM_ADDED_ALREADY + // } + + /// Returns the value of the underlying error corresponding to libcurl. + pub fn code(&self) -> curl_sys::CURLMcode { + self.code + } + + /// Returns curl's human-readable description of this error. + pub fn description(&self) -> &str { + unsafe { + let s = curl_sys::curl_multi_strerror(self.code); + assert!(!s.is_null()); + str::from_utf8(CStr::from_ptr(s).to_bytes()).unwrap() + } + } +} + +impl fmt::Display for MultiError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.description().fmt(f) + } +} + +impl fmt::Debug for MultiError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("MultiError") + .field("description", &self.description()) + .field("code", &self.code) + .finish() + } +} + +impl error::Error for MultiError {} + +/// An error from "form add" operations. +/// +/// THis structure wraps a `CURLFORMcode`. +#[derive(Clone, PartialEq)] +pub struct FormError { + code: curl_sys::CURLFORMcode, +} + +impl FormError { + /// Creates a new error from the underlying code returned by libcurl. + pub fn new(code: curl_sys::CURLFORMcode) -> FormError { + FormError { code } + } + + /// Returns whether this error corresponds to CURL_FORMADD_MEMORY. + pub fn is_memory(&self) -> bool { + self.code == curl_sys::CURL_FORMADD_MEMORY + } + + /// Returns whether this error corresponds to CURL_FORMADD_OPTION_TWICE. + pub fn is_option_twice(&self) -> bool { + self.code == curl_sys::CURL_FORMADD_OPTION_TWICE + } + + /// Returns whether this error corresponds to CURL_FORMADD_NULL. + pub fn is_null(&self) -> bool { + self.code == curl_sys::CURL_FORMADD_NULL + } + + /// Returns whether this error corresponds to CURL_FORMADD_UNKNOWN_OPTION. + pub fn is_unknown_option(&self) -> bool { + self.code == curl_sys::CURL_FORMADD_UNKNOWN_OPTION + } + + /// Returns whether this error corresponds to CURL_FORMADD_INCOMPLETE. + pub fn is_incomplete(&self) -> bool { + self.code == curl_sys::CURL_FORMADD_INCOMPLETE + } + + /// Returns whether this error corresponds to CURL_FORMADD_ILLEGAL_ARRAY. + pub fn is_illegal_array(&self) -> bool { + self.code == curl_sys::CURL_FORMADD_ILLEGAL_ARRAY + } + + /// Returns whether this error corresponds to CURL_FORMADD_DISABLED. + pub fn is_disabled(&self) -> bool { + self.code == curl_sys::CURL_FORMADD_DISABLED + } + + /// Returns the value of the underlying error corresponding to libcurl. + pub fn code(&self) -> curl_sys::CURLFORMcode { + self.code + } + + /// Returns a human-readable description of this error code. + pub fn description(&self) -> &str { + match self.code { + curl_sys::CURL_FORMADD_MEMORY => "allocation failure", + curl_sys::CURL_FORMADD_OPTION_TWICE => "one option passed twice", + curl_sys::CURL_FORMADD_NULL => "null pointer given for string", + curl_sys::CURL_FORMADD_UNKNOWN_OPTION => "unknown option", + curl_sys::CURL_FORMADD_INCOMPLETE => "form information not complete", + curl_sys::CURL_FORMADD_ILLEGAL_ARRAY => "illegal array in option", + curl_sys::CURL_FORMADD_DISABLED => { + "libcurl does not have support for this option compiled in" + } + _ => "unknown form error", + } + } +} + +impl fmt::Display for FormError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.description().fmt(f) + } +} + +impl fmt::Debug for FormError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("FormError") + .field("description", &self.description()) + .field("code", &self.code) + .finish() + } +} + +impl error::Error for FormError {} + +impl From<ffi::NulError> for Error { + fn from(_: ffi::NulError) -> Error { + Error { + code: curl_sys::CURLE_CONV_FAILED, + extra: None, + } + } +} + +impl From<Error> for io::Error { + fn from(e: Error) -> io::Error { + io::Error::new(io::ErrorKind::Other, e) + } +} + +impl From<ShareError> for io::Error { + fn from(e: ShareError) -> io::Error { + io::Error::new(io::ErrorKind::Other, e) + } +} + +impl From<MultiError> for io::Error { + fn from(e: MultiError) -> io::Error { + io::Error::new(io::ErrorKind::Other, e) + } +} + +impl From<FormError> for io::Error { + fn from(e: FormError) -> io::Error { + io::Error::new(io::ErrorKind::Other, e) + } +} diff --git a/vendor/curl/src/lib.rs b/vendor/curl/src/lib.rs new file mode 100644 index 000000000..2965e2bed --- /dev/null +++ b/vendor/curl/src/lib.rs @@ -0,0 +1,184 @@ +//! Rust bindings to the libcurl C library +//! +//! This crate contains bindings for an HTTP/HTTPS client which is powered by +//! [libcurl], the same library behind the `curl` command line tool. The API +//! currently closely matches that of libcurl itself, except that a Rustic layer +//! of safety is applied on top. +//! +//! [libcurl]: https://curl.haxx.se/libcurl/ +//! +//! # The "Easy" API +//! +//! The easiest way to send a request is to use the `Easy` api which corresponds +//! to `CURL` in libcurl. This handle supports a wide variety of options and can +//! be used to make a single blocking request in a thread. Callbacks can be +//! specified to deal with data as it arrives and a handle can be reused to +//! cache connections and such. +//! +//! ```rust,no_run +//! use std::io::{stdout, Write}; +//! +//! use curl::easy::Easy; +//! +//! // Write the contents of rust-lang.org to stdout +//! let mut easy = Easy::new(); +//! easy.url("https://www.rust-lang.org/").unwrap(); +//! easy.write_function(|data| { +//! stdout().write_all(data).unwrap(); +//! Ok(data.len()) +//! }).unwrap(); +//! easy.perform().unwrap(); +//! ``` +//! +//! # What about multiple concurrent HTTP requests? +//! +//! One option you have currently is to send multiple requests in multiple +//! threads, but otherwise libcurl has a "multi" interface for doing this +//! operation. Initial bindings of this interface can be found in the `multi` +//! module, but feedback is welcome! +//! +//! # Where does libcurl come from? +//! +//! This crate links to the `curl-sys` crate which is in turn responsible for +//! acquiring and linking to the libcurl library. Currently this crate will +//! build libcurl from source if one is not already detected on the system. +//! +//! There is a large number of releases for libcurl, all with different sets of +//! capabilities. Robust programs may wish to inspect `Version::get()` to test +//! what features are implemented in the linked build of libcurl at runtime. +//! +//! # Initialization +//! +//! The underlying libcurl library must be initialized before use and has +//! certain requirements on how this is done. Check the documentation for +//! [`init`] for more details. + +#![deny(missing_docs, missing_debug_implementations)] +#![doc(html_root_url = "https://docs.rs/curl/0.4")] + +use std::ffi::CStr; +use std::str; +use std::sync::Once; + +pub use crate::error::{Error, FormError, MultiError, ShareError}; +mod error; + +pub use crate::version::{Protocols, Version}; +mod version; + +pub mod easy; +pub mod multi; +mod panic; + +#[cfg(test)] +static INITIALIZED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Initializes the underlying libcurl library. +/// +/// The underlying libcurl library must be initialized before use, and must be +/// done so on the main thread before any other threads are created by the +/// program. This crate will do this for you automatically in the following +/// scenarios: +/// +/// - Creating a new [`Easy`][easy::Easy] or [`Multi`][multi::Multi] handle +/// - At program startup on Windows, macOS, Linux, Android, or FreeBSD systems +/// +/// This should be sufficient for most applications and scenarios, but in any +/// other case, it is strongly recommended that you call this function manually +/// as soon as your program starts. +/// +/// Calling this function more than once is harmless and has no effect. +#[inline] +pub fn init() { + /// Used to prevent concurrent or duplicate initialization. + static INIT: Once = Once::new(); + + INIT.call_once(|| { + #[cfg(need_openssl_init)] + openssl_probe::init_ssl_cert_env_vars(); + #[cfg(need_openssl_init)] + openssl_sys::init(); + + unsafe { + assert_eq!(curl_sys::curl_global_init(curl_sys::CURL_GLOBAL_ALL), 0); + } + + #[cfg(test)] + { + INITIALIZED.store(true, std::sync::atomic::Ordering::SeqCst); + } + + // Note that we explicitly don't schedule a call to + // `curl_global_cleanup`. The documentation for that function says + // + // > You must not call it when any other thread in the program (i.e. a + // > thread sharing the same memory) is running. This doesn't just mean + // > no other thread that is using libcurl. + // + // We can't ever be sure of that, so unfortunately we can't call the + // function. + }); +} + +/// An exported constructor function. On supported platforms, this will be +/// invoked automatically before the program's `main` is called. This is done +/// for the convenience of library users since otherwise the thread-safety rules +/// around initialization can be difficult to fulfill. +/// +/// This is a hidden public item to ensure the symbol isn't optimized away by a +/// rustc/LLVM bug: https://github.com/rust-lang/rust/issues/47384. As long as +/// any item in this module is used by the final binary (which `init` will be) +/// then this symbol should be preserved. +#[used] +#[doc(hidden)] +#[cfg_attr( + any(target_os = "linux", target_os = "freebsd", target_os = "android"), + link_section = ".init_array" +)] +#[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")] +#[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")] +pub static INIT_CTOR: extern "C" fn() = { + /// This is the body of our constructor function. + #[cfg_attr( + any(target_os = "linux", target_os = "android"), + link_section = ".text.startup" + )] + extern "C" fn init_ctor() { + init(); + } + + init_ctor +}; + +unsafe fn opt_str<'a>(ptr: *const libc::c_char) -> Option<&'a str> { + if ptr.is_null() { + None + } else { + Some(str::from_utf8(CStr::from_ptr(ptr).to_bytes()).unwrap()) + } +} + +fn cvt(r: curl_sys::CURLcode) -> Result<(), Error> { + if r == curl_sys::CURLE_OK { + Ok(()) + } else { + Err(Error::new(r)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[cfg(any( + target_os = "linux", + target_os = "macos", + target_os = "windows", + target_os = "freebsd", + target_os = "android" + ))] + fn is_initialized_before_main() { + assert!(INITIALIZED.load(std::sync::atomic::Ordering::SeqCst)); + } +} diff --git a/vendor/curl/src/multi.rs b/vendor/curl/src/multi.rs new file mode 100644 index 000000000..077561af5 --- /dev/null +++ b/vendor/curl/src/multi.rs @@ -0,0 +1,1323 @@ +//! Multi - initiating multiple requests simultaneously + +use std::fmt; +use std::marker; +use std::ptr; +use std::sync::Arc; +use std::time::Duration; + +use curl_sys; +use libc::{c_char, c_int, c_long, c_short, c_void}; + +#[cfg(unix)] +use libc::{pollfd, POLLIN, POLLOUT, POLLPRI}; + +use crate::easy::{Easy, Easy2, List}; +use crate::panic; +use crate::{Error, MultiError}; + +/// A multi handle for initiating multiple connections simultaneously. +/// +/// This structure corresponds to `CURLM` in libcurl and provides the ability to +/// have multiple transfers in flight simultaneously. This handle is then used +/// to manage each transfer. The main purpose of a `CURLM` is for the +/// *application* to drive the I/O rather than libcurl itself doing all the +/// blocking. Methods like `action` allow the application to inform libcurl of +/// when events have happened. +/// +/// Lots more documentation can be found on the libcurl [multi tutorial] where +/// the APIs correspond pretty closely with this crate. +/// +/// [multi tutorial]: https://curl.haxx.se/libcurl/c/libcurl-multi.html +pub struct Multi { + raw: Arc<RawMulti>, + data: Box<MultiData>, +} + +#[derive(Debug)] +struct RawMulti { + handle: *mut curl_sys::CURLM, +} + +struct MultiData { + socket: Box<dyn FnMut(Socket, SocketEvents, usize) + Send>, + timer: Box<dyn FnMut(Option<Duration>) -> bool + Send>, +} + +/// Message from the `messages` function of a multi handle. +/// +/// Currently only indicates whether a transfer is done. +pub struct Message<'multi> { + ptr: *mut curl_sys::CURLMsg, + _multi: &'multi Multi, +} + +/// Wrapper around an easy handle while it's owned by a multi handle. +/// +/// Once an easy handle has been added to a multi handle then it can no longer +/// be used via `perform`. This handle is also used to remove the easy handle +/// from the multi handle when desired. +pub struct EasyHandle { + // Safety: This *must* be before `easy` as it must be dropped first. + guard: DetachGuard, + easy: Easy, + // This is now effectively bound to a `Multi`, so it is no longer sendable. + _marker: marker::PhantomData<&'static Multi>, +} + +/// Wrapper around an easy handle while it's owned by a multi handle. +/// +/// Once an easy handle has been added to a multi handle then it can no longer +/// be used via `perform`. This handle is also used to remove the easy handle +/// from the multi handle when desired. +pub struct Easy2Handle<H> { + // Safety: This *must* be before `easy` as it must be dropped first. + guard: DetachGuard, + easy: Easy2<H>, + // This is now effectively bound to a `Multi`, so it is no longer sendable. + _marker: marker::PhantomData<&'static Multi>, +} + +/// A guard struct which guarantees that `curl_multi_remove_handle` will be +/// called on an easy handle, either manually or on drop. +struct DetachGuard { + multi: Arc<RawMulti>, + easy: *mut curl_sys::CURL, +} + +/// Notification of the events that have happened on a socket. +/// +/// This type is passed as an argument to the `action` method on a multi handle +/// to indicate what events have occurred on a socket. +pub struct Events { + bits: c_int, +} + +/// Notification of events that are requested on a socket. +/// +/// This type is yielded to the `socket_function` callback to indicate what +/// events are requested on a socket. +pub struct SocketEvents { + bits: c_int, +} + +/// Raw underlying socket type that the multi handles use +pub type Socket = curl_sys::curl_socket_t; + +/// File descriptor to wait on for use with the `wait` method on a multi handle. +pub struct WaitFd { + inner: curl_sys::curl_waitfd, +} + +/// A handle that can be used to wake up a thread that's blocked in [Multi::poll]. +/// The handle can be passed to and used from any thread. +#[cfg(feature = "poll_7_68_0")] +#[derive(Debug, Clone)] +pub struct MultiWaker { + raw: std::sync::Weak<RawMulti>, +} + +#[cfg(feature = "poll_7_68_0")] +unsafe impl Send for MultiWaker {} + +#[cfg(feature = "poll_7_68_0")] +unsafe impl Sync for MultiWaker {} + +impl Multi { + /// Creates a new multi session through which multiple HTTP transfers can be + /// initiated. + pub fn new() -> Multi { + unsafe { + crate::init(); + let ptr = curl_sys::curl_multi_init(); + assert!(!ptr.is_null()); + Multi { + raw: Arc::new(RawMulti { handle: ptr }), + data: Box::new(MultiData { + socket: Box::new(|_, _, _| ()), + timer: Box::new(|_| true), + }), + } + } + } + + /// Set the callback informed about what to wait for + /// + /// When the `action` function runs, it informs the application about + /// updates in the socket (file descriptor) status by doing none, one, or + /// multiple calls to the socket callback. The callback gets status updates + /// with changes since the previous time the callback was called. See + /// `action` for more details on how the callback is used and should work. + /// + /// The `SocketEvents` parameter informs the callback on the status of the + /// given socket, and the methods on that type can be used to learn about + /// what's going on with the socket. + /// + /// The third `usize` parameter is a custom value set by the `assign` method + /// below. + pub fn socket_function<F>(&mut self, f: F) -> Result<(), MultiError> + where + F: FnMut(Socket, SocketEvents, usize) + Send + 'static, + { + self._socket_function(Box::new(f)) + } + + fn _socket_function( + &mut self, + f: Box<dyn FnMut(Socket, SocketEvents, usize) + Send>, + ) -> Result<(), MultiError> { + self.data.socket = f; + let cb: curl_sys::curl_socket_callback = cb; + self.setopt_ptr( + curl_sys::CURLMOPT_SOCKETFUNCTION, + cb as usize as *const c_char, + )?; + let ptr = &*self.data as *const _; + self.setopt_ptr(curl_sys::CURLMOPT_SOCKETDATA, ptr as *const c_char)?; + return Ok(()); + + // TODO: figure out how to expose `_easy` + extern "C" fn cb( + _easy: *mut curl_sys::CURL, + socket: curl_sys::curl_socket_t, + what: c_int, + userptr: *mut c_void, + socketp: *mut c_void, + ) -> c_int { + panic::catch(|| unsafe { + let f = &mut (*(userptr as *mut MultiData)).socket; + f(socket, SocketEvents { bits: what }, socketp as usize) + }); + 0 + } + } + + /// Set data to associate with an internal socket + /// + /// This function creates an association in the multi handle between the + /// given socket and a private token of the application. This is designed + /// for `action` uses. + /// + /// When set, the token will be passed to all future socket callbacks for + /// the specified socket. + /// + /// If the given socket isn't already in use by libcurl, this function will + /// return an error. + /// + /// libcurl only keeps one single token associated with a socket, so + /// calling this function several times for the same socket will make the + /// last set token get used. + /// + /// The idea here being that this association (socket to token) is something + /// that just about every application that uses this API will need and then + /// libcurl can just as well do it since it already has an internal hash + /// table lookup for this. + /// + /// # Typical Usage + /// + /// In a typical application you allocate a struct or at least use some kind + /// of semi-dynamic data for each socket that we must wait for action on + /// when using the `action` approach. + /// + /// When our socket-callback gets called by libcurl and we get to know about + /// yet another socket to wait for, we can use `assign` to point out the + /// particular data so that when we get updates about this same socket + /// again, we don't have to find the struct associated with this socket by + /// ourselves. + pub fn assign(&self, socket: Socket, token: usize) -> Result<(), MultiError> { + unsafe { + cvt(curl_sys::curl_multi_assign( + self.raw.handle, + socket, + token as *mut _, + ))?; + Ok(()) + } + } + + /// Set callback to receive timeout values + /// + /// Certain features, such as timeouts and retries, require you to call + /// libcurl even when there is no activity on the file descriptors. + /// + /// Your callback function should install a non-repeating timer with the + /// interval specified. Each time that timer fires, call either `action` or + /// `perform`, depending on which interface you use. + /// + /// A timeout value of `None` means you should delete your timer. + /// + /// A timeout value of 0 means you should call `action` or `perform` (once) + /// as soon as possible. + /// + /// This callback will only be called when the timeout changes. + /// + /// The timer callback should return `true` on success, and `false` on + /// error. This callback can be used instead of, or in addition to, + /// `get_timeout`. + pub fn timer_function<F>(&mut self, f: F) -> Result<(), MultiError> + where + F: FnMut(Option<Duration>) -> bool + Send + 'static, + { + self._timer_function(Box::new(f)) + } + + fn _timer_function( + &mut self, + f: Box<dyn FnMut(Option<Duration>) -> bool + Send>, + ) -> Result<(), MultiError> { + self.data.timer = f; + let cb: curl_sys::curl_multi_timer_callback = cb; + self.setopt_ptr( + curl_sys::CURLMOPT_TIMERFUNCTION, + cb as usize as *const c_char, + )?; + let ptr = &*self.data as *const _; + self.setopt_ptr(curl_sys::CURLMOPT_TIMERDATA, ptr as *const c_char)?; + return Ok(()); + + // TODO: figure out how to expose `_multi` + extern "C" fn cb( + _multi: *mut curl_sys::CURLM, + timeout_ms: c_long, + user: *mut c_void, + ) -> c_int { + let keep_going = panic::catch(|| unsafe { + let f = &mut (*(user as *mut MultiData)).timer; + if timeout_ms == -1 { + f(None) + } else { + f(Some(Duration::from_millis(timeout_ms as u64))) + } + }) + .unwrap_or(false); + if keep_going { + 0 + } else { + -1 + } + } + } + + /// Enable or disable HTTP pipelining and multiplexing. + /// + /// When http_1 is true, enable HTTP/1.1 pipelining, which means that if + /// you add a second request that can use an already existing connection, + /// the second request will be "piped" on the same connection rather than + /// being executed in parallel. + /// + /// When multiplex is true, enable HTTP/2 multiplexing, which means that + /// follow-up requests can re-use an existing connection and send the new + /// request multiplexed over that at the same time as other transfers are + /// already using that single connection. + pub fn pipelining(&mut self, http_1: bool, multiplex: bool) -> Result<(), MultiError> { + let bitmask = if http_1 { curl_sys::CURLPIPE_HTTP1 } else { 0 } + | if multiplex { + curl_sys::CURLPIPE_MULTIPLEX + } else { + 0 + }; + self.setopt_long(curl_sys::CURLMOPT_PIPELINING, bitmask) + } + + /// Sets the max number of connections to a single host. + /// + /// Pass a long to indicate the max number of simultaneously open connections + /// to a single host (a host being the same as a host name + port number pair). + /// For each new session to a host, libcurl will open up a new connection up to the + /// limit set by the provided value. When the limit is reached, the sessions will + /// be pending until a connection becomes available. If pipelining is enabled, + /// libcurl will try to pipeline if the host is capable of it. + pub fn set_max_host_connections(&mut self, val: usize) -> Result<(), MultiError> { + self.setopt_long(curl_sys::CURLMOPT_MAX_HOST_CONNECTIONS, val as c_long) + } + + /// Sets the max simultaneously open connections. + /// + /// The set number will be used as the maximum number of simultaneously open + /// connections in total using this multi handle. For each new session, + /// libcurl will open a new connection up to the limit set by the provided + /// value. When the limit is reached, the sessions will be pending until + /// there are available connections. If pipelining is enabled, libcurl will + /// try to pipeline or use multiplexing if the host is capable of it. + pub fn set_max_total_connections(&mut self, val: usize) -> Result<(), MultiError> { + self.setopt_long(curl_sys::CURLMOPT_MAX_TOTAL_CONNECTIONS, val as c_long) + } + + /// Set size of connection cache. + /// + /// The set number will be used as the maximum amount of simultaneously open + /// connections that libcurl may keep in its connection cache after + /// completed use. By default libcurl will enlarge the size for each added + /// easy handle to make it fit 4 times the number of added easy handles. + /// + /// By setting this option, you can prevent the cache size from growing + /// beyond the limit set by you. + /// + /// When the cache is full, curl closes the oldest one in the cache to + /// prevent the number of open connections from increasing. + /// + /// See [`set_max_total_connections`](#method.set_max_total_connections) for + /// limiting the number of active connections. + pub fn set_max_connects(&mut self, val: usize) -> Result<(), MultiError> { + self.setopt_long(curl_sys::CURLMOPT_MAXCONNECTS, val as c_long) + } + + /// Sets the pipeline length. + /// + /// This sets the max number that will be used as the maximum amount of + /// outstanding requests in an HTTP/1.1 pipelined connection. This option + /// is only used for HTTP/1.1 pipelining, and not HTTP/2 multiplexing. + pub fn set_pipeline_length(&mut self, val: usize) -> Result<(), MultiError> { + self.setopt_long(curl_sys::CURLMOPT_MAX_PIPELINE_LENGTH, val as c_long) + } + + fn setopt_long(&mut self, opt: curl_sys::CURLMoption, val: c_long) -> Result<(), MultiError> { + unsafe { cvt(curl_sys::curl_multi_setopt(self.raw.handle, opt, val)) } + } + + fn setopt_ptr( + &mut self, + opt: curl_sys::CURLMoption, + val: *const c_char, + ) -> Result<(), MultiError> { + unsafe { cvt(curl_sys::curl_multi_setopt(self.raw.handle, opt, val)) } + } + + /// Add an easy handle to a multi session + /// + /// Adds a standard easy handle to the multi stack. This function call will + /// make this multi handle control the specified easy handle. + /// + /// When an easy interface is added to a multi handle, it will use a shared + /// connection cache owned by the multi handle. Removing and adding new easy + /// handles will not affect the pool of connections or the ability to do + /// connection re-use. + /// + /// If you have `timer_function` set in the multi handle (and you really + /// should if you're working event-based with `action` and friends), that + /// callback will be called from within this function to ask for an updated + /// timer so that your main event loop will get the activity on this handle + /// to get started. + /// + /// The easy handle will remain added to the multi handle until you remove + /// it again with `remove` on the returned handle - even when a transfer + /// with that specific easy handle is completed. + pub fn add(&self, mut easy: Easy) -> Result<EasyHandle, MultiError> { + // Clear any configuration set by previous transfers because we're + // moving this into a `Send+'static` situation now basically. + easy.transfer(); + + unsafe { + cvt(curl_sys::curl_multi_add_handle(self.raw.handle, easy.raw()))?; + } + Ok(EasyHandle { + guard: DetachGuard { + multi: self.raw.clone(), + easy: easy.raw(), + }, + easy, + _marker: marker::PhantomData, + }) + } + + /// Same as `add`, but works with the `Easy2` type. + pub fn add2<H>(&self, easy: Easy2<H>) -> Result<Easy2Handle<H>, MultiError> { + unsafe { + cvt(curl_sys::curl_multi_add_handle(self.raw.handle, easy.raw()))?; + } + Ok(Easy2Handle { + guard: DetachGuard { + multi: self.raw.clone(), + easy: easy.raw(), + }, + easy, + _marker: marker::PhantomData, + }) + } + + /// Remove an easy handle from this multi session + /// + /// Removes the easy handle from this multi handle. This will make the + /// returned easy handle be removed from this multi handle's control. + /// + /// When the easy handle has been removed from a multi stack, it is again + /// perfectly legal to invoke `perform` on it. + /// + /// Removing an easy handle while being used is perfectly legal and will + /// effectively halt the transfer in progress involving that easy handle. + /// All other easy handles and transfers will remain unaffected. + pub fn remove(&self, mut easy: EasyHandle) -> Result<Easy, MultiError> { + easy.guard.detach()?; + Ok(easy.easy) + } + + /// Same as `remove`, but for `Easy2Handle`. + pub fn remove2<H>(&self, mut easy: Easy2Handle<H>) -> Result<Easy2<H>, MultiError> { + easy.guard.detach()?; + Ok(easy.easy) + } + + /// Read multi stack informationals + /// + /// Ask the multi handle if there are any messages/informationals from the + /// individual transfers. Messages may include informationals such as an + /// error code from the transfer or just the fact that a transfer is + /// completed. More details on these should be written down as well. + pub fn messages<F>(&self, mut f: F) + where + F: FnMut(Message), + { + self._messages(&mut f) + } + + fn _messages(&self, f: &mut dyn FnMut(Message)) { + let mut queue = 0; + unsafe { + loop { + let ptr = curl_sys::curl_multi_info_read(self.raw.handle, &mut queue); + if ptr.is_null() { + break; + } + f(Message { ptr, _multi: self }) + } + } + } + + /// Inform of reads/writes available data given an action + /// + /// When the application has detected action on a socket handled by libcurl, + /// it should call this function with the sockfd argument set to + /// the socket with the action. When the events on a socket are known, they + /// can be passed `events`. When the events on a socket are unknown, pass + /// `Events::new()` instead, and libcurl will test the descriptor + /// internally. + /// + /// The returned integer will contain the number of running easy handles + /// within the multi handle. When this number reaches zero, all transfers + /// are complete/done. When you call `action` on a specific socket and the + /// counter decreases by one, it DOES NOT necessarily mean that this exact + /// socket/transfer is the one that completed. Use `messages` to figure out + /// which easy handle that completed. + /// + /// The `action` function informs the application about updates in the + /// socket (file descriptor) status by doing none, one, or multiple calls to + /// the socket callback function set with the `socket_function` method. They + /// update the status with changes since the previous time the callback was + /// called. + pub fn action(&self, socket: Socket, events: &Events) -> Result<u32, MultiError> { + let mut remaining = 0; + unsafe { + cvt(curl_sys::curl_multi_socket_action( + self.raw.handle, + socket, + events.bits, + &mut remaining, + ))?; + Ok(remaining as u32) + } + } + + /// Inform libcurl that a timeout has expired and sockets should be tested. + /// + /// The returned integer will contain the number of running easy handles + /// within the multi handle. When this number reaches zero, all transfers + /// are complete/done. When you call `action` on a specific socket and the + /// counter decreases by one, it DOES NOT necessarily mean that this exact + /// socket/transfer is the one that completed. Use `messages` to figure out + /// which easy handle that completed. + /// + /// Get the timeout time by calling the `timer_function` method. Your + /// application will then get called with information on how long to wait + /// for socket actions at most before doing the timeout action: call the + /// `timeout` method. You can also use the `get_timeout` function to + /// poll the value at any given time, but for an event-based system using + /// the callback is far better than relying on polling the timeout value. + pub fn timeout(&self) -> Result<u32, MultiError> { + let mut remaining = 0; + unsafe { + cvt(curl_sys::curl_multi_socket_action( + self.raw.handle, + curl_sys::CURL_SOCKET_BAD, + 0, + &mut remaining, + ))?; + Ok(remaining as u32) + } + } + + /// Get how long to wait for action before proceeding + /// + /// An application using the libcurl multi interface should call + /// `get_timeout` to figure out how long it should wait for socket actions - + /// at most - before proceeding. + /// + /// Proceeding means either doing the socket-style timeout action: call the + /// `timeout` function, or call `perform` if you're using the simpler and + /// older multi interface approach. + /// + /// The timeout value returned is the duration at this very moment. If 0, it + /// means you should proceed immediately without waiting for anything. If it + /// returns `None`, there's no timeout at all set. + /// + /// Note: if libcurl returns a `None` timeout here, it just means that + /// libcurl currently has no stored timeout value. You must not wait too + /// long (more than a few seconds perhaps) before you call `perform` again. + pub fn get_timeout(&self) -> Result<Option<Duration>, MultiError> { + let mut ms = 0; + unsafe { + cvt(curl_sys::curl_multi_timeout(self.raw.handle, &mut ms))?; + if ms == -1 { + Ok(None) + } else { + Ok(Some(Duration::from_millis(ms as u64))) + } + } + } + + /// Block until activity is detected or a timeout passes. + /// + /// The timeout is used in millisecond-precision. Large durations are + /// clamped at the maximum value curl accepts. + /// + /// The returned integer will contain the number of internal file + /// descriptors on which interesting events occured. + /// + /// This function is a simpler alternative to using `fdset()` and `select()` + /// and does not suffer from file descriptor limits. + /// + /// # Example + /// + /// ``` + /// use curl::multi::Multi; + /// use std::time::Duration; + /// + /// let m = Multi::new(); + /// + /// // Add some Easy handles... + /// + /// while m.perform().unwrap() > 0 { + /// m.wait(&mut [], Duration::from_secs(1)).unwrap(); + /// } + /// ``` + pub fn wait(&self, waitfds: &mut [WaitFd], timeout: Duration) -> Result<u32, MultiError> { + let timeout_ms = Multi::timeout_i32(timeout); + unsafe { + let mut ret = 0; + cvt(curl_sys::curl_multi_wait( + self.raw.handle, + waitfds.as_mut_ptr() as *mut _, + waitfds.len() as u32, + timeout_ms, + &mut ret, + ))?; + Ok(ret as u32) + } + } + + fn timeout_i32(timeout: Duration) -> i32 { + let secs = timeout.as_secs(); + if secs > (i32::MAX / 1000) as u64 { + // Duration too large, clamp at maximum value. + i32::MAX + } else { + secs as i32 * 1000 + timeout.subsec_nanos() as i32 / 1_000_000 + } + } + + /// Block until activity is detected or a timeout passes. + /// + /// The timeout is used in millisecond-precision. Large durations are + /// clamped at the maximum value curl accepts. + /// + /// The returned integer will contain the number of internal file + /// descriptors on which interesting events occurred. + /// + /// This function is a simpler alternative to using `fdset()` and `select()` + /// and does not suffer from file descriptor limits. + /// + /// While this method is similar to [Multi::wait], with the following + /// distinctions: + /// * If there are no handles added to the multi, poll will honor the + /// provided timeout, while [Multi::wait] returns immediately. + /// * If poll has blocked due to there being no activity on the handles in + /// the Multi, it can be woken up from any thread and at any time before + /// the timeout expires. + /// + /// Requires libcurl 7.66.0 or later. + /// + /// # Example + /// + /// ``` + /// use curl::multi::Multi; + /// use std::time::Duration; + /// + /// let m = Multi::new(); + /// + /// // Add some Easy handles... + /// + /// while m.perform().unwrap() > 0 { + /// m.poll(&mut [], Duration::from_secs(1)).unwrap(); + /// } + /// ``` + #[cfg(feature = "poll_7_68_0")] + pub fn poll(&self, waitfds: &mut [WaitFd], timeout: Duration) -> Result<u32, MultiError> { + let timeout_ms = Multi::timeout_i32(timeout); + unsafe { + let mut ret = 0; + cvt(curl_sys::curl_multi_poll( + self.raw.handle, + waitfds.as_mut_ptr() as *mut _, + waitfds.len() as u32, + timeout_ms, + &mut ret, + ))?; + Ok(ret as u32) + } + } + + /// Returns a new [MultiWaker] that can be used to wake up a thread that's + /// currently blocked in [Multi::poll]. + #[cfg(feature = "poll_7_68_0")] + pub fn waker(&self) -> MultiWaker { + MultiWaker::new(Arc::downgrade(&self.raw)) + } + + /// Reads/writes available data from each easy handle. + /// + /// This function handles transfers on all the added handles that need + /// attention in an non-blocking fashion. + /// + /// When an application has found out there's data available for this handle + /// or a timeout has elapsed, the application should call this function to + /// read/write whatever there is to read or write right now etc. This + /// method returns as soon as the reads/writes are done. This function does + /// not require that there actually is any data available for reading or + /// that data can be written, it can be called just in case. It will return + /// the number of handles that still transfer data. + /// + /// If the amount of running handles is changed from the previous call (or + /// is less than the amount of easy handles you've added to the multi + /// handle), you know that there is one or more transfers less "running". + /// You can then call `info` to get information about each individual + /// completed transfer, and that returned info includes `Error` and more. + /// If an added handle fails very quickly, it may never be counted as a + /// running handle. + /// + /// When running_handles is set to zero (0) on the return of this function, + /// there is no longer any transfers in progress. + /// + /// # Return + /// + /// Before libcurl version 7.20.0: If you receive `is_call_perform`, this + /// basically means that you should call `perform` again, before you select + /// on more actions. You don't have to do it immediately, but the return + /// code means that libcurl may have more data available to return or that + /// there may be more data to send off before it is "satisfied". Do note + /// that `perform` will return `is_call_perform` only when it wants to be + /// called again immediately. When things are fine and there is nothing + /// immediate it wants done, it'll return `Ok` and you need to wait for + /// "action" and then call this function again. + /// + /// This function only returns errors etc regarding the whole multi stack. + /// Problems still might have occurred on individual transfers even when + /// this function returns `Ok`. Use `info` to figure out how individual + /// transfers did. + pub fn perform(&self) -> Result<u32, MultiError> { + unsafe { + let mut ret = 0; + cvt(curl_sys::curl_multi_perform(self.raw.handle, &mut ret))?; + Ok(ret as u32) + } + } + + /// Extracts file descriptor information from a multi handle + /// + /// This function extracts file descriptor information from a given + /// handle, and libcurl returns its `fd_set` sets. The application can use + /// these to `select()` on, but be sure to `FD_ZERO` them before calling + /// this function as curl_multi_fdset only adds its own descriptors, it + /// doesn't zero or otherwise remove any others. The curl_multi_perform + /// function should be called as soon as one of them is ready to be read + /// from or written to. + /// + /// If no file descriptors are set by libcurl, this function will return + /// `Ok(None)`. Otherwise `Ok(Some(n))` will be returned where `n` the + /// highest descriptor number libcurl set. When `Ok(None)` is returned it + /// is because libcurl currently does something that isn't possible for + /// your application to monitor with a socket and unfortunately you can + /// then not know exactly when the current action is completed using + /// `select()`. You then need to wait a while before you proceed and call + /// `perform` anyway. + /// + /// When doing `select()`, you should use `get_timeout` to figure out + /// how long to wait for action. Call `perform` even if no activity has + /// been seen on the `fd_set`s after the timeout expires as otherwise + /// internal retries and timeouts may not work as you'd think and want. + /// + /// If one of the sockets used by libcurl happens to be larger than what + /// can be set in an `fd_set`, which on POSIX systems means that the file + /// descriptor is larger than `FD_SETSIZE`, then libcurl will try to not + /// set it. Setting a too large file descriptor in an `fd_set` implies an out + /// of bounds write which can cause crashes, or worse. The effect of NOT + /// storing it will possibly save you from the crash, but will make your + /// program NOT wait for sockets it should wait for... + pub fn fdset2( + &self, + read: Option<&mut curl_sys::fd_set>, + write: Option<&mut curl_sys::fd_set>, + except: Option<&mut curl_sys::fd_set>, + ) -> Result<Option<i32>, MultiError> { + unsafe { + let mut ret = 0; + let read = read.map(|r| r as *mut _).unwrap_or(ptr::null_mut()); + let write = write.map(|r| r as *mut _).unwrap_or(ptr::null_mut()); + let except = except.map(|r| r as *mut _).unwrap_or(ptr::null_mut()); + cvt(curl_sys::curl_multi_fdset( + self.raw.handle, + read, + write, + except, + &mut ret, + ))?; + if ret == -1 { + Ok(None) + } else { + Ok(Some(ret)) + } + } + } + + /// Does nothing and returns `Ok(())`. This method remains for backwards + /// compatibility. + /// + /// This method will be changed to take `self` in a future release. + #[doc(hidden)] + #[deprecated( + since = "0.4.30", + note = "cannot close safely without consuming self; \ + will be changed or removed in a future release" + )] + pub fn close(&self) -> Result<(), MultiError> { + Ok(()) + } + + /// Get a pointer to the raw underlying CURLM handle. + pub fn raw(&self) -> *mut curl_sys::CURLM { + self.raw.handle + } +} + +impl Drop for RawMulti { + fn drop(&mut self) { + unsafe { + let _ = cvt(curl_sys::curl_multi_cleanup(self.handle)); + } + } +} + +#[cfg(feature = "poll_7_68_0")] +impl MultiWaker { + /// Creates a new MultiWaker handle. + fn new(raw: std::sync::Weak<RawMulti>) -> Self { + Self { raw } + } + + /// Wakes up a thread that is blocked in [Multi::poll]. This method can be + /// invoked from any thread. + /// + /// Will return an error if the RawMulti has already been dropped. + /// + /// Requires libcurl 7.68.0 or later. + pub fn wakeup(&self) -> Result<(), MultiError> { + if let Some(raw) = self.raw.upgrade() { + unsafe { cvt(curl_sys::curl_multi_wakeup(raw.handle)) } + } else { + // This happens if the RawMulti has already been dropped: + Err(MultiError::new(curl_sys::CURLM_BAD_HANDLE)) + } + } +} + +fn cvt(code: curl_sys::CURLMcode) -> Result<(), MultiError> { + if code == curl_sys::CURLM_OK { + Ok(()) + } else { + Err(MultiError::new(code)) + } +} + +impl fmt::Debug for Multi { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Multi").field("raw", &self.raw).finish() + } +} + +macro_rules! impl_easy_getters { + () => { + impl_easy_getters! { + time_condition_unmet -> bool, + effective_url -> Option<&str>, + effective_url_bytes -> Option<&[u8]>, + response_code -> u32, + http_connectcode -> u32, + filetime -> Option<i64>, + download_size -> f64, + content_length_download -> f64, + total_time -> Duration, + namelookup_time -> Duration, + connect_time -> Duration, + appconnect_time -> Duration, + pretransfer_time -> Duration, + starttransfer_time -> Duration, + redirect_time -> Duration, + redirect_count -> u32, + redirect_url -> Option<&str>, + redirect_url_bytes -> Option<&[u8]>, + header_size -> u64, + request_size -> u64, + content_type -> Option<&str>, + content_type_bytes -> Option<&[u8]>, + os_errno -> i32, + primary_ip -> Option<&str>, + primary_port -> u16, + local_ip -> Option<&str>, + local_port -> u16, + cookies -> List, + } + }; + + ($($name:ident -> $ret:ty,)*) => { + $( + impl_easy_getters!($name, $ret, concat!( + "Same as [`Easy2::", + stringify!($name), + "`](../easy/struct.Easy2.html#method.", + stringify!($name), + ")." + )); + )* + }; + + ($name:ident, $ret:ty, $doc:expr) => { + #[doc = $doc] + pub fn $name(&mut self) -> Result<$ret, Error> { + self.easy.$name() + } + }; +} + +impl EasyHandle { + /// Sets an internal private token for this `EasyHandle`. + /// + /// This function will set the `CURLOPT_PRIVATE` field on the underlying + /// easy handle. + pub fn set_token(&mut self, token: usize) -> Result<(), Error> { + unsafe { + crate::cvt(curl_sys::curl_easy_setopt( + self.easy.raw(), + curl_sys::CURLOPT_PRIVATE, + token, + )) + } + } + + impl_easy_getters!(); + + /// Unpause reading on a connection. + /// + /// Using this function, you can explicitly unpause a connection that was + /// previously paused. + /// + /// A connection can be paused by letting the read or the write callbacks + /// return `ReadError::Pause` or `WriteError::Pause`. + /// + /// The chance is high that you will get your write callback called before + /// this function returns. + pub fn unpause_read(&self) -> Result<(), Error> { + self.easy.unpause_read() + } + + /// Unpause writing on a connection. + /// + /// Using this function, you can explicitly unpause a connection that was + /// previously paused. + /// + /// A connection can be paused by letting the read or the write callbacks + /// return `ReadError::Pause` or `WriteError::Pause`. A write callback that + /// returns pause signals to the library that it couldn't take care of any + /// data at all, and that data will then be delivered again to the callback + /// when the writing is later unpaused. + pub fn unpause_write(&self) -> Result<(), Error> { + self.easy.unpause_write() + } + + /// Get a pointer to the raw underlying CURL handle. + pub fn raw(&self) -> *mut curl_sys::CURL { + self.easy.raw() + } +} + +impl fmt::Debug for EasyHandle { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.easy.fmt(f) + } +} + +impl<H> Easy2Handle<H> { + /// Acquires a reference to the underlying handler for events. + pub fn get_ref(&self) -> &H { + self.easy.get_ref() + } + + /// Acquires a reference to the underlying handler for events. + pub fn get_mut(&mut self) -> &mut H { + self.easy.get_mut() + } + + /// Same as `EasyHandle::set_token` + pub fn set_token(&mut self, token: usize) -> Result<(), Error> { + unsafe { + crate::cvt(curl_sys::curl_easy_setopt( + self.easy.raw(), + curl_sys::CURLOPT_PRIVATE, + token, + )) + } + } + + impl_easy_getters!(); + + /// Unpause reading on a connection. + /// + /// Using this function, you can explicitly unpause a connection that was + /// previously paused. + /// + /// A connection can be paused by letting the read or the write callbacks + /// return `ReadError::Pause` or `WriteError::Pause`. + /// + /// The chance is high that you will get your write callback called before + /// this function returns. + pub fn unpause_read(&self) -> Result<(), Error> { + self.easy.unpause_read() + } + + /// Unpause writing on a connection. + /// + /// Using this function, you can explicitly unpause a connection that was + /// previously paused. + /// + /// A connection can be paused by letting the read or the write callbacks + /// return `ReadError::Pause` or `WriteError::Pause`. A write callback that + /// returns pause signals to the library that it couldn't take care of any + /// data at all, and that data will then be delivered again to the callback + /// when the writing is later unpaused. + pub fn unpause_write(&self) -> Result<(), Error> { + self.easy.unpause_write() + } + + /// Get a pointer to the raw underlying CURL handle. + pub fn raw(&self) -> *mut curl_sys::CURL { + self.easy.raw() + } +} + +impl<H: fmt::Debug> fmt::Debug for Easy2Handle<H> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.easy.fmt(f) + } +} + +impl DetachGuard { + /// Detach the referenced easy handle from its multi handle manually. + /// Subsequent calls to this method will have no effect. + fn detach(&mut self) -> Result<(), MultiError> { + if !self.easy.is_null() { + unsafe { + cvt(curl_sys::curl_multi_remove_handle( + self.multi.handle, + self.easy, + ))? + } + + // Set easy to null to signify that the handle was removed. + self.easy = ptr::null_mut(); + } + + Ok(()) + } +} + +impl Drop for DetachGuard { + fn drop(&mut self) { + let _ = self.detach(); + } +} + +impl<'multi> Message<'multi> { + /// If this message indicates that a transfer has finished, returns the + /// result of the transfer in `Some`. + /// + /// If the message doesn't indicate that a transfer has finished, then + /// `None` is returned. + /// + /// Note that the `result*_for` methods below should be preferred as they + /// provide better error messages as the associated error data on the + /// handle can be associated with the error type. + pub fn result(&self) -> Option<Result<(), Error>> { + unsafe { + if (*self.ptr).msg == curl_sys::CURLMSG_DONE { + Some(crate::cvt((*self.ptr).data as curl_sys::CURLcode)) + } else { + None + } + } + } + + /// Same as `result`, except only returns `Some` for the specified handle. + /// + /// Note that this function produces better error messages than `result` as + /// it uses `take_error_buf` to associate error information with the + /// returned error. + pub fn result_for(&self, handle: &EasyHandle) -> Option<Result<(), Error>> { + if !self.is_for(handle) { + return None; + } + let mut err = self.result(); + if let Some(Err(e)) = &mut err { + if let Some(s) = handle.easy.take_error_buf() { + e.set_extra(s); + } + } + err + } + + /// Same as `result`, except only returns `Some` for the specified handle. + /// + /// Note that this function produces better error messages than `result` as + /// it uses `take_error_buf` to associate error information with the + /// returned error. + pub fn result_for2<H>(&self, handle: &Easy2Handle<H>) -> Option<Result<(), Error>> { + if !self.is_for2(handle) { + return None; + } + let mut err = self.result(); + if let Some(Err(e)) = &mut err { + if let Some(s) = handle.easy.take_error_buf() { + e.set_extra(s); + } + } + err + } + + /// Returns whether this easy message was for the specified easy handle or + /// not. + pub fn is_for(&self, handle: &EasyHandle) -> bool { + unsafe { (*self.ptr).easy_handle == handle.easy.raw() } + } + + /// Same as `is_for`, but for `Easy2Handle`. + pub fn is_for2<H>(&self, handle: &Easy2Handle<H>) -> bool { + unsafe { (*self.ptr).easy_handle == handle.easy.raw() } + } + + /// Returns the token associated with the easy handle that this message + /// represents a completion for. + /// + /// This function will return the token assigned with + /// `EasyHandle::set_token`. This reads the `CURLINFO_PRIVATE` field of the + /// underlying `*mut CURL`. + pub fn token(&self) -> Result<usize, Error> { + unsafe { + let mut p = 0usize; + crate::cvt(curl_sys::curl_easy_getinfo( + (*self.ptr).easy_handle, + curl_sys::CURLINFO_PRIVATE, + &mut p, + ))?; + Ok(p) + } + } +} + +impl<'a> fmt::Debug for Message<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Message").field("ptr", &self.ptr).finish() + } +} + +impl Events { + /// Creates a new blank event bit mask. + pub fn new() -> Events { + Events { bits: 0 } + } + + /// Set or unset the whether these events indicate that input is ready. + pub fn input(&mut self, val: bool) -> &mut Events { + self.flag(curl_sys::CURL_CSELECT_IN, val) + } + + /// Set or unset the whether these events indicate that output is ready. + pub fn output(&mut self, val: bool) -> &mut Events { + self.flag(curl_sys::CURL_CSELECT_OUT, val) + } + + /// Set or unset the whether these events indicate that an error has + /// happened. + pub fn error(&mut self, val: bool) -> &mut Events { + self.flag(curl_sys::CURL_CSELECT_ERR, val) + } + + fn flag(&mut self, flag: c_int, val: bool) -> &mut Events { + if val { + self.bits |= flag; + } else { + self.bits &= !flag; + } + self + } +} + +impl fmt::Debug for Events { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Events") + .field("input", &(self.bits & curl_sys::CURL_CSELECT_IN != 0)) + .field("output", &(self.bits & curl_sys::CURL_CSELECT_OUT != 0)) + .field("error", &(self.bits & curl_sys::CURL_CSELECT_ERR != 0)) + .finish() + } +} + +impl SocketEvents { + /// Wait for incoming data. For the socket to become readable. + pub fn input(&self) -> bool { + self.bits & curl_sys::CURL_POLL_IN == curl_sys::CURL_POLL_IN + } + + /// Wait for outgoing data. For the socket to become writable. + pub fn output(&self) -> bool { + self.bits & curl_sys::CURL_POLL_OUT == curl_sys::CURL_POLL_OUT + } + + /// Wait for incoming and outgoing data. For the socket to become readable + /// or writable. + pub fn input_and_output(&self) -> bool { + self.bits & curl_sys::CURL_POLL_INOUT == curl_sys::CURL_POLL_INOUT + } + + /// The specified socket/file descriptor is no longer used by libcurl. + pub fn remove(&self) -> bool { + self.bits & curl_sys::CURL_POLL_REMOVE == curl_sys::CURL_POLL_REMOVE + } +} + +impl fmt::Debug for SocketEvents { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Events") + .field("input", &self.input()) + .field("output", &self.output()) + .field("remove", &self.remove()) + .finish() + } +} + +impl WaitFd { + /// Constructs an empty (invalid) WaitFd. + pub fn new() -> WaitFd { + WaitFd { + inner: curl_sys::curl_waitfd { + fd: 0, + events: 0, + revents: 0, + }, + } + } + + /// Set the file descriptor to wait for. + pub fn set_fd(&mut self, fd: Socket) { + self.inner.fd = fd; + } + + /// Indicate that the socket should poll on read events such as new data + /// received. + /// + /// Corresponds to `CURL_WAIT_POLLIN`. + pub fn poll_on_read(&mut self, val: bool) -> &mut WaitFd { + self.flag(curl_sys::CURL_WAIT_POLLIN, val) + } + + /// Indicate that the socket should poll on high priority read events such + /// as out of band data. + /// + /// Corresponds to `CURL_WAIT_POLLPRI`. + pub fn poll_on_priority_read(&mut self, val: bool) -> &mut WaitFd { + self.flag(curl_sys::CURL_WAIT_POLLPRI, val) + } + + /// Indicate that the socket should poll on write events such as the socket + /// being clear to write without blocking. + /// + /// Corresponds to `CURL_WAIT_POLLOUT`. + pub fn poll_on_write(&mut self, val: bool) -> &mut WaitFd { + self.flag(curl_sys::CURL_WAIT_POLLOUT, val) + } + + fn flag(&mut self, flag: c_short, val: bool) -> &mut WaitFd { + if val { + self.inner.events |= flag; + } else { + self.inner.events &= !flag; + } + self + } + + /// After a call to `wait`, returns `true` if `poll_on_read` was set and a + /// read event occured. + pub fn received_read(&self) -> bool { + self.inner.revents & curl_sys::CURL_WAIT_POLLIN == curl_sys::CURL_WAIT_POLLIN + } + + /// After a call to `wait`, returns `true` if `poll_on_priority_read` was set and a + /// priority read event occured. + pub fn received_priority_read(&self) -> bool { + self.inner.revents & curl_sys::CURL_WAIT_POLLPRI == curl_sys::CURL_WAIT_POLLPRI + } + + /// After a call to `wait`, returns `true` if `poll_on_write` was set and a + /// write event occured. + pub fn received_write(&self) -> bool { + self.inner.revents & curl_sys::CURL_WAIT_POLLOUT == curl_sys::CURL_WAIT_POLLOUT + } +} + +#[cfg(unix)] +impl From<pollfd> for WaitFd { + fn from(pfd: pollfd) -> WaitFd { + let mut events = 0; + if pfd.events & POLLIN == POLLIN { + events |= curl_sys::CURL_WAIT_POLLIN; + } + if pfd.events & POLLPRI == POLLPRI { + events |= curl_sys::CURL_WAIT_POLLPRI; + } + if pfd.events & POLLOUT == POLLOUT { + events |= curl_sys::CURL_WAIT_POLLOUT; + } + WaitFd { + inner: curl_sys::curl_waitfd { + fd: pfd.fd, + events, + revents: 0, + }, + } + } +} + +impl fmt::Debug for WaitFd { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("WaitFd") + .field("fd", &self.inner.fd) + .field("events", &self.inner.fd) + .field("revents", &self.inner.fd) + .finish() + } +} diff --git a/vendor/curl/src/panic.rs b/vendor/curl/src/panic.rs new file mode 100644 index 000000000..42cffd8f0 --- /dev/null +++ b/vendor/curl/src/panic.rs @@ -0,0 +1,34 @@ +use std::any::Any; +use std::cell::RefCell; +use std::panic::{self, AssertUnwindSafe}; + +thread_local!(static LAST_ERROR: RefCell<Option<Box<dyn Any + Send>>> = { + RefCell::new(None) +}); + +pub fn catch<T, F: FnOnce() -> T>(f: F) -> Option<T> { + match LAST_ERROR.try_with(|slot| slot.borrow().is_some()) { + Ok(true) => return None, + Ok(false) => {} + // we're in thread shutdown, so we're for sure not panicking and + // panicking again will abort, so no need to worry! + Err(_) => {} + } + + // Note that `AssertUnwindSafe` is used here as we prevent reentering + // arbitrary code due to the `LAST_ERROR` check above plus propagation of a + // panic after we return back to user code from C. + match panic::catch_unwind(AssertUnwindSafe(f)) { + Ok(ret) => Some(ret), + Err(e) => { + LAST_ERROR.with(|slot| *slot.borrow_mut() = Some(e)); + None + } + } +} + +pub fn propagate() { + if let Ok(Some(t)) = LAST_ERROR.try_with(|slot| slot.borrow_mut().take()) { + panic::resume_unwind(t) + } +} diff --git a/vendor/curl/src/version.rs b/vendor/curl/src/version.rs new file mode 100644 index 000000000..8bceaec10 --- /dev/null +++ b/vendor/curl/src/version.rs @@ -0,0 +1,501 @@ +use std::ffi::CStr; +use std::fmt; +use std::str; + +use libc::{c_char, c_int}; + +/// Version information about libcurl and the capabilities that it supports. +pub struct Version { + inner: *mut curl_sys::curl_version_info_data, +} + +unsafe impl Send for Version {} +unsafe impl Sync for Version {} + +/// An iterator over the list of protocols a version supports. +#[derive(Clone)] +pub struct Protocols<'a> { + cur: *const *const c_char, + _inner: &'a Version, +} + +impl Version { + /// Returns the libcurl version that this library is currently linked against. + pub fn num() -> &'static str { + unsafe { + let s = CStr::from_ptr(curl_sys::curl_version() as *const _); + str::from_utf8(s.to_bytes()).unwrap() + } + } + + /// Returns the libcurl version that this library is currently linked against. + pub fn get() -> Version { + unsafe { + let ptr = curl_sys::curl_version_info(curl_sys::CURLVERSION_NOW); + assert!(!ptr.is_null()); + Version { inner: ptr } + } + } + + /// Returns the human readable version string, + pub fn version(&self) -> &str { + unsafe { crate::opt_str((*self.inner).version).unwrap() } + } + + /// Returns a numeric representation of the version number + /// + /// This is a 24 bit number made up of the major number, minor, and then + /// patch number. For example 7.9.8 will return 0x070908. + pub fn version_num(&self) -> u32 { + unsafe { (*self.inner).version_num as u32 } + } + + /// Returns true if this was built with the vendored version of libcurl. + pub fn vendored(&self) -> bool { + curl_sys::vendored() + } + + /// Returns a human readable string of the host libcurl is built for. + /// + /// This is discovered as part of the build environment. + pub fn host(&self) -> &str { + unsafe { crate::opt_str((*self.inner).host).unwrap() } + } + + /// Returns whether libcurl supports IPv6 + pub fn feature_ipv6(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_IPV6) + } + + /// Returns whether libcurl supports SSL + pub fn feature_ssl(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_SSL) + } + + /// Returns whether libcurl supports HTTP deflate via libz + pub fn feature_libz(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_LIBZ) + } + + /// Returns whether libcurl supports HTTP NTLM + pub fn feature_ntlm(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_NTLM) + } + + /// Returns whether libcurl supports HTTP GSSNEGOTIATE + pub fn feature_gss_negotiate(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_GSSNEGOTIATE) + } + + /// Returns whether libcurl was built with debug capabilities + pub fn feature_debug(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_DEBUG) + } + + /// Returns whether libcurl was built with SPNEGO authentication + pub fn feature_spnego(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_SPNEGO) + } + + /// Returns whether libcurl was built with large file support + pub fn feature_largefile(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_LARGEFILE) + } + + /// Returns whether libcurl was built with support for IDNA, domain names + /// with international letters. + pub fn feature_idn(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_IDN) + } + + /// Returns whether libcurl was built with support for SSPI. + pub fn feature_sspi(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_SSPI) + } + + /// Returns whether libcurl was built with asynchronous name lookups. + pub fn feature_async_dns(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_ASYNCHDNS) + } + + /// Returns whether libcurl was built with support for character + /// conversions. + pub fn feature_conv(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_CONV) + } + + /// Returns whether libcurl was built with support for TLS-SRP. + pub fn feature_tlsauth_srp(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_TLSAUTH_SRP) + } + + /// Returns whether libcurl was built with support for NTLM delegation to + /// winbind helper. + pub fn feature_ntlm_wb(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_NTLM_WB) + } + + /// Returns whether libcurl was built with support for unix domain socket + pub fn feature_unix_domain_socket(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_UNIX_SOCKETS) + } + + /// Returns whether libcurl was built with support for HTTP2. + pub fn feature_http2(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_HTTP2) + } + + /// Returns whether libcurl was built with support for HTTP3. + pub fn feature_http3(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_HTTP3) + } + + /// Returns whether libcurl was built with support for Brotli. + pub fn feature_brotli(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_BROTLI) + } + + /// Returns whether libcurl was built with support for Alt-Svc. + pub fn feature_altsvc(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_ALTSVC) + } + + /// Returns whether libcurl was built with support for zstd + pub fn feature_zstd(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_ZSTD) + } + + /// Returns whether libcurl was built with support for unicode + pub fn feature_unicode(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_UNICODE) + } + + /// Returns whether libcurl was built with support for hsts + pub fn feature_hsts(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_HSTS) + } + + /// Returns whether libcurl was built with support for gsasl + pub fn feature_gsasl(&self) -> bool { + self.flag(curl_sys::CURL_VERSION_GSASL) + } + + fn flag(&self, flag: c_int) -> bool { + unsafe { (*self.inner).features & flag != 0 } + } + + /// Returns the version of OpenSSL that is used, or None if there is no SSL + /// support. + pub fn ssl_version(&self) -> Option<&str> { + unsafe { crate::opt_str((*self.inner).ssl_version) } + } + + /// Returns the version of libz that is used, or None if there is no libz + /// support. + pub fn libz_version(&self) -> Option<&str> { + unsafe { crate::opt_str((*self.inner).libz_version) } + } + + /// Returns an iterator over the list of protocols that this build of + /// libcurl supports. + pub fn protocols(&self) -> Protocols { + unsafe { + Protocols { + _inner: self, + cur: (*self.inner).protocols, + } + } + } + + /// If available, the human readable version of ares that libcurl is linked + /// against. + pub fn ares_version(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_SECOND { + crate::opt_str((*self.inner).ares) + } else { + None + } + } + } + + /// If available, the version of ares that libcurl is linked against. + pub fn ares_version_num(&self) -> Option<u32> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_SECOND { + Some((*self.inner).ares_num as u32) + } else { + None + } + } + } + + /// If available, the version of libidn that libcurl is linked against. + pub fn libidn_version(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_THIRD { + crate::opt_str((*self.inner).libidn) + } else { + None + } + } + } + + /// If available, the version of iconv libcurl is linked against. + pub fn iconv_version_num(&self) -> Option<u32> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_FOURTH { + Some((*self.inner).iconv_ver_num as u32) + } else { + None + } + } + } + + /// If available, the version of libssh that libcurl is linked against. + pub fn libssh_version(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_FOURTH { + crate::opt_str((*self.inner).libssh_version) + } else { + None + } + } + } + + /// If available, the version of brotli libcurl is linked against. + pub fn brotli_version_num(&self) -> Option<u32> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_FIFTH { + Some((*self.inner).brotli_ver_num) + } else { + None + } + } + } + + /// If available, the version of brotli libcurl is linked against. + pub fn brotli_version(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_FIFTH { + crate::opt_str((*self.inner).brotli_version) + } else { + None + } + } + } + + /// If available, the version of nghttp2 libcurl is linked against. + pub fn nghttp2_version_num(&self) -> Option<u32> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_SIXTH { + Some((*self.inner).nghttp2_ver_num) + } else { + None + } + } + } + + /// If available, the version of nghttp2 libcurl is linked against. + pub fn nghttp2_version(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_SIXTH { + crate::opt_str((*self.inner).nghttp2_version) + } else { + None + } + } + } + + /// If available, the version of quic libcurl is linked against. + pub fn quic_version(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_SIXTH { + crate::opt_str((*self.inner).quic_version) + } else { + None + } + } + } + + /// If available, the built-in default of CURLOPT_CAINFO. + pub fn cainfo(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_SEVENTH { + crate::opt_str((*self.inner).cainfo) + } else { + None + } + } + } + + /// If available, the built-in default of CURLOPT_CAPATH. + pub fn capath(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_SEVENTH { + crate::opt_str((*self.inner).capath) + } else { + None + } + } + } + + /// If avaiable, the numeric zstd version + /// + /// Represented as `(MAJOR << 24) | (MINOR << 12) | PATCH` + pub fn zstd_ver_num(&self) -> Option<u32> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_EIGHTH { + Some((*self.inner).zstd_ver_num) + } else { + None + } + } + } + + /// If available, the human readable version of zstd + pub fn zstd_version(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_EIGHTH { + crate::opt_str((*self.inner).zstd_version) + } else { + None + } + } + } + + /// If available, the human readable version of hyper + pub fn hyper_version(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_NINTH { + crate::opt_str((*self.inner).hyper_version) + } else { + None + } + } + } + + /// If available, the human readable version of hyper + pub fn gsasl_version(&self) -> Option<&str> { + unsafe { + if (*self.inner).age >= curl_sys::CURLVERSION_TENTH { + crate::opt_str((*self.inner).gsasl_version) + } else { + None + } + } + } +} + +impl fmt::Debug for Version { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("Version"); + f.field("version", &self.version()) + .field("rust_crate_version", &env!("CARGO_PKG_VERSION")) + .field("rust_sys_crate_version", &curl_sys::rust_crate_version()) + .field("vendored", &self.vendored()) + .field("host", &self.host()) + .field("feature_ipv6", &self.feature_ipv6()) + .field("feature_ssl", &self.feature_ssl()) + .field("feature_libz", &self.feature_libz()) + .field("feature_ntlm", &self.feature_ntlm()) + .field("feature_gss_negotiate", &self.feature_gss_negotiate()) + .field("feature_debug", &self.feature_debug()) + .field("feature_spnego", &self.feature_spnego()) + .field("feature_largefile", &self.feature_largefile()) + .field("feature_idn", &self.feature_idn()) + .field("feature_sspi", &self.feature_sspi()) + .field("feature_async_dns", &self.feature_async_dns()) + .field("feature_conv", &self.feature_conv()) + .field("feature_tlsauth_srp", &self.feature_tlsauth_srp()) + .field("feature_ntlm_wb", &self.feature_ntlm_wb()) + .field( + "feature_unix_domain_socket", + &self.feature_unix_domain_socket(), + ) + .field("feature_altsvc", &self.feature_altsvc()) + .field("feature_zstd", &self.feature_zstd()) + .field("feature_unicode", &self.feature_unicode()) + .field("feature_http3", &self.feature_http3()) + .field("feature_http2", &self.feature_http2()) + .field("feature_gsasl", &self.feature_gsasl()) + .field("feature_brotli", &self.feature_brotli()); + + if let Some(s) = self.ssl_version() { + f.field("ssl_version", &s); + } + if let Some(s) = self.libz_version() { + f.field("libz_version", &s); + } + if let Some(s) = self.ares_version() { + f.field("ares_version", &s); + } + if let Some(s) = self.libidn_version() { + f.field("libidn_version", &s); + } + if let Some(s) = self.iconv_version_num() { + f.field("iconv_version_num", &format!("{:x}", s)); + } + if let Some(s) = self.libssh_version() { + f.field("libssh_version", &s); + } + if let Some(s) = self.brotli_version_num() { + f.field("brotli_version_num", &format!("{:x}", s)); + } + if let Some(s) = self.brotli_version() { + f.field("brotli_version", &s); + } + if let Some(s) = self.nghttp2_version_num() { + f.field("nghttp2_version_num", &format!("{:x}", s)); + } + if let Some(s) = self.nghttp2_version() { + f.field("nghttp2_version", &s); + } + if let Some(s) = self.quic_version() { + f.field("quic_version", &s); + } + if let Some(s) = self.zstd_ver_num() { + f.field("zstd_ver_num", &format!("{:x}", s)); + } + if let Some(s) = self.zstd_version() { + f.field("zstd_version", &s); + } + if let Some(s) = self.cainfo() { + f.field("cainfo", &s); + } + if let Some(s) = self.capath() { + f.field("capath", &s); + } + if let Some(s) = self.hyper_version() { + f.field("hyper_version", &s); + } + if let Some(s) = self.gsasl_version() { + f.field("gsasl_version", &s); + } + + f.field("protocols", &self.protocols().collect::<Vec<_>>()); + + f.finish() + } +} + +impl<'a> Iterator for Protocols<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option<&'a str> { + unsafe { + if (*self.cur).is_null() { + return None; + } + let ret = crate::opt_str(*self.cur).unwrap(); + self.cur = self.cur.offset(1); + Some(ret) + } + } +} + +impl<'a> fmt::Debug for Protocols<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_list().entries(self.clone()).finish() + } +} diff --git a/vendor/curl/tests/atexit.rs b/vendor/curl/tests/atexit.rs new file mode 100644 index 000000000..0872a4e97 --- /dev/null +++ b/vendor/curl/tests/atexit.rs @@ -0,0 +1,17 @@ +use curl::easy::Easy; + +pub extern "C" fn hook() { + let mut easy = Easy::new(); + easy.url("google.com").unwrap(); + easy.write_function(|data| Ok(data.len())).unwrap(); + easy.perform().unwrap(); +} + +fn main() { + curl::init(); + hook(); + unsafe { + libc::atexit(hook); + } + println!("Finishing...") +} diff --git a/vendor/curl/tests/easy.rs b/vendor/curl/tests/easy.rs new file mode 100644 index 000000000..942922933 --- /dev/null +++ b/vendor/curl/tests/easy.rs @@ -0,0 +1,972 @@ +use std::cell::{Cell, RefCell}; +use std::io::Read; +use std::rc::Rc; +use std::str; +use std::time::Duration; + +macro_rules! t { + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; +} + +use curl::easy::{Easy, List, ReadError, Transfer, WriteError}; +use curl::Version; + +use crate::server::Server; +mod server; + +fn handle() -> Easy { + let mut e = Easy::new(); + t!(e.timeout(Duration::new(20, 0))); + e +} + +fn sink(data: &[u8]) -> Result<usize, WriteError> { + Ok(data.len()) +} + +#[test] +fn get_smoke() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut handle = handle(); + t!(handle.url(&s.url("/"))); + t!(handle.perform()); +} + +#[test] +fn download_zero_size() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut handle = handle(); + t!(handle.url(&s.url("/"))); + t!(handle.perform()); + assert_eq!(handle.download_size().unwrap(), 0_f64); +} + +#[test] +fn download_nonzero_size() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\nHello!"); + + let mut handle = handle(); + t!(handle.url(&s.url("/"))); + t!(handle.perform()); + assert_eq!(handle.download_size().unwrap(), 6_f64); +} + +#[test] +fn upload_zero_size() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut handle = handle(); + t!(handle.url(&s.url("/"))); + t!(handle.perform()); + assert_eq!(handle.upload_size().unwrap(), 0_f64); +} + +#[test] +fn upload_nonzero_size() { + let s = Server::new(); + s.receive( + "\ + PUT / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: 5\r\n\ + \r\n\ + data\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut data = "data\n".as_bytes(); + let mut list = List::new(); + t!(list.append("Expect:")); + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.put(true)); + t!(h.in_filesize(5)); + t!(h.upload(true)); + t!(h.http_headers(list)); + { + let mut h = h.transfer(); + t!(h.read_function(|buf| Ok(data.read(buf).unwrap()))); + t!(h.perform()); + } + + assert_eq!(h.upload_size().unwrap(), 5_f64); +} + +#[test] +fn get_path() { + let s = Server::new(); + s.receive( + "\ + GET /foo HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut handle = handle(); + t!(handle.url(&s.url("/foo"))); + t!(handle.perform()); +} + +#[test] +fn write_callback() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\nhello!"); + + let mut all = Vec::<u8>::new(); + { + let mut handle = handle(); + t!(handle.url(&s.url("/"))); + let mut handle = handle.transfer(); + t!(handle.write_function(|data| { + all.extend(data); + Ok(data.len()) + })); + t!(handle.perform()); + } + assert_eq!(all, b"hello!"); +} + +#[test] +fn resolve() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: example.com:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut list = List::new(); + t!(list.append(&format!("example.com:{}:127.0.0.1", s.addr().port()))); + let mut handle = handle(); + t!(handle.url(&format!("http://example.com:{}/", s.addr().port()))); + t!(handle.resolve(list)); + t!(handle.perform()); +} + +#[test] +fn progress() { + let s = Server::new(); + s.receive( + "\ + GET /foo HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\nHello!"); + + let mut hits = 0; + let mut dl = 0.0; + { + let mut handle = handle(); + t!(handle.url(&s.url("/foo"))); + t!(handle.progress(true)); + t!(handle.write_function(sink)); + + let mut handle = handle.transfer(); + t!(handle.progress_function(|_, a, _, _| { + hits += 1; + dl = a; + true + })); + t!(handle.perform()); + } + assert!(hits > 0); + assert_eq!(dl, 6.0); +} + +#[test] +fn headers() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ +HTTP/1.1 200 OK\r\n\ +Foo: bar\r\n\ +Bar: baz\r\n\ +\r\n +Hello!", + ); + + let mut headers = Vec::new(); + { + let mut handle = handle(); + t!(handle.url(&s.url("/"))); + + let mut handle = handle.transfer(); + t!(handle.header_function(|h| { + headers.push(str::from_utf8(h).unwrap().to_string()); + true + })); + t!(handle.write_function(sink)); + t!(handle.perform()); + } + assert_eq!( + headers, + vec![ + "HTTP/1.1 200 OK\r\n".to_string(), + "Foo: bar\r\n".to_string(), + "Bar: baz\r\n".to_string(), + "\r\n".to_string(), + ] + ); +} + +#[test] +fn fail_on_error() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 401 Not so good\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.fail_on_error(true)); + assert!(h.perform().is_err()); + + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 401 Not so good\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.fail_on_error(false)); + t!(h.perform()); +} + +#[test] +fn port() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: localhost:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url("http://localhost/")); + t!(h.port(s.addr().port())); + t!(h.perform()); +} + +#[test] +fn proxy() { + let s = Server::new(); + s.receive( + "\ + GET http://example.com/ HTTP/1.1\r\n\ + Host: example.com\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url("http://example.com/")); + t!(h.proxy(&s.url("/"))); + t!(h.perform()); +} + +#[test] +#[ignore] // fails on newer curl versions? seems benign +fn noproxy() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.proxy(&s.url("/"))); + t!(h.noproxy("127.0.0.1")); + t!(h.perform()); +} + +#[test] +fn misc() { + let mut h = handle(); + t!(h.tcp_nodelay(true)); + // t!(h.tcp_keepalive(true)); + // t!(h.tcp_keepidle(Duration::new(3, 0))); + // t!(h.tcp_keepintvl(Duration::new(3, 0))); + t!(h.buffer_size(10)); + + if Version::get().version_num() >= 0x073e00 { + // only available on curl 7.62.0 or later: + t!(h.upload_buffer_size(10)); + } + + t!(h.dns_cache_timeout(Duration::new(1, 0))); +} + +#[test] +fn dns_servers() { + let mut h = handle(); + // Tests are not using a libcurl with c-ares, so this + // always fails. Test anyway to make sure it returns + // an error instead of panicing. + assert!(h.dns_servers("").is_err()); + assert!(h.dns_servers("nonsense").is_err()); + assert!(h.dns_servers("8.8.8.8,8.8.4.4").is_err()); +} + +#[test] +fn userpass() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Authorization: Basic YmFyOg==\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.username("foo")); + t!(h.username("bar")); + t!(h.perform()); +} + +#[test] +fn accept_encoding() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Accept-Encoding: gzip\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.accept_encoding("gzip")); + t!(h.perform()); +} + +#[test] +fn follow_location() { + let s1 = Server::new(); + let s2 = Server::new(); + s1.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s1.send(&format!( + "\ + HTTP/1.1 301 Moved Permanently\r\n\ + Location: http://{}/foo\r\n\ + \r\n", + s2.addr() + )); + + s2.receive( + "\ + GET /foo HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s2.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s1.url("/"))); + t!(h.follow_location(true)); + t!(h.perform()); +} + +#[test] +fn put() { + let s = Server::new(); + s.receive( + "\ + PUT / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: 5\r\n\ + \r\n\ + data\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut data = "data\n".as_bytes(); + let mut list = List::new(); + t!(list.append("Expect:")); + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.put(true)); + t!(h.in_filesize(5)); + t!(h.upload(true)); + t!(h.http_headers(list)); + let mut h = h.transfer(); + t!(h.read_function(|buf| Ok(data.read(buf).unwrap()))); + t!(h.perform()); +} + +#[test] +fn post1() { + let s = Server::new(); + s.receive( + "\ + POST / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: 5\r\n\ + Content-Type: application/x-www-form-urlencoded\r\n\ + \r\n\ + data\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.post(true)); + t!(h.post_fields_copy(b"data\n")); + t!(h.perform()); +} + +#[test] +fn post2() { + let s = Server::new(); + s.receive( + "\ + POST / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: 5\r\n\ + Content-Type: application/x-www-form-urlencoded\r\n\ + \r\n\ + data\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.post(true)); + t!(h.post_fields_copy(b"data\n")); + t!(h.write_function(sink)); + t!(h.perform()); +} + +#[test] +fn post3() { + let s = Server::new(); + s.receive( + "\ + POST / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: 5\r\n\ + Content-Type: application/x-www-form-urlencoded\r\n\ + \r\n\ + data\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut data = "data\n".as_bytes(); + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.post(true)); + t!(h.post_field_size(5)); + let mut h = h.transfer(); + t!(h.read_function(|buf| Ok(data.read(buf).unwrap()))); + t!(h.perform()); +} + +#[test] +fn referer() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Referer: foo\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.referer("foo")); + t!(h.perform()); +} + +#[test] +fn useragent() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + User-Agent: foo\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.useragent("foo")); + t!(h.perform()); +} + +#[test] +fn custom_headers() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Foo: bar\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut custom = List::new(); + t!(custom.append("Foo: bar")); + t!(custom.append("Accept:")); + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.http_headers(custom)); + t!(h.perform()); +} + +#[test] +fn cookie() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Cookie: foo\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.cookie("foo")); + t!(h.perform()); +} + +#[test] +fn url_encoding() { + let mut h = handle(); + assert_eq!(h.url_encode(b"foo"), "foo"); + assert_eq!(h.url_encode(b"foo bar"), "foo%20bar"); + assert_eq!(h.url_encode(b"foo bar\xff"), "foo%20bar%FF"); + assert_eq!(h.url_encode(b""), ""); + assert_eq!(h.url_decode("foo"), b"foo"); + assert_eq!(h.url_decode("foo%20bar"), b"foo bar"); + assert_eq!(h.url_decode("foo%2"), b"foo%2"); + assert_eq!(h.url_decode("foo%xx"), b"foo%xx"); + assert_eq!(h.url_decode("foo%ff"), b"foo\xff"); + assert_eq!(h.url_decode(""), b""); +} + +#[test] +fn getters() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.cookie_file("/dev/null")); + t!(h.perform()); + assert_eq!(t!(h.response_code()), 200); + assert_eq!(t!(h.redirect_count()), 0); + assert_eq!(t!(h.redirect_url()), None); + assert_eq!(t!(h.content_type()), None); + + let addr = format!("http://{}/", s.addr()); + assert_eq!(t!(h.effective_url()), Some(&addr[..])); + + // TODO: test this + // let cookies = t!(h.cookies()).iter() + // .map(|s| s.to_vec()) + // .collect::<Vec<_>>(); + // assert_eq!(cookies.len(), 1); +} + +#[test] +#[should_panic] +fn panic_in_callback() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.header_function(|_| panic!())); + t!(h.perform()); +} + +#[test] +fn abort_read() { + let s = Server::new(); + s.receive( + "\ + PUT / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: 2\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.read_function(|_| Err(ReadError::Abort))); + t!(h.put(true)); + t!(h.in_filesize(2)); + let mut list = List::new(); + t!(list.append("Expect:")); + t!(h.http_headers(list)); + let err = h.perform().unwrap_err(); + assert!(err.is_aborted_by_callback()); +} + +#[test] +fn pause_write_then_resume() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ +HTTP/1.1 200 OK\r\n\ +\r\n +a\n +b", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.progress(true)); + + struct State<'a, 'b> { + paused: Cell<bool>, + unpaused: Cell<bool>, + transfer: RefCell<Transfer<'a, 'b>>, + } + + let h = Rc::new(State { + paused: Cell::new(false), + unpaused: Cell::new(false), + transfer: RefCell::new(h.transfer()), + }); + + let h2 = h.clone(); + t!(h.transfer + .borrow_mut() + .write_function(move |data| if h2.unpaused.get() { + h2.unpaused.set(false); + Ok(data.len()) + } else { + h2.paused.set(true); + Err(WriteError::Pause) + })); + let h2 = h.clone(); + t!(h.transfer + .borrow_mut() + .progress_function(move |_, _, _, _| { + if h2.paused.get() { + h2.paused.set(false); + h2.unpaused.set(true); + t!(h2.transfer.borrow().unpause_write()); + } + true + })); + t!(h.transfer.borrow().perform()); +} + +#[test] +fn perform_in_perform_is_bad() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ +HTTP/1.1 200 OK\r\n\ +\r\n +a\n +b", + ); + + let mut h = handle(); + t!(h.url(&s.url("/"))); + t!(h.progress(true)); + + let h = Rc::new(RefCell::new(h.transfer())); + + let h2 = h.clone(); + t!(h.borrow_mut().write_function(move |data| { + assert!(h2.borrow().perform().is_err()); + Ok(data.len()) + })); + t!(h.borrow().perform()); +} + +#[cfg(not(windows))] +#[test] +fn check_unix_socket() { + let s = Server::new_unix(); + s.receive( + "\ + POST / HTTP/1.1\r\n\ + Host: localhost\r\n\ + Accept: */*\r\n\ + Content-Length: 5\r\n\ + Content-Type: application/x-www-form-urlencoded\r\n\ + \r\n\ + data\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.unix_socket(s.path())); + t!(h.url(&s.url("/"))); + t!(h.post(true)); + t!(h.post_fields_copy(b"data\n")); + t!(h.perform()); +} + +#[cfg(feature = "upkeep_7_62_0")] +#[test] +fn test_upkeep() { + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut handle = handle(); + t!(handle.url(&s.url("/"))); + t!(handle.perform()); + + // Ensure that upkeep can be called on the handle without problem. + t!(handle.upkeep()); +} + +#[test] +fn path_as_is() { + let s = Server::new(); + s.receive( + "\ + GET /test/../ HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut h = handle(); + t!(h.url(&s.url("/test/../"))); + t!(h.path_as_is(true)); + t!(h.perform()); + + let addr = format!("http://{}/test/../", s.addr()); + assert_eq!(t!(h.response_code()), 200); + assert_eq!(t!(h.effective_url()), Some(&addr[..])); +} diff --git a/vendor/curl/tests/formdata b/vendor/curl/tests/formdata new file mode 100644 index 000000000..ce0136250 --- /dev/null +++ b/vendor/curl/tests/formdata @@ -0,0 +1 @@ +hello diff --git a/vendor/curl/tests/multi.rs b/vendor/curl/tests/multi.rs new file mode 100644 index 000000000..0c5e70150 --- /dev/null +++ b/vendor/curl/tests/multi.rs @@ -0,0 +1,297 @@ +#![cfg(unix)] + +use std::collections::HashMap; +use std::io::{Cursor, Read}; +use std::time::Duration; + +use curl::easy::{Easy, List}; +use curl::multi::Multi; + +macro_rules! t { + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; +} + +use crate::server::Server; +mod server; + +#[test] +fn smoke() { + let m = Multi::new(); + let mut e = Easy::new(); + + let s = Server::new(); + s.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + t!(e.url(&s.url("/"))); + let _e = t!(m.add(e)); + while t!(m.perform()) > 0 { + t!(m.wait(&mut [], Duration::from_secs(1))); + } +} + +#[test] +fn smoke2() { + let m = Multi::new(); + + let s1 = Server::new(); + s1.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s1.send("HTTP/1.1 200 OK\r\n\r\n"); + + let s2 = Server::new(); + s2.receive( + "\ + GET / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + \r\n", + ); + s2.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut e1 = Easy::new(); + t!(e1.url(&s1.url("/"))); + let _e1 = t!(m.add(e1)); + let mut e2 = Easy::new(); + t!(e2.url(&s2.url("/"))); + let _e2 = t!(m.add(e2)); + + while t!(m.perform()) > 0 { + t!(m.wait(&mut [], Duration::from_secs(1))); + } + + let mut done = 0; + m.messages(|msg| { + msg.result().unwrap().unwrap(); + done += 1; + }); + assert_eq!(done, 2); +} + +#[test] +fn upload_lots() { + use curl::multi::{Events, Socket, SocketEvents}; + + #[derive(Debug)] + enum Message { + Timeout(Option<Duration>), + Wait(Socket, SocketEvents, usize), + } + + let mut m = Multi::new(); + let poll = t!(mio::Poll::new()); + let (tx, rx) = mio_extras::channel::channel(); + let tx2 = tx.clone(); + t!(m.socket_function(move |socket, events, token| { + t!(tx2.send(Message::Wait(socket, events, token))); + })); + t!(m.timer_function(move |dur| { + t!(tx.send(Message::Timeout(dur))); + true + })); + + let s = Server::new(); + s.receive(&format!( + "\ + PUT / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: 131072\r\n\ + \r\n\ + {}\n", + vec!["a"; 128 * 1024 - 1].join("") + )); + s.send( + "\ + HTTP/1.1 200 OK\r\n\ + \r\n", + ); + + let mut data = vec![b'a'; 128 * 1024 - 1]; + data.push(b'\n'); + let mut data = Cursor::new(data); + let mut list = List::new(); + t!(list.append("Expect:")); + let mut h = Easy::new(); + t!(h.url(&s.url("/"))); + t!(h.put(true)); + t!(h.read_function(move |buf| Ok(data.read(buf).unwrap()))); + t!(h.in_filesize(128 * 1024)); + t!(h.upload(true)); + t!(h.http_headers(list)); + + t!(poll.register(&rx, mio::Token(0), mio::Ready::all(), mio::PollOpt::level())); + + let e = t!(m.add(h)); + + assert!(t!(m.perform()) > 0); + let mut next_token = 1; + let mut token_map = HashMap::new(); + let mut cur_timeout = None; + let mut events = mio::Events::with_capacity(128); + let mut running = true; + + while running { + let n = t!(poll.poll(&mut events, cur_timeout)); + + if n == 0 && t!(m.timeout()) == 0 { + running = false; + } + + for event in events.iter() { + while event.token() == mio::Token(0) { + match rx.try_recv() { + Ok(Message::Timeout(dur)) => cur_timeout = dur, + Ok(Message::Wait(socket, events, token)) => { + let evented = mio::unix::EventedFd(&socket); + if events.remove() { + token_map.remove(&token).unwrap(); + } else { + let mut e = mio::Ready::empty(); + if events.input() { + e |= mio::Ready::readable(); + } + if events.output() { + e |= mio::Ready::writable(); + } + if token == 0 { + let token = next_token; + next_token += 1; + t!(m.assign(socket, token)); + token_map.insert(token, socket); + t!(poll.register( + &evented, + mio::Token(token), + e, + mio::PollOpt::level() + )); + } else { + t!(poll.reregister( + &evented, + mio::Token(token), + e, + mio::PollOpt::level() + )); + } + } + } + Err(_) => break, + } + } + + if event.token() == mio::Token(0) { + continue; + } + + let token = event.token(); + let socket = token_map[&token.into()]; + let mut e = Events::new(); + if event.readiness().is_readable() { + e.input(true); + } + if event.readiness().is_writable() { + e.output(true); + } + if mio::unix::UnixReady::from(event.readiness()).is_error() { + e.error(true); + } + let remaining = t!(m.action(socket, &e)); + if remaining == 0 { + running = false; + } + } + } + + let mut done = 0; + m.messages(|m| { + m.result().unwrap().unwrap(); + done += 1; + }); + assert_eq!(done, 1); + + let mut e = t!(m.remove(e)); + assert_eq!(t!(e.response_code()), 200); +} + +// Tests passing raw file descriptors to Multi::wait. The test is limited to Linux only as the +// semantics of the underlying poll(2) system call used by curl apparently differ on other +// platforms, making the test fail. +#[cfg(target_os = "linux")] +#[test] +fn waitfds() { + use curl::multi::WaitFd; + use std::fs::File; + use std::os::unix::io::AsRawFd; + + let filenames = ["/dev/null", "/dev/zero", "/dev/urandom"]; + let files: Vec<File> = filenames + .iter() + .map(|filename| File::open(filename).unwrap()) + .collect(); + let mut waitfds: Vec<WaitFd> = files + .iter() + .map(|f| { + let mut waitfd = WaitFd::new(); + waitfd.set_fd(f.as_raw_fd()); + waitfd.poll_on_read(true); + waitfd + }) + .collect(); + + let m = Multi::new(); + let events = t!(m.wait(&mut waitfds, Duration::from_secs(1))); + assert_eq!(events, 3); + for waitfd in waitfds { + assert!(waitfd.received_read()); + } +} + +// Tests passing raw file descriptors to Multi::wait. The test is limited to Linux only as the +// semantics of the underlying poll(2) system call used by curl apparently differ on other +// platforms, making the test fail. +#[cfg(feature = "poll_7_68_0")] +#[cfg(target_os = "linux")] +#[test] +fn pollfds() { + use curl::multi::WaitFd; + use std::fs::File; + use std::os::unix::io::AsRawFd; + + let filenames = ["/dev/null", "/dev/zero", "/dev/urandom"]; + let files: Vec<File> = filenames + .iter() + .map(|filename| File::open(filename).unwrap()) + .collect(); + let mut waitfds: Vec<WaitFd> = files + .iter() + .map(|f| { + let mut waitfd = WaitFd::new(); + waitfd.set_fd(f.as_raw_fd()); + waitfd.poll_on_read(true); + waitfd + }) + .collect(); + + let m = Multi::new(); + let events = t!(m.poll(&mut waitfds, Duration::from_secs(1))); + assert_eq!(events, 3); + for waitfd in waitfds { + assert!(waitfd.received_read()); + } +} diff --git a/vendor/curl/tests/post.rs b/vendor/curl/tests/post.rs new file mode 100644 index 000000000..15e2df7d3 --- /dev/null +++ b/vendor/curl/tests/post.rs @@ -0,0 +1,118 @@ +use std::time::Duration; + +macro_rules! t { + ($e:expr) => { + match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + } + }; +} + +use curl::easy::{Easy, Form, List}; + +use crate::server::Server; +mod server; + +fn handle() -> Easy { + let mut e = Easy::new(); + t!(e.timeout(Duration::new(20, 0))); + let mut list = List::new(); + t!(list.append("Expect:")); + t!(e.http_headers(list)); + e +} + +#[test] +fn custom() { + let s = Server::new(); + s.receive( + "\ + POST / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: 142\r\n\ + Content-Type: multipart/form-data; boundary=--[..]\r\n\ + \r\n\ + --[..]\r\n\ + Content-Disposition: form-data; name=\"foo\"\r\n\ + \r\n\ + 1234\r\n\ + --[..]\r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut handle = handle(); + let mut form = Form::new(); + t!(form.part("foo").contents(b"1234").add()); + t!(handle.url(&s.url("/"))); + t!(handle.httppost(form)); + t!(handle.perform()); +} + +#[test] +fn buffer() { + let s = Server::new(); + s.receive( + "\ + POST / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: 181\r\n\ + Content-Type: multipart/form-data; boundary=--[..]\r\n\ + \r\n\ + --[..]\r\n\ + Content-Disposition: form-data; name=\"foo\"; filename=\"bar\"\r\n\ + Content-Type: foo/bar\r\n\ + \r\n\ + 1234\r\n\ + --[..]\r\n", + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut handle = handle(); + let mut form = Form::new(); + t!(form + .part("foo") + .buffer("bar", b"1234".to_vec()) + .content_type("foo/bar") + .add()); + t!(handle.url(&s.url("/"))); + t!(handle.httppost(form)); + t!(handle.perform()); +} + +#[test] +fn file() { + let s = Server::new(); + let formdata = include_str!("formdata"); + s.receive( + format!( + "\ + POST / HTTP/1.1\r\n\ + Host: 127.0.0.1:$PORT\r\n\ + Accept: */*\r\n\ + Content-Length: {}\r\n\ + Content-Type: multipart/form-data; boundary=--[..]\r\n\ + \r\n\ + --[..]\r\n\ + Content-Disposition: form-data; name=\"foo\"; filename=\"formdata\"\r\n\ + Content-Type: application/octet-stream\r\n\ + \r\n\ + {}\ + \r\n\ + --[..]\r\n", + 199 + formdata.len(), + formdata + ) + .as_str(), + ); + s.send("HTTP/1.1 200 OK\r\n\r\n"); + + let mut handle = handle(); + let mut form = Form::new(); + t!(form.part("foo").file("tests/formdata").add()); + t!(handle.url(&s.url("/"))); + t!(handle.httppost(form)); + t!(handle.perform()); +} diff --git a/vendor/curl/tests/protocols.rs b/vendor/curl/tests/protocols.rs new file mode 100644 index 000000000..7215fe972 --- /dev/null +++ b/vendor/curl/tests/protocols.rs @@ -0,0 +1,19 @@ +#[cfg(all(feature = "static-curl", not(feature = "protocol-ftp")))] +#[test] +fn static_with_ftp_disabled() { + assert!(curl::Version::get() + .protocols() + .filter(|&p| p == "ftp") + .next() + .is_none()); +} + +#[cfg(all(feature = "static-curl", feature = "protocol-ftp"))] +#[test] +fn static_with_ftp_enabled() { + assert!(curl::Version::get() + .protocols() + .filter(|&p| p == "ftp") + .next() + .is_some()); +} diff --git a/vendor/curl/tests/server/mod.rs b/vendor/curl/tests/server/mod.rs new file mode 100644 index 000000000..a474a1aa8 --- /dev/null +++ b/vendor/curl/tests/server/mod.rs @@ -0,0 +1,223 @@ +#![allow(dead_code)] + +use std::collections::HashSet; +use std::io::prelude::*; +use std::io::BufReader; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::path::PathBuf; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::thread; + +pub struct Server { + messages: Option<Sender<Message>>, + addr: Addr, + thread: Option<thread::JoinHandle<()>>, +} + +enum Message { + Read(String), + Write(String), +} + +enum Addr { + Tcp(SocketAddr), + Unix(PathBuf), +} + +fn run(stream: impl Read + Write, rx: &Receiver<Message>) { + let mut socket = BufReader::new(stream); + for msg in rx.iter() { + match msg { + Message::Read(ref expected) => { + let mut expected = &expected[..]; + let mut expected_headers = HashSet::new(); + while let Some(i) = expected.find('\n') { + let line = &expected[..i + 1]; + expected = &expected[i + 1..]; + expected_headers.insert(line); + if line == "\r\n" { + break; + } + } + + let mut expected_len = None; + while !expected_headers.is_empty() { + let mut actual = String::new(); + t!(socket.read_line(&mut actual)); + if actual.starts_with("Content-Length") { + let len = actual.split(": ").nth(1).unwrap(); + expected_len = len.trim().parse().ok(); + } + // various versions of libcurl do different things here + if actual == "Proxy-Connection: Keep-Alive\r\n" { + continue; + } + if expected_headers.remove(&actual[..]) { + continue; + } + + let mut found = None; + for header in expected_headers.iter() { + if lines_match(header, &actual) { + found = Some(header.clone()); + break; + } + } + if let Some(found) = found { + expected_headers.remove(&found); + continue; + } + panic!( + "unexpected header: {:?} (remaining headers {:?})", + actual, expected_headers + ); + } + for header in expected_headers { + panic!("expected header but not found: {:?}", header); + } + + let mut line = String::new(); + let mut socket = match expected_len { + Some(amt) => socket.by_ref().take(amt), + None => socket.by_ref().take(expected.len() as u64), + }; + while socket.limit() > 0 { + line.truncate(0); + t!(socket.read_line(&mut line)); + if line.is_empty() { + break; + } + if expected.is_empty() { + panic!("unexpected line: {:?}", line); + } + let i = expected.find('\n').unwrap_or(expected.len() - 1); + let expected_line = &expected[..i + 1]; + expected = &expected[i + 1..]; + if lines_match(expected_line, &line) { + continue; + } + panic!( + "lines didn't match:\n\ + expected: {:?}\n\ + actual: {:?}\n", + expected_line, line + ) + } + if !expected.is_empty() { + println!("didn't get expected data: {:?}", expected); + } + } + Message::Write(ref to_write) => { + t!(socket.get_mut().write_all(to_write.as_bytes())); + return; + } + } + } + + let mut dst = Vec::new(); + t!(socket.read_to_end(&mut dst)); + assert_eq!(dst.len(), 0); +} + +fn lines_match(expected: &str, mut actual: &str) -> bool { + for (i, part) in expected.split("[..]").enumerate() { + match actual.find(part) { + Some(j) => { + if i == 0 && j != 0 { + return false; + } + actual = &actual[j + part.len()..]; + } + None => return false, + } + } + actual.is_empty() || expected.ends_with("[..]") +} + +impl Server { + pub fn new() -> Server { + let listener = t!(TcpListener::bind("127.0.0.1:0")); + let addr = t!(listener.local_addr()); + let (tx, rx) = channel(); + let thread = thread::spawn(move || run(listener.accept().unwrap().0, &rx)); + Server { + messages: Some(tx), + addr: Addr::Tcp(addr), + thread: Some(thread), + } + } + + #[cfg(not(windows))] + pub fn new_unix() -> Server { + use std::os::unix::net::UnixListener; + + let path = "/tmp/easy_server.sock"; + std::fs::remove_file(path).ok(); + let listener = t!(UnixListener::bind(path)); + let (tx, rx) = channel(); + let thread = thread::spawn(move || run(listener.incoming().next().unwrap().unwrap(), &rx)); + Server { + messages: Some(tx), + addr: Addr::Unix(path.into()), + thread: Some(thread), + } + } + + pub fn receive(&self, msg: &str) { + self.msg(Message::Read(self.replace_port(msg))); + } + + fn replace_port(&self, msg: &str) -> String { + match &self.addr { + Addr::Tcp(addr) => msg.replace("$PORT", &addr.port().to_string()), + Addr::Unix(_) => msg.to_string(), + } + } + + pub fn send(&self, msg: &str) { + self.msg(Message::Write(self.replace_port(msg))); + } + + fn msg(&self, msg: Message) { + t!(self.messages.as_ref().unwrap().send(msg)); + } + + pub fn addr(&self) -> &SocketAddr { + match &self.addr { + Addr::Tcp(addr) => addr, + Addr::Unix(_) => panic!("server is a UnixListener"), + } + } + + #[cfg(not(windows))] + pub fn path(&self) -> &str { + match &self.addr { + Addr::Tcp(_) => panic!("server is a TcpListener"), + Addr::Unix(p) => p.as_os_str().to_str().unwrap(), + } + } + + pub fn url(&self, path: &str) -> String { + match &self.addr { + Addr::Tcp(addr) => format!("http://{}{}", addr, path), + Addr::Unix(_) => format!("http://localhost{}", path), + } + } +} + +impl Drop for Server { + fn drop(&mut self) { + match &self.addr { + Addr::Tcp(addr) => drop(TcpStream::connect(addr)), + Addr::Unix(p) => t!(std::fs::remove_file(p)), + } + + drop(self.messages.take()); + let res = self.thread.take().unwrap().join(); + if !thread::panicking() { + t!(res); + } else if let Err(e) = res { + println!("child server thread also failed: {:?}", e); + } + } +} |