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