Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sudo-project
GitHub Repository: sudo-project/sudo
Path: blob/main/lib/util/getdelim.c
1532 views
1
/*
2
* SPDX-License-Identifier: ISC
3
*
4
* Copyright (c) 2019-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
#ifndef HAVE_GETDELIM
22
23
#include <stdio.h>
24
#include <stdlib.h>
25
#include <string.h>
26
#include <limits.h>
27
28
#include <sudo_compat.h>
29
30
ssize_t
31
sudo_getdelim(char ** restrict buf, size_t * restrict bufsize, int delim,
32
FILE * restrict fp)
33
{
34
char *cp, *ep;
35
int ch;
36
37
if (*buf == NULL || *bufsize == 0) {
38
char *tmp = realloc(*buf, LINE_MAX);
39
if (tmp == NULL)
40
return -1;
41
*buf = tmp;
42
*bufsize = LINE_MAX;
43
}
44
cp = *buf;
45
ep = cp + *bufsize;
46
47
do {
48
if (cp + 1 >= ep) {
49
char *newbuf = reallocarray(*buf, *bufsize, 2);
50
if (newbuf == NULL)
51
goto bad;
52
*bufsize *= 2;
53
cp = newbuf + (cp - *buf);
54
ep = newbuf + *bufsize;
55
*buf = newbuf;
56
}
57
if ((ch = getc(fp)) == EOF) {
58
if (feof(fp))
59
break;
60
goto bad;
61
}
62
*cp++ = ch;
63
} while (ch != delim);
64
65
/* getdelim(3) should never return a length of 0. */
66
if (cp != *buf) {
67
*cp = '\0';
68
return (ssize_t)(cp - *buf);
69
}
70
bad:
71
/* Error, push back what was read if possible. */
72
while (cp > *buf) {
73
if (ungetc(*cp--, fp) == EOF)
74
break;
75
}
76
return -1;
77
}
78
#endif /* HAVE_GETDELIM */
79
80