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