Merge branch 'ma/gittutorial-fixes'
[git.git] / credential.c
blob7da326aa8585531e93e93aef64fda48538096c0f
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "config.h"
4 #include "credential.h"
5 #include "gettext.h"
6 #include "string-list.h"
7 #include "run-command.h"
8 #include "url.h"
9 #include "prompt.h"
10 #include "sigchain.h"
11 #include "strbuf.h"
12 #include "urlmatch.h"
13 #include "git-compat-util.h"
15 void credential_init(struct credential *c)
17 struct credential blank = CREDENTIAL_INIT;
18 memcpy(c, &blank, sizeof(*c));
21 void credential_clear(struct credential *c)
23 free(c->protocol);
24 free(c->host);
25 free(c->path);
26 free(c->username);
27 free(c->password);
28 string_list_clear(&c->helpers, 0);
29 strvec_clear(&c->wwwauth_headers);
31 credential_init(c);
34 int credential_match(const struct credential *want,
35 const struct credential *have)
37 #define CHECK(x) (!want->x || (have->x && !strcmp(want->x, have->x)))
38 return CHECK(protocol) &&
39 CHECK(host) &&
40 CHECK(path) &&
41 CHECK(username);
42 #undef CHECK
46 static int credential_from_potentially_partial_url(struct credential *c,
47 const char *url);
49 static int credential_config_callback(const char *var, const char *value,
50 void *data)
52 struct credential *c = data;
53 const char *key;
55 if (!skip_prefix(var, "credential.", &key))
56 return 0;
58 if (!value)
59 return config_error_nonbool(var);
61 if (!strcmp(key, "helper")) {
62 if (*value)
63 string_list_append(&c->helpers, value);
64 else
65 string_list_clear(&c->helpers, 0);
66 } else if (!strcmp(key, "username")) {
67 if (!c->username_from_proto) {
68 free(c->username);
69 c->username = xstrdup(value);
72 else if (!strcmp(key, "usehttppath"))
73 c->use_http_path = git_config_bool(var, value);
75 return 0;
78 static int proto_is_http(const char *s)
80 if (!s)
81 return 0;
82 return !strcmp(s, "https") || !strcmp(s, "http");
85 static void credential_describe(struct credential *c, struct strbuf *out);
86 static void credential_format(struct credential *c, struct strbuf *out);
88 static int select_all(const struct urlmatch_item *a,
89 const struct urlmatch_item *b)
91 return 0;
94 static int match_partial_url(const char *url, void *cb)
96 struct credential *c = cb;
97 struct credential want = CREDENTIAL_INIT;
98 int matches = 0;
100 if (credential_from_potentially_partial_url(&want, url) < 0)
101 warning(_("skipping credential lookup for key: credential.%s"),
102 url);
103 else
104 matches = credential_match(&want, c);
105 credential_clear(&want);
107 return matches;
110 static void credential_apply_config(struct credential *c)
112 char *normalized_url;
113 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
114 struct strbuf url = STRBUF_INIT;
116 if (!c->host)
117 die(_("refusing to work with credential missing host field"));
118 if (!c->protocol)
119 die(_("refusing to work with credential missing protocol field"));
121 if (c->configured)
122 return;
124 config.section = "credential";
125 config.key = NULL;
126 config.collect_fn = credential_config_callback;
127 config.cascade_fn = NULL;
128 config.select_fn = select_all;
129 config.fallback_match_fn = match_partial_url;
130 config.cb = c;
132 credential_format(c, &url);
133 normalized_url = url_normalize(url.buf, &config.url);
135 git_config(urlmatch_config_entry, &config);
136 string_list_clear(&config.vars, 1);
137 free(normalized_url);
138 urlmatch_config_release(&config);
139 strbuf_release(&url);
141 c->configured = 1;
143 if (!c->use_http_path && proto_is_http(c->protocol)) {
144 FREE_AND_NULL(c->path);
148 static void credential_describe(struct credential *c, struct strbuf *out)
150 if (!c->protocol)
151 return;
152 strbuf_addf(out, "%s://", c->protocol);
153 if (c->username && *c->username)
154 strbuf_addf(out, "%s@", c->username);
155 if (c->host)
156 strbuf_addstr(out, c->host);
157 if (c->path)
158 strbuf_addf(out, "/%s", c->path);
161 static void credential_format(struct credential *c, struct strbuf *out)
163 if (!c->protocol)
164 return;
165 strbuf_addf(out, "%s://", c->protocol);
166 if (c->username && *c->username) {
167 strbuf_add_percentencode(out, c->username, STRBUF_ENCODE_SLASH);
168 strbuf_addch(out, '@');
170 if (c->host)
171 strbuf_addstr(out, c->host);
172 if (c->path) {
173 strbuf_addch(out, '/');
174 strbuf_add_percentencode(out, c->path, 0);
178 static char *credential_ask_one(const char *what, struct credential *c,
179 int flags)
181 struct strbuf desc = STRBUF_INIT;
182 struct strbuf prompt = STRBUF_INIT;
183 char *r;
185 credential_describe(c, &desc);
186 if (desc.len)
187 strbuf_addf(&prompt, "%s for '%s': ", what, desc.buf);
188 else
189 strbuf_addf(&prompt, "%s: ", what);
191 r = git_prompt(prompt.buf, flags);
193 strbuf_release(&desc);
194 strbuf_release(&prompt);
195 return xstrdup(r);
198 static void credential_getpass(struct credential *c)
200 if (!c->username)
201 c->username = credential_ask_one("Username", c,
202 PROMPT_ASKPASS|PROMPT_ECHO);
203 if (!c->password)
204 c->password = credential_ask_one("Password", c,
205 PROMPT_ASKPASS);
208 int credential_read(struct credential *c, FILE *fp)
210 struct strbuf line = STRBUF_INIT;
212 while (strbuf_getline(&line, fp) != EOF) {
213 char *key = line.buf;
214 char *value = strchr(key, '=');
216 if (!line.len)
217 break;
219 if (!value) {
220 warning("invalid credential line: %s", key);
221 strbuf_release(&line);
222 return -1;
224 *value++ = '\0';
226 if (!strcmp(key, "username")) {
227 free(c->username);
228 c->username = xstrdup(value);
229 c->username_from_proto = 1;
230 } else if (!strcmp(key, "password")) {
231 free(c->password);
232 c->password = xstrdup(value);
233 } else if (!strcmp(key, "protocol")) {
234 free(c->protocol);
235 c->protocol = xstrdup(value);
236 } else if (!strcmp(key, "host")) {
237 free(c->host);
238 c->host = xstrdup(value);
239 } else if (!strcmp(key, "path")) {
240 free(c->path);
241 c->path = xstrdup(value);
242 } else if (!strcmp(key, "wwwauth[]")) {
243 strvec_push(&c->wwwauth_headers, value);
244 } else if (!strcmp(key, "password_expiry_utc")) {
245 errno = 0;
246 c->password_expiry_utc = parse_timestamp(value, NULL, 10);
247 if (c->password_expiry_utc == 0 || errno == ERANGE)
248 c->password_expiry_utc = TIME_MAX;
249 } else if (!strcmp(key, "url")) {
250 credential_from_url(c, value);
251 } else if (!strcmp(key, "quit")) {
252 c->quit = !!git_config_bool("quit", value);
255 * Ignore other lines; we don't know what they mean, but
256 * this future-proofs us when later versions of git do
257 * learn new lines, and the helpers are updated to match.
261 strbuf_release(&line);
262 return 0;
265 static void credential_write_item(FILE *fp, const char *key, const char *value,
266 int required)
268 if (!value && required)
269 BUG("credential value for %s is missing", key);
270 if (!value)
271 return;
272 if (strchr(value, '\n'))
273 die("credential value for %s contains newline", key);
274 fprintf(fp, "%s=%s\n", key, value);
277 void credential_write(const struct credential *c, FILE *fp)
279 credential_write_item(fp, "protocol", c->protocol, 1);
280 credential_write_item(fp, "host", c->host, 1);
281 credential_write_item(fp, "path", c->path, 0);
282 credential_write_item(fp, "username", c->username, 0);
283 credential_write_item(fp, "password", c->password, 0);
284 if (c->password_expiry_utc != TIME_MAX) {
285 char *s = xstrfmt("%"PRItime, c->password_expiry_utc);
286 credential_write_item(fp, "password_expiry_utc", s, 0);
287 free(s);
289 for (size_t i = 0; i < c->wwwauth_headers.nr; i++)
290 credential_write_item(fp, "wwwauth[]", c->wwwauth_headers.v[i], 0);
293 static int run_credential_helper(struct credential *c,
294 const char *cmd,
295 int want_output)
297 struct child_process helper = CHILD_PROCESS_INIT;
298 FILE *fp;
300 strvec_push(&helper.args, cmd);
301 helper.use_shell = 1;
302 helper.in = -1;
303 if (want_output)
304 helper.out = -1;
305 else
306 helper.no_stdout = 1;
308 if (start_command(&helper) < 0)
309 return -1;
311 fp = xfdopen(helper.in, "w");
312 sigchain_push(SIGPIPE, SIG_IGN);
313 credential_write(c, fp);
314 fclose(fp);
315 sigchain_pop(SIGPIPE);
317 if (want_output) {
318 int r;
319 fp = xfdopen(helper.out, "r");
320 r = credential_read(c, fp);
321 fclose(fp);
322 if (r < 0) {
323 finish_command(&helper);
324 return -1;
328 if (finish_command(&helper))
329 return -1;
330 return 0;
333 static int credential_do(struct credential *c, const char *helper,
334 const char *operation)
336 struct strbuf cmd = STRBUF_INIT;
337 int r;
339 if (helper[0] == '!')
340 strbuf_addstr(&cmd, helper + 1);
341 else if (is_absolute_path(helper))
342 strbuf_addstr(&cmd, helper);
343 else
344 strbuf_addf(&cmd, "git credential-%s", helper);
346 strbuf_addf(&cmd, " %s", operation);
347 r = run_credential_helper(c, cmd.buf, !strcmp(operation, "get"));
349 strbuf_release(&cmd);
350 return r;
353 void credential_fill(struct credential *c)
355 int i;
357 if (c->username && c->password)
358 return;
360 credential_apply_config(c);
362 for (i = 0; i < c->helpers.nr; i++) {
363 credential_do(c, c->helpers.items[i].string, "get");
364 if (c->password_expiry_utc < time(NULL)) {
365 /* Discard expired password */
366 FREE_AND_NULL(c->password);
367 /* Reset expiry to maintain consistency */
368 c->password_expiry_utc = TIME_MAX;
370 if (c->username && c->password)
371 return;
372 if (c->quit)
373 die("credential helper '%s' told us to quit",
374 c->helpers.items[i].string);
377 credential_getpass(c);
378 if (!c->username && !c->password)
379 die("unable to get password from user");
382 void credential_approve(struct credential *c)
384 int i;
386 if (c->approved)
387 return;
388 if (!c->username || !c->password || c->password_expiry_utc < time(NULL))
389 return;
391 credential_apply_config(c);
393 for (i = 0; i < c->helpers.nr; i++)
394 credential_do(c, c->helpers.items[i].string, "store");
395 c->approved = 1;
398 void credential_reject(struct credential *c)
400 int i;
402 credential_apply_config(c);
404 for (i = 0; i < c->helpers.nr; i++)
405 credential_do(c, c->helpers.items[i].string, "erase");
407 FREE_AND_NULL(c->username);
408 FREE_AND_NULL(c->password);
409 c->password_expiry_utc = TIME_MAX;
410 c->approved = 0;
413 static int check_url_component(const char *url, int quiet,
414 const char *name, const char *value)
416 if (!value)
417 return 0;
418 if (!strchr(value, '\n'))
419 return 0;
421 if (!quiet)
422 warning(_("url contains a newline in its %s component: %s"),
423 name, url);
424 return -1;
428 * Potentially-partial URLs can, but do not have to, contain
430 * - a protocol (or scheme) of the form "<protocol>://"
432 * - a host name (the part after the protocol and before the first slash after
433 * that, if any)
435 * - a user name and potentially a password (as "<user>[:<password>]@" part of
436 * the host name)
438 * - a path (the part after the host name, if any, starting with the slash)
440 * Missing parts will be left unset in `struct credential`. Thus, `https://`
441 * will have only the `protocol` set, `example.com` only the host name, and
442 * `/git` only the path.
444 * Note that an empty host name in an otherwise fully-qualified URL (e.g.
445 * `cert:///path/to/cert.pem`) will be treated as unset if we expect the URL to
446 * be potentially partial, and only then (otherwise, the empty string is used).
448 * The credential_from_url() function does not allow partial URLs.
450 static int credential_from_url_1(struct credential *c, const char *url,
451 int allow_partial_url, int quiet)
453 const char *at, *colon, *cp, *slash, *host, *proto_end;
455 credential_clear(c);
458 * Match one of:
459 * (1) proto://<host>/...
460 * (2) proto://<user>@<host>/...
461 * (3) proto://<user>:<pass>@<host>/...
463 proto_end = strstr(url, "://");
464 if (!allow_partial_url && (!proto_end || proto_end == url)) {
465 if (!quiet)
466 warning(_("url has no scheme: %s"), url);
467 return -1;
469 cp = proto_end ? proto_end + 3 : url;
470 at = strchr(cp, '@');
471 colon = strchr(cp, ':');
474 * A query or fragment marker before the slash ends the host portion.
475 * We'll just continue to call this "slash" for simplicity. Notably our
476 * "trim leading slashes" part won't skip over this part of the path,
477 * but that's what we'd want.
479 slash = cp + strcspn(cp, "/?#");
481 if (!at || slash <= at) {
482 /* Case (1) */
483 host = cp;
485 else if (!colon || at <= colon) {
486 /* Case (2) */
487 c->username = url_decode_mem(cp, at - cp);
488 if (c->username && *c->username)
489 c->username_from_proto = 1;
490 host = at + 1;
491 } else {
492 /* Case (3) */
493 c->username = url_decode_mem(cp, colon - cp);
494 if (c->username && *c->username)
495 c->username_from_proto = 1;
496 c->password = url_decode_mem(colon + 1, at - (colon + 1));
497 host = at + 1;
500 if (proto_end && proto_end - url > 0)
501 c->protocol = xmemdupz(url, proto_end - url);
502 if (!allow_partial_url || slash - host > 0)
503 c->host = url_decode_mem(host, slash - host);
504 /* Trim leading and trailing slashes from path */
505 while (*slash == '/')
506 slash++;
507 if (*slash) {
508 char *p;
509 c->path = url_decode(slash);
510 p = c->path + strlen(c->path) - 1;
511 while (p > c->path && *p == '/')
512 *p-- = '\0';
515 if (check_url_component(url, quiet, "username", c->username) < 0 ||
516 check_url_component(url, quiet, "password", c->password) < 0 ||
517 check_url_component(url, quiet, "protocol", c->protocol) < 0 ||
518 check_url_component(url, quiet, "host", c->host) < 0 ||
519 check_url_component(url, quiet, "path", c->path) < 0)
520 return -1;
522 return 0;
525 static int credential_from_potentially_partial_url(struct credential *c,
526 const char *url)
528 return credential_from_url_1(c, url, 1, 0);
531 int credential_from_url_gently(struct credential *c, const char *url, int quiet)
533 return credential_from_url_1(c, url, 0, quiet);
536 void credential_from_url(struct credential *c, const char *url)
538 if (credential_from_url_gently(c, url, 0) < 0)
539 die(_("credential url cannot be parsed: %s"), url);