configure.ac: do not check for malloc.h
[paraslash.git] / string.c
1 /*
2 * Copyright (C) 2004-2006 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 <regex.h>
26 #include <pwd.h>
27 #include <sys/utsname.h> /* uname() */
28 #include <string.h>
29
30 #include "error.h"
31
32 /**
33 * paraslash's version of realloc()
34 *
35 * \param p pointer to the memory block, may be NULL
36 * \param size desired new size
37 *
38 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
39 * i.e. there is no need to check the return value in the caller.
40 * \sa realloc(3)
41 */
42 __must_check __malloc void *para_realloc(void *p, size_t size)
43 {
44 /*
45 * No need to check for NULL pointers: If p is NULL, the call
46 * to realloc is equivalent to malloc(size)
47 */
48 if (!(p = realloc(p, size))) {
49 PARA_EMERG_LOG("%s", "realloc failed, aborting\n");
50 exit(EXIT_FAILURE);
51 }
52 return p;
53 }
54
55 /**
56 * paraslash's version of malloc()
57 *
58 * \param size desired new size
59 *
60 * A wrapper for malloc(3) which exits on errors.
61 * \sa malloc(3)
62 */
63 __must_check __malloc void *para_malloc(size_t size)
64 {
65 void *p = malloc(size);
66
67 if (!p) {
68 PARA_EMERG_LOG("%s", "malloc failed, aborting\n");
69 exit(EXIT_FAILURE);
70 }
71 return p;
72 }
73
74 /**
75 * paraslash's version of calloc()
76 *
77 * \param size desired new size
78 *
79 * A wrapper for calloc(3) which exits on errors.
80 * \sa calloc(3)
81 */
82 __must_check __malloc void *para_calloc(size_t size)
83 {
84 void *ret = para_malloc(size);
85
86 memset(ret, 0, size);
87 return ret;
88 }
89
90 /**
91 * paraslash's version of strdup()
92 *
93 * \param s: string to be duplicated
94 *
95 * A wrapper for strdup(3). It calls exit(EXIT_FAILURE) on
96 * errors, i.e. there is no need to check the return value in the caller.
97 * Moreover, this wrapper checks for \a s being NULL and returns an empty
98 * string in this case.
99 *
100 * \sa strdup(3)
101 */
102 __must_check __malloc char *para_strdup(const char *s)
103 {
104 char *ret;
105
106 if ((ret = strdup(s? s: "")))
107 return ret;
108 PARA_EMERG_LOG("%s", "strdup failed, aborting\n");
109 exit(EXIT_FAILURE);
110 }
111
112 /**
113 * allocate a sufficiently large string and print into it
114 *
115 * \param fmt usual format string
116 *
117 * Produce output according to \a fmt. No artificial bound on the length of the
118 * resulting string is imposed. This function either returns a pointer to a
119 * string that must be freed by the caller or aborts without returning.
120 *
121 * \sa printf(3)
122 */
123 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
124 {
125 char *msg;
126
127 PARA_VSPRINTF(fmt, msg);
128 return msg;
129 }
130
131 /**
132 * paraslash's version of strcat()
133 *
134 * \param a string to be appended to
135 * \param b string to append
136 *
137 * Append \a b to \a a. If \a a is NULL, return a copy of \a b, i.e.
138 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is NULL,
139 * return \a a without making a copy of \a a. Otherwise, construct the
140 * concatenation \a c, free \a a (but not \a b) and return \a c.
141 *
142 * \sa strcat(3)
143 */
144 __must_check __malloc char *para_strcat(char *a, const char *b)
145 {
146 char *tmp;
147
148 if (!a)
149 return para_strdup(b);
150 if (!b)
151 return a;
152 tmp = make_message("%s%s", a, b);
153 free(a);
154 return tmp;
155 }
156
157 /**
158 * paraslash's version of dirname()
159 *
160 * \param name pointer to The full path
161 *
162 * If \a name is \รพ NULL or the empty string, return \p NULL, Otherwise, Make a
163 * copy of \a name and return its directory component. Caller is responsible to
164 * free the result.
165 */
166 __must_check __malloc char *para_dirname(const char *name)
167 {
168 char *p, *ret;
169
170 if (!name || !*name)
171 return NULL;
172 ret = para_strdup(name);
173 p = strrchr(ret, '/');
174 if (!p)
175 *ret = '\0';
176 else
177 *p = '\0';
178 return ret;
179 }
180
181 /**
182 * paraslash's version of basename()
183 *
184 * \param name Pointer to the full path
185 *
186 * If \a name is \p NULL or the empty string, return \p NULL, Otherwise, make a
187 * copy of \a name and return its filename component. Caller is responsible to
188 * free the result.
189 */
190 __must_check __malloc char *para_basename(const char *name)
191 {
192 char *p;
193
194 if (!name || !*name)
195 return NULL;
196 p = strrchr(name, '/');
197 if (!p)
198 return para_strdup(name);
199 p++;
200 if (!*p)
201 return NULL;
202 return para_strdup(p);
203 }
204
205 /**
206 * simple search and replace routine
207 *
208 * \param src source string
209 * \param macro_name the name of the macro
210 * \param replacement the replacement format string
211 *
212 * Replace \a macro_name(arg) by \a replacement. \a replacement is a format
213 * string which may contain a single string conversion specifier which gets
214 * replaced by 'arg'.
215 *
216 * \return A string in which all matches in \a src are replaced, or NULL if an
217 * syntax error was encountered. Caller must free the result.
218 *
219 * \sa regcomp(3)
220 */
221 __must_check __malloc char *s_a_r(const char *src, const char* macro_name,
222 const char *replacement)
223 {
224 regex_t preg;
225 size_t nmatch = 1;
226 regmatch_t pmatch[1];
227 int eflags = 0;
228 char *dest = NULL;
229 const char *bufptr = src;
230
231 if (!macro_name || !replacement || !src)
232 return para_strdup(src);
233 regcomp(&preg, macro_name, 0);
234 while (regexec(&preg, bufptr, nmatch, pmatch, eflags)
235 != REG_NOMATCH) {
236 char *tmp, *arg, *o_bracket, *c_bracket;
237
238 o_bracket = strchr(bufptr + pmatch[0].rm_so, '(');
239 c_bracket = o_bracket? strchr(o_bracket, ')') : NULL;
240 if (!c_bracket)
241 goto out;
242 tmp = para_strdup(bufptr);
243 tmp[pmatch[0].rm_so] = '\0';
244 dest = para_strcat(dest, tmp);
245 free(tmp);
246
247 arg = para_strdup(o_bracket + 1);
248 arg[c_bracket - o_bracket - 1] = '\0';
249 tmp = make_message(replacement, arg);
250 free(arg);
251 dest = para_strcat(dest, tmp);
252 free(tmp);
253 bufptr = c_bracket;
254 bufptr++;
255 }
256 dest = para_strcat(dest, bufptr);
257 // PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
258 out:
259 regfree(&preg);
260 return dest;
261 }
262
263 /**
264 * replace a string according to a list of macros
265 *
266 * \param macro_list the array containing a macro/replacement pairs.
267 * \param src the source string
268 *
269 * This function just calls s_a_r() for each element of \a macro_list.
270 */
271 __must_check __malloc char *s_a_r_list(struct para_macro *macro_list, char *src)
272 {
273 struct para_macro *mp = macro_list;
274 char *ret = NULL, *tmp = para_strdup(src);
275
276 while (mp->name) {
277 ret = s_a_r(tmp, mp->name, mp->replacement);
278 free(tmp);
279 if (!ret) /* syntax error */
280 return NULL;
281 tmp = ret;
282 mp++;
283 }
284 //PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
285 return ret;
286 }
287
288 /**
289 * cut trailing newline
290 *
291 * \param buf the string to be chopped.
292 *
293 * Replace the last character in \a buf by zero if it is euqal to
294 * the newline character.
295 */
296 void chop(char *buf)
297 {
298 int n = strlen(buf);
299 if (!n)
300 return;
301 if (buf[n - 1] == '\n')
302 buf[n - 1] = '\0';
303 }
304
305 /**
306 * get a random filename
307 *
308 * This is by no means a secure way to create temporary files in a hostile
309 * direcory like /tmp. However, it is OK to use for temp files, fifos, sockets
310 * that are created in ~/.paraslash. Result must be freed by the caller.
311 */
312 __must_check __malloc char *para_tmpname(void)
313 {
314 struct timeval now;
315 gettimeofday(&now, NULL);
316 srand(now.tv_usec);
317 return make_message("%08i", rand());
318 }
319
320 /**
321 * create unique temporary file
322 *
323 * \param template the template to be passed to mkstemp()
324 * \param mode the desired mode of the tempfile
325 *
326 * This wrapper for mkstemp additionally uses fchmod() to
327 * set the given mode of the tempfile if mkstemp() returned success.
328 * Return value: The file descriptor of the temp file just created on success.
329 * On errors, -E_MKSTEMP or -E_FCHMOD is returned.
330 */
331 __must_check int para_mkstemp(char *template, mode_t mode)
332 {
333 int tmp, fd = mkstemp(template);
334
335 if (fd < 0)
336 return -E_MKSTEMP;
337 tmp = fchmod(fd, mode);
338 if (tmp >= 0)
339 return fd;
340 close(fd);
341 unlink(template);
342 return -E_FCHMOD;
343 }
344
345 /**
346 * get the logname of the current user
347 *
348 * \return A dynammically allocated string that must be freed by the caller. On
349 * errors, the string "unknown user" is returned, i.e. this function never
350 * returns NULL.
351 */
352 __must_check __malloc char *para_logname(void)
353 {
354 struct passwd *pw = getpwuid(getuid());
355 return para_strdup(pw? pw->pw_name : "unknown_user");
356 }
357
358 /**
359 * get the home directory of the current user
360 *
361 * \return A dynammically allocated string that must be freed by the caller. If
362 * the home directory could not be found, this function returns "/tmp".
363 */
364 __must_check __malloc char *para_homedir(void)
365 {
366 struct passwd *pw = getpwuid(getuid());
367 return para_strdup(pw? pw->pw_dir : "/tmp");
368 }
369
370 /**
371 * split string and return pointers to its parts.
372 *
373 * \param args the string to be split
374 * \param argv_ptr pointer to the list of substrings
375 * \param delim delimiter
376 *
377 * This function modifies \a args by replacing each occurance of \a delim by
378 * zero. A NULL-terminated array of pointers to char* is allocated dynamically
379 * and these pointers are initialized to point to the broken-up substrings
380 * within \a args. A pointer to this array is returned via \a argv_ptr. It's OK
381 * to call this function with \a args == NULL.
382 *
383 * \return The number of substrings found in \a args.
384 */
385
386 __must_check unsigned split_args(char *args, char ***argv_ptr, const char *delim)
387 {
388 char *p = args;
389 char **argv;
390 size_t n = 0, i, j;
391
392 p = args + strspn(args, delim);
393 for (;;) {
394 i = strcspn(p, delim);
395 if (!i)
396 break;
397 p += i;
398 n++;
399 p += strspn(p, delim);
400 }
401 *argv_ptr = para_malloc((n + 1) * sizeof(char *));
402 argv = *argv_ptr;
403 i = 0;
404 p = args + strspn(args, delim);
405 while (p) {
406 argv[i] = p;
407 j = strcspn(p, delim);
408 if (!j)
409 break;
410 p += strcspn(p, delim);
411 if (*p) {
412 *p = '\0';
413 p++;
414 p += strspn(p, delim);
415 }
416 i++;
417 }
418 argv[n] = NULL;
419 return n;
420 }
421
422 /**
423 * ensure that file descriptors 0, 1, and 2 are valid
424 *
425 * Common approach that opens /dev/null until it gets a file descriptor greater
426 * than two.
427 *
428 * \sa okir's Black Hats Manual.
429 */
430 void valid_fd_012(void)
431 {
432 while (1) {
433 int fd;
434
435 fd = open("/dev/null", O_RDWR);
436 if (fd < 0)
437 exit(EXIT_FAILURE);
438 if (fd > 2) {
439 close(fd);
440 break;
441 }
442 }
443 }
444
445 /**
446 * get the own hostname
447 *
448 * \return A dynammically allocated string containing the hostname.
449 *
450 * \sa uname(2)
451 */
452 __malloc char *para_hostname(void)
453 {
454 struct utsname u;
455
456 uname(&u);
457 return para_strdup(u.nodename);
458 }