contrib / credential / wincred / git-credential-wincred.con commit Merge branch 'sb/test-cherry-pick-submodule-getting-in-a-way' into maint (2ace172)
   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
  98        if (!wbuf || !wlen) {
  99                printf("%s=\n", what);
 100                return;
 101        }
 102
 103        int len = WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, NULL, 0, NULL,
 104            FALSE);
 105        buf = xmalloc(len);
 106
 107        if (!WideCharToMultiByte(CP_UTF8, 0, wbuf, wlen, buf, len, NULL, FALSE))
 108                die("WideCharToMultiByte failed!");
 109
 110        printf("%s=", what);
 111        fwrite(buf, 1, len, stdout);
 112        putchar('\n');
 113        free(buf);
 114}
 115
 116/*
 117 * Match an (optional) expected string and a delimiter in the target string,
 118 * consuming the matched text by updating the target pointer.
 119 */
 120
 121static LPCWSTR wcsstr_last(LPCWSTR str, LPCWSTR find)
 122{
 123        LPCWSTR res = NULL, pos;
 124        for (pos = wcsstr(str, find); pos; pos = wcsstr(pos + 1, find))
 125                res = pos;
 126        return res;
 127}
 128
 129static int match_part_with_last(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim, int last)
 130{
 131        LPCWSTR delim_pos, start = *ptarget;
 132        int len;
 133
 134        /* find start of delimiter (or end-of-string if delim is empty) */
 135        if (*delim)
 136                delim_pos = last ? wcsstr_last(start, delim) : wcsstr(start, delim);
 137        else
 138                delim_pos = start + wcslen(start);
 139
 140        /*
 141         * match text up to delimiter, or end of string (e.g. the '/' after
 142         * host is optional if not followed by a path)
 143         */
 144        if (delim_pos)
 145                len = delim_pos - start;
 146        else
 147                len = wcslen(start);
 148
 149        /* update ptarget if we either found a delimiter or need a match */
 150        if (delim_pos || want)
 151                *ptarget = delim_pos ? delim_pos + wcslen(delim) : start + len;
 152
 153        return !want || (!wcsncmp(want, start, len) && !want[len]);
 154}
 155
 156static int match_part(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim)
 157{
 158        return match_part_with_last(ptarget, want, delim, 0);
 159}
 160
 161static int match_part_last(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim)
 162{
 163        return match_part_with_last(ptarget, want, delim, 1);
 164}
 165
 166static int match_cred(const CREDENTIALW *cred)
 167{
 168        LPCWSTR target = cred->TargetName;
 169        if (wusername && wcscmp(wusername, cred->UserName ? cred->UserName : L""))
 170                return 0;
 171
 172        return match_part(&target, L"git", L":") &&
 173                match_part(&target, protocol, L"://") &&
 174                match_part_last(&target, wusername, L"@") &&
 175                match_part(&target, host, L"/") &&
 176                match_part(&target, path, L"");
 177}
 178
 179static void get_credential(void)
 180{
 181        CREDENTIALW **creds;
 182        DWORD num_creds;
 183        int i;
 184
 185        if (!CredEnumerateW(L"git:*", 0, &num_creds, &creds))
 186                return;
 187
 188        /* search for the first credential that matches username */
 189        for (i = 0; i < num_creds; ++i)
 190                if (match_cred(creds[i])) {
 191                        write_item("username", creds[i]->UserName,
 192                                creds[i]->UserName ? wcslen(creds[i]->UserName) : 0);
 193                        write_item("password",
 194                                (LPCWSTR)creds[i]->CredentialBlob,
 195                                creds[i]->CredentialBlobSize / sizeof(WCHAR));
 196                        break;
 197                }
 198
 199        CredFree(creds);
 200}
 201
 202static void store_credential(void)
 203{
 204        CREDENTIALW cred;
 205
 206        if (!wusername || !password)
 207                return;
 208
 209        cred.Flags = 0;
 210        cred.Type = CRED_TYPE_GENERIC;
 211        cred.TargetName = target;
 212        cred.Comment = L"saved by git-credential-wincred";
 213        cred.CredentialBlobSize = (wcslen(password)) * sizeof(WCHAR);
 214        cred.CredentialBlob = (LPVOID)password;
 215        cred.Persist = CRED_PERSIST_LOCAL_MACHINE;
 216        cred.AttributeCount = 0;
 217        cred.Attributes = NULL;
 218        cred.TargetAlias = NULL;
 219        cred.UserName = wusername;
 220
 221        if (!CredWriteW(&cred, 0))
 222                die("CredWrite failed");
 223}
 224
 225static void erase_credential(void)
 226{
 227        CREDENTIALW **creds;
 228        DWORD num_creds;
 229        int i;
 230
 231        if (!CredEnumerateW(L"git:*", 0, &num_creds, &creds))
 232                return;
 233
 234        for (i = 0; i < num_creds; ++i) {
 235                if (match_cred(creds[i]))
 236                        CredDeleteW(creds[i]->TargetName, creds[i]->Type, 0);
 237        }
 238
 239        CredFree(creds);
 240}
 241
 242static WCHAR *utf8_to_utf16_dup(const char *str)
 243{
 244        int wlen = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
 245        WCHAR *wstr = xmalloc(sizeof(WCHAR) * wlen);
 246        MultiByteToWideChar(CP_UTF8, 0, str, -1, wstr, wlen);
 247        return wstr;
 248}
 249
 250static void read_credential(void)
 251{
 252        char buf[1024];
 253
 254        while (fgets(buf, sizeof(buf), stdin)) {
 255                char *v;
 256                int len = strlen(buf);
 257                /* strip trailing CR / LF */
 258                while (len && strchr("\r\n", buf[len - 1]))
 259                        buf[--len] = 0;
 260
 261                if (!*buf)
 262                        break;
 263
 264                v = strchr(buf, '=');
 265                if (!v)
 266                        die("bad input: %s", buf);
 267                *v++ = '\0';
 268
 269                if (!strcmp(buf, "protocol"))
 270                        protocol = utf8_to_utf16_dup(v);
 271                else if (!strcmp(buf, "host"))
 272                        host = utf8_to_utf16_dup(v);
 273                else if (!strcmp(buf, "path"))
 274                        path = utf8_to_utf16_dup(v);
 275                else if (!strcmp(buf, "username")) {
 276                        wusername = utf8_to_utf16_dup(v);
 277                } else if (!strcmp(buf, "password"))
 278                        password = utf8_to_utf16_dup(v);
 279                else
 280                        die("unrecognized input");
 281        }
 282}
 283
 284int main(int argc, char *argv[])
 285{
 286        const char *usage =
 287            "usage: git credential-wincred <get|store|erase>\n";
 288
 289        if (!argv[1])
 290                die(usage);
 291
 292        /* git use binary pipes to avoid CRLF-issues */
 293        _setmode(_fileno(stdin), _O_BINARY);
 294        _setmode(_fileno(stdout), _O_BINARY);
 295
 296        read_credential();
 297
 298        load_cred_funcs();
 299
 300        if (!protocol || !(host || path))
 301                return 0;
 302
 303        /* prepare 'target', the unique key for the credential */
 304        wcscpy(target, L"git:");
 305        wcsncat(target, protocol, ARRAY_SIZE(target));
 306        wcsncat(target, L"://", ARRAY_SIZE(target));
 307        if (wusername) {
 308                wcsncat(target, wusername, ARRAY_SIZE(target));
 309                wcsncat(target, L"@", ARRAY_SIZE(target));
 310        }
 311        if (host)
 312                wcsncat(target, host, ARRAY_SIZE(target));
 313        if (path) {
 314                wcsncat(target, L"/", ARRAY_SIZE(target));
 315                wcsncat(target, path, ARRAY_SIZE(target));
 316        }
 317
 318        if (!strcmp(argv[1], "get"))
 319                get_credential();
 320        else if (!strcmp(argv[1], "store"))
 321                store_credential();
 322        else if (!strcmp(argv[1], "erase"))
 323                erase_credential();
 324        /* otherwise, ignore unknown action */
 325        return 0;
 326}