Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sudo-project
GitHub Repository: sudo-project/sudo
Path: blob/main/lib/iolog/iolog_write.c
1532 views
1
/*
2
* SPDX-License-Identifier: ISC
3
*
4
* Copyright (c) 2009-2021 Todd C. Miller <[email protected]>
5
*
6
* Permission to use, copy, modify, and distribute this software for any
7
* purpose with or without fee is hereby granted, provided that the above
8
* copyright notice and this permission notice appear in all copies.
9
*
10
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
*/
18
19
#include <config.h>
20
21
#include <stdio.h>
22
#ifdef HAVE_STDBOOL_H
23
# include <stdbool.h>
24
#else
25
# include <compat/stdbool.h>
26
#endif
27
#include <string.h>
28
#include <errno.h>
29
#include <limits.h>
30
#include <time.h>
31
32
#include <sudo_compat.h>
33
#include <sudo_debug.h>
34
#include <sudo_iolog.h>
35
36
/*
37
* Write to an I/O log, optionally compressing.
38
*/
39
ssize_t
40
iolog_write(struct iolog_file *iol, const void *buf, size_t len,
41
const char **errstr)
42
{
43
ssize_t ret;
44
debug_decl(iolog_write, SUDO_DEBUG_UTIL);
45
46
if (len > UINT_MAX || len > SSIZE_MAX) { // -V590
47
errno = EINVAL;
48
if (errstr != NULL)
49
*errstr = strerror(errno);
50
debug_return_ssize_t(-1);
51
}
52
53
#ifdef HAVE_ZLIB_H
54
if (iol->compressed) {
55
int errnum;
56
57
ret = gzwrite(iol->fd.g, buf, (unsigned int)len);
58
if (ret == 0) {
59
ret = -1;
60
if (errstr != NULL) {
61
*errstr = gzerror(iol->fd.g, &errnum);
62
if (errnum == Z_ERRNO)
63
*errstr = strerror(errno);
64
}
65
goto done;
66
}
67
if (iolog_get_flush()) {
68
if (gzflush(iol->fd.g, Z_SYNC_FLUSH) != Z_OK) {
69
ret = -1;
70
if (errstr != NULL) {
71
*errstr = gzerror(iol->fd.g, &errnum);
72
if (errnum == Z_ERRNO)
73
*errstr = strerror(errno);
74
}
75
goto done;
76
}
77
}
78
} else
79
#endif
80
{
81
ret = (ssize_t)fwrite(buf, 1, len, iol->fd.f);
82
if (ret != (ssize_t)len) {
83
ret = -1;
84
if (errstr != NULL)
85
*errstr = strerror(errno);
86
goto done;
87
}
88
if (iolog_get_flush()) {
89
if (fflush(iol->fd.f) != 0) {
90
ret = -1;
91
if (errstr != NULL)
92
*errstr = strerror(errno);
93
goto done;
94
}
95
}
96
}
97
98
done:
99
debug_return_ssize_t(ret);
100
}
101
102