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
//! HTTP Event Collector related functionality
//!
//! Based on <https://docs.splunk.com/Documentation/Splunk/9.0.4/Data/HECExamples>
//!

use std::cmp::min;
use std::collections::VecDeque;
use std::sync::Arc;

use log::error;
use reqwest::{header::HeaderMap, redirect::Policy, Client, Error};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::sync::RwLock;

use crate::search::AuthenticationMethod;
use crate::ServerConfig;

/// HEC Client
#[derive(Debug)]
pub struct HecClient {
    /// See [ServerConfig]
    pub serverconfig: ServerConfig,
    /// The target index - if this is None then it'll just let the server decide
    pub index: Option<String>,
    /// The target sourcetype - if this is None then it'll just let the server decide
    pub sourcetype: Option<String>,
    /// The target source - if this is None then it'll just let the server decide
    pub source: Option<String>,
    queue: Arc<RwLock<VecDeque<Box<Value>>>>,
    /// The user-agent string to send, defaults to `splunk-rs <version>`
    useragent: String,
    /// Connection timeout, defaults to 60 seconds
    pub timeout: u64,
}

impl Default for HecClient {
    fn default() -> Self {
        Self {
            serverconfig: ServerConfig {
                hostname: "localhost".to_string(),
                port: 8088,
                verify_tls: true,
                validate_ssl: true,
                auth_method: crate::search::AuthenticationMethod::Unknown,
                ..Default::default()
            },
            index: None,
            sourcetype: None,
            source: None,
            queue: Arc::new(RwLock::new(VecDeque::new())),
            useragent: format!("splunk-rs {}", env!("CARGO_PKG_VERSION")),
            timeout: 60,
        }
    }
}

lazy_static! {
    static ref HEC_HEALTH_EXPECTED_RESPONSE: serde_json::Value =
        serde_json::json!("{\"text\":\"HEC is healthy\",\"code\":17}");
}

#[derive(Debug, Serialize, Deserialize)]
/// Deserializer for the response from HEC Health Checks
pub struct HecHealthResult {
    text: String,
    code: u32,
}

impl HecClient {
    /// Create a new HEC client, specifying the token and hostname. Defaults to port 8088
    pub fn new(token: impl ToString, hostname: impl ToString) -> Self {
        let serverconfig = ServerConfig::new(hostname.to_string())
            .with_token(token.to_string())
            .with_port(8088);
        Self {
            serverconfig,
            ..Default::default()
        }
    }

    /// Start the HEC Client with a given server config
    pub fn with_serverconfig(serverconfig: ServerConfig) -> Self {
        Self {
            serverconfig,
            ..Default::default()
        }
    }

    /// Configure a custom user-agent string
    pub fn useragent(&mut self, useragent: impl ToString) {
        self.useragent = useragent.to_string();
    }

    async fn do_healthcheck(&self, endpoint: &str) -> Result<HecHealthResult, String> {
        let res = self
            .serverconfig
            .do_get(endpoint)
            .await
            .unwrap()
            .json::<HecHealthResult>()
            .await;

        res.map_err(|e| format!("{e:?}"))
    }

    /// Do a healthcheck and return the response
    pub async fn get_health(&self) -> Result<HecHealthResult, String> {
        self.do_healthcheck("/services/collector/health").await
    }

    /// The separate HEC health endpoint for ACK-related/enabled hosts
    pub async fn get_health_ack(&self) -> Result<HecHealthResult, String> {
        self.do_healthcheck("/services/collector/health?ack=true")
            .await
    }

    /// Set the index on the events you'll send
    pub fn with_index(mut self, index: impl ToString) -> Self {
        self.index = Some(index.to_string());
        self
    }

    /// Set the sourcetype on all events you send
    pub fn with_sourcetype(mut self, sourcetype: impl ToString) -> Self {
        self.sourcetype = Some(sourcetype.to_string());
        self
    }

    /// Set the source on all events you send
    pub fn with_source(mut self, source: impl ToString) -> Self {
        self.source = Some(source.to_string());
        self
    }

    /// send a single event to the HEC endpoint
    pub async fn send_event(&self, event: Value) -> Result<(), Error> {
        // Create a reqwest Client to send the HTTP request
        let client = self.get_client()?;

        // Create a map of headers to send with the request
        let mut headers = HeaderMap::new();
        let token = match self.serverconfig.auth_method.clone() {
            AuthenticationMethod::Token { token } => token,
            AuthenticationMethod::Basic {
                username: _,
                password,
            } => password,
            AuthenticationMethod::Unknown => {
                error!("Token is not set for HEC Event!");
                "".to_string()
            }

            // TODO: does HEC handle cookie auth? I don't think so?
            AuthenticationMethod::Cookie { cookie: _ } => unimplemented!("Can't use"),
        };
        headers.insert(
            "Authorization",
            format!("Splunk {}", token).parse().unwrap(),
        );
        headers.insert("Content-Type", "application/json".parse().unwrap());

        // Add index, sourcetype, and source fields to the payload if they are set
        let mut payload = json!({ "event": event });
        if let Some(index) = &self.index {
            payload["index"] = json!(index);
        }
        if let Some(sourcetype) = &self.sourcetype {
            payload["sourcetype"] = json!(sourcetype);
        }
        if let Some(source) = &self.source {
            payload["source"] = json!(source);
        }

        // Send the POST request with the payload and headers to the Splunk HEC endpoint
        let url = format!(
            "https://{}:{}/services/collector",
            self.serverconfig.hostname, self.serverconfig.port
        );
        let request_builder = client
            .post(&url)
            .headers(headers)
            .body(serde_json::to_string(&payload).unwrap());

        let result = request_builder.send().await?;

        result.error_for_status().unwrap();

        Ok(())
    }

    /// Creates the reqwest client with a consistent configuration
    fn get_client(&self) -> Result<Client, reqwest::Error> {
        let mut client = Client::builder()
            .timeout(std::time::Duration::from_secs(self.timeout))
            .user_agent(&self.useragent)
            .redirect(Policy::none());

        if self.serverconfig.verify_tls {
            client = client.danger_accept_invalid_certs(true);
        }

        client.build()
    }

    /// send data to the HEC endpoint
    pub async fn send_events(&self, events: Vec<Value>) -> Result<(), Error> {
        // Create a reqwest Client to send the HTTP request
        let client = self.get_client()?;

        // Create a map of headers to send with the request
        let mut headers = HeaderMap::new();
        let token = match self.serverconfig.auth_method.clone() {
            AuthenticationMethod::Token { token } => token,
            AuthenticationMethod::Basic {
                username: _,
                password,
            } => password,
            AuthenticationMethod::Unknown => {
                error!("Token is not set for HEC Event!");
                "".to_string()
            }
            // TODO: does HEC handle cookie auth? I don't think so.
            AuthenticationMethod::Cookie { cookie: _ } => todo!(),
        };
        headers.insert(
            "Authorization",
            format!("Splunk {}", token).parse().unwrap(),
        );
        headers.insert("Content-Type", "application/json".parse().unwrap());

        let payload_vec: Vec<String> = events
            .into_iter()
            .map(|event| {
                // Add index, sourcetype, and source fields to the payload if they are set - but not already in the event!
                let mut payload = json!({ "event": event });

                if let Some(index) = &self.index {
                    payload["index"] = Value::String(index.to_owned());
                }
                if let Some(sourcetype) = &self.sourcetype {
                    payload["sourcetype"] = Value::String(sourcetype.to_owned());
                }
                if let Some(source) = &self.source {
                    payload["source"] = Value::String(source.to_owned());
                }
                serde_json::to_string(&payload).unwrap()
            })
            .collect();

        let payload = payload_vec.join("\n");

        // Send the POST request with the payload and headers to the Splunk HEC endpoint
        let url = format!(
            "https://{}:{}/services/collector",
            self.serverconfig.hostname, self.serverconfig.port
        );
        let request_builder = client.post(&url).headers(headers).body(payload);

        let result = request_builder.send().await?;

        result.error_for_status().unwrap();

        Ok(())
    }

    /// add a new queue item
    pub async fn enqueue(&mut self, event: Value) {
        self.queue.write().await.push_back(Box::new(event))
    }

    /// get the current queue size
    pub async fn queue_size(&self) -> usize {
        self.queue.read().await.len()
    }

    /// Flush the queue out to HEC, defaults to batches of 1000
    pub async fn flush(&mut self, batch_size: Option<u32>) -> Result<usize, Error> {
        if self.queue.read().await.is_empty() {
            return Ok(0);
        }

        let batch_size = batch_size.unwrap_or(1000);

        let mut sent: usize = 0;
        loop {
            if self.queue.read().await.is_empty() {
                break;
            }
            let mut queue = self.queue.write().await;
            let queue_len = queue.len();
            let events = queue.drain(0..min(queue_len, batch_size as usize));
            // TODO: handle max payload size, because sometimes posting a gig of data is bad
            let payload: Vec<Value> = events.into_iter().map(|e| *e).collect();
            sent += payload.len();

            self.send_events(payload).await?;
        }

        Ok(sent)
    }
}