1use std::fmt::{Debug, Formatter};
4use std::fs::OpenOptions;
5use std::io::Write;
6use std::path::{Path, PathBuf};
7
8use crate::{MDB_CLIENT_ERROR_CONTEXT, get_config_path};
9use malwaredb_api::{
10 GetAPIKeyResponse, GetUserInfoResponse, Labels, PartialHashSearchType, Report, SearchRequest,
11 SearchRequestParameters, SearchResponse, SearchType, ServerInfo, ServerResponse,
12 SimilarSamplesResponse, Sources, SupportedFileTypes, YaraSearchRequest,
13 YaraSearchRequestResponse, YaraSearchResponse, digest::HashType,
14};
15use malwaredb_types::exec::pe32::EXE;
16
17use anyhow::{Context, Result, bail, ensure};
18use base64::Engine;
19use base64::engine::general_purpose;
20use fuzzyhash::FuzzyHash;
21use malwaredb_lzjd2::lzjd::LzDigest;
22use serde::{Deserialize, Serialize};
23use sha2::{Digest, Sha256};
24use tlsh_fixed::TlshBuilder;
25use tracing::{error, info, trace, warn};
26use uuid::Uuid;
27use zeroize::{Zeroize, ZeroizeOnDrop};
28
29#[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
31#[derive(Deserialize, Serialize, Zeroize, ZeroizeOnDrop)]
32pub struct MdbClient {
33 pub url: String,
35
36 api_key: String,
38
39 #[zeroize(skip)]
41 #[serde(skip)]
42 client: reqwest::blocking::Client,
43
44 #[cfg(target_os = "macos")]
46 #[zeroize(skip)]
47 #[serde(skip)]
48 cert: Option<crate::macos::CertificateData>,
49}
50
51impl MdbClient {
52 pub fn new(url: String, api_key: String, cert_path: Option<PathBuf>) -> Result<Self> {
63 let mut url = url;
64 let url = if url.ends_with('/') {
65 url.pop();
66 url
67 } else {
68 url
69 };
70
71 let cert = if let Some(path) = cert_path {
72 Some((crate::path_load_cert(&path)?, path))
73 } else {
74 None
75 };
76
77 let builder = reqwest::blocking::ClientBuilder::new()
78 .deflate(true)
79 .gzip(true)
80 .zstd(true)
81 .use_rustls_tls()
82 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
83
84 let client = if let Some(((_cert_type, cert), _path)) = &cert {
85 builder.add_root_certificate(cert.clone()).build()
86 } else {
87 builder.build()
88 }?;
89
90 #[cfg(target_os = "macos")]
91 let cert = if let Some(((cert_type, _cert), cert_path)) = &cert {
92 Some(crate::macos::CertificateData {
93 cert_type: *cert_type,
94 cert_bytes: std::fs::read(cert_path)?,
95 })
96 } else {
97 None
98 };
99
100 Ok(Self {
101 url,
102 api_key,
103 client,
104
105 #[cfg(target_os = "macos")]
106 cert,
107 })
108 }
109
110 pub fn anonymous(url: String, save: bool, cert_path: Option<PathBuf>) -> Result<Self> {
116 let mut url = url;
117 let url = if url.ends_with('/') {
118 url.pop();
119 url
120 } else {
121 url
122 };
123
124 let builder = reqwest::blocking::ClientBuilder::new()
125 .gzip(true)
126 .zstd(true)
127 .use_rustls_tls()
128 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
129
130 let cert = if let Some(path) = cert_path {
131 Some((crate::path_load_cert(&path)?, path))
132 } else {
133 None
134 };
135
136 let client = if let Some(((_cert_type, cert), _cert_path)) = &cert {
137 builder.add_root_certificate(cert.clone()).build()
138 } else {
139 builder.build()
140 }?;
141
142 let info = client
143 .get(format!("{url}{}", malwaredb_api::USER_INFO_URL))
144 .send()?
145 .json::<ServerResponse<GetUserInfoResponse>>()
146 .context(MDB_CLIENT_ERROR_CONTEXT)?;
147
148 if let ServerResponse::Success(info) = info {
149 ensure!(info.id > 0);
150 } else {
151 bail!("Anonymous access is not allowed");
152 }
153
154 #[cfg(target_os = "macos")]
155 let cert = if let Some(((cert_type, _cert), cert_path)) = &cert {
156 Some(crate::macos::CertificateData {
157 cert_type: *cert_type,
158 cert_bytes: std::fs::read(cert_path)?,
159 })
160 } else {
161 None
162 };
163
164 let client = Self {
165 url,
166 api_key: "anonymous".to_string(),
167 client,
168
169 #[cfg(target_os = "macos")]
170 cert,
171 };
172
173 let server_info = client.server_info()?;
174 if server_info.mdb_version > *crate::MDB_VERSION_SEMVER {
175 warn!(
176 "Server version {:?} is newer than client {:?}, consider updating.",
177 server_info.mdb_version,
178 crate::MDB_VERSION_SEMVER
179 );
180 }
181
182 if save && let Err(e) = client.save() {
183 error!("Anonymous connection successful but failed to save config: {e}");
184 bail!("Anonymous connection successful but failed to save config: {e}");
185 }
186
187 Ok(client)
188 }
189
190 pub fn login(
201 url: String,
202 username: String,
203 password: String,
204 save: bool,
205 cert_path: Option<PathBuf>,
206 ) -> Result<Self> {
207 let mut url = url;
208 let url = if url.ends_with('/') {
209 url.pop();
210 url
211 } else {
212 url
213 };
214
215 let api_request = malwaredb_api::GetAPIKeyRequest {
216 user: username,
217 password,
218 };
219
220 let builder = reqwest::blocking::ClientBuilder::new()
221 .gzip(true)
222 .zstd(true)
223 .use_rustls_tls()
224 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
225
226 let cert = if let Some(path) = cert_path {
227 Some((crate::path_load_cert(&path)?, path))
228 } else {
229 None
230 };
231
232 let client = if let Some(((_cert_type, cert), _path)) = &cert {
233 builder.add_root_certificate(cert.clone()).build()
234 } else {
235 builder.build()
236 }?;
237
238 let res = client
239 .post(format!("{url}{}", malwaredb_api::USER_LOGIN_URL))
240 .json(&api_request)
241 .send()?
242 .json::<ServerResponse<GetAPIKeyResponse>>()
243 .context(MDB_CLIENT_ERROR_CONTEXT)?;
244
245 let res = match res {
246 ServerResponse::Success(res) => res,
247 ServerResponse::Error(err) => return Err(err.into()),
248 };
249
250 #[cfg(target_os = "macos")]
251 let cert = if let Some(((cert_type, _cert), cert_path)) = &cert {
252 Some(crate::macos::CertificateData {
253 cert_type: *cert_type,
254 cert_bytes: std::fs::read(cert_path)?,
255 })
256 } else {
257 None
258 };
259
260 let client = MdbClient {
261 url,
262 api_key: res.key.clone(),
263 client,
264
265 #[cfg(target_os = "macos")]
266 cert,
267 };
268
269 let server_info = client.server_info()?;
270 if server_info.mdb_version > *crate::MDB_VERSION_SEMVER {
271 warn!(
272 "Server version {:?} is newer than client {:?}, consider updating.",
273 server_info.mdb_version,
274 crate::MDB_VERSION_SEMVER
275 );
276 }
277
278 if save && let Err(e) = client.save() {
279 error!("Login successful but failed to save config: {e}");
280 bail!("Login successful but failed to save config: {e}");
281 }
282 Ok(client)
283 }
284
285 pub fn reset_key(&self) -> Result<()> {
291 let response = self
292 .client
293 .get(format!("{}{}", self.url, malwaredb_api::USER_LOGOUT_URL))
294 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
295 .send()
296 .context(MDB_CLIENT_ERROR_CONTEXT)?;
297 if !response.status().is_success() {
298 bail!("failed to reset API key, was it correct?");
299 }
300 Ok(())
301 }
302
303 pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
310 let name = path.as_ref().display();
311 let config =
312 std::fs::read_to_string(&path).context(format!("failed to read config file {name}"))?;
313 let cfg: MdbClient =
314 toml::from_str(&config).context(format!("failed to parse config file {name}"))?;
315 Ok(cfg)
316 }
317
318 pub fn load() -> Result<Self> {
331 #[cfg(target_os = "macos")]
332 {
333 if let Ok((api_key, url, cert)) = crate::macos::retrieve_credentials() {
334 let builder = reqwest::blocking::ClientBuilder::new()
335 .gzip(true)
336 .zstd(true)
337 .use_rustls_tls()
338 .user_agent(concat!("mdb_client/", env!("CARGO_PKG_VERSION")));
339
340 let client = if let Some(cert) = &cert {
341 builder.add_root_certificate(cert.as_cert()?).build()
342 } else {
343 builder.build()
344 }?;
345
346 return Ok(Self {
347 url,
348 api_key,
349 client,
350 cert,
351 });
352 }
353 }
354
355 let path = get_config_path(false)?;
356 if path.exists() {
357 return Self::from_file(path);
358 }
359 bail!("config file not found")
360 }
361
362 pub fn save(&self) -> Result<()> {
370 #[cfg(target_os = "macos")]
371 {
372 if crate::macos::save_credentials(&self.url, &self.api_key, self.cert.clone()).is_ok() {
373 return Ok(());
374 }
375 }
376
377 let toml = toml::to_string(self)?;
378 let path = get_config_path(true)?;
379
380 let mut options = OpenOptions::new();
381 options
382 .write(true)
383 .create(true)
384 .append(false)
385 .truncate(false);
386
387 #[cfg(target_family = "unix")]
388 {
389 use std::os::unix::fs::OpenOptionsExt;
390
391 options.mode(0o600);
392 }
393
394 let mut file = options.open(&path)?;
395 write!(file, "{toml}").context(format!("failed to write mdb config to {}", path.display()))
396 }
397
398 pub fn delete(&self) -> Result<()> {
405 #[cfg(target_os = "macos")]
406 crate::macos::clear_credentials();
407
408 let path = get_config_path(false)?;
409 if path.exists() {
410 std::fs::remove_file(&path)
411 .context(format!("failed to delete client config file {}", path.display()))?;
412 }
413 Ok(())
414 }
415
416 pub fn server_info(&self) -> Result<ServerInfo> {
424 let response = self
425 .client
426 .get(format!("{}{}", self.url, malwaredb_api::SERVER_INFO_URL))
427 .send()?
428 .json::<ServerResponse<ServerInfo>>()
429 .context(MDB_CLIENT_ERROR_CONTEXT)?;
430
431 match response {
432 ServerResponse::Success(info) => Ok(info),
433 ServerResponse::Error(e) => Err(e.into()),
434 }
435 }
436
437 pub fn supported_types(&self) -> Result<SupportedFileTypes> {
443 let response = self
444 .client
445 .get(format!("{}{}", self.url, malwaredb_api::SUPPORTED_FILE_TYPES_URL))
446 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
447 .send()?
448 .json::<ServerResponse<SupportedFileTypes>>()
449 .context(MDB_CLIENT_ERROR_CONTEXT)?;
450
451 match response {
452 ServerResponse::Success(types) => Ok(types),
453 ServerResponse::Error(e) => Err(e.into()),
454 }
455 }
456
457 pub fn whoami(&self) -> Result<GetUserInfoResponse> {
464 let response = self
465 .client
466 .get(format!("{}{}", self.url, malwaredb_api::USER_INFO_URL))
467 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
468 .send()?
469 .json::<ServerResponse<GetUserInfoResponse>>()
470 .context(MDB_CLIENT_ERROR_CONTEXT)?;
471
472 match response {
473 ServerResponse::Success(info) => Ok(info),
474 ServerResponse::Error(e) => Err(e.into()),
475 }
476 }
477
478 pub fn labels(&self) -> Result<Labels> {
485 let response = self
486 .client
487 .get(format!("{}{}", self.url, malwaredb_api::LIST_LABELS_URL))
488 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
489 .send()?
490 .json::<ServerResponse<Labels>>()
491 .context(MDB_CLIENT_ERROR_CONTEXT)?;
492
493 match response {
494 ServerResponse::Success(labels) => Ok(labels),
495 ServerResponse::Error(e) => Err(e.into()),
496 }
497 }
498
499 pub fn sources(&self) -> Result<Sources> {
506 let response = self
507 .client
508 .get(format!("{}{}", self.url, malwaredb_api::LIST_SOURCES_URL))
509 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
510 .send()?
511 .json::<ServerResponse<Sources>>()
512 .context(MDB_CLIENT_ERROR_CONTEXT)?;
513
514 match response {
515 ServerResponse::Success(sources) => Ok(sources),
516 ServerResponse::Error(e) => Err(e.into()),
517 }
518 }
519
520 pub fn submit(
527 &self,
528 contents: impl AsRef<[u8]>,
529 file_name: String,
530 source_id: u32,
531 ) -> Result<bool> {
532 let mut hasher = Sha256::new();
533 hasher.update(&contents);
534 let result = hasher.finalize();
535
536 let encoded = general_purpose::STANDARD.encode(contents);
537
538 let payload = malwaredb_api::NewSampleB64 {
539 file_name,
540 source_id,
541 file_contents_b64: encoded,
542 sha256: hex::encode(result),
543 };
544
545 match self
546 .client
547 .post(format!("{}{}", self.url, malwaredb_api::UPLOAD_SAMPLE_JSON_URL))
548 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
549 .json(&payload)
550 .send()
551 {
552 Ok(res) => {
553 if !res.status().is_success() {
554 info!("Code {} sending {}", res.status(), payload.file_name);
555 }
556 Ok(res.status().is_success())
557 }
558 Err(e) => {
559 let status: String = e
560 .status()
561 .map(|s| s.as_str().to_string())
562 .unwrap_or_default();
563 error!("Error{status} sending {}: {e}", payload.file_name);
564 bail!(e.to_string())
565 }
566 }
567 }
568
569 pub fn submit_as_cbor(
577 &self,
578 contents: impl AsRef<[u8]>,
579 file_name: String,
580 source_id: u32,
581 ) -> Result<bool> {
582 let mut hasher = Sha256::new();
583 hasher.update(&contents);
584 let result = hasher.finalize();
585
586 let payload = malwaredb_api::NewSampleBytes {
587 file_name,
588 source_id,
589 file_contents: contents.as_ref().to_vec(),
590 sha256: hex::encode(result),
591 };
592
593 let mut bytes = Vec::with_capacity(payload.file_contents.len());
594 ciborium::ser::into_writer(&payload, &mut bytes)?;
595
596 match self
597 .client
598 .post(format!("{}{}", self.url, malwaredb_api::UPLOAD_SAMPLE_CBOR_URL))
599 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
600 .header("content-type", "application/cbor")
601 .body(bytes)
602 .send()
603 {
604 Ok(res) => {
605 if !res.status().is_success() {
606 info!("Code {} sending {}", res.status(), payload.file_name);
607 }
608 Ok(res.status().is_success())
609 }
610 Err(e) => {
611 let status: String = e
612 .status()
613 .map(|s| s.as_str().to_string())
614 .unwrap_or_default();
615 error!("Error{status} sending {}: {e}", payload.file_name);
616 bail!(e.to_string())
617 }
618 }
619 }
620
621 pub fn partial_search(
627 &self,
628 partial_hash: Option<(PartialHashSearchType, String)>,
629 name: Option<String>,
630 response: PartialHashSearchType,
631 limit: u32,
632 ) -> Result<SearchResponse> {
633 let query = SearchRequest {
634 search: SearchType::Search(SearchRequestParameters {
635 partial_hash,
636 file_name: name,
637 response,
638 limit,
639 labels: None,
640 file_type: None,
641 magic: None,
642 }),
643 };
644
645 self.do_search_request(&query)
646 }
647
648 #[allow(clippy::too_many_arguments)]
654 pub fn partial_search_labels_type(
655 &self,
656 partial_hash: Option<(PartialHashSearchType, String)>,
657 name: Option<String>,
658 response: PartialHashSearchType,
659 labels: Option<Vec<String>>,
660 file_type: Option<String>,
661 magic: Option<String>,
662 limit: u32,
663 ) -> Result<SearchResponse> {
664 let query = SearchRequest {
665 search: SearchType::Search(SearchRequestParameters {
666 partial_hash,
667 file_name: name,
668 response,
669 limit,
670 file_type,
671 magic,
672 labels,
673 }),
674 };
675
676 self.do_search_request(&query)
677 }
678
679 pub fn next_page_search(&self, response: &SearchResponse) -> Result<SearchResponse> {
685 if let Some(uuid) = response.pagination {
686 let request = SearchRequest {
687 search: SearchType::Continuation(uuid),
688 };
689 return self.do_search_request(&request);
690 }
691
692 bail!("Pagination not available")
693 }
694
695 fn do_search_request(&self, query: &SearchRequest) -> Result<SearchResponse> {
696 ensure!(
697 query.is_valid(),
698 "Query isn't valid: hash isn't hexidecimal or both the hashes and file name are empty"
699 );
700
701 let response = self
702 .client
703 .post(format!("{}{}", self.url, malwaredb_api::SEARCH_URL))
704 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
705 .json(query)
706 .send()?
707 .json::<ServerResponse<SearchResponse>>()
708 .context(MDB_CLIENT_ERROR_CONTEXT)?;
709
710 match response {
711 ServerResponse::Success(search) => Ok(search),
712 ServerResponse::Error(e) => Err(e.into()),
713 }
714 }
715
716 pub fn retrieve(&self, hash: &str, cart: bool) -> Result<Vec<u8>> {
723 let api_endpoint = if cart {
724 format!("{}{hash}", malwaredb_api::DOWNLOAD_SAMPLE_CART_URL)
725 } else {
726 format!("{}{hash}", malwaredb_api::DOWNLOAD_SAMPLE_URL)
727 };
728
729 let res = self
730 .client
731 .get(format!("{}{api_endpoint}", self.url))
732 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
733 .send()?;
734
735 if !res.status().is_success() {
736 bail!("Received code {}", res.status());
737 }
738
739 let content_digest = res.headers().get("content-digest").map(ToOwned::to_owned);
740 let body = res.bytes()?;
741 let bytes = body.to_vec();
742
743 if let Some(digest) = content_digest {
745 let hash = HashType::from_content_digest_header(digest.to_str()?)?;
746 if hash.verify(&bytes) {
747 trace!("Hash verified for sample {hash}");
748 } else {
749 error!("Hash mismatch for sample {hash}");
750 }
751 } else {
752 warn!("No content digest header received for sample {hash}");
753 }
754
755 Ok(bytes)
756 }
757
758 pub fn report(&self, hash: &str) -> Result<Report> {
765 let response = self
766 .client
767 .get(format!("{}{}/{hash}", self.url, malwaredb_api::SAMPLE_REPORT_URL))
768 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
769 .send()?
770 .json::<ServerResponse<Report>>()
771 .context(MDB_CLIENT_ERROR_CONTEXT)?;
772
773 match response {
774 ServerResponse::Success(report) => Ok(report),
775 ServerResponse::Error(e) => Err(e.into()),
776 }
777 }
778
779 pub fn similar(&self, contents: &[u8]) -> Result<SimilarSamplesResponse> {
787 let mut hashes = vec![];
788 let ssdeep_hash = FuzzyHash::new(contents);
789
790 let lzjd_str = LzDigest::from(contents).to_string();
791 hashes.push((malwaredb_api::SimilarityHashType::LZJD, lzjd_str));
792 hashes.push((malwaredb_api::SimilarityHashType::SSDeep, ssdeep_hash.to_string()));
793
794 let mut builder = TlshBuilder::new(
795 tlsh_fixed::BucketKind::Bucket256,
796 tlsh_fixed::ChecksumKind::ThreeByte,
797 tlsh_fixed::Version::Version4,
798 );
799
800 builder.update(contents);
801 if let Ok(hasher) = builder.build() {
802 hashes.push((malwaredb_api::SimilarityHashType::TLSH, hasher.hash()));
803 }
804
805 if let Ok(exe) = EXE::from(contents)
806 && let Some(imports) = exe.imports
807 {
808 hashes
809 .push((malwaredb_api::SimilarityHashType::ImportHash, hex::encode(imports.hash())));
810 hashes.push((malwaredb_api::SimilarityHashType::FuzzyImportHash, imports.fuzzy_hash()));
811 }
812
813 let request = malwaredb_api::SimilarSamplesRequest { hashes };
814
815 let response = self
816 .client
817 .post(format!("{}{}", self.url, malwaredb_api::SIMILAR_SAMPLES_URL))
818 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
819 .json(&request)
820 .send()?
821 .json::<ServerResponse<SimilarSamplesResponse>>()
822 .context(MDB_CLIENT_ERROR_CONTEXT)?;
823
824 match response {
825 ServerResponse::Success(similar) => Ok(similar),
826 ServerResponse::Error(e) => Err(e.into()),
827 }
828 }
829
830 pub fn yara_search(&self, yara: &str) -> Result<YaraSearchRequestResponse> {
836 let yara = YaraSearchRequest {
837 rules: vec![yara.to_string()],
838 response: PartialHashSearchType::SHA256,
839 };
840
841 let response = self
842 .client
843 .post(format!("{}{}", self.url, malwaredb_api::YARA_SEARCH_URL))
844 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
845 .json(&yara)
846 .send()?
847 .json::<ServerResponse<YaraSearchRequestResponse>>()?;
848
849 match response {
850 ServerResponse::Success(similar) => Ok(similar),
851 ServerResponse::Error(e) => Err(e.into()),
852 }
853 }
854
855 pub fn yara_result(&self, uuid: Uuid) -> Result<YaraSearchResponse> {
861 let response = self
862 .client
863 .get(format!("{}{}/{uuid}", self.url, malwaredb_api::YARA_SEARCH_URL))
864 .header(malwaredb_api::MDB_API_HEADER, &self.api_key)
865 .send()?
866 .json::<ServerResponse<YaraSearchResponse>>()?;
867
868 match response {
869 ServerResponse::Success(sources) => Ok(sources),
870 ServerResponse::Error(e) => Err(e.into()),
871 }
872 }
873}
874
875impl Debug for MdbClient {
876 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
877 use crate::MDB_VERSION;
878
879 writeln!(f, "MDB Client v{MDB_VERSION}: {}", self.url)
880 }
881}
882
883#[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
898pub struct IterableHashSearchResult<'a> {
899 pub response: SearchResponse,
901
902 client: &'a MdbClient,
904}
905
906impl<'a> IterableHashSearchResult<'a> {
907 #[must_use]
909 pub fn from(response: SearchResponse, client: &'a MdbClient) -> Self {
910 Self { response, client }
911 }
912}
913
914impl Iterator for IterableHashSearchResult<'_> {
915 type Item = String;
916
917 fn next(&mut self) -> Option<Self::Item> {
918 if let Some(hash) = self.response.hashes.pop() {
919 Some(hash)
920 } else if let Some(uuid) = self.response.pagination {
921 let request = SearchRequest {
922 search: SearchType::Continuation(uuid),
923 };
924
925 self.response = match self.client.do_search_request(&request) {
926 Ok(response) => response,
927 Err(e) => {
928 warn!("Failed to continue search: {e}");
929 return None;
930 }
931 };
932
933 self.response.hashes.pop()
934 } else {
935 None
936 }
937 }
938}
939
940#[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
942pub struct IterableSampleSearchResult<'a> {
943 pub response: SearchResponse,
945
946 client: &'a MdbClient,
948}
949
950impl<'a> IterableSampleSearchResult<'a> {
951 #[must_use]
953 pub fn from(response: SearchResponse, client: &'a MdbClient) -> Self {
954 Self { response, client }
955 }
956}
957
958impl Iterator for IterableSampleSearchResult<'_> {
959 type Item = Vec<u8>;
960
961 fn next(&mut self) -> Option<Self::Item> {
962 if let Some(hash) = self.response.hashes.pop() {
963 let binary = match self.client.retrieve(&hash, false) {
964 Ok(binary) => binary,
965 Err(e) => {
966 error!("Failed to download {hash}: {e}");
967 return None;
968 }
969 };
970 Some(binary)
971 } else if let Some(uuid) = self.response.pagination {
972 let request = SearchRequest {
973 search: SearchType::Continuation(uuid),
974 };
975
976 self.response = match self.client.do_search_request(&request) {
977 Ok(response) => response,
978 Err(e) => {
979 warn!("Failed to continue search: {e}");
980 return None;
981 }
982 };
983
984 if let Some(hash) = self.response.hashes.pop() {
985 let binary = match self.client.retrieve(&hash, false) {
986 Ok(binary) => binary,
987 Err(e) => {
988 error!("Failed to download {hash}: {e}");
989 return None;
990 }
991 };
992 Some(binary)
993 } else {
994 None
995 }
996 } else {
997 None
998 }
999 }
1000}