refs/files: fix NULL pointer deref when releasing ref store
[git/gitster.git] / credential.c
blob758528b291a28f850411d7e781b40b2c5f919ddc
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 free(c->credential);
29 free(c->oauth_refresh_token);
30 free(c->authtype);
31 string_list_clear(&c->helpers, 0);
32 strvec_clear(&c->wwwauth_headers);
33 strvec_clear(&c->state_headers);
34 strvec_clear(&c->state_headers_to_send);
36 credential_init(c);
39 void credential_next_state(struct credential *c)
41 strvec_clear(&c->state_headers_to_send);
42 SWAP(c->state_headers, c->state_headers_to_send);
45 void credential_clear_secrets(struct credential *c)
47 FREE_AND_NULL(c->password);
48 FREE_AND_NULL(c->credential);
51 static void credential_set_capability(struct credential_capability *capa,
52 enum credential_op_type op_type)
54 switch (op_type) {
55 case CREDENTIAL_OP_INITIAL:
56 capa->request_initial = 1;
57 break;
58 case CREDENTIAL_OP_HELPER:
59 capa->request_helper = 1;
60 break;
61 case CREDENTIAL_OP_RESPONSE:
62 capa->response = 1;
63 break;
68 void credential_set_all_capabilities(struct credential *c,
69 enum credential_op_type op_type)
71 credential_set_capability(&c->capa_authtype, op_type);
72 credential_set_capability(&c->capa_state, op_type);
75 static void announce_one(struct credential_capability *cc, const char *name, FILE *fp) {
76 if (cc->request_initial)
77 fprintf(fp, "capability %s\n", name);
80 void credential_announce_capabilities(struct credential *c, FILE *fp) {
81 fprintf(fp, "version 0\n");
82 announce_one(&c->capa_authtype, "authtype", fp);
83 announce_one(&c->capa_state, "state", fp);
86 int credential_match(const struct credential *want,
87 const struct credential *have, int match_password)
89 #define CHECK(x) (!want->x || (have->x && !strcmp(want->x, have->x)))
90 return CHECK(protocol) &&
91 CHECK(host) &&
92 CHECK(path) &&
93 CHECK(username) &&
94 (!match_password || CHECK(password)) &&
95 (!match_password || CHECK(credential));
96 #undef CHECK
100 static int credential_from_potentially_partial_url(struct credential *c,
101 const char *url);
103 static int credential_config_callback(const char *var, const char *value,
104 const struct config_context *ctx UNUSED,
105 void *data)
107 struct credential *c = data;
108 const char *key;
110 if (!skip_prefix(var, "credential.", &key))
111 return 0;
113 if (!value)
114 return config_error_nonbool(var);
116 if (!strcmp(key, "helper")) {
117 if (*value)
118 string_list_append(&c->helpers, value);
119 else
120 string_list_clear(&c->helpers, 0);
121 } else if (!strcmp(key, "username")) {
122 if (!c->username_from_proto) {
123 free(c->username);
124 c->username = xstrdup(value);
127 else if (!strcmp(key, "usehttppath"))
128 c->use_http_path = git_config_bool(var, value);
130 return 0;
133 static int proto_is_http(const char *s)
135 if (!s)
136 return 0;
137 return !strcmp(s, "https") || !strcmp(s, "http");
140 static void credential_describe(struct credential *c, struct strbuf *out);
141 static void credential_format(struct credential *c, struct strbuf *out);
143 static int select_all(const struct urlmatch_item *a UNUSED,
144 const struct urlmatch_item *b UNUSED)
146 return 0;
149 static int match_partial_url(const char *url, void *cb)
151 struct credential *c = cb;
152 struct credential want = CREDENTIAL_INIT;
153 int matches = 0;
155 if (credential_from_potentially_partial_url(&want, url) < 0)
156 warning(_("skipping credential lookup for key: credential.%s"),
157 url);
158 else
159 matches = credential_match(&want, c, 0);
160 credential_clear(&want);
162 return matches;
165 static void credential_apply_config(struct credential *c)
167 char *normalized_url;
168 struct urlmatch_config config = URLMATCH_CONFIG_INIT;
169 struct strbuf url = STRBUF_INIT;
171 if (!c->host)
172 die(_("refusing to work with credential missing host field"));
173 if (!c->protocol)
174 die(_("refusing to work with credential missing protocol field"));
176 if (c->configured)
177 return;
179 config.section = "credential";
180 config.key = NULL;
181 config.collect_fn = credential_config_callback;
182 config.cascade_fn = NULL;
183 config.select_fn = select_all;
184 config.fallback_match_fn = match_partial_url;
185 config.cb = c;
187 credential_format(c, &url);
188 normalized_url = url_normalize(url.buf, &config.url);
190 git_config(urlmatch_config_entry, &config);
191 string_list_clear(&config.vars, 1);
192 free(normalized_url);
193 urlmatch_config_release(&config);
194 strbuf_release(&url);
196 c->configured = 1;
198 if (!c->use_http_path && proto_is_http(c->protocol)) {
199 FREE_AND_NULL(c->path);
203 static void credential_describe(struct credential *c, struct strbuf *out)
205 if (!c->protocol)
206 return;
207 strbuf_addf(out, "%s://", c->protocol);
208 if (c->username && *c->username)
209 strbuf_addf(out, "%s@", c->username);
210 if (c->host)
211 strbuf_addstr(out, c->host);
212 if (c->path)
213 strbuf_addf(out, "/%s", c->path);
216 static void credential_format(struct credential *c, struct strbuf *out)
218 if (!c->protocol)
219 return;
220 strbuf_addf(out, "%s://", c->protocol);
221 if (c->username && *c->username) {
222 strbuf_add_percentencode(out, c->username, STRBUF_ENCODE_SLASH);
223 strbuf_addch(out, '@');
225 if (c->host)
226 strbuf_addstr(out, c->host);
227 if (c->path) {
228 strbuf_addch(out, '/');
229 strbuf_add_percentencode(out, c->path, 0);
233 static char *credential_ask_one(const char *what, struct credential *c,
234 int flags)
236 struct strbuf desc = STRBUF_INIT;
237 struct strbuf prompt = STRBUF_INIT;
238 char *r;
240 credential_describe(c, &desc);
241 if (desc.len)
242 strbuf_addf(&prompt, "%s for '%s': ", what, desc.buf);
243 else
244 strbuf_addf(&prompt, "%s: ", what);
246 r = git_prompt(prompt.buf, flags);
248 strbuf_release(&desc);
249 strbuf_release(&prompt);
250 return xstrdup(r);
253 static void credential_getpass(struct credential *c)
255 if (!c->username)
256 c->username = credential_ask_one("Username", c,
257 PROMPT_ASKPASS|PROMPT_ECHO);
258 if (!c->password)
259 c->password = credential_ask_one("Password", c,
260 PROMPT_ASKPASS);
263 int credential_has_capability(const struct credential_capability *capa,
264 enum credential_op_type op_type)
267 * We're checking here if each previous step indicated that we had the
268 * capability. If it did, then we want to pass it along; conversely, if
269 * it did not, we don't want to report that to our caller.
271 switch (op_type) {
272 case CREDENTIAL_OP_HELPER:
273 return capa->request_initial;
274 case CREDENTIAL_OP_RESPONSE:
275 return capa->request_initial && capa->request_helper;
276 default:
277 return 0;
281 int credential_read(struct credential *c, FILE *fp,
282 enum credential_op_type op_type)
284 struct strbuf line = STRBUF_INIT;
286 while (strbuf_getline(&line, fp) != EOF) {
287 char *key = line.buf;
288 char *value = strchr(key, '=');
290 if (!line.len)
291 break;
293 if (!value) {
294 warning("invalid credential line: %s", key);
295 strbuf_release(&line);
296 return -1;
298 *value++ = '\0';
300 if (!strcmp(key, "username")) {
301 free(c->username);
302 c->username = xstrdup(value);
303 c->username_from_proto = 1;
304 } else if (!strcmp(key, "password")) {
305 free(c->password);
306 c->password = xstrdup(value);
307 } else if (!strcmp(key, "credential")) {
308 free(c->credential);
309 c->credential = xstrdup(value);
310 } else if (!strcmp(key, "protocol")) {
311 free(c->protocol);
312 c->protocol = xstrdup(value);
313 } else if (!strcmp(key, "host")) {
314 free(c->host);
315 c->host = xstrdup(value);
316 } else if (!strcmp(key, "path")) {
317 free(c->path);
318 c->path = xstrdup(value);
319 } else if (!strcmp(key, "ephemeral")) {
320 c->ephemeral = !!git_config_bool("ephemeral", value);
321 } else if (!strcmp(key, "wwwauth[]")) {
322 strvec_push(&c->wwwauth_headers, value);
323 } else if (!strcmp(key, "state[]")) {
324 strvec_push(&c->state_headers, value);
325 } else if (!strcmp(key, "capability[]")) {
326 if (!strcmp(value, "authtype"))
327 credential_set_capability(&c->capa_authtype, op_type);
328 else if (!strcmp(value, "state"))
329 credential_set_capability(&c->capa_state, op_type);
330 } else if (!strcmp(key, "continue")) {
331 c->multistage = !!git_config_bool("continue", value);
332 } else if (!strcmp(key, "password_expiry_utc")) {
333 errno = 0;
334 c->password_expiry_utc = parse_timestamp(value, NULL, 10);
335 if (c->password_expiry_utc == 0 || errno == ERANGE)
336 c->password_expiry_utc = TIME_MAX;
337 } else if (!strcmp(key, "oauth_refresh_token")) {
338 free(c->oauth_refresh_token);
339 c->oauth_refresh_token = xstrdup(value);
340 } else if (!strcmp(key, "authtype")) {
341 free(c->authtype);
342 c->authtype = xstrdup(value);
343 } else if (!strcmp(key, "url")) {
344 credential_from_url(c, value);
345 } else if (!strcmp(key, "quit")) {
346 c->quit = !!git_config_bool("quit", value);
349 * Ignore other lines; we don't know what they mean, but
350 * this future-proofs us when later versions of git do
351 * learn new lines, and the helpers are updated to match.
355 strbuf_release(&line);
356 return 0;
359 static void credential_write_item(FILE *fp, const char *key, const char *value,
360 int required)
362 if (!value && required)
363 BUG("credential value for %s is missing", key);
364 if (!value)
365 return;
366 if (strchr(value, '\n'))
367 die("credential value for %s contains newline", key);
368 fprintf(fp, "%s=%s\n", key, value);
371 void credential_write(const struct credential *c, FILE *fp,
372 enum credential_op_type op_type)
374 if (credential_has_capability(&c->capa_authtype, op_type))
375 credential_write_item(fp, "capability[]", "authtype", 0);
376 if (credential_has_capability(&c->capa_state, op_type))
377 credential_write_item(fp, "capability[]", "state", 0);
379 if (credential_has_capability(&c->capa_authtype, op_type)) {
380 credential_write_item(fp, "authtype", c->authtype, 0);
381 credential_write_item(fp, "credential", c->credential, 0);
382 if (c->ephemeral)
383 credential_write_item(fp, "ephemeral", "1", 0);
385 credential_write_item(fp, "protocol", c->protocol, 1);
386 credential_write_item(fp, "host", c->host, 1);
387 credential_write_item(fp, "path", c->path, 0);
388 credential_write_item(fp, "username", c->username, 0);
389 credential_write_item(fp, "password", c->password, 0);
390 credential_write_item(fp, "oauth_refresh_token", c->oauth_refresh_token, 0);
391 if (c->password_expiry_utc != TIME_MAX) {
392 char *s = xstrfmt("%"PRItime, c->password_expiry_utc);
393 credential_write_item(fp, "password_expiry_utc", s, 0);
394 free(s);
396 for (size_t i = 0; i < c->wwwauth_headers.nr; i++)
397 credential_write_item(fp, "wwwauth[]", c->wwwauth_headers.v[i], 0);
398 if (credential_has_capability(&c->capa_state, op_type)) {
399 if (c->multistage)
400 credential_write_item(fp, "continue", "1", 0);
401 for (size_t i = 0; i < c->state_headers_to_send.nr; i++)
402 credential_write_item(fp, "state[]", c->state_headers_to_send.v[i], 0);
406 static int run_credential_helper(struct credential *c,
407 const char *cmd,
408 int want_output)
410 struct child_process helper = CHILD_PROCESS_INIT;
411 FILE *fp;
413 strvec_push(&helper.args, cmd);
414 helper.use_shell = 1;
415 helper.in = -1;
416 if (want_output)
417 helper.out = -1;
418 else
419 helper.no_stdout = 1;
421 if (start_command(&helper) < 0)
422 return -1;
424 fp = xfdopen(helper.in, "w");
425 sigchain_push(SIGPIPE, SIG_IGN);
426 credential_write(c, fp, want_output ? CREDENTIAL_OP_HELPER : CREDENTIAL_OP_RESPONSE);
427 fclose(fp);
428 sigchain_pop(SIGPIPE);
430 if (want_output) {
431 int r;
432 fp = xfdopen(helper.out, "r");
433 r = credential_read(c, fp, CREDENTIAL_OP_HELPER);
434 fclose(fp);
435 if (r < 0) {
436 finish_command(&helper);
437 return -1;
441 if (finish_command(&helper))
442 return -1;
443 return 0;
446 static int credential_do(struct credential *c, const char *helper,
447 const char *operation)
449 struct strbuf cmd = STRBUF_INIT;
450 int r;
452 if (helper[0] == '!')
453 strbuf_addstr(&cmd, helper + 1);
454 else if (is_absolute_path(helper))
455 strbuf_addstr(&cmd, helper);
456 else
457 strbuf_addf(&cmd, "git credential-%s", helper);
459 strbuf_addf(&cmd, " %s", operation);
460 r = run_credential_helper(c, cmd.buf, !strcmp(operation, "get"));
462 strbuf_release(&cmd);
463 return r;
466 void credential_fill(struct credential *c, int all_capabilities)
468 int i;
470 if ((c->username && c->password) || c->credential)
471 return;
473 credential_next_state(c);
474 c->multistage = 0;
476 credential_apply_config(c);
477 if (all_capabilities)
478 credential_set_all_capabilities(c, CREDENTIAL_OP_INITIAL);
480 for (i = 0; i < c->helpers.nr; i++) {
481 credential_do(c, c->helpers.items[i].string, "get");
482 if (c->password_expiry_utc < time(NULL)) {
483 /* Discard expired password */
484 FREE_AND_NULL(c->password);
485 /* Reset expiry to maintain consistency */
486 c->password_expiry_utc = TIME_MAX;
488 if ((c->username && c->password) || c->credential) {
489 strvec_clear(&c->wwwauth_headers);
490 return;
492 if (c->quit)
493 die("credential helper '%s' told us to quit",
494 c->helpers.items[i].string);
497 credential_getpass(c);
498 if (!c->username && !c->password && !c->credential)
499 die("unable to get password from user");
502 void credential_approve(struct credential *c)
504 int i;
506 if (c->approved)
507 return;
508 if (((!c->username || !c->password) && !c->credential) || c->password_expiry_utc < time(NULL))
509 return;
511 credential_next_state(c);
513 credential_apply_config(c);
515 for (i = 0; i < c->helpers.nr; i++)
516 credential_do(c, c->helpers.items[i].string, "store");
517 c->approved = 1;
520 void credential_reject(struct credential *c)
522 int i;
524 credential_next_state(c);
526 credential_apply_config(c);
528 for (i = 0; i < c->helpers.nr; i++)
529 credential_do(c, c->helpers.items[i].string, "erase");
531 FREE_AND_NULL(c->username);
532 FREE_AND_NULL(c->password);
533 FREE_AND_NULL(c->credential);
534 FREE_AND_NULL(c->oauth_refresh_token);
535 c->password_expiry_utc = TIME_MAX;
536 c->approved = 0;
539 static int check_url_component(const char *url, int quiet,
540 const char *name, const char *value)
542 if (!value)
543 return 0;
544 if (!strchr(value, '\n'))
545 return 0;
547 if (!quiet)
548 warning(_("url contains a newline in its %s component: %s"),
549 name, url);
550 return -1;
554 * Potentially-partial URLs can, but do not have to, contain
556 * - a protocol (or scheme) of the form "<protocol>://"
558 * - a host name (the part after the protocol and before the first slash after
559 * that, if any)
561 * - a user name and potentially a password (as "<user>[:<password>]@" part of
562 * the host name)
564 * - a path (the part after the host name, if any, starting with the slash)
566 * Missing parts will be left unset in `struct credential`. Thus, `https://`
567 * will have only the `protocol` set, `example.com` only the host name, and
568 * `/git` only the path.
570 * Note that an empty host name in an otherwise fully-qualified URL (e.g.
571 * `cert:///path/to/cert.pem`) will be treated as unset if we expect the URL to
572 * be potentially partial, and only then (otherwise, the empty string is used).
574 * The credential_from_url() function does not allow partial URLs.
576 static int credential_from_url_1(struct credential *c, const char *url,
577 int allow_partial_url, int quiet)
579 const char *at, *colon, *cp, *slash, *host, *proto_end;
581 credential_clear(c);
584 * Match one of:
585 * (1) proto://<host>/...
586 * (2) proto://<user>@<host>/...
587 * (3) proto://<user>:<pass>@<host>/...
589 proto_end = strstr(url, "://");
590 if (!allow_partial_url && (!proto_end || proto_end == url)) {
591 if (!quiet)
592 warning(_("url has no scheme: %s"), url);
593 return -1;
595 cp = proto_end ? proto_end + 3 : url;
596 at = strchr(cp, '@');
597 colon = strchr(cp, ':');
600 * A query or fragment marker before the slash ends the host portion.
601 * We'll just continue to call this "slash" for simplicity. Notably our
602 * "trim leading slashes" part won't skip over this part of the path,
603 * but that's what we'd want.
605 slash = cp + strcspn(cp, "/?#");
607 if (!at || slash <= at) {
608 /* Case (1) */
609 host = cp;
611 else if (!colon || at <= colon) {
612 /* Case (2) */
613 c->username = url_decode_mem(cp, at - cp);
614 if (c->username && *c->username)
615 c->username_from_proto = 1;
616 host = at + 1;
617 } else {
618 /* Case (3) */
619 c->username = url_decode_mem(cp, colon - cp);
620 if (c->username && *c->username)
621 c->username_from_proto = 1;
622 c->password = url_decode_mem(colon + 1, at - (colon + 1));
623 host = at + 1;
626 if (proto_end && proto_end - url > 0)
627 c->protocol = xmemdupz(url, proto_end - url);
628 if (!allow_partial_url || slash - host > 0)
629 c->host = url_decode_mem(host, slash - host);
630 /* Trim leading and trailing slashes from path */
631 while (*slash == '/')
632 slash++;
633 if (*slash) {
634 char *p;
635 c->path = url_decode(slash);
636 p = c->path + strlen(c->path) - 1;
637 while (p > c->path && *p == '/')
638 *p-- = '\0';
641 if (check_url_component(url, quiet, "username", c->username) < 0 ||
642 check_url_component(url, quiet, "password", c->password) < 0 ||
643 check_url_component(url, quiet, "protocol", c->protocol) < 0 ||
644 check_url_component(url, quiet, "host", c->host) < 0 ||
645 check_url_component(url, quiet, "path", c->path) < 0)
646 return -1;
648 return 0;
651 static int credential_from_potentially_partial_url(struct credential *c,
652 const char *url)
654 return credential_from_url_1(c, url, 1, 0);
657 int credential_from_url_gently(struct credential *c, const char *url, int quiet)
659 return credential_from_url_1(c, url, 0, quiet);
662 void credential_from_url(struct credential *c, const char *url)
664 if (credential_from_url_gently(c, url, 0) < 0)
665 die(_("credential url cannot be parsed: %s"), url);