wincred: handle empty username/password correctly
[git/mingw/4msysgit.git] / contrib / credential / wincred / git-credential-wincred.c
blob219999d2734cd3a77ba3d2c67326f17e8d2d2bb5
1 /*
2 * A git credential helper that interface with Windows' Credential Manager
4 */
5 #include <windows.h>
6 #include <stdio.h>
7 #include <io.h>
8 #include <fcntl.h>
10 /* common helpers */
12 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
14 static void die(const char *err, ...)
16 char msg[4096];
17 va_list params;
18 va_start(params, err);
19 vsnprintf(msg, sizeof(msg), err, params);
20 fprintf(stderr, "%s\n", msg);
21 va_end(params);
22 exit(1);
25 static void *xmalloc(size_t size)
27 void *ret = malloc(size);
28 if (!ret && !size)
29 ret = malloc(1);
30 if (!ret)
31 die("Out of memory");
32 return ret;
35 /* MinGW doesn't have wincred.h, so we need to define stuff */
37 typedef struct _CREDENTIAL_ATTRIBUTEW {
38 LPWSTR Keyword;
39 DWORD Flags;
40 DWORD ValueSize;
41 LPBYTE Value;
42 } CREDENTIAL_ATTRIBUTEW, *PCREDENTIAL_ATTRIBUTEW;
44 typedef struct _CREDENTIALW {
45 DWORD Flags;
46 DWORD Type;
47 LPWSTR TargetName;
48 LPWSTR Comment;
49 FILETIME LastWritten;
50 DWORD CredentialBlobSize;
51 LPBYTE CredentialBlob;
52 DWORD Persist;
53 DWORD AttributeCount;
54 PCREDENTIAL_ATTRIBUTEW Attributes;
55 LPWSTR TargetAlias;
56 LPWSTR UserName;
57 } CREDENTIALW, *PCREDENTIALW;
59 #define CRED_TYPE_GENERIC 1
60 #define CRED_PERSIST_LOCAL_MACHINE 2
61 #define CRED_MAX_ATTRIBUTES 64
63 typedef BOOL (WINAPI *CredWriteWT)(PCREDENTIALW, DWORD);
64 typedef BOOL (WINAPI *CredEnumerateWT)(LPCWSTR, DWORD, DWORD *,
65 PCREDENTIALW **);
66 typedef VOID (WINAPI *CredFreeT)(PVOID);
67 typedef BOOL (WINAPI *CredDeleteWT)(LPCWSTR, DWORD, DWORD);
69 static HMODULE advapi;
70 static CredWriteWT CredWriteW;
71 static CredEnumerateWT CredEnumerateW;
72 static CredFreeT CredFree;
73 static CredDeleteWT CredDeleteW;
75 static void load_cred_funcs(void)
77 /* load DLLs */
78 advapi = LoadLibrary("advapi32.dll");
79 if (!advapi)
80 die("failed to load advapi32.dll");
82 /* get function pointers */
83 CredWriteW = (CredWriteWT)GetProcAddress(advapi, "CredWriteW");
84 CredEnumerateW = (CredEnumerateWT)GetProcAddress(advapi,
85 "CredEnumerateW");
86 CredFree = (CredFreeT)GetProcAddress(advapi, "CredFree");
87 CredDeleteW = (CredDeleteWT)GetProcAddress(advapi, "CredDeleteW");
88 if (!CredWriteW || !CredEnumerateW || !CredFree || !CredDeleteW)
89 die("failed to load functions");
92 static WCHAR *wusername, *password, *protocol, *host, *path, target[1024];
94 static void write_item(const char *what, LPCWSTR wbuf, int wlen)
96 char *buf;
98 if (!wbuf || !wlen) {
99 printf("%s=\n", what);
100 return;
103 int len = WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, NULL, 0, NULL,
104 FALSE);
105 buf = xmalloc(len);
107 if (!WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, buf, len, NULL, FALSE))
108 die("WideCharToMultiByte failed!");
110 printf("%s=", what);
111 fwrite(buf, 1, len, stdout);
112 putchar('\n');
113 free(buf);
117 * Match an (optional) expected string and a delimiter in the target string,
118 * consuming the matched text by updating the target pointer.
120 static int match_part(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim)
122 LPCWSTR delim_pos, start = *ptarget;
123 int len;
125 /* find start of delimiter (or end-of-string if delim is empty) */
126 if (*delim)
127 delim_pos = wcsstr(start, delim);
128 else
129 delim_pos = start + wcslen(start);
132 * match text up to delimiter, or end of string (e.g. the '/' after
133 * host is optional if not followed by a path)
135 if (delim_pos)
136 len = delim_pos - start;
137 else
138 len = wcslen(start);
140 /* update ptarget if we either found a delimiter or need a match */
141 if (delim_pos || want)
142 *ptarget = delim_pos ? delim_pos + wcslen(delim) : start + len;
144 return !want || (!wcsncmp(want, start, len) && !want[len]);
147 static int match_cred(const CREDENTIALW *cred)
149 LPCWSTR target = cred->TargetName;
150 if (wusername && wcscmp(wusername, cred->UserName ? cred->UserName : L""))
151 return 0;
153 return match_part(&target, L"git", L":") &&
154 match_part(&target, protocol, L"://") &&
155 match_part(&target, wusername, L"@") &&
156 match_part(&target, host, L"/") &&
157 match_part(&target, path, L"");
160 static void get_credential(void)
162 CREDENTIALW **creds;
163 DWORD num_creds;
164 int i;
166 if (!CredEnumerateW(L"git:*", 0, &num_creds, &creds))
167 return;
169 /* search for the first credential that matches username */
170 for (i = 0; i < num_creds; ++i)
171 if (match_cred(creds[i])) {
172 write_item("username", creds[i]->UserName,
173 creds[i]->UserName ? wcslen(creds[i]->UserName) : 0);
174 write_item("password",
175 (LPCWSTR)creds[i]->CredentialBlob,
176 creds[i]->CredentialBlobSize / sizeof(WCHAR));
177 break;
180 CredFree(creds);
183 static void store_credential(void)
185 CREDENTIALW cred;
187 if (!wusername || !password)
188 return;
190 cred.Flags = 0;
191 cred.Type = CRED_TYPE_GENERIC;
192 cred.TargetName = target;
193 cred.Comment = L"saved by git-credential-wincred";
194 cred.CredentialBlobSize = (wcslen(password)) * sizeof(WCHAR);
195 cred.CredentialBlob = (LPVOID)password;
196 cred.Persist = CRED_PERSIST_LOCAL_MACHINE;
197 cred.AttributeCount = 0;
198 cred.Attributes = NULL;
199 cred.TargetAlias = NULL;
200 cred.UserName = wusername;
202 if (!CredWriteW(&cred, 0))
203 die("CredWrite failed");
206 static void erase_credential(void)
208 CREDENTIALW **creds;
209 DWORD num_creds;
210 int i;
212 if (!CredEnumerateW(L"git:*", 0, &num_creds, &creds))
213 return;
215 for (i = 0; i < num_creds; ++i) {
216 if (match_cred(creds[i]))
217 CredDeleteW(creds[i]->TargetName, creds[i]->Type, 0);
220 CredFree(creds);
223 static WCHAR *utf8_to_utf16_dup(const char *str)
225 int wlen = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
226 WCHAR *wstr = xmalloc(sizeof(WCHAR) * wlen);
227 MultiByteToWideChar(CP_UTF8, 0, str, -1, wstr, wlen);
228 return wstr;
231 static void read_credential(void)
233 char buf[1024];
235 while (fgets(buf, sizeof(buf), stdin)) {
236 char *v;
237 int len = strlen(buf);
238 /* strip trailing CR / LF */
239 while (len && strchr("\r\n", buf[len - 1]))
240 buf[--len] = 0;
242 if (!*buf)
243 break;
245 v = strchr(buf, '=');
246 if (!v)
247 die("bad input: %s", buf);
248 *v++ = '\0';
250 if (!strcmp(buf, "protocol"))
251 protocol = utf8_to_utf16_dup(v);
252 else if (!strcmp(buf, "host"))
253 host = utf8_to_utf16_dup(v);
254 else if (!strcmp(buf, "path"))
255 path = utf8_to_utf16_dup(v);
256 else if (!strcmp(buf, "username")) {
257 wusername = utf8_to_utf16_dup(v);
258 } else if (!strcmp(buf, "password"))
259 password = utf8_to_utf16_dup(v);
260 else
261 die("unrecognized input");
265 int main(int argc, char *argv[])
267 const char *usage =
268 "usage: git credential-wincred <get|store|erase>\n";
270 if (!argv[1])
271 die(usage);
273 /* git use binary pipes to avoid CRLF-issues */
274 _setmode(_fileno(stdin), _O_BINARY);
275 _setmode(_fileno(stdout), _O_BINARY);
277 read_credential();
279 load_cred_funcs();
281 if (!protocol || !(host || path))
282 return 0;
284 /* prepare 'target', the unique key for the credential */
285 wcscpy(target, L"git:");
286 wcsncat(target, protocol, ARRAY_SIZE(target));
287 wcsncat(target, L"://", ARRAY_SIZE(target));
288 if (wusername) {
289 wcsncat(target, wusername, ARRAY_SIZE(target));
290 wcsncat(target, L"@", ARRAY_SIZE(target));
292 if (host)
293 wcsncat(target, host, ARRAY_SIZE(target));
294 if (path) {
295 wcsncat(target, L"/", ARRAY_SIZE(target));
296 wcsncat(target, path, ARRAY_SIZE(target));
299 if (!strcmp(argv[1], "get"))
300 get_credential();
301 else if (!strcmp(argv[1], "store"))
302 store_credential();
303 else if (!strcmp(argv[1], "erase"))
304 erase_credential();
305 /* otherwise, ignore unknown action */
306 return 0;