Skip to main content

cpanel_rs/
client.rs

1use crate::CpanelError;
2use reqwest::{
3    header::{HeaderMap, HeaderName},
4    Client,
5};
6use std::{
7    future::Future,
8    sync::Arc,
9    time::{Duration, Instant},
10};
11
12/// Authentication method used by the cPanel / WHM client.
13///
14/// - [`Password`] — Standard Basic auth. Works for both cPanel UAPI and WHM JSON API.
15/// - [`Key`] — WHM raw access key auth (`WHM user:key`). Requires a raw key generated
16///   in WHM > **Manage Remote Access Key**.
17/// - [`Token`] — cPanel API Token auth (`Authorization: cpanel <user>:<token>`).
18///   Grants granular, scoped permissions without requiring a full account password
19///   or root access. Generate tokens in cPanel > **Home > Security Center > API Tokens**.
20///
21/// [`Password`]: AuthMethod::Password
22/// [`Key`]: AuthMethod::Key
23/// [`Token`]: AuthMethod::Token
24#[derive(Debug, Clone)]
25pub enum AuthMethod {
26    /// Password-based authentication.
27    Password {
28        /// The account username.
29        username: String,
30        /// The account password.
31        password: String,
32    },
33    /// WHM raw key authentication.
34    Key {
35        /// The WHM root username (usually `"root"`).
36        username: String,
37        /// The raw access key string.
38        key: String,
39    },
40    /// cPanel API Token authentication.
41    Token {
42        /// The cPanel account username.
43        username: String,
44        /// The API token string (not the hashed/keyified version).
45        token: String,
46    },
47}
48
49/// Configuration for automatic retry on transient failures.
50///
51/// When enabled, each API call will be retried up to `max_retries` times with
52/// exponential backoff when the server returns a 429 (rate limit) or 503
53/// (unavailable) status, or when a connection error occurs.
54///
55/// # Example
56///
57/// ```
58/// use cpanel_rs::RetryPolicy;
59///
60/// let policy = RetryPolicy::default()
61///     .max_retries(3)
62///     .base_delay(std::time::Duration::from_millis(100));
63/// ```
64#[derive(Debug, Clone)]
65pub struct RetryPolicy {
66    /// Maximum number of retry attempts (default: 3).
67    pub max_retries: u32,
68    /// Base delay between retries in milliseconds (default: 250).
69    pub base_delay_ms: u64,
70    /// Whether to jitter the delay to avoid thundering herd (default: true).
71    pub jitter: bool,
72}
73
74impl Default for RetryPolicy {
75    fn default() -> Self {
76        Self {
77            max_retries: 3,
78            base_delay_ms: 250,
79            jitter: true,
80        }
81    }
82}
83
84impl RetryPolicy {
85    /// Sets the maximum number of retries.
86    pub fn max_retries(mut self, n: u32) -> Self {
87        self.max_retries = n;
88        self
89    }
90
91    /// Sets the base delay.
92    pub fn base_delay(mut self, delay: Duration) -> Self {
93        self.base_delay_ms = delay.as_millis() as u64;
94        self
95    }
96
97    /// Enables or disables jitter on retry delays.
98    pub fn jitter(mut self, enabled: bool) -> Self {
99        self.jitter = enabled;
100        self
101    }
102
103    /// Computes the delay for a given retry attempt using exponential backoff.
104    pub(crate) fn delay(&self, attempt: u32) -> Duration {
105        let exp = 2u64.checked_pow(attempt).unwrap_or(u64::MAX);
106        let mut delay = self.base_delay_ms.saturating_mul(exp);
107        if self.jitter {
108            use rand::Rng;
109            let jitter: u64 = rand::thread_rng().gen_range(0..delay.max(1));
110            delay = delay.saturating_add(jitter);
111        }
112        Duration::from_millis(delay)
113    }
114
115    /// Returns `true` if the error indicates a transient condition worth retrying.
116    pub(crate) fn is_retryable(&self, err: &CpanelError) -> bool {
117        match err {
118            CpanelError::Http(e) => matches!(
119                e.status(),
120                Some(reqwest::StatusCode::TOO_MANY_REQUESTS)
121                    | Some(reqwest::StatusCode::SERVICE_UNAVAILABLE)
122                    | Some(reqwest::StatusCode::BAD_GATEWAY)
123                    | Some(reqwest::StatusCode::GATEWAY_TIMEOUT)
124            ),
125            _ => false,
126        }
127    }
128}
129
130/// The cPanel & WHM API client.
131///
132/// This is the main entry point of the crate. It provides typed wrappers around
133/// both the **UAPI** (user-level, port 2083) and **WHM JSON API** (admin-level,
134/// port 2087) endpoints.
135///
136/// # Constructing a Client
137///
138/// ```
139/// use cpanel_rs::CpanelClient;
140///
141/// // Simple: host, port, username, password
142/// let client = CpanelClient::simple("server.example.com", 2087, "root", "mypass").unwrap();
143///
144/// // Or with the builder for timeouts, TLS options, etc.
145/// use cpanel_rs::CpanelBuilder;
146/// let client = CpanelBuilder::new("server.example.com", 2087, "root")
147///     .password("mypass")
148///     .timeout(std::time::Duration::from_secs(30))
149///     .build()
150///     .unwrap();
151/// ```
152///
153/// # Port Conventions
154///
155/// | Service | Default Port | Protocol |
156/// |---------|-------------|----------|
157/// | cPanel UAPI | `2083` | HTTPS (auto-detected) |
158/// | WHM JSON API | `2087` | HTTPS (auto-detected) |
159///
160/// Any other port will use plain HTTP unless you explicitly configure it.
161#[derive(Debug, Clone)]
162pub struct CpanelClient {
163    host: String,
164    port: u16,
165    use_ssl: bool,
166    username: String,
167    auth: AuthMethod,
168    http_client: Client,
169    additional_headers: HeaderMap,
170    retry_policy: Arc<RetryPolicy>,
171}
172
173impl CpanelClient {
174    /// Creates a new client with explicit connection parameters.
175    ///
176    /// Pass **either** `password` or `key` — both cannot be set at the same time.
177    ///
178    /// # Arguments
179    ///
180    /// * `host` — Server hostname or IP address.
181    /// * `port` — API port (e.g. `2083` for cPanel, `2087` for WHM).
182    /// * `username` — The cPanel/WHM account username.
183    /// * `password` — The account password, or `None` if using key auth.
184    /// * `key` — A WHM raw access key, or `None` if using password auth.
185    /// * `use_ssl` — Set to `true` for HTTPS, `false` for HTTP.
186    pub fn new(
187        host: &str,
188        port: u16,
189        username: &str,
190        password: Option<&str>,
191        key: Option<&str>,
192        use_ssl: bool,
193    ) -> Result<Self, CpanelError> {
194        let auth = match (password, key) {
195            (Some(p), None) => AuthMethod::Password {
196                username: username.to_string(),
197                password: p.to_string(),
198            },
199            (None, Some(k)) => AuthMethod::Key {
200                username: username.to_string(),
201                key: k.to_string(),
202            },
203            (Some(_), Some(_)) => {
204                return Err(CpanelError::Auth(
205                    "Cannot specify both password and key; choose one".into(),
206                ))
207            }
208            (None, None) => {
209                return Err(CpanelError::Auth(
210                    "Must provide either password or key".into(),
211                ))
212            }
213        };
214
215        let http_client = Client::builder().build().map_err(CpanelError::Http)?;
216
217        Ok(CpanelClient {
218            host: host.to_string(),
219            port,
220            use_ssl,
221            username: username.to_string(),
222            auth,
223            http_client,
224            additional_headers: HeaderMap::new(),
225            retry_policy: Arc::new(RetryPolicy::default()),
226        })
227    }
228
229    /// Convenience constructor for password-only auth with auto-detected SSL.
230    ///
231    /// Uses HTTPS for ports 2083/2087, HTTP otherwise.
232    pub fn simple(
233        host: &str,
234        port: u16,
235        username: &str,
236        password: &str,
237    ) -> Result<Self, CpanelError> {
238        Self::new(
239            host,
240            port,
241            username,
242            Some(password),
243            None,
244            port == 2083 || port == 2087,
245        )
246    }
247
248    /// Creates a client using a pre-built [`reqwest::Client`].
249    pub fn with_client(
250        host: &str,
251        port: u16,
252        username: &str,
253        password: &str,
254        client: Client,
255    ) -> Self {
256        Self {
257            host: host.to_string(),
258            port,
259            use_ssl: port == 2083 || port == 2087,
260            username: username.to_string(),
261            auth: AuthMethod::Password {
262                username: username.to_string(),
263                password: password.to_string(),
264            },
265            http_client: client,
266            additional_headers: HeaderMap::new(),
267            retry_policy: Arc::new(RetryPolicy::default()),
268        }
269    }
270
271    /// Returns the server hostname or IP address.
272    pub fn host(&self) -> &str {
273        &self.host
274    }
275
276    /// Returns the API port number.
277    pub fn port(&self) -> u16 {
278        self.port
279    }
280
281    /// Returns the configured username.
282    pub fn username(&self) -> &str {
283        &self.username
284    }
285
286    /// Returns the full base URL (e.g. `https://server.example.com:2087`).
287    pub fn base_url(&self) -> String {
288        let scheme = if self.use_ssl { "https" } else { "http" };
289        format!("{}://{}:{}", scheme, self.host, self.port)
290    }
291
292    /// Creates a client from environment variables.
293    ///
294    /// Requires the `dotenv` feature to be enabled.
295    #[cfg(feature = "dotenv")]
296    pub fn from_env() -> Result<Self, CpanelError> {
297        dotenv::dotenv().ok();
298        let host = std::env::var("CPANEL_HOST")
299            .map_err(|_| CpanelError::Auth("CPANEL_HOST not set".into()))?;
300        let port: u16 = std::env::var("CPANEL_PORT")
301            .map_err(|_| CpanelError::Auth("CPANEL_PORT not set".into()))
302            .and_then(|s| {
303                s.parse()
304                    .map_err(|_| CpanelError::Auth("CPANEL_PORT must be a number".into()))
305            })?;
306        let username = std::env::var("CPANEL_USER")
307            .map_err(|_| CpanelError::Auth("CPANEL_USER not set".into()))?;
308        let password = std::env::var("CPANEL_PASSWORD")
309            .map_err(|_| CpanelError::Auth("CPANEL_PASSWORD not set".into()))?;
310        Self::new(&host, port, &username, Some(&password), None, true)
311    }
312
313    /// Sets the retry policy for this client.
314    ///
315    /// When enabled, transient errors (429, 503, connection failures) will be
316    /// retried up to [`RetryPolicy::max_retries`] times with exponential backoff.
317    ///
318    /// # Example
319    ///
320    /// ```
321    /// use cpanel_rs::{CpanelClient, RetryPolicy};
322    ///
323    /// let client = CpanelClient::simple("server.example.com", 2087, "root", "pass").unwrap();
324    /// let client = client.with_retry_policy(
325    ///     RetryPolicy::default()
326    ///         .max_retries(5)
327    ///         .base_delay(std::time::Duration::from_millis(500)),
328    /// );
329    /// ```
330    pub fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
331        self.retry_policy = Arc::new(policy);
332        self
333    }
334
335    /// Returns the current retry policy.
336    pub fn retry_policy(&self) -> &RetryPolicy {
337        &self.retry_policy
338    }
339
340    /// Returns an auto-paginating async stream over all WHM accounts.
341    ///
342    /// Requires the `stream` feature. Each item is a [`AccountInfo`](crate::models::AccountInfo).
343    /// The stream fetches pages of 50 accounts at a time until exhaustion.
344    ///
345    /// # Example
346    ///
347    /// ```no_run
348    /// use cpanel_rs::CpanelClient;
349    /// use futures::StreamExt;
350    ///
351    /// #[tokio::main]
352    /// async fn main() -> Result<(), cpanel_rs::CpanelError> {
353    ///     let client = CpanelClient::simple("server.example.com", 2087, "root", "pass").unwrap();
354    ///     let mut stream = client.stream_accounts();
355    ///     while let Some(acct) = stream.next().await {
356    ///         let acct = acct?;
357    ///         println!("{} @ {}", acct.username, acct.domain);
358    ///     }
359    ///     Ok(())
360    /// }
361    /// ```
362    #[cfg(feature = "stream")]
363    pub fn stream_accounts(&self) -> crate::streams::AccountsStream {
364        crate::streams::AccountsStream::new(self)
365    }
366
367    /// Returns an async stream over file entries in a directory.
368    ///
369    /// Requires the `stream` feature. Each item is a
370    /// [`FileManagerEntry`](crate::models::FileManagerEntry).
371    ///
372    /// # Example
373    ///
374    /// ```no_run
375    /// use cpanel_rs::CpanelClient;
376    /// use futures::StreamExt;
377    ///
378    /// #[tokio::main]
379    /// async fn main() -> Result<(), cpanel_rs::CpanelError> {
380    ///     let client = CpanelClient::simple("server.example.com", 2083, "user", "pass").unwrap();
381    ///     let mut stream = client.stream_files("user", "/public_html");
382    ///     while let Some(entry) = stream.next().await {
383    ///         let entry = entry?;
384    ///         println!("{} ({})", entry.name, entry.type_);
385    ///     }
386    ///     Ok(())
387    /// }
388    /// ```
389    #[cfg(feature = "stream")]
390    pub fn stream_files(&self, user: &str, path: &str) -> crate::streams::FilesStream {
391        crate::streams::FilesStream::new(self, user, path)
392    }
393
394    /// Sends a raw UAPI request and returns the deserialized response.
395    pub async fn uapi<D: for<'de> serde::Deserialize<'de>>(
396        &self,
397        module: &str,
398        func: &str,
399        params: &[(&str, &str)],
400    ) -> Result<D, CpanelError> {
401        let result = self.send_uapi(module, func, params).await?;
402        let call = format!("{}.{}", module, func);
403
404        if let Some(ref errors) = result.errors {
405            let failure = crate::types::ApiFailure {
406                call: call.clone(),
407                errors: errors.clone(),
408                messages: result.messages.clone().unwrap_or_default(),
409                result_code: result.metadata.as_ref().and_then(|m| m.result),
410                reason: result.metadata.as_ref().and_then(|m| m.reason.clone()),
411                ..Default::default()
412            };
413            if !failure.has_errors() {
414                return Err(CpanelError::ApiWarning(failure));
415            }
416            return Err(CpanelError::ApiError(failure));
417        }
418
419        if let Some(ref warnings) = result.messages {
420            if !warnings.is_empty() {
421                let failure = crate::types::ApiFailure {
422                    call,
423                    warnings: warnings.clone(),
424                    result_code: result.metadata.as_ref().and_then(|m| m.result),
425                    reason: result.metadata.as_ref().and_then(|m| m.reason.clone()),
426                    ..Default::default()
427                };
428                return Err(CpanelError::ApiWarning(failure));
429            }
430        }
431
432        result
433            .data
434            .ok_or_else(|| CpanelError::InvalidResponse("No data in UAPI response".into()))
435    }
436
437    /// Sends a raw WHM API request and returns the deserialized response.
438    pub async fn whm<D: for<'de> serde::Deserialize<'de>>(
439        &self,
440        function: &str,
441        params: &[(&str, &str)],
442    ) -> Result<D, CpanelError> {
443        let result = self.send_whm(function, params).await?;
444        let call = format!("whm.{}", function);
445
446        if result.status != 1 {
447            let failure = crate::types::ApiFailure {
448                call: call.clone(),
449                message: result
450                    .errors
451                    .as_ref()
452                    .and_then(|e| e.first().cloned())
453                    .unwrap_or_else(|| result.metadata.reason.clone().unwrap_or_default()),
454                errors: result.errors.unwrap_or_default(),
455                messages: result.messages.unwrap_or_default(),
456                whm_result: Some(result.metadata.result),
457                whm_status: Some(result.metadata.status),
458                reason: result.metadata.reason.clone(),
459                ..Default::default()
460            };
461            return Err(CpanelError::ApiError(failure));
462        }
463
464        if let Some(ref warnings) = result.messages {
465            if !warnings.is_empty() {
466                let failure = crate::types::ApiFailure {
467                    call,
468                    warnings: warnings.clone(),
469                    whm_result: Some(result.metadata.result),
470                    whm_status: Some(result.metadata.status),
471                    reason: result.metadata.reason.clone(),
472                    ..Default::default()
473                };
474                return Err(CpanelError::ApiWarning(failure));
475            }
476        }
477
478        result
479            .data
480            .ok_or_else(|| CpanelError::InvalidResponse("No data in WHM response".into()))
481    }
482
483    // ── Internal helpers ──────────────────────────────────────────────────────
484
485    fn build_url(&self, path: &str) -> String {
486        let scheme = if self.use_ssl { "https" } else { "http" };
487        format!("{}://{}:{}{}", scheme, self.host, self.port, path)
488    }
489
490    pub(crate) fn auth_headers(&self) -> HeaderMap {
491        use base64::engine::{general_purpose::STANDARD, Engine};
492        let mut headers = self.additional_headers.clone();
493
494        match &self.auth {
495            AuthMethod::Password { username, password } => {
496                let cred = STANDARD.encode(format!("{}:{}", username, password));
497                headers.insert(
498                    reqwest::header::AUTHORIZATION,
499                    format!("Basic {}", cred).parse().unwrap(),
500                );
501            }
502            AuthMethod::Key { username, key } => {
503                headers.insert(
504                    reqwest::header::AUTHORIZATION,
505                    format!("WHM {}:{}", username, key).parse().unwrap(),
506                );
507            }
508            AuthMethod::Token { username, token } => {
509                headers.insert(
510                    reqwest::header::AUTHORIZATION,
511                    format!("cpanel {}:{}", username, token).parse().unwrap(),
512                );
513            }
514        }
515
516        headers
517    }
518
519    pub(crate) fn http_client(&self) -> &Client {
520        &self.http_client
521    }
522
523    async fn do_request(&self, url: String) -> Result<(reqwest::StatusCode, String), CpanelError> {
524        #[cfg(feature = "tracing")]
525        let start = Instant::now();
526        #[cfg(feature = "tracing")]
527        tracing::debug!(url = %url, "sending request");
528        let resp = self
529            .http_client
530            .get(&url)
531            .headers(self.auth_headers())
532            .send()
533            .await?;
534        let status = resp.status();
535        let body = resp.text().await?;
536        #[cfg(feature = "tracing")]
537        tracing::debug!(
538            status = ?status,
539            latency_ms = %start.elapsed().as_millis(),
540            "request completed"
541        );
542        Ok((status, body))
543    }
544
545    async fn send_with_retry<F, Fut, R>(&self, request_fn: F) -> Result<R, CpanelError>
546    where
547        F: Fn() -> Fut,
548        Fut: Future<Output = Result<R, CpanelError>>,
549    {
550        let policy = self.retry_policy.clone();
551        let mut attempt = 0u32;
552
553        loop {
554            match request_fn().await {
555                Ok(val) => return Ok(val),
556                Err(e) if attempt < policy.max_retries && policy.is_retryable(&e) => {
557                    #[cfg(feature = "tracing")]
558                    tracing::warn!(
559                        attempt,
560                        max_retries = policy.max_retries,
561                        error = ?e,
562                        "retrying after transient error"
563                    );
564                    tokio::time::sleep(policy.delay(attempt)).await;
565                    attempt += 1;
566                }
567                Err(e) => return Err(e),
568            }
569        }
570    }
571
572    async fn send_uapi<T: for<'de> serde::Deserialize<'de>>(
573        &self,
574        module: &str,
575        func: &str,
576        params: &[(&str, &str)],
577    ) -> Result<crate::types::UapiResult<T>, CpanelError> {
578        let mut url = self.build_url(&format!(
579            "/json-api/{}?cpanel_jsonapi_module={}&cpanel_jsonapi_apiversion=2&cpanel_jsonapi_func={}",
580            self.username, module, func
581        ));
582        for (k, v) in params {
583            url.push_str(&format!("&{}={}", k, urlencoding::encode(v)));
584        }
585
586        let (status, body) = self
587            .send_with_retry(|| {
588                let url = url.clone();
589                async move { self.do_request(url).await }
590            })
591            .await?;
592
593        if status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS {
594            return Err(CpanelError::ApiError(crate::types::ApiFailure {
595                message: format!("HTTP {}", status),
596                call: format!("{}.{}", module, func),
597                ..Default::default()
598            }));
599        }
600
601        let api_resp: crate::types::ApiResponse<crate::types::UapiResult<T>> =
602            serde_json::from_str(&body).map_err(CpanelError::Serialization)?;
603
604        if !api_resp.is_ok() {
605            return Err(CpanelError::ApiError(crate::types::ApiFailure {
606                message: api_resp.status_msg,
607                call: format!("{}.{}", module, func),
608                ..Default::default()
609            }));
610        }
611
612        api_resp
613            .data
614            .ok_or_else(|| CpanelError::InvalidResponse("No data".into()))
615    }
616
617    async fn send_whm<T: for<'de> serde::Deserialize<'de>>(
618        &self,
619        function: &str,
620        params: &[(&str, &str)],
621    ) -> Result<crate::types::WhmApiResponse<T>, CpanelError> {
622        let mut url = self.build_url(&format!(
623            "/json-api/whmapi1?api.version=1&function={}",
624            function
625        ));
626        for (k, v) in params {
627            url.push_str(&format!("&{}={}", k, urlencoding::encode(v)));
628        }
629
630        let (status, body) = self
631            .send_with_retry(|| {
632                let url = url.clone();
633                async move { self.do_request(url).await }
634            })
635            .await?;
636
637        if status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS {
638            return Err(CpanelError::ApiError(crate::types::ApiFailure {
639                message: format!("HTTP {}", status),
640                call: format!("whm.{}", function),
641                ..Default::default()
642            }));
643        }
644
645        let api_resp: crate::types::ApiResponse<crate::types::WhmApiResponse<T>> =
646            serde_json::from_str(&body).map_err(CpanelError::Serialization)?;
647
648        if !api_resp.is_ok() {
649            return Err(CpanelError::ApiError(crate::types::ApiFailure {
650                message: api_resp.status_msg,
651                call: format!("whm.{}", function),
652                ..Default::default()
653            }));
654        }
655
656        api_resp
657            .data
658            .ok_or_else(|| CpanelError::InvalidResponse("No data".into()))
659    }
660}
661
662/// Builder for constructing a [`CpanelClient`] with full control over connection settings.
663///
664/// # Example
665///
666/// ```no_run
667/// use cpanel_rs::CpanelBuilder;
668///
669/// let client = CpanelBuilder::new("server.example.com", 2087, "root")
670///     .password("secret")
671///     .timeout(std::time::Duration::from_secs(30))
672///     .disable_tls_verification()
673///     .header("X-Request-ID", "abc-123")
674///     .build()
675///     .unwrap();
676/// ```
677#[derive(Debug, Clone)]
678pub struct CpanelBuilder {
679    host: String,
680    port: u16,
681    username: String,
682    auth: AuthMethod,
683    timeout: Option<Duration>,
684    disable_tls_verify: bool,
685    additional_headers: Vec<(String, String)>,
686}
687
688impl CpanelBuilder {
689    /// Creates a new builder.
690    ///
691    /// After calling `new()`, chain either [`Self::password`], [`Self::key`], or [`Self::token`]
692    /// before calling [`Self::build`].
693    pub fn new(host: &str, port: u16, username: &str) -> Self {
694        Self {
695            host: host.to_string(),
696            port,
697            username: username.to_string(),
698            auth: AuthMethod::Password {
699                username: username.to_string(),
700                password: String::new(),
701            },
702            timeout: None,
703            disable_tls_verify: false,
704            additional_headers: Vec::new(),
705        }
706    }
707
708    /// Sets password-based authentication.
709    pub fn password(mut self, password: &str) -> Self {
710        self.auth = AuthMethod::Password {
711            username: self.username.clone(),
712            password: password.to_string(),
713        };
714        self
715    }
716
717    /// Sets WHM raw key authentication.
718    pub fn key(mut self, key: &str) -> Self {
719        self.auth = AuthMethod::Key {
720            username: self.username.clone(),
721            key: key.to_string(),
722        };
723        self
724    }
725
726    /// Sets cPanel API Token authentication.
727    ///
728    /// Generate tokens in cPanel > **Home > Security Center > API Tokens**.
729    /// The raw/unhashed token string must be passed here.
730    pub fn token(mut self, token: &str) -> Self {
731        self.auth = AuthMethod::Token {
732            username: self.username.clone(),
733            token: token.to_string(),
734        };
735        self
736    }
737
738    /// Sets the HTTP request timeout.
739    pub fn timeout(mut self, timeout: Duration) -> Self {
740        self.timeout = Some(timeout);
741        self
742    }
743
744    /// Disables TLS certificate and hostname verification.
745    ///
746    /// **Only** use this when connecting to servers with self-signed certificates.
747    pub fn disable_tls_verification(mut self) -> Self {
748        self.disable_tls_verify = true;
749        self
750    }
751
752    /// Adds a custom HTTP header to every request.
753    pub fn header(mut self, key: &str, value: &str) -> Self {
754        self.additional_headers
755            .push((key.to_string(), value.to_string()));
756        self
757    }
758
759    /// Builds the [`CpanelClient`].
760    pub fn build(self) -> Result<CpanelClient, CpanelError> {
761        let use_ssl = self.port == 2083 || self.port == 2087;
762
763        let http_client = {
764            let mut builder = Client::builder();
765            if let Some(to) = self.timeout {
766                builder = builder.timeout(to);
767            }
768            if self.disable_tls_verify {
769                builder = builder.danger_accept_invalid_certs(true);
770            }
771            builder.build().map_err(CpanelError::Http)?
772        };
773
774        let mut additional_headers = HeaderMap::new();
775        for (k, v) in self.additional_headers {
776            let name: HeaderName = k.parse().unwrap();
777            let value: reqwest::header::HeaderValue = v.parse().unwrap();
778            additional_headers.insert(name, value);
779        }
780
781        Ok(CpanelClient {
782            host: self.host,
783            port: self.port,
784            use_ssl,
785            username: self.username,
786            auth: self.auth,
787            http_client,
788            additional_headers,
789            retry_policy: Arc::new(RetryPolicy::default()),
790        })
791    }
792}
793
794pub use crate::types::{
795    ApiFailure, ApiResponse, CpanelResult, Metadata, StackFrame, UapiResult, WhmApiResponse,
796    WhmMetadata,
797};