-
Notifications
You must be signed in to change notification settings - Fork 1
/
utmpx.rs
987 lines (879 loc) · 29 KB
/
utmpx.rs
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
// src/data/utmp.rs
//! Implement [`Utmpx`] for [`utmpx`] C structs (sometimes referred to
//! as the older [`utmp`] C struct).
//!
//! [`Utmpx`]: self::Utmpx
//! [`utmpx`]: https://github.com/freebsd/freebsd-src/blob/release/12.4.0/include/utmpx.h#L43-L56
//! [`utmp`]: https://elixir.bootlin.com/glibc/glibc-2.37/source/bits/utmp.h#L57
#[doc(hidden)]
pub use crate::common::{Bytes, CharSz, Count, FPath, FileOffset, NLu8, ResultS3};
use crate::data::datetime::{
DateTimeL,
DateTimeLOpt,
FixedOffset,
LocalResult,
NaiveDateTime,
TimeZone,
};
use crate::readers::blockreader::{
BlockOffset,
BlockReader,
BlockSz,
};
#[cfg(any(debug_assertions, test))]
use crate::debug::printers::byte_to_char_noraw;
use std::fmt;
use std::mem::size_of;
use ::lazy_static::lazy_static;
/// target_os that support `uapi` crate.
#[doc(hidden)]
macro_rules! cfg_supports_uapi {
{ $($item:item)* } => {
$(
#[cfg(not(any(
target_os = "windows",
)))]
$item
)*
}
}
/// target_os that does not support `uapi` crate.
#[doc(hidden)]
macro_rules! cfg_supports_uapi_not {
{ $($item:item)* } => {
$(
#[cfg(any(
// Windows fails to compile with `uapi` crate.
// running: "C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise\\VC\\Tools\\MSVC\\14.35.32215\\bin\\HostX64\\x64\\cl.exe" "-nologo" "-MD" "-Z7" "-Brepro" "-W4" "-FoD:\\a\\super-speedy-syslog-searcher\\super-speedy-syslog-searcher\\target\\debug\\build\\uapi-1fbc59aac9b2d86f\\out\\src/black_box.o" "-c" "src/black_box.c"
// src/black_box.c(2): error C2065: 'asm': undeclared identifier
// src/black_box.c(2): error C2143: syntax error: missing ';' before 'volatile'
target_os = "windows",
))]
$item
)*
}
}
/// Support `uapi` but uses old `utmpx` version 1 definitions.
///
/// Does not define:
/// ut_exit
/// ut_session
/// ut_addr_v6
///
/// See https://github.com/freebsd/freebsd-src/blob/release/13.1.0/include/utmpx.h#L43-L56
/// See https://github.com/mahkoh/uapi/issues/15
#[doc(hidden)]
#[allow(unused_macros)]
macro_rules! cfg_uapi_old {
{ $($item:item)* } => {
$(
#[cfg(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
))]
$item
)*
}
}
/// Support `uapi` but uses new `utmpx` definitions.
#[doc(hidden)]
#[allow(unused_macros)]
macro_rules! cfg_uapi_new {
{ $($item:item)* } => {
$(
#[cfg(not(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
)))]
$item
)*
}
}
cfg_supports_uapi!{
pub use ::uapi::c::utmpx;
}
cfg_supports_uapi!{
// FreeBSD does not define __timeval, __exit_status
// compile fails with:
// error[E0432]: unresolved imports `uapi::c::__timeval`, `uapi::c::__exit_status`
// also see https://github.com/mahkoh/uapi/issues/15
cfg_uapi_new!{
pub use ::uapi::c::{
__timeval,
__exit_status,
};
}
}
#[allow(unused_imports)]
use ::more_asserts::{
assert_ge,
assert_gt,
assert_le,
assert_lt,
debug_assert_ge,
debug_assert_gt,
debug_assert_le,
debug_assert_lt,
};
#[allow(unused_imports)]
use ::si_trace_print::{defn, defo, defx, defñ, den, deo, dex, deñ};
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// The following code is copied and modified from crate `uapi` https://docs.rs/uapi/0.2.10/uapi/c/struct.utmpx.html
// which is under the MIT license https://github.com/mahkoh/uapi/blob/86d032c60bb33c4aa888085f9b50bf6e19f7ba24/LICENSE-MIT
// and "Copyright (c) The uapi developers"
#[cfg(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
target_os = "windows",
))]
#[doc(hidden)]
#[derive(Clone, Copy)]
#[repr(C)]
pub struct __timeval {
pub tv_sec: i32,
pub tv_usec: i32,
}
#[cfg(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
target_os = "windows",
))]
#[doc(hidden)]
#[derive(Clone, Copy)]
#[repr(C)]
pub struct __exit_status {
pub e_termination: i16,
pub e_exit: i16,
}
cfg_supports_uapi_not!{
#[doc(hidden)]
#[derive(Clone, Copy)]
#[repr(C)]
pub struct utmpx {
pub ut_type: i16,
pub ut_pid: i32,
pub ut_line: [i8; 32],
pub ut_id: [i8; 4],
pub ut_user: [i8; 32],
pub ut_host: [i8; 256],
pub ut_exit: __exit_status,
pub ut_session: i32,
pub ut_tv: __timeval,
pub ut_addr_v6: [i32; 4],
/* private fields */
pub __glibc_reserved: [i8; 20],
}
}
// end copied code from crate `uapi` under MIT license
/// [`size_of::<utmpx>`] (384).
///
/// [`size_of::<utmpx>`]: std::mem::size_of
pub const UTMPX_SZ: usize = size_of::<utmpx>();
/// [`UTMPX_SZ`] as a [`FileOffset`].
///
/// [`UTMPX_SZ`]: UTMPX_SZ
/// [`FileOffset`]: crate::common::FileOffset
pub const UTMPX_SZ_FO: FileOffset = UTMPX_SZ as FileOffset;
/// Map [`.ut_type`] value, implied in the index offset, to a `str`
/// representation.
///
/// See [`man utmp`].
///
/// [`.ut_type`]: https://docs.rs/uapi/0.2.10/uapi/c/struct.utmpx.html#structfield.ut_type
/// [`man utmp`]: https://man7.org/linux/man-pages/man5/utmp.5.html
pub const UT_TYPE_VAL_TO_STR: &[&str] = &[
"EMPTY",
"RUN_LVL",
"BOOT_TIME",
"NEW_TIME",
"OLD_TIME",
"INIT_PROCESS",
"LOGIN_PROCESS",
"USER_PROCESS",
"DEAD_PROCESS",
"ACCOUNTING",
];
lazy_static! {
/// fallback `DateTimeL` for failed conversions
static ref DEFAULT_DT: DateTimeL = {
DateTimeL::from_utc(
NaiveDateTime::from_timestamp_opt(0, 0).unwrap(),
FixedOffset::east_opt(0).unwrap(),
)
};
}
/// A [`Utmpx`] holds a [C struct `utmpx`] and it's [`FileOffset`] and derived
/// [`DateTimeL`].
///
/// [`Utmpx`]: self::Utmpx
/// [C struct `utmpx`]: https://docs.rs/uapi/0.2.10/uapi/c/struct.utmpx.html
/// [`FileOffset`]: crate::common::FileOffset
/// [`DateTimeL`]: crate::data::datetime::DateTimeL
#[derive(Clone, Copy)]
pub struct Utmpx {
/// The [`utmpx`] entry data.
///
/// [`utmpx`]: https://docs.rs/uapi/0.2.10/uapi/c/struct.utmpx.html
pub entry: utmpx,
/// The byte offset into the file where this `Utmpx` begins.
pub fileoffset: FileOffset,
/// The derived DateTime instance using function
/// [`convert_tvsec_utvcsec_datetime`].
///
/// [`convert_tvsec_utvcsec_datetime`]: convert_tvsec_utvcsec_datetime
dt: DateTimeL,
}
impl fmt::Debug for Utmpx {
fn fmt(
&self,
f: &mut fmt::Formatter,
) -> fmt::Result {
f.debug_struct("Utmpx")
.field("fileoffset", &self.fileoffset)
.field("dt", &self.dt)
.finish()
}
}
#[cfg(not(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
)))]
/// [`__timeval.tv_sec` second type] from `utmpx.h`
///
/// [`__timeval.tv_sec` second type]: https://docs.rs/uapi/0.2.10/uapi/c/struct.__timeval.html
#[allow(non_camel_case_types)]
pub type tv_sec_type = i32;
#[cfg(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
))]
#[allow(non_camel_case_types)]
pub type tv_sec_type = i64;
#[cfg(not(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
)))]
/// [`__timeval.tv_usec` microsecond type] from `utmpx.h`
///
/// [`__timeval.tv_usec` microsecond type]: https://docs.rs/uapi/0.2.10/uapi/c/struct.__timeval.html
#[allow(non_camel_case_types)]
pub type tv_usec_type = i32;
#[cfg(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
))]
#[allow(non_camel_case_types)]
pub type tv_usec_type = i64;
/// nanosecond type
#[allow(non_camel_case_types)]
pub type nsecs_type = u32;
/// Index into a `[u8]` buffer. Used by [`as_bytes`].
///
/// [`as_bytes`]: self::Utmpx::as_bytes
pub type BufIndex = usize;
/// Information returned from [`as_bytes`].
///
/// Variant `Ok` holds
/// - number of bytes copied
/// - start index of datetime substring
/// - end index of datetime substring
///
/// Variant `Fail` holds number of bytes copied
///
///
/// [`as_bytes`]: self::Utmpx::as_bytes
pub enum InfoAsBytes {
Ok(usize, BufIndex, BufIndex),
Fail(usize),
}
/// Convert `utmpx.__timeval` types [`tv_sec`] and [`tv_usec`] to a
/// [`DateTimeL`] instance.
///
/// Allow lossy microsecond conversion.
/// Return `None` if second conversion fails.
///
/// [`tv_sec`]: https://docs.rs/uapi/0.2.10/uapi/c/struct.__timeval.html#structfield.tv_sec
/// [`tv_usec`]: https://docs.rs/uapi/0.2.10/uapi/c/struct.__timeval.html#structfield.tv_usec
pub fn convert_tvsec_utvcsec_datetime(
tv_sec: tv_sec_type,
tv_usec: tv_usec_type,
tz_offset: &FixedOffset,
) -> DateTimeLOpt {
// Firstly, convert microseconds to nanoseconds.
// If conversion fails then use zero.
let mut nsec: nsecs_type = match tv_usec.try_into() {
Ok(val) => val,
Err(_) => 0,
};
nsec = match nsec.checked_mul(1000) {
Some(val) => val,
None => 0,
};
// Secondly, convert seconds.
// If conversion fails then return None.
let tv_sec_i64: i64 = match tv_sec.try_into() {
Ok(val) => val,
Err(_) => {
return None;
}
};
defñ!("{:?}.timestamp({}, {})", tz_offset, tv_sec_i64, nsec);
match tz_offset.timestamp_opt(
tv_sec_i64, nsec
) {
LocalResult::None => {
// try again with zero nanoseconds
match tz_offset.timestamp_opt(tv_sec_i64, 0) {
LocalResult::None => None,
LocalResult::Single(dt) => Some(dt),
LocalResult::Ambiguous(dt, _) => Some(dt),
}
}
LocalResult::Single(dt) => Some(dt),
LocalResult::Ambiguous(dt, _) => Some(dt),
}
}
/// Convert `[u8]` bytes to a [`utmpx`] instance.
/// Returns `None` if the buffer is too small.
///
/// unsafe.
///
/// [`utmpx`]: https://docs.rs/uapi/0.2.10/uapi/c/struct.utmpx.html
pub fn buffer_to_utmpx(buffer: &[u8]) -> Option<utmpx> {
if buffer.len() < UTMPX_SZ {
return None;
}
unsafe {
Some(std::ptr::read(buffer.as_ptr() as *const _))
}
}
/// Helper to `Utmpx::as_bytes`.
/// Write a byte to the buffer at the given index.
/// If the index is out of bounds, return `InfoAsBytes::Fail`.
macro_rules! set_u8_buffer_at_or_err {
($buffer:ident, $at:ident, $c:expr) => (
if $at >= $buffer.len() {
return InfoAsBytes::Fail($at);
}
$buffer[$at] = $c;
$at += 1;
)
}
/// Helper to `Utmpx::as_bytes`.
/// Write a byte to the buffer at the given index.
/// If the index is out of bounds, return `InfoAsBytes::Fail`.
macro_rules! set_i8_buffer_at_or_err {
($buffer:ident, $at:ident, $c:expr) => (
let c_: u8 = match ($c).try_into() {
Ok(val) => val,
Err(_) => 0,
};
set_u8_buffer_at_or_err!($buffer, $at, c_);
)
}
impl Utmpx {
/// Create a new `Utmpx`.
pub fn new(
fileoffset: FileOffset,
tz_offset: &FixedOffset,
entry: utmpx,
) -> Utmpx {
// See
// https://docs.rs/uapi/0.2.10/uapi/c/struct.utmpx.html
// https://docs.rs/uapi/0.2.10/uapi/c/struct.__timeval.html
let tv_sec: tv_sec_type = entry.ut_tv.tv_sec.into();
let tv_usec: tv_usec_type = entry.ut_tv.tv_usec.into();
// XXX: still not sure if it's better to panic or somehow alert caller
// that the time conversion failed. A failed time conversion means
// the data is most likely invalid/wrong format.
let dt = match convert_tvsec_utvcsec_datetime(tv_sec, tv_usec, tz_offset) {
Some(dt) => dt,
None => {
defñ!("tv_sec {}, tv_usec {}", tv_sec, tv_usec);
*DEFAULT_DT
}
};
defñ!("tv_sec {}, tv_usec {}, dt {:?}", tv_sec, tv_usec, dt);
Utmpx {
fileoffset,
entry,
dt,
}
}
/// Length of a `Utmpx` in bytes.
pub const fn len(self: &Utmpx) -> usize {
UTMPX_SZ
}
/// Clippy recommends `fn is_empty` since there is a `len()`.
pub const fn is_empty(self: &Utmpx) -> bool {
self.len() == 0
}
/// [`FileOffset`] at beginning of the `Utmpx` (inclusive).
///
/// [`FileOffset`]: crate::common::FileOffset
pub const fn fileoffset_begin(self: &Utmpx) -> FileOffset {
self.fileoffset
}
/// [`FileOffset`] at one byte past ending of the `Utmpx` (exclusive).
///
/// [`FileOffset`]: crate::common::FileOffset
pub const fn fileoffset_end(self: &Utmpx) -> FileOffset {
self.fileoffset + (self.len() as FileOffset)
}
/// First [`BlockOffset`] of underlying [`Block`s] for the given
/// [`BlockSz`].
///
/// [`BlockOffset`]: crate::readers::blockreader::BlockOffset
/// [`Block`s]: crate::readers::blockreader::Block
/// [`BlockSz`]: crate::readers::blockreader::BlockSz
pub fn blockoffset_begin(&self, blocksz: BlockSz) -> BlockOffset {
BlockReader::block_offset_at_file_offset(
self.fileoffset_begin(),
blocksz
)
}
/// Last [`BlockOffset`] of underlying [`Block`s] for the given
/// [`BlockSz`].
///
/// [`BlockOffset`s]: crate::readers::blockreader::BlockOffset
/// [`Block`s]: crate::readers::blockreader::Block
/// [`BlockSz`]: crate::readers::blockreader::BlockSz
pub fn blockoffset_end(&self, blocksz: BlockSz) -> BlockOffset {
BlockReader::block_offset_at_file_offset(
self.fileoffset_end(),
blocksz
)
}
/// Return a reference to [`self.dt`] (`DateTimeL`).
///
/// [`self.dt`]: Utmpx::dt
pub const fn dt(self: &Utmpx) -> &DateTimeL {
&self.dt
}
/// Copy the `Utmpx` into the passed `buffer` as printable bytes.
/// When successful, returns a [`InfoAsBytes::Ok`] variant with
/// number of bytes copied, start index of datetime substring, and
/// end index of datetime substring.
///
/// If copying fails, returns a [`InfoAsBytes::Fail`] variant with
/// number of bytes copied.
///
/// Efficient function to copy the `Utmpx` into a single re-usable
/// buffer for printing.
pub fn as_bytes(self: &Utmpx, buffer: &mut [u8])
-> InfoAsBytes
{
let utmpx1: &utmpx = &self.entry;
const ULEN: i16 = UT_TYPE_VAL_TO_STR.len() as i16;
let buflen: usize = buffer.len();
let mut at: usize = 0;
/*
https://docs.rs/uapi/0.2.10/uapi/c/index.html
https://linux.die.net/man/5/utmpx
#define EMPTY 0 /* Record does not contain valid info (formerly known as UT_UNKNOWN on Linux) */
#define RUN_LVL 1 /* Change in system run-level (see init(8)) */
#define BOOT_TIME 2 /* Time of system boot (in ut_tv) */
#define NEW_TIME 3 /* Time after system clock change (in ut_tv) */
#define OLD_TIME 4 /* Time before system clock change (in ut_tv) */
#define INIT_PROCESS 5 /* Process spawned by init(8) */
#define LOGIN_PROCESS 6 /* Session leader process for user login */
#define USER_PROCESS 7 /* Normal process */
#define DEAD_PROCESS 8 /* Terminated process */
#define ACCOUNTING 9 /* Not implemented */
pub struct utmpx {
pub ut_type: i16,
pub ut_pid: i32,
pub ut_line: [i8; 32],
pub ut_id: [i8; 4],
pub ut_user: [i8; 32],
pub ut_host: [i8; 256],
pub ut_exit: __exit_status,
pub ut_session: i32,
pub ut_tv: __timeval,
pub ut_addr_v6: [i32; 4],
/* private fields */
}
pub struct __exit_status {
pub e_termination: i16,
pub e_exit: i16,
}
pub struct __timeval {
pub tv_sec: i32,
pub tv_usec: i32,
}
*/
// ut_type
let ut_types: &str = match &utmpx1.ut_type {
n if &0 <= n && n < &ULEN => UT_TYPE_VAL_TO_STR[*n as usize],
_ => "",
};
for b_ in ut_types.bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
// ut_pid
for b_ in " ut_pid ".bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
for b_ in utmpx1.ut_pid.to_string().as_str().bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
// ut_line
for b_ in " ut_line '".bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
for b_ in utmpx1.ut_line.iter() {
if b_ == &0 {
break;
}
set_i8_buffer_at_or_err!(buffer, at, *b_);
}
// ut_id
for b_ in "' ut_id '".bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
for b_ in utmpx1.ut_id.iter() {
if b_ == &0 {
break;
}
set_i8_buffer_at_or_err!(buffer, at, *b_);
}
// ut_user
for b_ in "' ut_user '".bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
for b_ in utmpx1.ut_user.iter() {
if b_ == &0 {
break;
}
set_i8_buffer_at_or_err!(buffer, at, *b_);
}
// ut_host
for b_ in "' ut_host '".bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
for b_ in utmpx1.ut_host.iter() {
if b_ == &0 {
break;
}
set_i8_buffer_at_or_err!(buffer, at, *b_);
}
// cfg_uapi_new!
#[cfg(not(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
)))]
{
// ut_session
for b_ in "' ut_session ".bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
for b_ in utmpx1.ut_session.to_string().as_str().bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
// ut_addr_v6
for b in format!(" ut_addr_v6 {0:X}:{1:X}:{2:X}:{3:X} ",
&utmpx1.ut_addr_v6[0],
&utmpx1.ut_addr_v6[1],
&utmpx1.ut_addr_v6[2],
&utmpx1.ut_addr_v6[3],
).as_str().as_bytes().iter() {
let b_ = *b;
set_u8_buffer_at_or_err!(buffer, at, b_);
}
// ut_exit.e_termination
for b_ in "e_termination ".bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
for b_ in utmpx1.ut_exit.e_termination.to_string().as_str().bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
// ut_exit.e_exit
for b_ in " e_exit ".bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
for b_ in utmpx1.ut_exit.e_exit.to_string().as_str().bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
}
if at >= buflen {
return InfoAsBytes::Fail(at);
}
buffer[at] = b' ';
at += 1;
// ut_tv.tv_sec
let dt_beg: BufIndex = at;
for b_ in utmpx1.ut_tv.tv_sec.to_string().as_str().bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
if at >= buflen {
return InfoAsBytes::Fail(at);
}
buffer[at] = b'.';
at += 1;
// ut_tv.tv_usec
for b_ in utmpx1.ut_tv.tv_usec.to_string().as_str().bytes() {
set_u8_buffer_at_or_err!(buffer, at, b_);
}
if at >= buflen {
return InfoAsBytes::Fail(at);
}
let dt_end: BufIndex = at;
buffer[at] = b'\n';
at += 1;
if at >= buflen {
return InfoAsBytes::Fail(at);
}
buffer[at] = b'\0';
debug_assert_le!(dt_beg, dt_end);
debug_assert_le!(dt_end, at);
InfoAsBytes::Ok(at, dt_beg, dt_end)
}
/// Create `String` from known bytes referenced by `self.lineparts`.
///
/// `raw` is `true` means use byte characters as-is.
/// `raw` is `false` means replace formatting characters or non-printable
/// characters with pictoral representation (i.e. use
/// [`byte_to_char_noraw`]).
///
/// XXX: very inefficient and not always correct! *only* intended to help
/// humans visually inspect stderr output.
///
/// [`byte_to_char_noraw`]: crate::debug::printers::byte_to_char_noraw
#[doc(hidden)]
#[allow(non_snake_case)]
#[cfg(any(debug_assertions, test))]
fn impl_to_String_raw(
self: &Utmpx,
raw: bool,
) -> String {
/*
https://docs.rs/uapi/0.2.10/uapi/c/index.html
https://linux.die.net/man/5/utmpx
#define EMPTY 0 /* Record does not contain valid info (formerly known as UT_UNKNOWN on Linux) */
#define RUN_LVL 1 /* Change in system run-level (see init(8)) */
#define BOOT_TIME 2 /* Time of system boot (in ut_tv) */
#define NEW_TIME 3 /* Time after system clock change (in ut_tv) */
#define OLD_TIME 4 /* Time before system clock change (in ut_tv) */
#define INIT_PROCESS 5 /* Process spawned by init(8) */
#define LOGIN_PROCESS 6 /* Session leader process for user login */
#define USER_PROCESS 7 /* Normal process */
#define DEAD_PROCESS 8 /* Terminated process */
#define ACCOUNTING 9 /* Not implemented */
pub struct utmpx {
pub ut_type: i16,
pub ut_pid: i32,
pub ut_line: [i8; 32],
pub ut_id: [i8; 4],
pub ut_user: [i8; 32],
pub ut_host: [i8; 256],
pub ut_exit: __exit_status,
pub ut_session: i32,
pub ut_tv: __timeval,
pub ut_addr_v6: [i32; 4],
/* private fields */
}
pub struct __exit_status {
pub e_termination: i16,
pub e_exit: i16,
}
pub struct __timeval {
pub tv_sec: i32,
pub tv_usec: i32,
}
*/
let mut buf: String = String::with_capacity(100);
let utmpx1: &utmpx = &self.entry;
const ULEN: i16 = UT_TYPE_VAL_TO_STR.len() as i16;
let ut_types: &str = match &utmpx1.ut_type {
n if &0 <= n && n < &ULEN => UT_TYPE_VAL_TO_STR[*n as usize],
_ => "",
};
buf.push_str(format!("ut_type {} ({}) ", utmpx1.ut_type, ut_types).as_str());
buf.push_str(format!("ut_pid {0:02} ", &utmpx1.ut_pid).as_str());
let mut at: usize = 0;
const MARK: char = '|';
buf.push_str("ut_line[…] '");
for ut_line in utmpx1.ut_line.iter() {
let c: char = match raw {
true => *ut_line as u8 as char,
false => byte_to_char_noraw(*ut_line as u8),
};
//if c == '\0' {
// break;
//}
buf.push(c);
at += 1;
if ut_line == &0 {
break;
}
}
if at < utmpx1.ut_line.len() {
let mut mark: bool = false;
for ut_line in utmpx1.ut_line.iter().skip(at) {
if ut_line == &0 {
continue;
}
if ! mark {
buf.push(MARK);
mark = true;
}
let c: char = match raw {
true => *ut_line as u8 as char,
false => byte_to_char_noraw(*ut_line as u8),
};
buf.push(c);
at += 1;
}
}
buf.push_str("' ");
buf.push_str(" ut_id[…] '");
at = 0;
for ut_id in utmpx1.ut_id.iter() {
let c: char = match raw {
true => *ut_id as u8 as char,
false => byte_to_char_noraw(*ut_id as u8),
};
//if c == '\0' {
// break;
//}
buf.push(c);
at += 1;
if ut_id == &0 {
break;
}
}
if at < utmpx1.ut_id.len() {
let mut mark: bool = false;
for ut_id in utmpx1.ut_id.iter().skip(at) {
if ut_id == &0 {
continue;
}
if ! mark {
buf.push(MARK);
mark = true;
}
let c: char = match raw {
true => *ut_id as u8 as char,
false => byte_to_char_noraw(*ut_id as u8),
};
buf.push(c);
at += 1;
}
}
buf.push_str("' ");
buf.push_str("ut_user[…] '");
at = 0;
for ut_user in utmpx1.ut_user.iter() {
let c: char = match raw {
true => *ut_user as u8 as char,
false => byte_to_char_noraw(*ut_user as u8),
};
buf.push(c);
at += 1;
}
if at < utmpx1.ut_user.len() {
let mut mark: bool = false;
for ut_user in utmpx1.ut_user.iter().skip(at) {
if ut_user == &0 {
continue;
}
if ! mark {
buf.push(MARK);
mark = true;
}
let c: char = match raw {
true => *ut_user as u8 as char,
false => byte_to_char_noraw(*ut_user as u8),
};
buf.push(c);
at += 1;
}
}
buf.push_str("' ");
buf.push_str("ut_host[…] '");
at = 0;
for ut_host in utmpx1.ut_host.iter() {
let c: char = match raw {
true => *ut_host as u8 as char,
false => byte_to_char_noraw(*ut_host as u8),
};
buf.push(c);
at += 1;
if ut_host == &0 {
break;
}
}
if at < utmpx1.ut_host.len() {
let mut mark: bool = false;
for ut_host in utmpx1.ut_host.iter().skip(at) {
if ut_host == &0 {
continue;
}
if ! mark {
buf.push(MARK);
mark = true;
}
let c: char = match raw {
true => *ut_host as u8 as char,
false => byte_to_char_noraw(*ut_host as u8),
};
buf.push(c);
at += 1;
}
}
buf.push_str("' ");
// cfg_uapi_new!
#[cfg(not(any(
target_os = "freebsd",
target_os = "macos",
target_os = "ios",
)))]
{
buf.push_str(format!("ut_session {} ", &utmpx1.ut_session).as_str());
buf.push_str(format!("addr_v6 {0:X}:{1:X}:{2:X}:{3:X} ",
&utmpx1.ut_addr_v6[0],
&utmpx1.ut_addr_v6[1],
&utmpx1.ut_addr_v6[2],
&utmpx1.ut_addr_v6[3],
).as_str());
//for (i, ut_addr_v6) in utmpx1.ut_addr_v6.iter().enumerate() {
// println!("utmpx.ut_addr_v6[{1:2}]: {0:02} (0x{0:2x}) (0b{0:08b})", &ut_addr_v6, i);
//}
buf.push_str(format!("e_termination {} ", &utmpx1.ut_exit.e_termination).as_str());
buf.push_str(format!("e_exit {} ", &utmpx1.ut_exit.e_exit).as_str());
}
let _tv_sec = utmpx1.ut_tv.tv_sec;
let _tv_usec = utmpx1.ut_tv.tv_usec;
buf.push_str(format!("tv_sec {} ", &utmpx1.ut_tv.tv_sec).as_str());
buf.push_str(format!("tv_usec {} (", &utmpx1.ut_tv.tv_usec).as_str());
let dts: String = self.dt.to_rfc3339();
buf.push_str(dts.as_str());
buf.push(')');
buf
}
// TODO fix non_snake_case
/// `Utmpx` to `String`.
#[doc(hidden)]
#[allow(non_snake_case)]
#[cfg(any(debug_assertions, test))]
pub fn to_String_raw(self: &Utmpx) -> String {
self.impl_to_String_raw(true)
}
/// `Utmpx` to `String` but using printable chars for
/// non-printable and/or formatting characters.
#[doc(hidden)]
#[allow(non_snake_case)]
#[cfg(any(debug_assertions, test))]
pub fn to_String_noraw(self: &Utmpx) -> String {
self.impl_to_String_raw(false)
}
}