pwmc: better output of status messages.
[libpwmd.git] / src / misc.c
blob660310365598f624069f33f71c15f962422a3555
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006-2010 Ben Kibbey <bjk@luxsci.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02110-1301 USA
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
23 #include <stdio.h>
24 #include <unistd.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <libpwmd.h>
28 #include "misc.h"
30 char *_expand_homedir(char *str, struct passwd *pw)
32 char *p = str;
33 char *pwbuf = NULL;
34 char *result;
36 if (!p)
37 return NULL;
39 if (*p != '~' || *(p+1) != '/')
40 return pwmd_strdup(p);
42 if (!pw) {
43 struct passwd t;
45 pwbuf = _getpwuid(&t);
47 if (!pwbuf)
48 return NULL;
50 pw = &t;
53 p += 2;
54 result = pwmd_strdup_printf("%s/%s", pw->pw_dir, p);
56 if (pwbuf)
57 pwmd_free(pwbuf);
59 return result;
62 char *_getpwuid(struct passwd *pwd)
64 size_t size = sysconf(_SC_GETPW_R_SIZE_MAX);
65 struct passwd *result;
66 char *buf;
67 int n;
69 if (size == -1)
70 size = 16384;
72 buf = pwmd_malloc(size);
74 if (!buf)
75 return NULL;
77 n = getpwuid_r(getuid(), pwd, buf, size, &result);
79 if (n) {
80 pwmd_free(buf);
81 errno = n;
82 return NULL;
85 if (!result) {
86 pwmd_free(buf);
87 return NULL;
90 errno = n;
91 return buf;
95 * Borrowed from libassuan.
97 char *_percent_escape(const char *atext)
99 const unsigned char *s;
100 int len;
101 char *buf, *p;
103 if (!atext)
104 return NULL;
106 len = strlen(atext) * 3 + 1;
107 buf = (char *)pwmd_malloc(len);
109 if (!buf)
110 return NULL;
112 p = buf;
114 for (s=(const unsigned char *)atext; *s; s++) {
115 if (*s < ' ') {
116 sprintf (p, "%%%02X", *s);
117 p += 3;
119 else
120 *p++ = *s;
123 *p = 0;
124 return buf;