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