syslog_rs/a_sync/
syslog_async_internal.rs

1/*-
2 * syslog-rs - a syslog client translated from libc to rust
3 * 
4 * Copyright 2025 Aleksandr Morozov
5 * 
6 * The syslog-rs crate can be redistributed and/or modified
7 * under the terms of either of the following licenses:
8 *
9 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
10 *                     
11 *   2. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
12 */
13
14
15use std::borrow::Cow;
16use std::fmt;
17use std::marker::PhantomData;
18
19use nix::libc;
20
21use crate::a_sync::syslog_trait::AsyncSyslogApi;
22use crate::formatters::SyslogFormatter;
23use crate::map_error_os;
24use crate::portable;
25use crate::common::*;
26use crate::error::SyRes;
27use crate::socket::TapType;
28use crate::AsyncSyslogDestination;
29
30use super::async_socket::*;
31
32/// A trait which generalize some operations which are different from the
33/// various async providers i.e `smol` or `tokio` or external.
34#[allow(async_fn_in_trait)]
35pub trait AsyncSyslogInternalIO: fmt::Debug + Send + 'static
36{
37    /// Sends a message to syscons device. Usually this is a `/dev/console`
38    /// defined by crate::common::PATH_CONSOLE.
39    /// 
40    /// # Arguemnts
41    /// 
42    /// * `logstat` - a instance setup [LogStat].
43    /// 
44    /// * `msg_payload` - a payload of the syslog message (without headers).
45    async fn send_to_syscons(logstat: LogStat, msg_payload: &str);
46
47    /// Sends a message to stderr device.
48    /// 
49    /// # Arguemnts
50    /// 
51    /// * `logstat` - a instance setup [LogStat].
52    /// 
53    /// * `msg` - a payload of the syslog message (without headers).
54    async fn send_to_stderr(logstat: LogStat, msg: &str);
55
56    /// Sleep the current task for `us` microseconds.
57    /// 
58    /// # Arguments
59    /// 
60    /// * `us` - microseconds.
61    async fn sleep_micro(us: u64);
62}
63
64/// A trait which generalize the mutex from the std lib's of multiple async executors.
65/// The trait should be implemented on the mutex direclty.
66#[allow(async_fn_in_trait)]
67pub trait AsyncMutex<F: SyslogFormatter, D: AsyncSyslogDestination, DS: AsyncSyslogApi<F, D>>
68{
69    /// A mutex guard type.
70    type MutxGuard<'mux>: AsyncMutexGuard<'mux, F, D, DS> where Self: 'mux;
71
72    /// Creates new mutex instance for type which implements the [AsyncSyslogApi].
73    fn a_new(v: DS) -> Self;
74
75    /// Locks the mutex emmiting the `mutex guard`.
76    async fn a_lock<'mux>(&'mux self) -> Self::MutxGuard<'mux>;
77}
78
79/// A trait which generalize the mutex guarding emited by the mutex from various async executors.
80pub trait AsyncMutexGuard<'mux, F: SyslogFormatter, D: AsyncSyslogDestination, DS: AsyncSyslogApi<F, D>>
81{
82    /// Returns the reference to the inner type of the mutex guard.
83    fn guard(&self) -> &DS;
84
85    /// Returns the mutable reference to the inner type of the mutex guard.
86    fn guard_mut(&mut self) -> &mut DS;
87}
88
89/// Internal structure of the syslog async client.
90#[derive(Debug)]
91pub struct AsyncSyslogInternal<F: SyslogFormatter + Send, D: AsyncSyslogDestination, IO: AsyncSyslogInternalIO>
92{
93    /// An identification i.e program name, thread name
94    logtag: String, 
95
96    /// A pid of the program.
97    logpid: String,
98
99    /// Defines how syslog operates
100    logstat: LogStat,
101
102    /// Holds the facility 
103    facility: LogFacility,
104
105    /// A logmask
106    logmask: i32,
107
108    /// A stream
109    stream: D::SocketTap,
110
111    /// Phantom for [SyslogFormatter]
112    _p: PhantomData<F>,
113
114    /// Phantom for the [AsyncSyslogInternalIO] which provides writing to console and other IO.
115    _p2: PhantomData<IO>,
116}
117
118
119impl<F: SyslogFormatter + Send, D: AsyncSyslogDestination, IO: AsyncSyslogInternalIO> AsyncSyslogInternal<F, D, IO>
120{
121    /// Creates new instance of [SyslogInternal] which contains all 
122    /// client syslog logic.
123    ///
124    /// # Arguments
125    ///
126    /// * `ident` - An optional argument which takes ref to str. If none, the
127    ///     ident will be set later. Yje ident will be trucated to 48 UTF8
128    ///     chars.
129    /// 
130    /// * `logstat` - A [LogStat] flags separated by '|'
131    /// 
132    /// * `facility` - A [LogFacility] flag
133    /// 
134    /// * `req_tap` - A type of the syslog instance reuired. See [SyslogDestination].
135    /// 
136    /// # Returns
137    ///
138    /// A [SyRes] is returned with following:
139    /// 
140    /// * [Result::Ok] - with the instance.
141    /// 
142    /// * [Result::Err] - with error description.
143    pub(crate) 
144    fn new(
145        ident: Option<&str>, 
146        logstat: LogStat, 
147        facility: LogFacility, 
148        req_tap: D
149    ) -> SyRes<Self>
150    {
151        // check if log_facility is invalid
152        let log_facility =
153            if facility.is_empty() == false && 
154                (facility & !LogMask::LOG_FACMASK).is_empty() == true
155            {
156                facility
157            }
158            else
159            {
160                // default facility code
161                LogFacility::LOG_USER
162            };
163
164        let logtag = 
165            match ident
166            {
167                Some(r) => 
168                    truncate_n(r, RFC_MAX_APP_NAME).to_string(),
169                None => 
170                    truncate_n(
171                        portable::p_getprogname()
172                            .unwrap_or("".to_string())
173                            .as_str(),
174                        RFC_MAX_APP_NAME
175                    )
176                    .to_string()
177            };
178
179        let sock = D::SocketTap::new(req_tap)?;
180
181        return Ok(
182            Self
183            {
184                logtag: logtag,
185                logpid: portable::get_pid().to_string(),
186                logstat: logstat, 
187                facility: log_facility,
188                logmask: 0xff,
189                stream: sock,
190                _p: PhantomData,
191                _p2: PhantomData,
192            }
193        );
194    }
195
196    #[inline]
197    pub(crate) 
198    fn is_logmasked(&self, pri: i32) -> bool
199    {
200        if ((1 << (pri & LogMask::LOG_PRIMASK)) & self.logmask) == 0
201        {
202            return true;
203        }
204
205        return false;
206    }
207
208        /// Returns the type of the socket.
209    #[inline]
210    pub(crate)
211    fn get_taptype(&self) -> TapType
212    {
213        return self.stream.get_type();
214    }
215
216    /* 
217    /// Returns the maximum msg size in bytes. (Full msg with headers.)
218    #[inline]
219    pub(crate) 
220    fn get_max_msg_size(&self) -> usize
221    {
222        return self.stream.get_max_msg_size();
223    }
224    */
225
226    #[inline]
227    pub(crate) 
228    fn set_logtag<L: AsRef<str>>(&mut self, logtag: L, update_pid: bool)
229    {
230        self.logtag = 
231            truncate_n(logtag.as_ref(), RFC_MAX_APP_NAME).to_string();
232
233        if update_pid == true
234        {
235            self.logpid = portable::get_pid().to_string();
236        }
237
238        return;
239    }
240
241    /// Disconnects the unix stream from syslog.
242    #[inline]
243    pub(crate) async 
244    fn disconnectlog(&mut self)  -> SyRes<()>
245    {
246        return 
247            self
248                .stream
249                .disconnectlog()
250                .await
251                .map_err(|e| map_error_os!(e, "can not disconnect log properly"));
252    }
253}
254
255impl<F: SyslogFormatter + Send, D: AsyncSyslogDestination, IO: AsyncSyslogInternalIO> AsyncSyslogApi<F, D>
256for AsyncSyslogInternal<F, D, IO>
257{
258    async 
259    fn update_tap_data(&mut self, tap_data: D) -> SyRes<()>
260    {
261        let is_con = self.stream.is_connected();
262
263        if is_con == true
264        {
265            self
266                .stream
267                .disconnectlog()
268                .await
269                .map_err(|e|
270                    map_error_os!(e, "update_tap_data() can not disconnect log properly")
271                )?;
272        }
273
274        self.stream.update_tap_data(tap_data);
275
276        if is_con == true
277        {
278            // replace with new instance
279            self.stream.connectlog().await?;
280        }
281
282        return Ok(());
283    }
284 
285    #[inline]
286    fn change_identity(&mut self, ident: &str)
287    {
288        self.set_logtag(ident, true);
289    }
290
291    async 
292    fn reconnect(&mut self) -> SyRes<()>
293    {
294        self.disconnectlog().await?;
295
296        self.connectlog().await?;
297
298        return Ok(());
299    }
300
301    async 
302    fn closelog(&mut self) -> SyRes<()>
303    {
304        return self.disconnectlog().await;
305    }
306    
307    fn set_logmask(&mut self, logmask: i32) -> i32
308    {
309        let oldmask = self.logmask;
310
311        if logmask != 0
312        {
313            self.logmask = logmask;
314        }
315
316        return oldmask;
317    }
318
319
320    /// Connects unix stream to the syslog and sets up the properties of
321    /// the unix stream.
322    #[inline]
323    async 
324    fn connectlog(&mut self) -> SyRes<()>
325    {
326        return self.stream.connectlog().await;
327    }
328    
329    /// An internal function which is called by the syslog or vsyslog.
330    async 
331    fn vsyslog1(&mut self, mut pri: Priority, fmt: F)
332    {
333        // check for invalid bits
334        if let Err(e) = pri.check_invalid_bits()
335        {
336            IO::send_to_stderr(self.logstat, &e.to_string()).await;
337        }
338
339        /*match check_invalid_bits(&mut pri)
340        {
341            Ok(_) => {},
342            Err(_e) => self.vsyslog1(get_internal_log(), fmt).await
343        }*/
344
345        // check priority against setlogmask
346        if self.is_logmasked(pri.bits()) == true
347        {
348            return;
349        }
350
351        // set default facility if not specified in pri
352        if (pri.bits() & LOG_FACMASK) == 0
353        {
354            pri.set_facility(self.facility);
355        };
356
357        let mut msg_formatted = 
358            fmt.vsyslog1_format(D::SocketTap::get_max_msg_size(), pri, &self.logtag, &self.logpid);
359
360        // output to stderr if required
361        IO::send_to_stderr(self.logstat, msg_formatted.get_stderr_output()).await;
362
363        if self.stream.is_connected() == false
364        {
365            // open connection
366            match self.connectlog().await
367            {
368                Ok(_) => {},
369                Err(e) =>
370                {
371                    IO::send_to_stderr(self.logstat, &e.into_inner() ).await;
372                    return;
373                }
374            }
375        }
376        
377        let fullmsg = msg_formatted.get_full_msg();
378
379
380        // There are two possible scenarios when send may fail:
381        // 1. syslog temporary unavailable
382        // 2. syslog out of buffer space
383        // If we are connected to priv socket then in case of 1 we reopen connection
384        //      and retry once.
385        // If we are connected to unpriv then in case of 2 repeatedly retrying to send
386        //      until syslog socket buffer space will be cleared
387
388        loop
389        {
390            match self.stream.send(fullmsg.as_bytes()).await
391            {
392                Ok(_) => return,
393                Err(err) =>
394                {   
395                    if self.get_taptype().is_network() == false
396                    {
397                        if let Some(libc::ENOBUFS) = err.raw_os_error()
398                        {
399                            // scenario 2
400                            if self.get_taptype().is_priv() == true
401                            {
402                                break;
403                            }
404
405                            IO::sleep_micro(1).await;
406                            //sleep(Duration::from_micros(1)).await;
407                        }
408                        else
409                        {
410                            // scenario 1
411                            let _ = self.disconnectlog().await;
412                            match self.connectlog().await
413                            {
414                                Ok(_) => {},
415                                Err(_e) => break,
416                            }
417
418                            // if resend will fail then probably the scn 2 will take place
419                        } 
420                    }
421                    else
422                    {
423                        let _ = self.disconnectlog().await;
424                        match self.connectlog().await
425                        {
426                            Ok(_) => {},
427                            Err(_e) => break,
428                        }
429                    }  
430                }
431            }
432        } // loop
433
434
435        // If program reached this point then transmission over socket failed.
436        // Try to output message to console
437
438        IO::send_to_syscons(self.logstat, msg_formatted.get_stderr_output()).await;
439    }
440}