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#[derive(Debug, Clone)]
25pub enum AuthMethod {
26 Password {
28 username: String,
30 password: String,
32 },
33 Key {
35 username: String,
37 key: String,
39 },
40 Token {
42 username: String,
44 token: String,
46 },
47}
48
49#[derive(Debug, Clone)]
65pub struct RetryPolicy {
66 pub max_retries: u32,
68 pub base_delay_ms: u64,
70 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 pub fn max_retries(mut self, n: u32) -> Self {
87 self.max_retries = n;
88 self
89 }
90
91 pub fn base_delay(mut self, delay: Duration) -> Self {
93 self.base_delay_ms = delay.as_millis() as u64;
94 self
95 }
96
97 pub fn jitter(mut self, enabled: bool) -> Self {
99 self.jitter = enabled;
100 self
101 }
102
103 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 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#[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 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 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 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 pub fn host(&self) -> &str {
273 &self.host
274 }
275
276 pub fn port(&self) -> u16 {
278 self.port
279 }
280
281 pub fn username(&self) -> &str {
283 &self.username
284 }
285
286 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 #[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 pub fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
331 self.retry_policy = Arc::new(policy);
332 self
333 }
334
335 pub fn retry_policy(&self) -> &RetryPolicy {
337 &self.retry_policy
338 }
339
340 #[cfg(feature = "stream")]
363 pub fn stream_accounts(&self) -> crate::streams::AccountsStream {
364 crate::streams::AccountsStream::new(self)
365 }
366
367 #[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 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 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 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#[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 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 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 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 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 pub fn timeout(mut self, timeout: Duration) -> Self {
740 self.timeout = Some(timeout);
741 self
742 }
743
744 pub fn disable_tls_verification(mut self) -> Self {
748 self.disable_tls_verify = true;
749 self
750 }
751
752 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 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};