| 1 | /* filenames.c - Functions for dealing with filenames. |
| 2 | Copyright (C) 1998, 1999, 2000, 2001, 2003, |
| 3 | 2004, 2005 Free Software Foundation, Inc. |
| 4 | Copyright (C) 2004, 2005, 2007, 2008 g10 Code GmbH |
| 5 | |
| 6 | This file is part of Poldi. |
| 7 | |
| 8 | Poldi is free software; you can redistribute it and/or modify it |
| 9 | under the terms of the GNU General Public License as published by |
| 10 | the Free Software Foundation; either version 3 of the License, or |
| 11 | (at your option) any later version. |
| 12 | |
| 13 | Poldi is distributed in the hope that it will be useful, but |
| 14 | WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 16 | General Public License for more details. |
| 17 | |
| 18 | You should have received a copy of the GNU General Public License |
| 19 | along with this program; if not, see |
| 20 | <http://www.gnu.org/licenses/>. */ |
| 21 | |
| 22 | #include <poldi.h> |
| 23 | |
| 24 | #include <stdarg.h> |
| 25 | #include <string.h> |
| 26 | #include <stdlib.h> |
| 27 | #include <errno.h> |
| 28 | |
| 29 | /* Construct a filename from the NULL terminated list of parts, |
| 30 | including tilde expansion at the beginning. Stores the newly |
| 31 | allocated string in *PATH, which needs to be freed with xfree(). |
| 32 | Returns error code. This is based on make_filename() as found in |
| 33 | jnlib. */ |
| 34 | gpg_error_t |
| 35 | make_filename (char **path, const char *first_part, ...) |
| 36 | { |
| 37 | va_list ap; |
| 38 | size_t n; |
| 39 | const char *s; |
| 40 | char *name, *home, *p; |
| 41 | gpg_error_t err = 0; |
| 42 | |
| 43 | name = NULL; |
| 44 | |
| 45 | va_start (ap, first_part); |
| 46 | n = strlen (first_part) + 1; |
| 47 | while ((s = va_arg (ap, const char *))) |
| 48 | n += strlen (s) + 1; |
| 49 | va_end (ap); |
| 50 | |
| 51 | home = NULL; |
| 52 | if (*first_part == '~' && first_part[1] == '/') |
| 53 | { |
| 54 | home = getenv ("HOME"); |
| 55 | if (home && *home) |
| 56 | n += strlen (home); |
| 57 | } |
| 58 | |
| 59 | name = xtrymalloc (n); |
| 60 | if (!name) |
| 61 | { |
| 62 | err = gpg_error_from_errno (errno); |
| 63 | goto out; |
| 64 | } |
| 65 | |
| 66 | p = name; |
| 67 | if (home) |
| 68 | { |
| 69 | p = stpcpy (p, home); |
| 70 | p = stpcpy (p, first_part+1); |
| 71 | } |
| 72 | else |
| 73 | p = stpcpy (p, first_part); |
| 74 | |
| 75 | va_start (ap, first_part); |
| 76 | while ((s = va_arg (ap, const char *))) |
| 77 | { |
| 78 | p = stpcpy (p, "/"); |
| 79 | p = stpcpy (p, s); |
| 80 | } |
| 81 | va_end (ap); |
| 82 | |
| 83 | out: |
| 84 | |
| 85 | *path = name; |
| 86 | |
| 87 | return err; |
| 88 | } |
| 89 | |
| 90 | /* END */ |