string.c para_realloc(): report requested size on realloc failures
[paraslash.git] / string.c
1 /*
2 * Copyright (C) 2004-2007 Andre Noll <maan@systemlinux.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
17 */
18
19 /** \file string.c memory allocation and string handling functions */
20
21 #include "para.h"
22 #include "string.h"
23
24 #include <sys/time.h> /* gettimeofday */
25 #include <pwd.h>
26 #include <sys/utsname.h> /* uname() */
27 #include <string.h>
28
29 #include "error.h"
30
31 /**
32 * paraslash's version of realloc()
33 *
34 * \param p pointer to the memory block, may be NULL
35 * \param size desired new size
36 *
37 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
38 * i.e. there is no need to check the return value in the caller.
39 *
40 * \return A pointer to the newly allocated memory, which is suitably aligned
41 * for any kind of variable and may be different from \p p.
42 *
43 * \sa realloc(3)
44 */
45 __must_check __malloc void *para_realloc(void *p, size_t size)
46 {
47 /*
48 * No need to check for NULL pointers: If p is NULL, the call
49 * to realloc is equivalent to malloc(size)
50 */
51 if (!(p = realloc(p, size))) {
52 PARA_EMERG_LOG("realloc failed (size = %zu), aborting\n",
53 size);
54 exit(EXIT_FAILURE);
55 }
56 return p;
57 }
58
59 /**
60 * paraslash's version of malloc()
61 *
62 * \param size desired new size
63 *
64 * A wrapper for malloc(3) which exits on errors.
65 *
66 * \return A pointer to the allocated memory, which is suitably aligned for any
67 * kind of variable.
68 *
69 * \sa malloc(3)
70 */
71 __must_check __malloc void *para_malloc(size_t size)
72 {
73 void *p = malloc(size);
74
75 if (!p) {
76 PARA_EMERG_LOG("%s", "malloc failed, aborting\n");
77 exit(EXIT_FAILURE);
78 }
79 return p;
80 }
81
82 /**
83 * paraslash's version of calloc()
84 *
85 * \param size desired new size
86 *
87 * A wrapper for calloc(3) which exits on errors.
88 *
89 * \return A pointer to the allocated and zeroed-out memory, which is suitably
90 * aligned for any kind of variable.
91 *
92 * \sa calloc(3)
93 */
94 __must_check __malloc void *para_calloc(size_t size)
95 {
96 void *ret = para_malloc(size);
97
98 memset(ret, 0, size);
99 return ret;
100 }
101
102 /**
103 * paraslash's version of strdup()
104 *
105 * \param s string to be duplicated
106 *
107 * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
108 * there is no need to check the return value in the caller.
109 *
110 * \return A pointer to the duplicated string. If \p s was the NULL pointer,
111 * an pointer to an empty string is returned.
112 *
113 * \sa strdup(3)
114 */
115 __must_check __malloc char *para_strdup(const char *s)
116 {
117 char *ret;
118
119 if ((ret = strdup(s? s: "")))
120 return ret;
121 PARA_EMERG_LOG("%s", "strdup failed, aborting\n");
122 exit(EXIT_FAILURE);
123 }
124
125 /**
126 * allocate a sufficiently large string and print into it
127 *
128 * \param fmt usual format string
129 *
130 * Produce output according to \p fmt. No artificial bound on the length of the
131 * resulting string is imposed.
132 *
133 * \return This function either returns a pointer to a string that must be
134 * freed by the caller or aborts without returning.
135 *
136 * \sa printf(3)
137 */
138 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
139 {
140 char *msg;
141
142 PARA_VSPRINTF(fmt, msg);
143 return msg;
144 }
145
146 /**
147 * paraslash's version of strcat()
148 *
149 * \param a string to be appended to
150 * \param b string to append
151 *
152 * Append \p b to \p a.
153 *
154 * \return If \p a is NULL, return a pointer to a copy of \p b, i.e.
155 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \p b is NULL,
156 * return \p a without making a copy of \p a. Otherwise, construct the
157 * concatenation \p c, free \p a (but not \p b) and return \p c.
158 *
159 * \sa strcat(3)
160 */
161 __must_check __malloc char *para_strcat(char *a, const char *b)
162 {
163 char *tmp;
164
165 if (!a)
166 return para_strdup(b);
167 if (!b)
168 return a;
169 tmp = make_message("%s%s", a, b);
170 free(a);
171 return tmp;
172 }
173
174 /**
175 * paraslash's version of dirname()
176 *
177 * \param name pointer to the full path
178 *
179 * Compute the directory component of \p name
180 *
181 * \return If \p name is \รพ NULL or the empty string, return \p NULL.
182 * Otherwise, Make a copy of \p name and return its directory component. Caller
183 * is responsible to free the result.
184 */
185 __must_check __malloc char *para_dirname(const char *name)
186 {
187 char *p, *ret;
188
189 if (!name || !*name)
190 return NULL;
191 ret = para_strdup(name);
192 p = strrchr(ret, '/');
193 if (!p)
194 *ret = '\0';
195 else
196 *p = '\0';
197 return ret;
198 }
199
200 /**
201 * paraslash's version of basename()
202 *
203 * \param name Pointer to the full path
204 *
205 * Compute the filename component of \p name
206 *
207 * \return If \p name is \p NULL or the empty string, return \p NULL,
208 * Otherwise, make a copy of \p name and return its filename component. Caller
209 * is responsible to free the result.
210 */
211 __must_check __malloc char *para_basename(const char *name)
212 {
213 char *p;
214
215 if (!name || !*name)
216 return NULL;
217 p = strrchr(name, '/');
218 if (!p)
219 return para_strdup(name);
220 p++;
221 if (!*p)
222 return NULL;
223 return para_strdup(p);
224 }
225
226 /**
227 * cut trailing newline
228 *
229 * \param buf the string to be chopped.
230 *
231 * Replace the last character in \p buf by zero if it is euqal to
232 * the newline character.
233 */
234 void chop(char *buf)
235 {
236 int n = strlen(buf);
237 if (!n)
238 return;
239 if (buf[n - 1] == '\n')
240 buf[n - 1] = '\0';
241 }
242
243 /**
244 * get a random filename
245 *
246 * This is by no means a secure way to create temporary files in a hostile
247 * direcory like \p /tmp. However, it is OK to use for temp files, fifos,
248 * sockets that are created in ~/.paraslash. Result must be freed by the
249 * caller.
250 *
251 * \return a pointer to a random filename.
252 */
253 __must_check __malloc char *para_tmpname(void)
254 {
255 struct timeval now;
256 gettimeofday(&now, NULL);
257 srand(now.tv_usec);
258 return make_message("%08i", rand());
259 }
260
261 /**
262 * create unique temporary file
263 *
264 * \param template the template to be passed to mkstemp()
265 * \param mode the desired mode of the tempfile
266 *
267 * This wrapper for mkstemp additionally uses fchmod() to
268 * set the given mode of the tempfile if mkstemp() returned success.
269 *
270 * \return The file descriptor of the temp file just created on success.
271 * On errors, -E_MKSTEMP or -E_FCHMOD is returned.
272 */
273 __must_check int para_mkstemp(char *template, mode_t mode)
274 {
275 int tmp, fd = mkstemp(template);
276
277 if (fd < 0)
278 return -E_MKSTEMP;
279 tmp = fchmod(fd, mode);
280 if (tmp >= 0)
281 return fd;
282 close(fd);
283 unlink(template);
284 return -E_FCHMOD;
285 }
286
287 /**
288 * get the logname of the current user
289 *
290 * \return A dynammically allocated string that must be freed by the caller. On
291 * errors, the string "unknown user" is returned, i.e. this function never
292 * returns NULL.
293 *
294 * \sa getpwuid(3)
295 */
296 __must_check __malloc char *para_logname(void)
297 {
298 struct passwd *pw = getpwuid(getuid());
299 return para_strdup(pw? pw->pw_name : "unknown_user");
300 }
301
302 /**
303 * get the home directory of the current user
304 *
305 * \return A dynammically allocated string that must be freed by the caller. If
306 * the home directory could not be found, this function returns "/tmp".
307 */
308 __must_check __malloc char *para_homedir(void)
309 {
310 struct passwd *pw = getpwuid(getuid());
311 return para_strdup(pw? pw->pw_dir : "/tmp");
312 }
313
314 /**
315 * split string and return pointers to its parts.
316 *
317 * \param args the string to be split
318 * \param argv_ptr pointer to the list of substrings
319 * \param delim delimiter
320 *
321 * This function modifies \a args by replacing each occurance of \a delim by
322 * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
323 * and these pointers are initialized to point to the broken-up substrings
324 * within \a args. A pointer to this array is returned via \a argv_ptr. It's OK
325 * to call this function with \a args \a == \p NULL.
326 *
327 * \return The number of substrings found in \a args.
328 */
329 __must_check unsigned split_args(char *args, char ***argv_ptr, const char *delim)
330 {
331 char *p = args;
332 char **argv;
333 size_t n = 0, i, j;
334
335 p = args + strspn(args, delim);
336 for (;;) {
337 i = strcspn(p, delim);
338 if (!i)
339 break;
340 p += i;
341 n++;
342 p += strspn(p, delim);
343 }
344 *argv_ptr = para_malloc((n + 1) * sizeof(char *));
345 argv = *argv_ptr;
346 i = 0;
347 p = args + strspn(args, delim);
348 while (p) {
349 argv[i] = p;
350 j = strcspn(p, delim);
351 if (!j)
352 break;
353 p += strcspn(p, delim);
354 if (*p) {
355 *p = '\0';
356 p++;
357 p += strspn(p, delim);
358 }
359 i++;
360 }
361 argv[n] = NULL;
362 return n;
363 }
364
365 /**
366 * ensure that file descriptors 0, 1, and 2 are valid
367 *
368 * Common approach that opens /dev/null until it gets a file descriptor greater
369 * than two.
370 *
371 * \sa okir's Black Hats Manual.
372 */
373 void valid_fd_012(void)
374 {
375 while (1) {
376 int fd;
377
378 fd = open("/dev/null", O_RDWR);
379 if (fd < 0)
380 exit(EXIT_FAILURE);
381 if (fd > 2) {
382 close(fd);
383 break;
384 }
385 }
386 }
387
388 /**
389 * get the own hostname
390 *
391 * \return A dynammically allocated string containing the hostname.
392 *
393 * \sa uname(2)
394 */
395 __malloc char *para_hostname(void)
396 {
397 struct utsname u;
398
399 uname(&u);
400 return para_strdup(u.nodename);
401 }