1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use reqwest::{self};
use serde::{de::DeserializeOwned, Deserialize};
use simple_error;
use std::collections::HashMap;
use std::error::Error;
use std::net::IpAddr;

/// Summary Raw Struct
#[derive(Deserialize, Debug)]
pub struct SummaryRaw {
    /// Number of domains being blocked
    pub domains_being_blocked: u64,

    /// Number of DNS queries today
    pub dns_queries_today: u64,

    /// Number of Ads blocked today
    pub ads_blocked_today: u64,

    /// Percentage of queries blocked today
    pub ads_percentage_today: f64,

    /// Number of unique domains
    pub unique_domains: u64,

    /// Number of queries forwarded
    pub queries_forwarded: u64,

    /// Number of queries cached
    pub queries_cached: u64,

    /// Number of clients ever seen
    pub clients_ever_seen: u64,

    /// Number of unique clients
    pub unique_clients: u64,

    /// Number of DNS queries of all types
    pub dns_queries_all_types: u64,

    /// Number of NODATA replies
    #[serde(rename = "reply_NODATA")]
    pub reply_nodata: u64,

    /// Number of NXDOMAIN replies
    #[serde(rename = "reply_NXDOMAIN")]
    pub reply_nxdomain: u64,

    /// Number of CNAME replies
    #[serde(rename = "reply_CNAME")]
    pub reply_cname: u64,

    /// Number of IP replies
    #[serde(rename = "reply_IP")]
    pub reply_ip: u64,

    /// Privacy level
    pub privacy_level: u64,

    /// Pi Hole status
    pub status: String,
}

/// Summary Struct
#[derive(Deserialize, Debug)]
pub struct Summary {
    /// Formatted number of domains being blocked
    pub domains_being_blocked: String,

    /// Formatted number of DNS queries today
    pub dns_queries_today: String,

    /// Formatted number of Ads blocked today
    pub ads_blocked_today: String,

    /// Formatted percentage of queries blocked today
    pub ads_percentage_today: String,

    /// Formatted number of unique domains
    pub unique_domains: String,

    /// Formatted number of queries forwarded
    pub queries_forwarded: String,

    /// Formatted number of queries cached
    pub queries_cached: String,

    /// Formatted number of clients ever seen
    pub clients_ever_seen: String,

    /// Formatted number of unique clients
    pub unique_clients: String,

    /// Formatted number of DNS queries of all types
    pub dns_queries_all_types: String,

    /// Formatted number of NODATA replies
    #[serde(rename = "reply_NODATA")]
    pub reply_nodata: String,

    /// Formatted number of NXDOMAIN replies
    #[serde(rename = "reply_NXDOMAIN")]
    pub reply_nxdomain: String,

    /// Formatted number of CNAME replies
    #[serde(rename = "reply_CNAME")]
    pub reply_cname: String,

    /// Formatted number of IP replies
    #[serde(rename = "reply_IP")]
    pub reply_ip: String,

    /// Privacy level
    pub privacy_level: String,

    /// Pi Hole status
    pub status: String,
}

/// Over Time Data Struct
#[derive(Deserialize, Debug)]
pub struct OverTimeData {
    /// Mapping from time to number of domains
    pub domains_over_time: HashMap<i64, u64>,

    /// Mapping from time to number of ads
    pub ads_over_time: HashMap<i64, u64>,
}

/// Top Items Struct
#[derive(Deserialize, Debug)]
pub struct TopItems {
    /// Top queries mapping from domain to number of requests
    pub top_queries: HashMap<String, u64>,

    /// Top ads mapping from domain to number of requests
    pub top_ads: HashMap<String, u64>,
}

/// Top Clients Struct
#[derive(Deserialize, Debug)]
pub struct TopClients {
    /// Top sources mapping from "IP" or "hostname|IP" to number of requests.
    pub top_sources: HashMap<String, u64>,
}

/// Top Clients Blocked Struct
#[derive(Deserialize, Debug)]
pub struct TopClientsBlocked {
    /// Top sources blocked mapping from "IP" or "hostname|IP" to number of blocked requests.
    pub top_sources_blocked: HashMap<String, u64>,
}

/// Forward Destinations Struct
#[derive(Deserialize, Debug)]
pub struct ForwardDestinations {
    /// Forward destinations mapping from "human_readable_name|IP" to the percentage of requests answered.
    pub forward_destinations: HashMap<String, f64>,
}

/// Query Types Struct
#[derive(Deserialize, Debug)]
pub struct QueryTypes {
    /// Query types mapping from query type (A, AAAA, PTR, etc.) to the percentage of queries which are of that type.
    pub querytypes: HashMap<String, f64>,
}

/// Query Struct
#[derive(Deserialize, Debug)]
pub struct Query {
    /// Timestamp of query
    pub timestring: String,

    /// Type of query (A, AAAA, PTR, etc.)
    pub query_type: String,

    /// Requested domain name
    pub domain: String,

    /// Requesting client IP or hostname
    pub client: String,

    /// Status as String
    pub answer_type: String,
}

/// All Queries Struct
#[derive(Deserialize, Debug)]
pub struct AllQueries {
    /// List of queries
    data: Vec<Query>,
}

/// Status Struct
#[derive(Deserialize, Debug)]
pub struct Status {
    /// Status, "enabled" or "disabled"
    pub status: String,
}

/// Version Struct
#[derive(Deserialize, Debug)]
pub struct Version {
    /// Version
    pub version: u32,
}

/// Cache Info Struct
#[derive(Deserialize, Debug)]
pub struct CacheInfo {
    /// Cache size
    #[serde(rename = "cache-size")]
    pub cache_size: u64,

    /// Number of evicted cache entries
    #[serde(rename = "cache-live-freed")]
    pub cache_live_freed: u64,

    /// Number of cache entries inserted
    #[serde(rename = "cache-inserted")]
    pub cache_inserted: u64,
}

/// Client Name Struct
#[derive(Deserialize, Debug)]
pub struct ClientName {
    /// Client name
    pub name: String,

    /// Client IP
    pub ip: IpAddr,
}

/// Network Client Struct
#[derive(Deserialize, Debug)]
pub struct NetworkClient {
    /// Client ID
    pub id: u64,

    /// IP addresses of client
    pub ip: Vec<IpAddr>,

    /// Hardware address
    pub hwaddr: String,

    /// Interface
    pub interface: String,

    /// Hostname
    pub name: String,

    /// Time first seen
    #[serde(rename = "firstSeen")]
    pub first_seen: u64,

    /// Time of last query
    #[serde(rename = "lastQuery")]
    pub last_query: u64,

    /// Number of queries
    #[serde(rename = "numQueries")]
    pub num_queries: u64,

    /// MAC Vendor
    #[serde(rename = "macVendor")]
    pub mac_vendor: String,
}

/// Network Struct
#[derive(Deserialize, Debug)]
pub struct Network {
    /// List of network clients
    pub network: Vec<NetworkClient>,
}

/// Pi Hole API Struct
pub struct PiHoleAPI {
    /// Pi Hole host
    host: String,

    /// Optional API key
    api_key: Option<String>,
}

impl PiHoleAPI {
    /// Creates a new Pi Hole API instance.
    /// `host` must begin with the protocol e.g. http:// or https://
    pub fn new(host: String, api_key: Option<String>) -> Self {
        Self { host, api_key }
    }

    pub fn set_api_key(&mut self, api_key: &String) {
        self.api_key = Some(api_key.into());
    }

    async fn simple_json_request<T>(&self, path_query: String) -> Result<T, Box<dyn Error>>
    where
        T: DeserializeOwned,
    {
        let response = reqwest::get(&format!("{}{}", self.host, path_query)).await?;
        Ok(response.json().await?)
    }

    async fn authenticated_json_request<T>(&self, path_query: String) -> Result<T, Box<dyn Error>>
    where
        T: DeserializeOwned,
    {
        if self.api_key == None {
            simple_error::bail!("API key is required for authenticated requests");
        }
        let auth_path_query;
        match path_query.contains("?") {
            true => {
                auth_path_query = format!(
                    "{}{}&auth={}",
                    self.host,
                    path_query,
                    self.api_key.as_ref().unwrap()
                )
            }
            false => {
                auth_path_query = format!(
                    "{}{}?auth={}",
                    self.host,
                    path_query,
                    self.api_key.as_ref().unwrap()
                )
            }
        }
        let response = reqwest::get(&auth_path_query).await?;
        Ok(response.json().await?)
    }

    /// Get statistics in a raw format (no number format)
    pub async fn get_summary_raw(&self) -> Result<SummaryRaw, Box<dyn Error>> {
        self.simple_json_request("/admin/api.php?summaryRaw".to_string())
            .await
    }

    /// Get statistics in a formatted style
    pub async fn get_summary(&self) -> Result<Summary, Box<dyn Error>> {
        self.simple_json_request("/admin/api.php?summary".to_string())
            .await
    }

    /// Get statistics on the number of domains and ads for each 10 minute period
    pub async fn get_over_time_data_10_mins(&self) -> Result<OverTimeData, Box<dyn Error>> {
        self.simple_json_request("/admin/api.php?overTimeData10mins".to_string())
            .await
    }

    /// Get the top domains and ads and the number of queries for each. Limit the number of items with `count`.
    /// API key required.
    pub async fn get_top_items(&self, count: Option<u32>) -> Result<TopItems, Box<dyn Error>> {
        self.authenticated_json_request(format!("/admin/api.php?topItems={}", count.unwrap_or(10)))
            .await
    }

    /// Get the top clients and the number of queries for each. Limit the number of items with `count`.
    /// API key required.
    pub async fn get_top_clients(&self, count: Option<u32>) -> Result<TopClients, Box<dyn Error>> {
        self.authenticated_json_request(format!(
            "/admin/api.php?topClients={}",
            count.unwrap_or(10)
        ))
        .await
    }

    /// Get the top clients blocked and the number of queries for each. Limit the number of items with `count`.
    /// API key required.
    pub async fn get_top_clients_blocked(
        &self,
        count: Option<u32>,
    ) -> Result<TopClientsBlocked, Box<dyn Error>> {
        self.authenticated_json_request(format!(
            "/admin/api.php?topClientsBlocked={}",
            count.unwrap_or(10)
        ))
        .await
    }

    /// Get the number of queries forwarded and the target.
    /// API key required.
    pub async fn get_forward_destinations(&self) -> Result<ForwardDestinations, Box<dyn Error>> {
        self.authenticated_json_request("/admin/api.php?getForwardDestinations".to_string())
            .await
    }

    /// Get the number of queries per type.
    /// API key required.
    pub async fn get_query_types(&self) -> Result<QueryTypes, Box<dyn Error>> {
        self.authenticated_json_request("/admin/api.php?getQueryTypes".to_string())
            .await
    }

    /// Get all DNS query data. Limit the number of items with `count`.
    /// API key required.
    pub async fn get_all_queries(&self, count: u32) -> Result<AllQueries, Box<dyn Error>> {
        let mut raw_data: HashMap<String, Vec<Vec<String>>> = self
            .authenticated_json_request(format!("/admin/api.php?getAllQueries={}", count))
            .await?;

        // Convert the queries from a list into a more useful Query struct
        let data = AllQueries {
            data: raw_data
                .remove("data")
                .unwrap()
                .iter()
                .map(|raw_query| Query {
                    timestring: raw_query[0].clone(),
                    query_type: raw_query[1].clone(),
                    domain: raw_query[2].clone(),
                    client: raw_query[3].clone(),
                    answer_type: raw_query[4].clone(),
                })
                .collect(),
        };
        Ok(data)
    }

    /// Enable the Pi-Hole.
    /// API key required.
    pub async fn enable(&self) -> Result<Status, Box<dyn Error>> {
        self.authenticated_json_request("/admin/api.php?enable".to_string())
            .await
    }

    /// Disable the Pi-Hole for `seconds` seconds.
    /// API key required.
    pub async fn disable(&self, seconds: u64) -> Result<Status, Box<dyn Error>> {
        self.authenticated_json_request(format!("/admin/api.php?disable={}", seconds))
            .await
    }

    /// Get the Pi-Hole version.
    pub async fn get_version(&self) -> Result<Version, Box<dyn Error>> {
        self.simple_json_request("/admin/api.php?version".to_string())
            .await
    }

    /// Get statistics about the DNS cache.
    /// API key required.
    pub async fn get_cache_info(&self) -> Result<CacheInfo, Box<dyn Error>> {
        let mut raw_data: HashMap<String, CacheInfo> = self
            .authenticated_json_request("/admin/api.php?getCacheInfo".to_string())
            .await?;
        Ok(raw_data.remove("cacheinfo").expect("Missing cache info"))
    }

    /// Get hostname and IP for hosts
    /// API key required.
    pub async fn get_client_names(&self) -> Result<Vec<ClientName>, Box<dyn Error>> {
        let mut raw_data: HashMap<String, Vec<ClientName>> = self
            .authenticated_json_request("/admin/api.php?getClientNames".to_string())
            .await?;
        Ok(raw_data
            .remove("clients")
            .expect("Missing clients attribute"))
    }

    /// Get queries by client over time. Maps timestamp to the number of queries by clients.
    /// Order of clients in the Vector is the same as for get_client_names
    /// API key required.
    pub async fn get_over_time_data_clients(
        &self,
    ) -> Result<HashMap<u64, Vec<u64>>, Box<dyn Error>> {
        let mut raw_data: HashMap<String, HashMap<u64, Vec<u64>>> = self
            .authenticated_json_request("/admin/api.php?overTimeDataClients".to_string())
            .await?;
        Ok(raw_data
            .remove("over_time")
            .expect("Missing over_time attribute"))
    }

    /// Get information about network clients.
    /// API key required.
    pub async fn get_network(&self) -> Result<Network, Box<dyn Error>> {
        self.authenticated_json_request("/admin/api_db.php?network".to_string())
            .await
    }

    /// Get the total number of queries received.
    /// API key required.
    pub async fn get_queries_count(&self) -> Result<u64, Box<dyn Error>> {
        let mut raw_data: HashMap<String, u64> = self
            .authenticated_json_request("/admin/api_db.php?getQueriesCount".to_string())
            .await?;
        Ok(raw_data.remove("count").expect("Missing count attribute"))
    }

    /// Add domains to a list.
    /// Acceptable lists are: `white`, `black`, `white_regex`, `black_regex`, `white_wild`, `black_wild`, `audit`.
    /// API key required.
    pub async fn add(&self, domains: Vec<String>, list: String) -> Result<(), Box<dyn Error>> {
        let url = format!(
            "{}/admin/api.php?add={}&list={}&auth={}",
            self.host,
            domains.join(" "),
            list,
            self.api_key.as_ref().unwrap_or(&"".to_string())
        );
        let body = reqwest::get(&url).await?.text().await?;
        match body.contains("Success") {
            true => Ok(()),
            false => simple_error::bail!("Pi-Hole API error: ".to_string() + &body),
        }
    }
}