52c5183b418e772ee5a603eddb4290755769919e
[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 <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  *
41  * \return A pointer to  the newly allocated memory, which is suitably aligned
42  * for any kind of variable and may be different from \p p.
43  *
44  * \sa realloc(3)
45  */
46 __must_check __malloc void *para_realloc(void *p, size_t size)
47 {
48         /*
49          * No need to check for NULL pointers: If p is NULL, the  call
50          * to realloc is equivalent to malloc(size)
51          */
52         if (!(p = realloc(p, size))) {
53                 PARA_EMERG_LOG("%s", "realloc failed, aborting\n");
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  * A pointer to the allocated and zeroed-out memory, which is suitably aligned
90  * 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 exit(EXIT_FAILURE) on errors, i.e. there
108  * 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  * simple search and replace routine
228  *
229  * \param src source string
230  * \param macro_name the name of the macro
231  * \param replacement the replacement format string
232  *
233  * In \p src, replace each occurence of \p macro_name(arg) by the string
234  * determined by the \p replacement format string. \p replacement may (but
235  * needs not) contain a single string conversion specifier (%s) which gets
236  * replaced by \p arg.
237  *
238  * \return A string in which all matches in \p src are replaced, or \p NULL if
239  * an syntax error was encountered. Caller must free the result.
240  *
241  * \sa regcomp(3)
242  */
243 __must_check __malloc char *s_a_r(const char *src, const char* macro_name,
244                 const char *replacement)
245 {
246         regex_t preg;
247         size_t  nmatch = 1;
248         regmatch_t pmatch[1];
249         int eflags = 0;
250         char *dest = NULL;
251         const char *bufptr = src;
252
253         if (!macro_name || !replacement || !src)
254                 return para_strdup(src);
255         regcomp(&preg, macro_name, 0);
256         while (regexec(&preg,  bufptr, nmatch, pmatch, eflags)
257                         != REG_NOMATCH) {
258                 char *tmp, *arg, *o_bracket, *c_bracket;
259
260                 o_bracket = strchr(bufptr + pmatch[0].rm_so, '(');
261                 c_bracket = o_bracket? strchr(o_bracket, ')') : NULL;
262                 if (!c_bracket)
263                         goto out;
264                 tmp = para_strdup(bufptr);
265                 tmp[pmatch[0].rm_so] = '\0';
266                 dest = para_strcat(dest, tmp);
267                 free(tmp);
268
269                 arg = para_strdup(o_bracket + 1);
270                 arg[c_bracket - o_bracket - 1] = '\0';
271                 tmp = make_message(replacement, arg);
272                 free(arg);
273                 dest = para_strcat(dest, tmp);
274                 free(tmp);
275                 bufptr = c_bracket;
276                 bufptr++;
277         }
278         dest = para_strcat(dest, bufptr);
279 //      PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
280 out:
281         regfree(&preg);
282         return dest;
283 }
284
285 /**
286  * replace a string according to a list of macros
287  *
288  * \param macro_list the array containing a macro/replacement pairs.
289  * \param src the source string
290  *
291  * This function just calls s_a_r() for each element of \p macro_list.
292  *
293  * \return \p NULL if one of the underlying calls to \p s_a_r returned \p NULL.
294  * Otherwise the completely expanded version of \p src is returned.
295  */
296 __must_check __malloc char *s_a_r_list(struct para_macro *macro_list, char *src)
297 {
298         struct para_macro *mp = macro_list;
299         char *ret = NULL, *tmp = para_strdup(src);
300
301         while (mp->name) {
302                 ret = s_a_r(tmp, mp->name, mp->replacement);
303                 free(tmp);
304                 if (!ret) /* syntax error */
305                         return NULL;
306                 tmp = ret;
307                 mp++;
308         }
309         //PARA_DEBUG_LOG("%s: returning %s\n", __func__, dest);
310         return ret;
311 }
312
313 /**
314  * cut trailing newline
315  *
316  * \param buf the string to be chopped.
317  *
318  * Replace the last character in \p buf by zero if it is euqal to
319  * the newline character.
320  */
321 void chop(char *buf)
322 {
323         int n = strlen(buf);
324         if (!n)
325                 return;
326         if (buf[n - 1] == '\n')
327                 buf[n - 1] = '\0';
328 }
329
330 /**
331  * get a random filename
332  *
333  * This is by no means a secure way to create temporary files in a hostile
334  * direcory like \p /tmp. However, it is OK to use for temp files, fifos,
335  * sockets that are created in ~/.paraslash. Result must be freed by the
336  * caller.
337  *
338  * \return a pointer to a random filename.
339  */
340 __must_check __malloc char *para_tmpname(void)
341 {
342         struct timeval now;
343         gettimeofday(&now, NULL);
344         srand(now.tv_usec);
345         return make_message("%08i", rand());
346 }
347
348 /**
349  * create unique temporary file
350  *
351  * \param template the template to be passed to mkstemp()
352  * \param mode the desired mode of the tempfile
353  *
354  * This wrapper for mkstemp additionally uses fchmod() to
355  * set the given mode of the tempfile if mkstemp() returned success.
356  *
357  * \return The file descriptor of the temp file just created on success.
358  * On errors, -E_MKSTEMP or -E_FCHMOD is returned.
359  */
360 __must_check int para_mkstemp(char *template, mode_t mode)
361 {
362         int tmp, fd = mkstemp(template);
363
364         if (fd < 0)
365                 return -E_MKSTEMP;
366         tmp = fchmod(fd, mode);
367         if (tmp >= 0)
368                 return fd;
369         close(fd);
370         unlink(template);
371         return -E_FCHMOD;
372 }
373
374 /**
375  * get the logname of the current user
376  *
377  * \return A dynammically allocated string that must be freed by the caller. On
378  * errors, the string "unknown user" is returned, i.e. this function never
379  * returns NULL.
380  *
381  * \sa getpwuid(3)
382  */
383 __must_check __malloc char *para_logname(void)
384 {
385         struct passwd *pw = getpwuid(getuid());
386         return para_strdup(pw? pw->pw_name : "unknown_user");
387 }
388
389 /**
390  * get the home directory of the current user
391  *
392  * \return A dynammically allocated string that must be freed by the caller. If
393  * the home directory could not be found, this function returns "/tmp".
394  */
395 __must_check __malloc char *para_homedir(void)
396 {
397         struct passwd *pw = getpwuid(getuid());
398         return para_strdup(pw? pw->pw_dir : "/tmp");
399 }
400
401 /**
402  * split string and return pointers to its parts.
403  *
404  * \param args the string to be split
405  * \param argv_ptr  pointer to the list of substrings
406  * \param delim delimiter
407  *
408  * This function modifies \p args by replacing each occurance of \p delim by
409  * zero. A NULL-terminated array of pointers to char* is allocated dynamically
410  * and these pointers are initialized to point to the broken-up substrings
411  * within \p args. A pointer to this array is returned via \p argv_ptr. It's OK
412  * to call this function with \p args \p == \p NULL.
413  *
414  * \return The number of substrings found in \p args.
415  */
416 __must_check unsigned split_args(char *args, char ***argv_ptr, const char *delim)
417 {
418         char *p = args;
419         char **argv;
420         size_t n = 0, i, j;
421
422         p = args + strspn(args, delim);
423         for (;;) {
424                 i = strcspn(p, delim);
425                 if (!i)
426                         break;
427                 p += i;
428                 n++;
429                 p += strspn(p, delim);
430         }
431         *argv_ptr = para_malloc((n + 1) * sizeof(char *));
432         argv = *argv_ptr;
433         i = 0;
434         p = args + strspn(args, delim);
435         while (p) {
436                 argv[i] = p;
437                 j = strcspn(p, delim);
438                 if (!j)
439                         break;
440                 p += strcspn(p, delim);
441                 if (*p) {
442                         *p = '\0';
443                         p++;
444                         p += strspn(p, delim);
445                 }
446                 i++;
447         }
448         argv[n] = NULL;
449         return n;
450 }
451
452 /**
453  * ensure that file descriptors 0, 1, and 2 are valid
454  *
455  * Common approach that opens /dev/null until it gets a file descriptor greater
456  * than two.
457  *
458  * \sa okir's Black Hats Manual.
459  */
460 void valid_fd_012(void)
461 {
462         while (1) {
463         int     fd;
464
465                 fd = open("/dev/null", O_RDWR);
466                 if (fd < 0)
467                         exit(EXIT_FAILURE);
468                 if (fd > 2) {
469                         close(fd);
470                         break;
471                 }
472         }
473 }
474
475 /**
476  * get the own hostname
477  *
478  * \return A dynammically allocated string containing the hostname.
479  *
480  * \sa uname(2)
481  */
482 __malloc char *para_hostname(void)
483 {
484         struct utsname u;
485
486         uname(&u);
487         return para_strdup(u.nodename);
488 }