9ad6bfb8edd7e616e61c16acec38f9a4d5bdb8e3
[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         unsigned int seed;
257
258         gettimeofday(&now, NULL);
259         seed = now.tv_usec;
260         srand(seed);
261         return make_message("%08i", rand());
262 }
263
264 /**
265  * create unique temporary file
266  *
267  * \param template the template to be passed to mkstemp()
268  * \param mode the desired mode of the tempfile
269  *
270  * This wrapper for mkstemp additionally uses fchmod() to
271  * set the given mode of the tempfile if mkstemp() returned success.
272  *
273  * \return The file descriptor of the temp file just created on success.
274  * On errors, -E_MKSTEMP or -E_FCHMOD is returned.
275  */
276 __must_check int para_mkstemp(char *template, mode_t mode)
277 {
278         int tmp, fd = mkstemp(template);
279
280         if (fd < 0)
281                 return -E_MKSTEMP;
282         tmp = fchmod(fd, mode);
283         if (tmp >= 0)
284                 return fd;
285         close(fd);
286         unlink(template);
287         return -E_FCHMOD;
288 }
289
290 /**
291  * get the logname of the current user
292  *
293  * \return A dynammically allocated string that must be freed by the caller. On
294  * errors, the string "unknown user" is returned, i.e. this function never
295  * returns NULL.
296  *
297  * \sa getpwuid(3)
298  */
299 __must_check __malloc char *para_logname(void)
300 {
301         struct passwd *pw = getpwuid(getuid());
302         return para_strdup(pw? pw->pw_name : "unknown_user");
303 }
304
305 /**
306  * get the home directory of the current user
307  *
308  * \return A dynammically allocated string that must be freed by the caller. If
309  * the home directory could not be found, this function returns "/tmp".
310  */
311 __must_check __malloc char *para_homedir(void)
312 {
313         struct passwd *pw = getpwuid(getuid());
314         return para_strdup(pw? pw->pw_dir : "/tmp");
315 }
316
317 /**
318  * split string and return pointers to its parts.
319  *
320  * \param args the string to be split
321  * \param argv_ptr  pointer to the list of substrings
322  * \param delim delimiter
323  *
324  * This function modifies \a args by replacing each occurance of \a delim by
325  * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
326  * and these pointers are initialized to point to the broken-up substrings
327  * within \a args. A pointer to this array is returned via \a argv_ptr. It's OK
328  * to call this function with \a args \a == \p NULL.
329  *
330  * \return The number of substrings found in \a args.
331  */
332 __must_check unsigned split_args(char *args, char ***argv_ptr, const char *delim)
333 {
334         char *p = args;
335         char **argv;
336         size_t n = 0, i, j;
337
338         p = args + strspn(args, delim);
339         for (;;) {
340                 i = strcspn(p, delim);
341                 if (!i)
342                         break;
343                 p += i;
344                 n++;
345                 p += strspn(p, delim);
346         }
347         *argv_ptr = para_malloc((n + 1) * sizeof(char *));
348         argv = *argv_ptr;
349         i = 0;
350         p = args + strspn(args, delim);
351         while (p) {
352                 argv[i] = p;
353                 j = strcspn(p, delim);
354                 if (!j)
355                         break;
356                 p += strcspn(p, delim);
357                 if (*p) {
358                         *p = '\0';
359                         p++;
360                         p += strspn(p, delim);
361                 }
362                 i++;
363         }
364         argv[n] = NULL;
365         return n;
366 }
367
368 /**
369  * ensure that file descriptors 0, 1, and 2 are valid
370  *
371  * Common approach that opens /dev/null until it gets a file descriptor greater
372  * than two.
373  *
374  * \sa okir's Black Hats Manual.
375  */
376 void valid_fd_012(void)
377 {
378         while (1) {
379         int     fd;
380
381                 fd = open("/dev/null", O_RDWR);
382                 if (fd < 0)
383                         exit(EXIT_FAILURE);
384                 if (fd > 2) {
385                         close(fd);
386                         break;
387                 }
388         }
389 }
390
391 /**
392  * get the own hostname
393  *
394  * \return A dynammically allocated string containing the hostname.
395  *
396  * \sa uname(2)
397  */
398 __malloc char *para_hostname(void)
399 {
400         struct utsname u;
401
402         uname(&u);
403         return para_strdup(u.nodename);
404 }