contrib / credential / wincred / git-credential-wincred.con commit Sync with 2.6.2 (0c4dd78)
   1/*
   2 * A git credential helper that interface with Windows' Credential Manager
   3 *
   4 */
   5#include <windows.h>
   6#include <stdio.h>
   7#include <io.h>
   8#include <fcntl.h>
   9
  10/* common helpers */
  11
  12#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
  13
  14static void die(const char *err, ...)
  15{
  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);
  23}
  24
  25static void *xmalloc(size_t size)
  26{
  27        void *ret = malloc(size);
  28        if (!ret && !size)
  29                ret = malloc(1);
  30        if (!ret)
  31                 die("Out of memory");
  32        return ret;
  33}
  34
  35/* MinGW doesn't have wincred.h, so we need to define stuff */
  36
  37typedef struct _CREDENTIAL_ATTRIBUTEW {
  38        LPWSTR Keyword;
  39        DWORD  Flags;
  40        DWORD  ValueSize;
  41        LPBYTE Value;
  42} CREDENTIAL_ATTRIBUTEW, *PCREDENTIAL_ATTRIBUTEW;
  43
  44typedef 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;
  58
  59#define CRED_TYPE_GENERIC 1
  60#define CRED_PERSIST_LOCAL_MACHINE 2
  61#define CRED_MAX_ATTRIBUTES 64
  62
  63typedef BOOL (WINAPI *CredWriteWT)(PCREDENTIALW, DWORD);
  64typedef BOOL (WINAPI *CredEnumerateWT)(LPCWSTR, DWORD, DWORD *,
  65    PCREDENTIALW **);
  66typedef VOID (WINAPI *CredFreeT)(PVOID);
  67typedef BOOL (WINAPI *CredDeleteWT)(LPCWSTR, DWORD, DWORD);
  68
  69static HMODULE advapi;
  70static CredWriteWT CredWriteW;
  71static CredEnumerateWT CredEnumerateW;
  72static CredFreeT CredFree;
  73static CredDeleteWT CredDeleteW;
  74
  75static void load_cred_funcs(void)
  76{
  77        /* load DLLs */
  78        advapi = LoadLibrary("advapi32.dll");
  79        if (!advapi)
  80                die("failed to load advapi32.dll");
  81
  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");
  90}
  91
  92static WCHAR *wusername, *password, *protocol, *host, *path, target[1024];
  93
  94static void write_item(const char *what, LPCWSTR wbuf, int wlen)
  95{
  96        char *buf;
  97        int len = WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, NULL, 0, NULL,
  98            FALSE);
  99        buf = xmalloc(len);
 100
 101        if (!WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, buf, len, NULL, FALSE))
 102                die("WideCharToMultiByte failed!");
 103
 104        printf("%s=", what);
 105        fwrite(buf, 1, len, stdout);
 106        putchar('\n');
 107        free(buf);
 108}
 109
 110/*
 111 * Match an (optional) expected string and a delimiter in the target string,
 112 * consuming the matched text by updating the target pointer.
 113 */
 114
 115static LPCWSTR wcsstr_last(LPCWSTR str, LPCWSTR find)
 116{
 117        LPCWSTR res = NULL, pos;
 118        for (pos = wcsstr(str, find); pos; pos = wcsstr(pos + 1, find))
 119                res = pos;
 120        return res;
 121}
 122
 123static int match_part_with_last(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim, int last)
 124{
 125        LPCWSTR delim_pos, start = *ptarget;
 126        int len;
 127
 128        /* find start of delimiter (or end-of-string if delim is empty) */
 129        if (*delim)
 130                delim_pos = last ? wcsstr_last(start, delim) : wcsstr(start, delim);
 131        else
 132                delim_pos = start + wcslen(start);
 133
 134        /*
 135         * match text up to delimiter, or end of string (e.g. the '/' after
 136         * host is optional if not followed by a path)
 137         */
 138        if (delim_pos)
 139                len = delim_pos - start;
 140        else
 141                len = wcslen(start);
 142
 143        /* update ptarget if we either found a delimiter or need a match */
 144        if (delim_pos || want)
 145                *ptarget = delim_pos ? delim_pos + wcslen(delim) : start + len;
 146
 147        return !want || (!wcsncmp(want, start, len) && !want[len]);
 148}
 149
 150static int match_part(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim)
 151{
 152        return match_part_with_last(ptarget, want, delim, 0);
 153}
 154
 155static int match_part_last(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim)
 156{
 157        return match_part_with_last(ptarget, want, delim, 1);
 158}
 159
 160static int match_cred(const CREDENTIALW *cred)
 161{
 162        LPCWSTR target = cred->TargetName;
 163        if (wusername && wcscmp(wusername, cred->UserName))
 164                return 0;
 165
 166        return match_part(&target, L"git", L":") &&
 167                match_part(&target, protocol, L"://") &&
 168                match_part_last(&target, wusername, L"@") &&
 169                match_part(&target, host, L"/") &&
 170                match_part(&target, path, L"");
 171}
 172
 173static void get_credential(void)
 174{
 175        CREDENTIALW **creds;
 176        DWORD num_creds;
 177        int i;
 178
 179        if (!CredEnumerateW(L"git:*", 0, &num_creds, &creds))
 180                return;
 181
 182        /* search for the first credential that matches username */
 183        for (i = 0; i < num_creds; ++i)
 184                if (match_cred(creds[i])) {
 185                        write_item("username", creds[i]->UserName,
 186                                wcslen(creds[i]->UserName));
 187                        write_item("password",
 188                                (LPCWSTR)creds[i]->CredentialBlob,
 189                                creds[i]->CredentialBlobSize / sizeof(WCHAR));
 190                        break;
 191                }
 192
 193        CredFree(creds);
 194}
 195
 196static void store_credential(void)
 197{
 198        CREDENTIALW cred;
 199
 200        if (!wusername || !password)
 201                return;
 202
 203        cred.Flags = 0;
 204        cred.Type = CRED_TYPE_GENERIC;
 205        cred.TargetName = target;
 206        cred.Comment = L"saved by git-credential-wincred";
 207        cred.CredentialBlobSize = (wcslen(password)) * sizeof(WCHAR);
 208        cred.CredentialBlob = (LPVOID)password;
 209        cred.Persist = CRED_PERSIST_LOCAL_MACHINE;
 210        cred.AttributeCount = 0;
 211        cred.Attributes = NULL;
 212        cred.TargetAlias = NULL;
 213        cred.UserName = wusername;
 214
 215        if (!CredWriteW(&cred, 0))
 216                die("CredWrite failed");
 217}
 218
 219static void erase_credential(void)
 220{
 221        CREDENTIALW **creds;
 222        DWORD num_creds;
 223        int i;
 224
 225        if (!CredEnumerateW(L"git:*", 0, &num_creds, &creds))
 226                return;
 227
 228        for (i = 0; i < num_creds; ++i) {
 229                if (match_cred(creds[i]))
 230                        CredDeleteW(creds[i]->TargetName, creds[i]->Type, 0);
 231        }
 232
 233        CredFree(creds);
 234}
 235
 236static WCHAR *utf8_to_utf16_dup(const char *str)
 237{
 238        int wlen = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
 239        WCHAR *wstr = xmalloc(sizeof(WCHAR) * wlen);
 240        MultiByteToWideChar(CP_UTF8, 0, str, -1, wstr, wlen);
 241        return wstr;
 242}
 243
 244static void read_credential(void)
 245{
 246        char buf[1024];
 247
 248        while (fgets(buf, sizeof(buf), stdin)) {
 249                char *v;
 250                int len = strlen(buf);
 251                /* strip trailing CR / LF */
 252                while (len && strchr("\r\n", buf[len - 1]))
 253                        buf[--len] = 0;
 254
 255                if (!*buf)
 256                        break;
 257
 258                v = strchr(buf, '=');
 259                if (!v)
 260                        die("bad input: %s", buf);
 261                *v++ = '\0';
 262
 263                if (!strcmp(buf, "protocol"))
 264                        protocol = utf8_to_utf16_dup(v);
 265                else if (!strcmp(buf, "host"))
 266                        host = utf8_to_utf16_dup(v);
 267                else if (!strcmp(buf, "path"))
 268                        path = utf8_to_utf16_dup(v);
 269                else if (!strcmp(buf, "username")) {
 270                        wusername = utf8_to_utf16_dup(v);
 271                } else if (!strcmp(buf, "password"))
 272                        password = utf8_to_utf16_dup(v);
 273                else
 274                        die("unrecognized input");
 275        }
 276}
 277
 278int main(int argc, char *argv[])
 279{
 280        const char *usage =
 281            "usage: git credential-wincred <get|store|erase>\n";
 282
 283        if (!argv[1])
 284                die(usage);
 285
 286        /* git use binary pipes to avoid CRLF-issues */
 287        _setmode(_fileno(stdin), _O_BINARY);
 288        _setmode(_fileno(stdout), _O_BINARY);
 289
 290        read_credential();
 291
 292        load_cred_funcs();
 293
 294        if (!protocol || !(host || path))
 295                return 0;
 296
 297        /* prepare 'target', the unique key for the credential */
 298        wcscpy(target, L"git:");
 299        wcsncat(target, protocol, ARRAY_SIZE(target));
 300        wcsncat(target, L"://", ARRAY_SIZE(target));
 301        if (wusername) {
 302                wcsncat(target, wusername, ARRAY_SIZE(target));
 303                wcsncat(target, L"@", ARRAY_SIZE(target));
 304        }
 305        if (host)
 306                wcsncat(target, host, ARRAY_SIZE(target));
 307        if (path) {
 308                wcsncat(target, L"/", ARRAY_SIZE(target));
 309                wcsncat(target, path, ARRAY_SIZE(target));
 310        }
 311
 312        if (!strcmp(argv[1], "get"))
 313                get_credential();
 314        else if (!strcmp(argv[1], "store"))
 315                store_credential();
 316        else if (!strcmp(argv[1], "erase"))
 317                erase_credential();
 318        /* otherwise, ignore unknown action */
 319        return 0;
 320}