use std::io::Error as IOError;
use std::io::Read;
pub mod bulk_get_file;
pub mod http_error;
#[cfg(test)]
#[allow(dead_code)]
pub(crate) mod mock_constants;
pub mod structures;
pub use bulk_get_file::{format_get_file_error_message, get_file_json_indicates_error};
pub(crate) fn check_key_text(api_key: &str) -> ZBResult<()> {
if api_key != api_key.trim() || api_key.chars().any(|c| c.is_control()) {
return Err(ZBError::explicit(
"api_key has surrounding whitespace or control characters",
));
}
Ok(())
}
pub(crate) fn redacted_key(api_key: &str) -> &'static str {
if api_key.is_empty() {
""
} else {
"***"
}
}
pub const CONTENT_TYPE_JSON: &str = "application/json";
pub const CONTENT_TYPE_STREAM: &str = "application/octet-stream";
pub const MAX_JSON_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
pub const MAX_GETFILE_BYTES: usize = 256 * 1024 * 1024;
pub(crate) fn read_limited(
mut reader: impl Read,
max_bytes: usize,
message: &str,
) -> ZBResult<Vec<u8>> {
let mut body = Vec::new();
reader.by_ref().take(max_bytes as u64 + 1).read_to_end(&mut body)?;
if body.len() > max_bytes {
return Err(ZBError::explicit(message));
}
Ok(body)
}
#[cfg(test)]
mod response_limit_tests {
use super::read_limited;
use std::io::{self, Read};
struct CountingReader {
remaining: usize,
read: usize,
}
impl Read for CountingReader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = buf.len().min(self.remaining);
buf[..n].fill(b'x');
self.remaining -= n;
self.read += n;
Ok(n)
}
}
#[test]
fn stops_at_one_byte_past_limit() {
let mut source = CountingReader {
remaining: 10_000,
read: 0,
};
let error = read_limited(&mut source, 32, "too large").unwrap_err();
assert_eq!(error.to_string(), "too large");
assert_eq!(source.read, 33);
}
#[test]
fn accepts_body_at_limit() {
let body = read_limited(&b"exact"[..], 5, "too large").unwrap();
assert_eq!(body, b"exact");
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ApiBaseUrl {
Default,
USA,
EU,
}
impl ApiBaseUrl {
pub fn as_str(&self) -> &'static str {
match self {
ApiBaseUrl::Default => "https://api.zerobounce.net/v2/",
ApiBaseUrl::USA => "https://api-us.zerobounce.net/v2/",
ApiBaseUrl::EU => "https://api-eu.zerobounce.net/v2/",
}
}
}
impl From<ApiBaseUrl> for String {
fn from(url: ApiBaseUrl) -> Self {
url.as_str().to_string()
}
}
impl From<&ApiBaseUrl> for String {
fn from(url: &ApiBaseUrl) -> Self {
url.as_str().to_string()
}
}
pub fn encode_path_segment(value: &str) -> String {
let mut encoded = String::with_capacity(value.len());
for byte in value.as_bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
encoded.push(*byte as char)
}
_ => encoded.push_str(&format!("%{:02X}", byte)),
}
}
encoded
}
pub const BULK_URI: &str = "https://bulkapi.zerobounce.net/v2";
pub const LIST_EVALUATOR_URI: &str = "https://bulkapi.zerobounce.net/v2/listevaluator";
pub const INBOX_PLACEMENT_URI: &str = "https://bulkapi.zerobounce.net/api/ipt";
pub const ENDPOINT_CREDITS: &str = "/getcredits";
pub const ENDPOINT_ACTIVITY_DATA: &str = "/activity";
pub const ENDPOINT_SCORING: &str = "/scoring";
pub const ENDPOINT_VALIDATE: &str = "/validate";
pub const ENDPOINT_API_USAGE: &str = "/getapiusage";
pub const ENDPOINT_BATCH_VALIDATE: &str = "/validatebatch";
pub const ENDPOINT_FILE_SEND: &str = "/sendfile";
pub const ENDPOINT_FILE_STATUS: &str = "/filestatus";
pub const ENDPOINT_FILE_RESULT: &str = "/getfile";
pub const ENDPOINT_FILE_DELETE: &str = "/deletefile";
pub const ENDPOINT_SCORING_SEND: &str = "/scoring/sendfile";
pub const ENDPOINT_SCORING_STATUS: &str = "/scoring/filestatus";
pub const ENDPOINT_SCORING_RESULT: &str = "/scoring/getfile";
pub const ENDPOINT_SCORING_DELETE: &str = "/scoring/deletefile";
pub const ENDPOINT_EMAIL_FINDER: &str = "/guessformat";
pub const S_VALID: &str = "valid";
pub const S_INVALID: &str = "invalid";
pub const S_CATCH_ALL: &str = "catch-all";
pub const S_UNKNOWN: &str = "unknown";
pub const S_SPAMTRAP: &str = "spamtrap";
pub const S_ABUSE: &str = "abuse";
pub const S_DO_NOT_MAIL: &str = "do_not_mail";
pub const SS_ANTISPAM_SYSTEM: &str = "antispam_system";
pub const SS_GREYLISTED: &str = "greylisted";
pub const SS_MAIL_SERVER_TEMPORARY_ERROR: &str = "mail_server_temporary_error";
pub const SS_FORCIBLE_DISCONNECT: &str = "forcible_disconnect";
pub const SS_MAIL_SERVER_DID_NOT_RESPOND: &str = "mail_server_did_not_respond";
pub const SS_TIMEOUT_EXCEEDED: &str = "timeout_exceeded";
pub const SS_FAILED_SMTP_CONNECTION: &str = "failed_smtp_connection";
pub const SS_MAILBOX_QUOTA_EXCEEDED: &str = "mailbox_quota_exceeded";
pub const SS_EXCEPTION_OCCURRED: &str = "exception_occurred";
pub const SS_POSSIBLE_TRAP: &str = "possible_trap";
pub const SS_ROLE_BASED: &str = "role_based";
pub const SS_GLOBAL_SUPPRESSION: &str = "global_suppression";
pub const SS_MAILBOX_NOT_FOUND: &str = "mailbox_not_found";
pub const SS_NO_DNS_ENTRIES: &str = "no_dns_entries";
pub const SS_FAILED_SYNTAX_CHECK: &str = "failed_syntax_check";
pub const SS_POSSIBLE_TYPO: &str = "possible_typo";
pub const SS_UNROUTABLE_IP_ADDRESS: &str = "unroutable_ip_address";
pub const SS_LEADING_PERIOD_REMOVED: &str = "leading_period_removed";
pub const SS_DOES_NOT_ACCEPT_MAIL: &str = "does_not_accept_mail";
pub const SS_ALIAS_ADDRESS: &str = "alias_address";
pub const SS_ROLE_BASED_CATCH_ALL: &str = "role_based_catch_all";
pub const SS_DISPOSABLE: &str = "disposable";
pub const SS_TOXIC: &str = "toxic";
pub const SS_ACCEPT_ALL: &str = "accept_all";
pub const SS_AI_AGENT_MAILBOX: &str = "ai_agent_mailbox";
#[derive(Debug)]
#[non_exhaustive]
pub enum ZBError {
ExplicitError(String),
ApiError { status: u16, message: String },
JsonError(serde_json::Error),
IntParseError(std::num::ParseIntError),
RequestError(reqwest::Error),
IOError(IOError),
}
pub type ZBResult<T> = Result<T, ZBError>;
impl ZBError {
pub fn explicit(string: &str) -> ZBError {
ZBError::ExplicitError(string.to_string())
}
pub fn api(status: u16, message: impl Into<String>) -> ZBError {
ZBError::ApiError {
status,
message: message.into(),
}
}
pub fn status_code(&self) -> Option<u16> {
match self {
ZBError::ApiError { status, .. } => Some(*status),
_ => None,
}
}
}
impl std::fmt::Display for ZBError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ZBError::ExplicitError(message) => write!(formatter, "{message}"),
ZBError::ApiError { message, .. } => write!(formatter, "{message}"),
ZBError::JsonError(_) => {
write!(
formatter,
"ZeroBounce returned a response that is not valid JSON."
)
}
ZBError::IntParseError(_) => write!(
formatter,
"ZeroBounce returned a response that could not be read."
),
ZBError::RequestError(error) => write!(formatter, "{error}"),
ZBError::IOError(error) => write!(formatter, "{error}"),
}
}
}
impl std::error::Error for ZBError {}
fn redact_api_key(url: &mut reqwest::Url) {
if !url.query_pairs().any(|(key, _)| key == "api_key") {
return;
}
let pairs: Vec<(String, String)> = url
.query_pairs()
.map(|(key, value)| {
let value = if key == "api_key" {
"REDACTED".to_string()
} else {
value.into_owned()
};
(key.into_owned(), value)
})
.collect();
url.query_pairs_mut().clear().extend_pairs(pairs);
}
impl From<reqwest::Error> for ZBError {
fn from(mut value: reqwest::Error) -> ZBError {
if let Some(url) = value.url_mut() {
redact_api_key(url);
}
ZBError::RequestError(value)
}
}
impl From<serde_json::Error> for ZBError {
fn from(value: serde_json::Error) -> ZBError {
ZBError::JsonError(value)
}
}
impl From<IOError> for ZBError {
fn from(value: IOError) -> Self {
ZBError::IOError(value)
}
}