Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sudo-project
GitHub Repository: sudo-project/sudo
Path: blob/main/lib/eventlog/logwrap.c
1532 views
1
/*
2
* SPDX-License-Identifier: ISC
3
*
4
* Copyright (c) 2011, 2014-2020 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
#include <stdlib.h>
23
#include <string.h>
24
25
#include <sudo_compat.h>
26
#include <sudo_debug.h>
27
#include <sudo_util.h>
28
#include <sudo_eventlog.h>
29
30
size_t
31
eventlog_writeln(FILE * restrict fp, char * restrict line, size_t linelen, size_t maxlen)
32
{
33
const char *indent = "";
34
char *beg = line;
35
char *end;
36
int len;
37
size_t outlen = 0;
38
debug_decl(eventlog_writeln, SUDO_DEBUG_UTIL);
39
40
if (maxlen < sizeof(EVENTLOG_INDENT)) {
41
/* Maximum length too small, disable wrapping. */
42
outlen = fwrite(line, 1, linelen, fp);
43
if (outlen != linelen)
44
debug_return_size_t((size_t)-1);
45
if (fputc('\n', fp) == EOF)
46
debug_return_size_t((size_t)-1);
47
debug_return_size_t(outlen + 1);
48
}
49
50
/*
51
* Print out line with word wrap around maxlen characters.
52
*/
53
while (linelen > maxlen) {
54
end = beg + maxlen;
55
while (end != beg && *end != ' ')
56
end--;
57
if (beg == end) {
58
/* Unable to find word break within maxlen, look beyond. */
59
end = strchr(beg + maxlen, ' ');
60
if (end == NULL)
61
break; /* no word break */
62
}
63
len = fprintf(fp, "%s%.*s\n", indent, (int)(end - beg), beg);
64
if (len < 0)
65
debug_return_size_t((size_t)-1);
66
outlen += (size_t)len;
67
while (*end == ' ')
68
end++;
69
linelen -= (size_t)(end - beg);
70
beg = end;
71
if (indent[0] == '\0') {
72
indent = EVENTLOG_INDENT;
73
maxlen -= sizeof(EVENTLOG_INDENT) - 1;
74
}
75
}
76
/* Print remainder, if any. */
77
if (linelen) {
78
len = fprintf(fp, "%s%s\n", indent, beg);
79
if (len < 0)
80
debug_return_size_t((size_t)-1);
81
outlen += (size_t)len;
82
}
83
84
debug_return_size_t(outlen);
85
}
86
87