ssh.c cleanup.
[libpwmd.git] / src / misc.c
blobebcf12d377cfcafe27e62775de939696e87424d3
1 /* vim:tw=78:ts=8:sw=4:set ft=c: */
2 /*
3 Copyright (C) 2006-2009 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 #include <stdio.h>
20 #include <unistd.h>
21 #include <string.h>
22 #include <errno.h>
23 #include <libpwmd.h>
24 #include "misc.h"
26 char *_expand_homedir(char *str, struct passwd *pw)
28 char *p = str;
29 char *pwbuf = NULL;
30 char *result;
32 if (!p)
33 return NULL;
35 if (*p != '~' || *(p+1) != '/')
36 return pwmd_strdup(p);
38 if (!pw) {
39 struct passwd t;
41 pwbuf = _getpwuid(&t);
43 if (!pwbuf)
44 return NULL;
46 pw = &t;
49 p += 2;
50 result = pwmd_strdup_printf("%s/%s", pw->pw_dir, p);
52 if (pwbuf)
53 pwmd_free(pwbuf);
55 return result;
58 char *_getpwuid(struct passwd *pwd)
60 size_t size = sysconf(_SC_GETPW_R_SIZE_MAX);
61 struct passwd *result;
62 char *buf;
63 int n;
65 if (size == -1)
66 size = 16384;
68 buf = pwmd_malloc(size);
70 if (!buf)
71 return NULL;
73 n = getpwuid_r(getuid(), pwd, buf, size, &result);
75 if (n) {
76 pwmd_free(buf);
77 errno = n;
78 return NULL;
81 if (!result) {
82 pwmd_free(buf);
83 return NULL;
86 errno = n;
87 return buf;
90 char *_to_hex(const char *str, size_t slen)
92 int i;
93 char *buf = pwmd_malloc(slen*2+1);
95 if (!buf)
96 return NULL;
98 for (i = 0, buf[0] = 0; i < slen; i++) {
99 char tmp[3];
101 sprintf(tmp, "%02x", (unsigned char)str[i]);
102 strcat(buf, tmp);
105 return buf;
109 * Borrowed from libassuan.
111 char *_percent_escape(const char *atext)
113 const unsigned char *s;
114 int len = strlen(atext) * 3 + 1;
115 char *buf = (char *)pwmd_malloc(len), *p = buf;
117 if (!buf)
118 return NULL;
120 for (s=(const unsigned char *)atext; *s; s++) {
121 if (*s < ' ') {
122 sprintf (p, "%%%02X", *s);
123 p += 3;
125 else
126 *p++ = *s;
129 *p = 0;
130 return buf;