-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.c
120 lines (94 loc) · 2.36 KB
/
util.c
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
/* $OpenBSD: util.c,v 1.127 2016/05/16 17:43:18 gilles Exp $ */
/*
* Copyright (c) 2000,2001 Markus Friedl. All rights reserved.
* Copyright (c) 2008 Gilles Chehade <[email protected]>
* Copyright (c) 2009 Jacek Masiulaniec <[email protected]>
* Copyright (c) 2012 Eric Faurot <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "compat.h"
#include <sys/types.h>
#include <netinet/in.h>
#include <ctype.h>
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#include "log.h"
void *
xmalloc(size_t size, const char *where)
{
void *r;
if ((r = malloc(size)) == NULL) {
log_warnx("%s: malloc(%zu)", where, size);
fatalx("exiting");
}
return (r);
}
void *
xcalloc(size_t nmemb, size_t size, const char *where)
{
void *r;
if ((r = calloc(nmemb, size)) == NULL) {
log_warnx("%s: calloc(%zu, %zu)", where, nmemb, size);
fatalx("exiting");
}
return (r);
}
char *
xstrdup(const char *str, const char *where)
{
char *r;
if ((r = strdup(str)) == NULL) {
log_warnx("%s: strdup(%p)", where, str);
fatalx("exiting");
}
return (r);
}
void *
xmemdup(const void *ptr, size_t size, const char *where)
{
void *r;
if ((r = malloc(size)) == NULL) {
log_warnx("%s: malloc(%zu)", where, size);
fatalx("exiting");
}
memmove(r, ptr, size);
return (r);
}
char *
strip(char *s)
{
size_t l;
while (isspace((unsigned char)*s))
s++;
for (l = strlen(s); l; l--) {
if (!isspace((unsigned char)s[l-1]))
break;
s[l-1] = '\0';
}
return (s);
}
int
lowercase(char *buf, const char *s, size_t len)
{
if (len == 0)
return 0;
if (strlcpy(buf, s, len) >= len)
return 0;
while (*buf != '\0') {
*buf = tolower((unsigned char)*buf);
buf++;
}
return 1;
}