remote.c 71.3 KB
Newer Older
Carlos Martín Nieto committed
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
Carlos Martín Nieto committed
3
 *
Vicent Marti committed
4 5
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
Carlos Martín Nieto committed
6 7
 */

8 9
#include "remote.h"

10 11
#include "buf.h"
#include "branch.h"
Carlos Martín Nieto committed
12 13
#include "config.h"
#include "repository.h"
14
#include "fetch.h"
15
#include "refs.h"
16 17
#include "refspec.h"
#include "fetchhead.h"
18
#include "push.h"
19
#include "proxy.h"
Carlos Martín Nieto committed
20

21 22 23 24 25
#include "git2/config.h"
#include "git2/types.h"
#include "git2/oid.h"
#include "git2/net.h"

26 27 28
#define CONFIG_URL_FMT "remote.%s.url"
#define CONFIG_PUSHURL_FMT "remote.%s.pushurl"
#define CONFIG_FETCH_FMT "remote.%s.fetch"
29
#define CONFIG_PUSH_FMT "remote.%s.push"
30
#define CONFIG_TAGOPT_FMT "remote.%s.tagopt"
31

32
static int dwim_refspecs(git_vector *out, git_vector *refspecs, git_vector *refs);
33
static int lookup_remote_prune_config(git_remote *remote, git_config *config, const char *name);
34
static int apply_insteadof(char **out, git_config *config, const char *url, int direction, bool use_default_if_empty);
35

36
static int add_refspec_to(git_vector *vector, const char *string, bool is_fetch)
Carlos Martín Nieto committed
37
{
38
	git_refspec *spec;
Carlos Martín Nieto committed
39

40
	spec = git__calloc(1, sizeof(git_refspec));
41
	GIT_ERROR_CHECK_ALLOC(spec);
42

43 44 45 46
	if (git_refspec__parse(spec, string, is_fetch) < 0) {
		git__free(spec);
		return -1;
	}
47 48

	spec->push = !is_fetch;
49
	if (git_vector_insert(vector, spec) < 0) {
50
		git_refspec__dispose(spec);
51 52 53
		git__free(spec);
		return -1;
	}
Carlos Martín Nieto committed
54

55
	return 0;
Carlos Martín Nieto committed
56 57
}

58 59 60 61 62
static int add_refspec(git_remote *remote, const char *string, bool is_fetch)
{
	return add_refspec_to(&remote->refspecs, string, is_fetch);
}

63 64
static int download_tags_value(git_remote *remote, git_config *cfg)
{
65
	git_config_entry *ce;
66
	git_str buf = GIT_STR_INIT;
67 68
	int error;

69
	if (git_str_printf(&buf, "remote.%s.tagopt", remote->name) < 0)
70 71
		return -1;

72 73
	error = git_config__lookup_entry(&ce, cfg, git_str_cstr(&buf), false);
	git_str_dispose(&buf);
74

75 76 77 78 79
	if (!error && ce && ce->value) {
		if (!strcmp(ce->value, "--no-tags"))
			remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_NONE;
		else if (!strcmp(ce->value, "--tags"))
			remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_ALL;
80
	}
81

82
	git_config_entry_free(ce);
83 84 85
	return error;
}

86 87
static int ensure_remote_name_is_valid(const char *name)
{
88
	int valid, error;
89

90 91 92
	error = git_remote_name_is_valid(&valid, name);

	if (!error && !valid) {
93 94
		git_error_set(
			GIT_ERROR_CONFIG,
95
			"'%s' is not a valid remote name.", name ? name : "(null)");
96 97 98 99 100 101
		error = GIT_EINVALIDSPEC;
	}

	return error;
}

102 103 104
static int write_add_refspec(git_repository *repo, const char *name, const char *refspec, bool fetch)
{
	git_config *cfg;
105
	git_str var = GIT_STR_INIT;
106
	git_refspec spec;
107 108 109 110 111 112 113 114 115 116 117
	const char *fmt;
	int error;

	if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
	    return error;

	fmt = fetch ? CONFIG_FETCH_FMT : CONFIG_PUSH_FMT;

	if ((error = ensure_remote_name_is_valid(name)) < 0)
		return error;

118
	if ((error = git_refspec__parse(&spec, refspec, fetch)) < 0)
119 120
		return error;

121
	git_refspec__dispose(&spec);
122

123
	if ((error = git_str_printf(&var, fmt, name)) < 0)
124 125 126
		return error;

	/*
Aaron Franke committed
127
	 * "$^" is an unmatchable regexp: it will not match anything at all, so
128 129 130 131 132 133 134 135
	 * all values will be considered new and we will not replace any
	 * present value.
	 */
	if ((error = git_config_set_multivar(cfg, var.ptr, "$^", refspec)) < 0) {
		goto cleanup;
	}

cleanup:
136
	git_str_dispose(&var);
137 138 139
	return 0;
}

140
static int canonicalize_url(git_str *out, const char *in)
141
{
142
	if (in == NULL || strlen(in) == 0) {
143
		git_error_set(GIT_ERROR_INVALID, "cannot set empty URL");
144 145
		return GIT_EINVALIDSPEC;
	}
146

147
#ifdef GIT_WIN32
148 149 150 151 152
	/* Given a UNC path like \\server\path, we need to convert this
	 * to //server/path for compatibility with core git.
	 */
	if (in[0] == '\\' && in[1] == '\\' &&
		(git__isalpha(in[2]) || git__isdigit(in[2]))) {
153
		const char *c;
154
		for (c = in; *c; c++)
155
			git_str_putc(out, *c == '\\' ? '/' : *c);
156

157
		return git_str_oom(out) ? -1 : 0;
158 159 160
	}
#endif

161
	return git_str_puts(out, in);
162 163
}

164
static int default_fetchspec_for_name(git_str *buf, const char *name)
165
{
166
	if (git_str_printf(buf, "+refs/heads/*:refs/remotes/%s/*", name) < 0)
167 168 169 170 171
		return -1;

	return 0;
}

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
static int ensure_remote_doesnot_exist(git_repository *repo, const char *name)
{
	int error;
	git_remote *remote;

	error = git_remote_lookup(&remote, repo, name);

	if (error == GIT_ENOTFOUND)
		return 0;

	if (error < 0)
		return error;

	git_remote_free(remote);

187
	git_error_set(GIT_ERROR_CONFIG, "remote '%s' already exists", name);
188 189 190 191

	return GIT_EEXISTS;
}

192
int git_remote_create_options_init(git_remote_create_options *opts, unsigned int version)
193
{
194 195 196 197 198
	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
		opts, version, git_remote_create_options, GIT_REMOTE_CREATE_OPTIONS_INIT);
	return 0;
}

199
#ifndef GIT_DEPRECATE_HARD
200 201 202 203
int git_remote_create_init_options(git_remote_create_options *opts, unsigned int version)
{
	return git_remote_create_options_init(opts, version);
}
204
#endif
205

206
int git_remote_create_with_opts(git_remote **out, const char *url, const git_remote_create_options *opts)
207 208
{
	git_remote *remote = NULL;
209
	git_config *config_ro = NULL, *config_rw;
210 211 212
	git_str canonical_url = GIT_STR_INIT;
	git_str var = GIT_STR_INIT;
	git_str specbuf = GIT_STR_INIT;
213
	const git_remote_create_options dummy_opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
214
	int error = -1;
215

216 217
	GIT_ASSERT_ARG(out);
	GIT_ASSERT_ARG(url);
218

219 220 221 222
	if (!opts) {
		opts = &dummy_opts;
	}

223
	GIT_ERROR_CHECK_VERSION(opts, GIT_REMOTE_CREATE_OPTIONS_VERSION, "git_remote_create_options");
224 225 226 227 228 229 230 231 232 233 234 235 236 237

	if (opts->name != NULL) {
		if ((error = ensure_remote_name_is_valid(opts->name)) < 0)
			return error;

		if (opts->repository &&
		    (error = ensure_remote_doesnot_exist(opts->repository, opts->name)) < 0)
			return error;
	}

	if (opts->repository) {
		if ((error = git_repository_config_snapshot(&config_ro, opts->repository)) < 0)
			goto on_error;
	}
238

239
	remote = git__calloc(1, sizeof(git_remote));
240
	GIT_ERROR_CHECK_ALLOC(remote);
241

242
	remote->repo = opts->repository;
243

244
	if ((error = git_vector_init(&remote->refs, 8, NULL)) < 0 ||
245
		(error = canonicalize_url(&canonical_url, url)) < 0)
246
		goto on_error;
247

248
	if (opts->repository && !(opts->flags & GIT_REMOTE_CREATE_SKIP_INSTEADOF)) {
249 250 251
		if ((error = apply_insteadof(&remote->url, config_ro, canonical_url.ptr, GIT_DIRECTION_FETCH, true)) < 0 ||
		    (error = apply_insteadof(&remote->pushurl, config_ro, canonical_url.ptr, GIT_DIRECTION_PUSH, false)) < 0)
			goto on_error;
252 253
	} else {
		remote->url = git__strdup(canonical_url.ptr);
254
		GIT_ERROR_CHECK_ALLOC(remote->url);
255
	}
256

257 258
	if (opts->name != NULL) {
		remote->name = git__strdup(opts->name);
259
		GIT_ERROR_CHECK_ALLOC(remote->name);
260

261
		if (opts->repository &&
262
		    ((error = git_str_printf(&var, CONFIG_URL_FMT, opts->name)) < 0 ||
263 264
		    (error = git_repository_config__weakptr(&config_rw, opts->repository)) < 0 ||
		    (error = git_config_set_string(config_rw, var.ptr, canonical_url.ptr)) < 0))
265
			goto on_error;
266 267
	}

268 269 270 271 272 273 274 275 276
	if (opts->fetchspec != NULL ||
	    (opts->name && !(opts->flags & GIT_REMOTE_CREATE_SKIP_DEFAULT_FETCHSPEC))) {
		const char *fetch = NULL;
		if (opts->fetchspec) {
			fetch = opts->fetchspec;
		} else {
			if ((error = default_fetchspec_for_name(&specbuf, opts->name)) < 0)
				goto on_error;

277
			fetch = git_str_cstr(&specbuf);
278 279 280
		}

		if ((error = add_refspec(remote, fetch, true)) < 0)
281 282
			goto on_error;

283
		/* only write for named remotes with a repository */
284
		if (opts->repository && opts->name &&
285
		    ((error = write_add_refspec(opts->repository, opts->name, fetch, true)) < 0 ||
286
		    (error = lookup_remote_prune_config(remote, config_ro, opts->name)) < 0))
287 288
			goto on_error;

289
		/* Move the data over to where the matching functions can find them */
Leo Yang committed
290
		if ((error = dwim_refspecs(&remote->active_refspecs, &remote->refspecs, &remote->refs)) < 0)
291
			goto on_error;
292 293
	}

294
	/* A remote without a name doesn't download tags */
295
	if (!opts->name)
296
		remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_NONE;
297 298 299
	else
		remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_AUTO;

300

301
	git_str_dispose(&var);
302

303
	*out = remote;
Edward Thomson committed
304
	error = 0;
305 306

on_error:
Edward Thomson committed
307 308 309
	if (error)
		git_remote_free(remote);

310
	git_config_free(config_ro);
311 312 313
	git_str_dispose(&specbuf);
	git_str_dispose(&canonical_url);
	git_str_dispose(&var);
314
	return error;
315 316
}

317 318
int git_remote_create(git_remote **out, git_repository *repo, const char *name, const char *url)
{
319
	git_str buf = GIT_STR_INIT;
320
	int error;
321
	git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
322

323 324 325 326 327 328 329
	/* Those 2 tests are duplicated here because of backward-compatibility */
	if ((error = ensure_remote_name_is_valid(name)) < 0)
		return error;

	if (canonicalize_url(&buf, url) < 0)
		return GIT_ERROR;

330
	git_str_clear(&buf);
331 332 333 334

	opts.repository = repo;
	opts.name = name;

335
	error = git_remote_create_with_opts(out, url, &opts);
336

337
	git_str_dispose(&buf);
338

339
	return error;
340 341
}

342 343 344
int git_remote_create_with_fetchspec(git_remote **out, git_repository *repo, const char *name, const char *url, const char *fetch)
{
	int error;
345
	git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT;
346 347 348 349

	if ((error = ensure_remote_name_is_valid(name)) < 0)
		return error;

350 351 352
	opts.repository = repo;
	opts.name = name;
	opts.fetchspec = fetch;
353
	opts.flags = GIT_REMOTE_CREATE_SKIP_DEFAULT_FETCHSPEC;
354

355
	return git_remote_create_with_opts(out, url, &opts);
356 357
}

358
int git_remote_create_anonymous(git_remote **out, git_repository *repo, const char *url)
359
{
360 361 362 363
	git_remote_create_options opts = GIT_REMOTE_CREATE_OPTIONS_INIT;

	opts.repository = repo;

364
	return git_remote_create_with_opts(out, url, &opts);
365 366
}

367 368
int git_remote_create_detached(git_remote **out, const char *url)
{
369
	return git_remote_create_with_opts(out, url, NULL);
370 371
}

372
int git_remote_dup(git_remote **dest, git_remote *source)
Arthur Schreiber committed
373
{
374
	size_t i;
375
	int error = 0;
376
	git_refspec *spec;
Arthur Schreiber committed
377
	git_remote *remote = git__calloc(1, sizeof(git_remote));
378
	GIT_ERROR_CHECK_ALLOC(remote);
Arthur Schreiber committed
379 380 381

	if (source->name != NULL) {
		remote->name = git__strdup(source->name);
382
		GIT_ERROR_CHECK_ALLOC(remote->name);
Arthur Schreiber committed
383 384 385 386
	}

	if (source->url != NULL) {
		remote->url = git__strdup(source->url);
387
		GIT_ERROR_CHECK_ALLOC(remote->url);
Arthur Schreiber committed
388 389 390 391
	}

	if (source->pushurl != NULL) {
		remote->pushurl = git__strdup(source->pushurl);
392
		GIT_ERROR_CHECK_ALLOC(remote->pushurl);
Arthur Schreiber committed
393 394 395 396
	}

	remote->repo = source->repo;
	remote->download_tags = source->download_tags;
397
	remote->prune_refs = source->prune_refs;
Arthur Schreiber committed
398

399 400 401 402 403
	if (git_vector_init(&remote->refs, 32, NULL) < 0 ||
	    git_vector_init(&remote->refspecs, 2, NULL) < 0 ||
	    git_vector_init(&remote->active_refspecs, 2, NULL) < 0) {
		error = -1;
		goto cleanup;
Arthur Schreiber committed
404 405
	}

406 407 408 409
	git_vector_foreach(&source->refspecs, i, spec) {
		if ((error = add_refspec(remote, spec->string, !spec->push)) < 0)
			goto cleanup;
	}
410

Arthur Schreiber committed
411 412
	*dest = remote;

413 414 415 416 417 418
cleanup:

	if (error < 0)
		git__free(remote);

	return error;
Arthur Schreiber committed
419 420
}

421 422 423 424 425 426 427
struct refspec_cb_data {
	git_remote *remote;
	int fetch;
};

static int refspec_cb(const git_config_entry *entry, void *payload)
{
428
	struct refspec_cb_data *data = (struct refspec_cb_data *)payload;
429
	return add_refspec(data->remote, entry->value, data->fetch);
430 431
}

432
static int get_optional_config(
433
	bool *found, git_config *config, git_str *buf,
434
	git_config_foreach_cb cb, void *payload)
435 436
{
	int error = 0;
437
	const char *key = git_str_cstr(buf);
438

439
	if (git_str_oom(buf))
440 441 442
		return -1;

	if (cb != NULL)
443
		error = git_config_get_multivar_foreach(config, key, NULL, cb, payload);
444 445 446
	else
		error = git_config_get_string(payload, config, key);

447 448 449
	if (found)
		*found = !error;

450
	if (error == GIT_ENOTFOUND) {
451
		git_error_clear();
452 453 454 455 456 457
		error = 0;
	}

	return error;
}

458
int git_remote_lookup(git_remote **out, git_repository *repo, const char *name)
Carlos Martín Nieto committed
459
{
460
	git_remote *remote = NULL;
461
	git_str buf = GIT_STR_INIT;
Carlos Martín Nieto committed
462
	const char *val;
463
	int error = 0;
464
	git_config *config;
465
	struct refspec_cb_data data = { NULL };
466
	bool optional_setting_found = false, found;
467

468 469 470
	GIT_ASSERT_ARG(out);
	GIT_ASSERT_ARG(repo);
	GIT_ASSERT_ARG(name);
471

472 473 474
	if ((error = ensure_remote_name_is_valid(name)) < 0)
		return error;

475
	if ((error = git_repository_config_snapshot(&config, repo)) < 0)
476
		return error;
477

478
	remote = git__calloc(1, sizeof(git_remote));
479
	GIT_ERROR_CHECK_ALLOC(remote);
Carlos Martín Nieto committed
480 481

	remote->name = git__strdup(name);
482
	GIT_ERROR_CHECK_ALLOC(remote->name);
Carlos Martín Nieto committed
483

484 485
	if (git_vector_init(&remote->refs, 32, NULL) < 0 ||
	    git_vector_init(&remote->refspecs, 2, NULL) < 0 ||
486
	    git_vector_init(&remote->passive_refspecs, 2, NULL) < 0 ||
487
	    git_vector_init(&remote->active_refspecs, 2, NULL) < 0) {
488 489 490
		error = -1;
		goto cleanup;
	}
491

492
	if ((error = git_str_printf(&buf, "remote.%s.url", name)) < 0)
493
		goto cleanup;
Carlos Martín Nieto committed
494

495
	if ((error = get_optional_config(&found, config, &buf, NULL, (void *)&val)) < 0)
Carlos Martín Nieto committed
496
		goto cleanup;
497

498 499
	optional_setting_found |= found;

500
	remote->repo = repo;
501
	remote->download_tags = GIT_REMOTE_DOWNLOAD_TAGS_AUTO;
502 503

	if (found && strlen(val) > 0) {
504 505 506
		if ((error = apply_insteadof(&remote->url, config, val, GIT_DIRECTION_FETCH, true)) < 0 ||
		    (error = apply_insteadof(&remote->pushurl, config, val, GIT_DIRECTION_PUSH, false)) < 0)
			goto cleanup;
507
	}
Carlos Martín Nieto committed
508

509
	val = NULL;
510 511
	git_str_clear(&buf);
	git_str_printf(&buf, "remote.%s.pushurl", name);
512

513
	if ((error = get_optional_config(&found, config, &buf, NULL, (void *)&val)) < 0)
514 515
		goto cleanup;

516 517 518 519
	optional_setting_found |= found;

	if (!optional_setting_found) {
		error = GIT_ENOTFOUND;
520
		git_error_set(GIT_ERROR_CONFIG, "remote '%s' does not exist", name);
521
		goto cleanup;
522
	}
523

524
	if (found && strlen(val) > 0) {
525
		if (remote->pushurl)
526
			git__free(remote->pushurl);
527 528 529

		if ((error = apply_insteadof(&remote->pushurl, config, val, GIT_DIRECTION_FETCH, true)) < 0)
			goto cleanup;
530 531
	}

532 533
	data.remote = remote;
	data.fetch = true;
534

535 536
	git_str_clear(&buf);
	git_str_printf(&buf, "remote.%s.fetch", name);
537

538
	if ((error = get_optional_config(NULL, config, &buf, refspec_cb, &data)) < 0)
539
		goto cleanup;
Carlos Martín Nieto committed
540

541
	data.fetch = false;
542 543
	git_str_clear(&buf);
	git_str_printf(&buf, "remote.%s.push", name);
Carlos Martín Nieto committed
544

545
	if ((error = get_optional_config(NULL, config, &buf, refspec_cb, &data)) < 0)
Carlos Martín Nieto committed
546 547
		goto cleanup;

548
	if ((error = download_tags_value(remote, config)) < 0)
549 550
		goto cleanup;

551 552 553 554
	if ((error = lookup_remote_prune_config(remote, config, name)) < 0)
		goto cleanup;

	/* Move the data over to where the matching functions can find them */
Leo Yang committed
555
	if ((error = dwim_refspecs(&remote->active_refspecs, &remote->refspecs, &remote->refs)) < 0)
556 557 558 559 560 561
		goto cleanup;

	*out = remote;

cleanup:
	git_config_free(config);
562
	git_str_dispose(&buf);
563 564 565 566 567 568 569 570 571

	if (error < 0)
		git_remote_free(remote);

	return error;
}

static int lookup_remote_prune_config(git_remote *remote, git_config *config, const char *name)
{
572
	git_str buf = GIT_STR_INIT;
573 574
	int error = 0;

575
	git_str_printf(&buf, "remote.%s.prune", name);
576

577
	if ((error = git_config_get_bool(&remote->prune_refs, config, git_str_cstr(&buf))) < 0) {
578
		if (error == GIT_ENOTFOUND) {
579
			git_error_clear();
580 581 582

			if ((error = git_config_get_bool(&remote->prune_refs, config, "fetch.prune")) < 0) {
				if (error == GIT_ENOTFOUND) {
583
					git_error_clear();
David Calavera committed
584
					error = 0;
585 586 587 588 589
				}
			}
		}
	}

590
	git_str_dispose(&buf);
Carlos Martín Nieto committed
591 592 593
	return error;
}

Ben Straub committed
594
const char *git_remote_name(const git_remote *remote)
Carlos Martín Nieto committed
595
{
596
	GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
Carlos Martín Nieto committed
597 598 599
	return remote->name;
}

Etienne Samson committed
600 601
git_repository *git_remote_owner(const git_remote *remote)
{
602
	GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
Etienne Samson committed
603 604 605
	return remote->repo;
}

Ben Straub committed
606
const char *git_remote_url(const git_remote *remote)
Carlos Martín Nieto committed
607
{
608
	GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
Carlos Martín Nieto committed
609 610 611
	return remote->url;
}

612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
int git_remote_set_instance_url(git_remote *remote, const char *url)
{
	char *tmp;

	GIT_ASSERT_ARG(remote);
	GIT_ASSERT_ARG(url);

	if ((tmp = git__strdup(url)) == NULL)
		return -1;

	git__free(remote->url);
	remote->url = tmp;

	return 0;
}

628
static int set_url(git_repository *repo, const char *remote, const char *pattern, const char *url)
629
{
630
	git_config *cfg;
631
	git_str buf = GIT_STR_INIT, canonical_url = GIT_STR_INIT;
632
	int error;
633

634 635
	GIT_ASSERT_ARG(repo);
	GIT_ASSERT_ARG(remote);
636

637 638 639 640 641 642
	if ((error = ensure_remote_name_is_valid(remote)) < 0)
		return error;

	if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
		return error;

643
	if ((error = git_str_printf(&buf, pattern, remote)) < 0)
644 645 646 647 648 649 650 651 652 653 654 655
		return error;

	if (url) {
		if ((error = canonicalize_url(&canonical_url, url)) < 0)
			goto cleanup;

		error = git_config_set_string(cfg, buf.ptr, url);
	} else {
		error = git_config_delete_entry(cfg, buf.ptr);
	}

cleanup:
656 657
	git_str_dispose(&canonical_url);
	git_str_dispose(&buf);
658 659 660 661 662 663 664

	return error;
}

int git_remote_set_url(git_repository *repo, const char *remote, const char *url)
{
	return set_url(repo, remote, CONFIG_URL_FMT, url);
665 666
}

Ben Straub committed
667
const char *git_remote_pushurl(const git_remote *remote)
668
{
669
	GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
670 671 672
	return remote->pushurl;
}

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
int git_remote_set_instance_pushurl(git_remote *remote, const char *url)
{
	char *tmp;

	GIT_ASSERT_ARG(remote);
	GIT_ASSERT_ARG(url);

	if ((tmp = git__strdup(url)) == NULL)
		return -1;

	git__free(remote->pushurl);
	remote->pushurl = tmp;

	return 0;
}

689
int git_remote_set_pushurl(git_repository *repo, const char *remote, const char *url)
690
{
691
	return set_url(repo, remote, CONFIG_PUSHURL_FMT, url);
692 693
}

694
static int resolve_url(
695
	git_str *resolved_url,
696 697 698
	const char *url,
	int direction,
	const git_remote_callbacks *callbacks)
699
{
700 701 702 703
#ifdef GIT_DEPRECATE_HARD
	GIT_UNUSED(direction);
	GIT_UNUSED(callbacks);
#else
704 705
	git_buf buf = GIT_BUF_INIT;
	int error;
706 707

	if (callbacks && callbacks->resolve_url) {
708
		error = callbacks->resolve_url(&buf, url, direction, callbacks->payload);
709

710 711
		if (error != GIT_PASSTHROUGH) {
			git_error_set_after_callback_function(error, "git_resolve_url_cb");
712

713 714 715 716
			git_str_set(resolved_url, buf.ptr, buf.size);
			git_buf_dispose(&buf);

			return error;
717 718
		}
	}
719
#endif
720

721
	return git_str_sets(resolved_url, url);
722 723
}

724
int git_remote__urlfordirection(
725
	git_str *url_out,
726 727 728
	struct git_remote *remote,
	int direction,
	const git_remote_callbacks *callbacks)
729 730 731
{
	const char *url = NULL;

732 733
	GIT_ASSERT_ARG(remote);
	GIT_ASSERT_ARG(direction == GIT_DIRECTION_FETCH || direction == GIT_DIRECTION_PUSH);
734

735 736 737 738 739 740 741 742 743 744
	if (callbacks && callbacks->remote_ready) {
		int status = callbacks->remote_ready(remote, direction, callbacks->payload);

		if (status != 0 && status != GIT_PASSTHROUGH) {
			git_error_set_after_callback_function(status, "git_remote_ready_cb");
			return status;
		}
	}

	if (direction == GIT_DIRECTION_FETCH)
745
		url = remote->url;
746
	else if (direction == GIT_DIRECTION_PUSH)
747
		url = remote->pushurl ? remote->pushurl : remote->url;
748

749 750 751 752 753 754
	if (!url) {
		git_error_set(GIT_ERROR_INVALID,
			"malformed remote '%s' - missing %s URL",
			remote->name ? remote->name : "(anonymous)",
			direction == GIT_DIRECTION_FETCH ? "fetch" : "push");
		return GIT_EINVALID;
755
	}
756

757
	return resolve_url(url_out, url, direction, callbacks);
758 759
}

760 761 762
int git_remote_connect_options_init(
	git_remote_connect_options *opts,
	unsigned int version)
763
{
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
		opts, version, git_remote_connect_options, GIT_REMOTE_CONNECT_OPTIONS_INIT);
	return 0;
}

int git_remote_connect_options_dup(
	git_remote_connect_options *dst,
	const git_remote_connect_options *src)
{
	memcpy(dst, src, sizeof(git_remote_connect_options));

	if (git_proxy_options_dup(&dst->proxy_opts, &src->proxy_opts) < 0 ||
	    git_strarray_copy(&dst->custom_headers, &src->custom_headers) < 0)
		return -1;

	return 0;
}

void git_remote_connect_options_dispose(git_remote_connect_options *opts)
{
	if (!opts)
		return;

	git_strarray_dispose(&opts->custom_headers);
	git_proxy_options_dispose(&opts->proxy_opts);
}

static size_t http_header_name_length(const char *http_header)
{
	const char *colon = strchr(http_header, ':');
	if (!colon)
		return 0;
	return colon - http_header;
}

static bool is_malformed_http_header(const char *http_header)
{
	const char *c;
	size_t name_len;

	/* Disallow \r and \n */
	if ((c = strchr(http_header, '\r')) != NULL)
		return true;
	if ((c = strchr(http_header, '\n')) != NULL)
		return true;

	/* Require a header name followed by : */
	if ((name_len = http_header_name_length(http_header)) < 1)
		return true;

	return false;
}

static char *forbidden_custom_headers[] = {
	"User-Agent",
	"Host",
	"Accept",
	"Content-Type",
	"Transfer-Encoding",
	"Content-Length",
};

static bool is_forbidden_custom_header(const char *custom_header)
{
	unsigned long i;
	size_t name_len = http_header_name_length(custom_header);

	/* Disallow headers that we set */
	for (i = 0; i < ARRAY_SIZE(forbidden_custom_headers); i++)
		if (strncmp(forbidden_custom_headers[i], custom_header, name_len) == 0)
			return true;

	return false;
}

static int validate_custom_headers(const git_strarray *custom_headers)
{
	size_t i;

	if (!custom_headers)
844 845
		return 0;

846 847 848 849 850 851 852 853 854 855 856 857 858
	for (i = 0; i < custom_headers->count; i++) {
		if (is_malformed_http_header(custom_headers->strings[i])) {
			git_error_set(GIT_ERROR_INVALID, "custom HTTP header '%s' is malformed", custom_headers->strings[i]);
			return -1;
		}

		if (is_forbidden_custom_header(custom_headers->strings[i])) {
			git_error_set(GIT_ERROR_INVALID, "custom HTTP header '%s' is already set by libgit2", custom_headers->strings[i]);
			return -1;
		}
	}

	return 0;
859 860
}

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
static int lookup_redirect_config(
	git_remote_redirect_t *out,
	git_repository *repo)
{
	git_config *config;
	const char *value;
	int bool_value, error = 0;

	if (!repo) {
		*out = GIT_REMOTE_REDIRECT_INITIAL;
		return 0;
	}

	if ((error = git_repository_config_snapshot(&config, repo)) < 0)
		goto done;

	if ((error = git_config_get_string(&value, config, "http.followRedirects")) < 0) {
		if (error == GIT_ENOTFOUND) {
			*out = GIT_REMOTE_REDIRECT_INITIAL;
			error = 0;
		}

		goto done;
	}

	if (git_config_parse_bool(&bool_value, value) == 0) {
		*out = bool_value ? GIT_REMOTE_REDIRECT_ALL :
		                    GIT_REMOTE_REDIRECT_NONE;
	} else if (strcasecmp(value, "initial") == 0) {
		*out = GIT_REMOTE_REDIRECT_INITIAL;
	} else {
		git_error_set(GIT_ERROR_CONFIG, "invalid configuration setting '%s' for 'http.followRedirects'", value);
		error = -1;
	}

done:
	git_config_free(config);
	return error;
}

901 902
int git_remote_connect_options_normalize(
	git_remote_connect_options *dst,
903
	git_repository *repo,
904
	const git_remote_connect_options *src)
905
{
906
	git_remote_connect_options_dispose(dst);
907
	git_remote_connect_options_init(dst, GIT_REMOTE_CONNECT_OPTIONS_VERSION);
908

909 910 911 912
	if (src) {
		GIT_ERROR_CHECK_VERSION(src, GIT_REMOTE_CONNECT_OPTIONS_VERSION, "git_remote_connect_options");
		GIT_ERROR_CHECK_VERSION(&src->callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
		GIT_ERROR_CHECK_VERSION(&src->proxy_opts, GIT_PROXY_OPTIONS_VERSION, "git_proxy_options");
913

914 915 916 917
		if (validate_custom_headers(&src->custom_headers) < 0 ||
		    git_remote_connect_options_dup(dst, src) < 0)
			return -1;
	}
918

919 920 921 922
	if (dst->follow_redirects == 0) {
		if (lookup_redirect_config(&dst->follow_redirects, repo) < 0)
			return -1;
	}
923

924
	return 0;
925 926
}

927 928 929 930
int git_remote_connect_ext(
	git_remote *remote,
	git_direction direction,
	const git_remote_connect_options *given_opts)
931
{
932
	git_remote_connect_options opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
933
	git_str url = GIT_STR_INIT;
934
	git_transport *t;
935
	int error;
936

937
	GIT_ASSERT_ARG(remote);
938

939 940
	if (given_opts)
		memcpy(&opts, given_opts, sizeof(git_remote_connect_options));
941

942 943
	GIT_ERROR_CHECK_VERSION(&opts.callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
	GIT_ERROR_CHECK_VERSION(&opts.proxy_opts, GIT_PROXY_OPTIONS_VERSION, "git_proxy_options");
944

945 946
	t = remote->transport;

947
	if ((error = git_remote__urlfordirection(&url, remote, direction, &opts.callbacks)) < 0)
948
		goto on_error;
949

950 951
	/* If we don't have a transport object yet, and the caller specified a
	 * custom transport factory, use that */
952 953
	if (!t && opts.callbacks.transport &&
	    (error = opts.callbacks.transport(&t, remote, opts.callbacks.payload)) < 0)
954
		goto on_error;
955 956 957

	/* If we still don't have a transport, then use the global
	 * transport registrations which map URI schemes to transport factories */
958 959
	if (!t && (error = git_transport_new(&t, remote, url.ptr)) < 0)
		goto on_error;
960

961
	if ((error = t->connect(t, url.ptr, direction, &opts)) != 0)
962
		goto on_error;
963 964 965

	remote->transport = t;

966
	git_str_dispose(&url);
967

968
	return 0;
969

970
on_error:
971 972 973
	if (t)
		t->free(t);

974
	git_str_dispose(&url);
975 976 977 978

	if (t == remote->transport)
		remote->transport = NULL;

979
	return error;
980 981
}

982 983 984 985 986 987
int git_remote_connect(
	git_remote *remote,
	git_direction direction,
	const git_remote_callbacks *callbacks,
	const git_proxy_options *proxy,
	const git_strarray *custom_headers)
988
{
989 990 991 992
	git_remote_connect_options opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;

	if (callbacks)
		memcpy(&opts.callbacks, callbacks, sizeof(git_remote_callbacks));
993

994 995
	if (proxy)
		memcpy(&opts.proxy_opts, proxy, sizeof(git_proxy_options));
996

997 998 999 1000
	if (custom_headers)
		memcpy(&opts.custom_headers, custom_headers, sizeof(git_strarray));

	return git_remote_connect_ext(remote, direction, &opts);
1001 1002
}

1003
int git_remote_ls(const git_remote_head ***out, size_t *size, git_remote *remote)
1004
{
1005
	GIT_ASSERT_ARG(remote);
1006

1007
	if (!remote->transport) {
1008
		git_error_set(GIT_ERROR_NET, "this remote has never connected");
1009 1010 1011
		return -1;
	}

1012
	return remote->transport->ls(out, size, remote->transport);
1013 1014
}

1015
static int lookup_config(char **out, git_config *cfg, const char *name)
1016
{
1017 1018
	git_config_entry *ce = NULL;
	int error;
1019

1020
	if ((error = git_config__lookup_entry(&ce, cfg, name, false)) < 0)
1021 1022
		return error;

1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
	if (ce && ce->value) {
		*out = git__strdup(ce->value);
		GIT_ERROR_CHECK_ALLOC(*out);
	} else {
		error = GIT_ENOTFOUND;
	}

	git_config_entry_free(ce);
	return error;
}
1033

1034 1035 1036
static void url_config_trim(git_net_url *url)
{
	size_t len = strlen(url->path);
1037

1038 1039 1040 1041 1042 1043
	if (url->path[len - 1] == '/') {
		len--;
	} else {
		while (len && url->path[len - 1] != '/')
			len--;
	}
1044

1045
	url->path[len] = '\0';
1046 1047
}

1048
static int http_proxy_config(char **out, git_remote *remote, git_net_url *url)
1049
{
Laurence McGlashan committed
1050
	git_config *cfg = NULL;
1051
	git_str buf = GIT_STR_INIT;
1052
	git_net_url lookup_url = GIT_NET_URL_INIT;
1053
	int error;
1054

1055
	if ((error = git_net_url_dup(&lookup_url, url)) < 0)
1056
		goto done;
1057

1058
	if (remote->repo) {
1059
		if ((error = git_repository_config(&cfg, remote->repo)) < 0)
1060 1061 1062 1063 1064 1065
			goto done;
	} else {
		if ((error = git_config_open_default(&cfg)) < 0)
			goto done;
	}

1066 1067
	/* remote.<name>.proxy config setting */
	if (remote->name && remote->name[0]) {
1068
		git_str_clear(&buf);
1069

1070
		if ((error = git_str_printf(&buf, "remote.%s.proxy", remote->name)) < 0 ||
1071 1072 1073
		    (error = lookup_config(out, cfg, buf.ptr)) != GIT_ENOTFOUND)
			goto done;
	}
1074

1075
	while (true) {
1076
		git_str_clear(&buf);
1077

1078
		if ((error = git_str_puts(&buf, "http.")) < 0 ||
1079
		    (error = git_net_url_fmt(&buf, &lookup_url)) < 0 ||
1080
		    (error = git_str_puts(&buf, ".proxy")) < 0 ||
1081 1082
		    (error = lookup_config(out, cfg, buf.ptr)) != GIT_ENOTFOUND)
			goto done;
1083

1084 1085
		if (! lookup_url.path[0])
			break;
1086

1087 1088
		url_config_trim(&lookup_url);
	}
1089

1090
	git_str_clear(&buf);
1091

1092
	error = lookup_config(out, cfg, "http.proxy");
1093

1094
done:
1095
	git_config_free(cfg);
1096
	git_str_dispose(&buf);
1097 1098 1099
	git_net_url_dispose(&lookup_url);
	return error;
}
1100

1101 1102
static int http_proxy_env(char **out, git_remote *remote, git_net_url *url)
{
1103
	git_str proxy_env = GIT_STR_INIT, no_proxy_env = GIT_STR_INIT;
1104 1105
	bool use_ssl = (strcmp(url->scheme, "https") == 0);
	int error;
1106

1107
	GIT_UNUSED(remote);
1108

1109
	/* http_proxy / https_proxy environment variables */
1110
	error = git__getenv(&proxy_env, use_ssl ? "https_proxy" : "http_proxy");
1111

1112 1113
	/* try uppercase environment variables */
	if (error == GIT_ENOTFOUND)
1114
		error = git__getenv(&proxy_env, use_ssl ? "HTTPS_PROXY" : "HTTP_PROXY");
1115

1116 1117
	if (error)
		goto done;
1118

1119 1120
	/* no_proxy/NO_PROXY environment variables */
	error = git__getenv(&no_proxy_env, "no_proxy");
1121

1122 1123 1124
	if (error == GIT_ENOTFOUND)
		error = git__getenv(&no_proxy_env, "NO_PROXY");

1125 1126
	if (error && error != GIT_ENOTFOUND)
		goto done;
1127

1128
	if (!git_net_url_matches_pattern_list(url, no_proxy_env.ptr))
1129
		*out = git_str_detach(&proxy_env);
1130 1131
	else
		error = GIT_ENOTFOUND;
1132

1133
done:
1134 1135
	git_str_dispose(&proxy_env);
	git_str_dispose(&no_proxy_env);
1136
	return error;
1137 1138
}

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
int git_remote__http_proxy(char **out, git_remote *remote, git_net_url *url)
{
	int error;

	GIT_ASSERT_ARG(out);
	GIT_ASSERT_ARG(remote);

	*out = NULL;

	/*
	 * Go through the possible sources for proxy configuration,
	 * Examine the various git config options first, then
	 * consult environment variables.
	 */
	if ((error = http_proxy_config(out, remote, url)) != GIT_ENOTFOUND ||
	    (error = http_proxy_env(out, remote, url)) != GIT_ENOTFOUND)
		return error;

	return 0;
}

1160 1161
/* DWIM `refspecs` based on `refs` and append the output to `out` */
static int dwim_refspecs(git_vector *out, git_vector *refspecs, git_vector *refs)
1162
{
1163
	size_t i;
1164 1165 1166
	git_refspec *spec;

	git_vector_foreach(refspecs, i, spec) {
1167 1168 1169
		if (git_refspec__dwim_one(out, spec, refs) < 0)
			return -1;
	}
1170

1171 1172
	return 0;
}
1173

1174 1175 1176 1177
static void free_refspecs(git_vector *vec)
{
	size_t i;
	git_refspec *spec;
1178

1179
	git_vector_foreach(vec, i, spec) {
1180
		git_refspec__dispose(spec);
1181
		git__free(spec);
1182 1183
	}

1184
	git_vector_clear(vec);
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
}

static int remote_head_cmp(const void *_a, const void *_b)
{
	const git_remote_head *a = (git_remote_head *) _a;
	const git_remote_head *b = (git_remote_head *) _b;

	return git__strcmp_cb(a->name, b->name);
}

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
static int ls_to_vector(git_vector *out, git_remote *remote)
{
	git_remote_head **heads;
	size_t heads_len, i;

	if (git_remote_ls((const git_remote_head ***)&heads, &heads_len, remote) < 0)
		return -1;

	if (git_vector_init(out, heads_len, remote_head_cmp) < 0)
		return -1;

	for (i = 0; i < heads_len; i++) {
		if (git_vector_insert(out, heads[i]) < 0)
			return -1;
	}

	return 0;
}

1214 1215 1216 1217 1218
#define copy_opts(out, in) \
	if (in) { \
		(out)->callbacks = (in)->callbacks; \
		(out)->proxy_opts = (in)->proxy_opts; \
		(out)->custom_headers = (in)->custom_headers; \
1219
		(out)->follow_redirects = (in)->follow_redirects; \
1220 1221
	}

1222 1223
GIT_INLINE(int) connect_opts_from_fetch_opts(
	git_remote_connect_options *out,
1224
	git_remote *remote,
1225 1226 1227 1228
	const git_fetch_options *fetch_opts)
{
	git_remote_connect_options tmp = GIT_REMOTE_CONNECT_OPTIONS_INIT;
	copy_opts(&tmp, fetch_opts);
1229
	return git_remote_connect_options_normalize(out, remote->repo, &tmp);
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
}

static int connect_or_reset_options(
	git_remote *remote,
	int direction,
	git_remote_connect_options *opts)
{
	if (!git_remote_connected(remote)) {
		return git_remote_connect_ext(remote, direction, opts);
	} else {
		return remote->transport->set_connect_opts(remote->transport, opts);
1241
	}
1242
}
1243

1244 1245 1246 1247 1248 1249 1250 1251 1252
/* Download from an already connected remote. */
static int git_remote__download(
	git_remote *remote,
	const git_strarray *refspecs,
	const git_fetch_options *opts)
{
	git_vector *to_active, specs = GIT_VECTOR_INIT, refs = GIT_VECTOR_INIT;
	size_t i;
	int error;
1253

1254
	if (ls_to_vector(&refs, remote) < 0)
1255 1256
		return -1;

1257
	if ((error = git_vector_init(&specs, 0, NULL)) < 0)
1258 1259
		goto on_error;

1260
	remote->passed_refspecs = 0;
1261
	if (!refspecs || !refspecs->count) {
1262 1263 1264 1265 1266 1267 1268 1269
		to_active = &remote->refspecs;
	} else {
		for (i = 0; i < refspecs->count; i++) {
			if ((error = add_refspec_to(&specs, refspecs->strings[i], true)) < 0)
				goto on_error;
		}

		to_active = &specs;
1270
		remote->passed_refspecs = 1;
1271 1272
	}

1273 1274 1275
	free_refspecs(&remote->passive_refspecs);
	if ((error = dwim_refspecs(&remote->passive_refspecs, &remote->refspecs, &refs)) < 0)
		goto on_error;
1276

1277
	free_refspecs(&remote->active_refspecs);
1278
	error = dwim_refspecs(&remote->active_refspecs, to_active, &refs);
1279

1280
	git_vector_free(&refs);
1281 1282
	free_refspecs(&specs);
	git_vector_free(&specs);
1283 1284

	if (error < 0)
1285
		goto on_error;
1286

1287 1288 1289 1290 1291
	if (remote->push) {
		git_push_free(remote->push);
		remote->push = NULL;
	}

1292
	if ((error = git_fetch_negotiate(remote, opts)) < 0)
1293
		goto on_error;
1294

1295
	error = git_fetch_download_pack(remote);
1296 1297 1298 1299 1300 1301

on_error:
	git_vector_free(&refs);
	free_refspecs(&specs);
	git_vector_free(&specs);
	return error;
1302 1303
}

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
int git_remote_download(
	git_remote *remote,
	const git_strarray *refspecs,
	const git_fetch_options *opts)
{
	git_remote_connect_options connect_opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
	int error;

	GIT_ASSERT_ARG(remote);

	if (!remote->repo) {
		git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
		return -1;
	}

1319
	if (connect_opts_from_fetch_opts(&connect_opts, remote, opts) < 0)
1320 1321 1322 1323 1324 1325 1326 1327
		return -1;

	if ((error = connect_or_reset_options(remote, GIT_DIRECTION_FETCH, &connect_opts)) < 0)
		return error;

	return git_remote__download(remote, refspecs, opts);
}

1328
int git_remote_fetch(
1329 1330 1331 1332
	git_remote *remote,
	const git_strarray *refspecs,
	const git_fetch_options *opts,
	const char *reflog_message)
1333
{
1334
	int error, update_fetchhead = 1;
1335
	git_remote_autotag_option_t tagopt = remote->download_tags;
1336
	bool prune = false;
1337
	git_str reflog_msg_buf = GIT_STR_INIT;
1338 1339 1340 1341 1342 1343 1344 1345 1346
	git_remote_connect_options connect_opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;

	GIT_ASSERT_ARG(remote);

	if (!remote->repo) {
		git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
		return -1;
	}

1347
	if (connect_opts_from_fetch_opts(&connect_opts, remote, opts) < 0)
1348 1349 1350 1351
		return -1;

	if ((error = connect_or_reset_options(remote, GIT_DIRECTION_FETCH, &connect_opts)) < 0)
		return error;
1352 1353

	if (opts) {
1354
		update_fetchhead = opts->update_fetchhead;
1355
		tagopt = opts->download_tags;
1356
	}
1357 1358

	/* Connect and download everything */
1359
	error = git_remote__download(remote, refspecs, opts);
1360 1361 1362 1363

	/* We don't need to be connected anymore */
	git_remote_disconnect(remote);

1364 1365
	/* If the download failed, return the error */
	if (error != 0)
1366
		goto done;
1367

1368 1369
	/* Default reflog message */
	if (reflog_message)
1370
		git_str_sets(&reflog_msg_buf, reflog_message);
1371
	else {
1372
		git_str_printf(&reflog_msg_buf, "fetch %s",
1373 1374 1375
				remote->name ? remote->name : remote->url);
	}

1376
	/* Create "remote/foo" branches for all remote branches */
1377
	error = git_remote_update_tips(remote, &connect_opts.callbacks, update_fetchhead, tagopt, git_str_cstr(&reflog_msg_buf));
1378
	git_str_dispose(&reflog_msg_buf);
1379
	if (error < 0)
1380
		goto done;
1381

1382 1383
	if (opts && opts->prune == GIT_FETCH_PRUNE)
		prune = true;
1384
	else if (opts && opts->prune == GIT_FETCH_PRUNE_UNSPECIFIED && remote->prune_refs)
1385 1386 1387 1388 1389 1390 1391
		prune = true;
	else if (opts && opts->prune == GIT_FETCH_NO_PRUNE)
		prune = false;
	else
		prune = remote->prune_refs;

	if (prune)
1392
		error = git_remote_prune(remote, &connect_opts.callbacks);
1393

1394 1395
done:
	git_remote_connect_options_dispose(&connect_opts);
1396
	return error;
1397 1398
}

1399 1400 1401 1402 1403
static int remote_head_for_fetchspec_src(git_remote_head **out, git_vector *update_heads, const char *fetchspec_src)
{
	unsigned int i;
	git_remote_head *remote_ref;

1404 1405
	GIT_ASSERT_ARG(update_heads);
	GIT_ASSERT_ARG(fetchspec_src);
1406 1407

	*out = NULL;
nulltoken committed
1408 1409 1410 1411 1412

	git_vector_foreach(update_heads, i, remote_ref) {
		if (strcmp(remote_ref->name, fetchspec_src) == 0) {
			*out = remote_ref;
			break;
1413 1414 1415 1416 1417 1418
		}
	}

	return 0;
}

1419
static int ref_to_update(int *update, git_str *remote_name, git_remote *remote, git_refspec *spec, const char *ref_name)
1420 1421 1422
{
	int error = 0;
	git_repository *repo;
1423 1424
	git_str upstream_remote = GIT_STR_INIT;
	git_str upstream_name = GIT_STR_INIT;
1425 1426 1427 1428 1429

	repo = git_remote_owner(remote);

	if ((!git_reference__is_branch(ref_name)) ||
	    !git_remote_name(remote) ||
1430 1431 1432 1433 1434
	    (error = git_branch__upstream_remote(&upstream_remote, repo, ref_name) < 0) ||
	    git__strcmp(git_remote_name(remote), git_str_cstr(&upstream_remote)) ||
	    (error = git_branch__upstream_name(&upstream_name, repo, ref_name)) < 0 ||
	    !git_refspec_dst_matches(spec, git_str_cstr(&upstream_name)) ||
	    (error = git_refspec__rtransform(remote_name, spec, upstream_name.ptr)) < 0) {
1435 1436
		/* Not an error if there is no upstream */
		if (error == GIT_ENOTFOUND) {
1437
			git_error_clear();
1438 1439 1440 1441 1442 1443 1444 1445
			error = 0;
		}

		*update = 0;
	} else {
		*update = 1;
	}

1446 1447
	git_str_dispose(&upstream_remote);
	git_str_dispose(&upstream_name);
1448 1449 1450
	return error;
}

1451
static int remote_head_for_ref(git_remote_head **out, git_remote *remote, git_refspec *spec, git_vector *update_heads, git_reference *ref)
1452 1453
{
	git_reference *resolved_ref = NULL;
1454
	git_str remote_name = GIT_STR_INIT;
1455
	git_config *config = NULL;
1456
	const char *ref_name;
1457
	int error = 0, update;
1458

1459 1460 1461
	GIT_ASSERT_ARG(out);
	GIT_ASSERT_ARG(spec);
	GIT_ASSERT_ARG(ref);
1462 1463 1464

	*out = NULL;

1465 1466 1467
	error = git_reference_resolve(&resolved_ref, ref);

	/* If we're in an unborn branch, let's pretend nothing happened */
1468
	if (error == GIT_ENOTFOUND && git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) {
1469 1470 1471 1472 1473 1474
		ref_name = git_reference_symbolic_target(ref);
		error = 0;
	} else {
		ref_name = git_reference_name(resolved_ref);
	}

1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
	/*
	 * The ref name may be unresolvable - perhaps it's pointing to
	 * something invalid.  In this case, there is no remote head for
	 * this ref.
	 */
	if (!ref_name) {
		error = 0;
		goto cleanup;
	}

1485
	if ((error = ref_to_update(&update, &remote_name, remote, spec, ref_name)) < 0)
1486 1487
		goto cleanup;

1488
	if (update)
1489
		error = remote_head_for_fetchspec_src(out, update_heads, git_str_cstr(&remote_name));
1490 1491

cleanup:
1492
	git_str_dispose(&remote_name);
1493
	git_reference_free(resolved_ref);
1494
	git_config_free(config);
1495 1496 1497
	return error;
}

1498
static int git_remote_write_fetchhead(git_remote *remote, git_refspec *spec, git_vector *update_heads)
1499 1500 1501 1502 1503 1504 1505 1506 1507
{
	git_reference *head_ref = NULL;
	git_fetchhead_ref *fetchhead_ref;
	git_remote_head *remote_ref, *merge_remote_ref;
	git_vector fetchhead_refs;
	bool include_all_fetchheads;
	unsigned int i = 0;
	int error = 0;

1508
	GIT_ASSERT_ARG(remote);
1509

1510 1511 1512 1513
	/* no heads, nothing to do */
	if (update_heads->length == 0)
		return 0;

1514 1515 1516 1517 1518 1519 1520 1521 1522
	if (git_vector_init(&fetchhead_refs, update_heads->length, git_fetchhead_ref_cmp) < 0)
		return -1;

	/* Iff refspec is * (but not subdir slash star), include tags */
	include_all_fetchheads = (strcmp(GIT_REFS_HEADS_DIR "*", git_refspec_src(spec)) == 0);

	/* Determine what to merge: if refspec was a wildcard, just use HEAD */
	if (git_refspec_is_wildcard(spec)) {
		if ((error = git_reference_lookup(&head_ref, remote->repo, GIT_HEAD_FILE)) < 0 ||
1523
			(error = remote_head_for_ref(&merge_remote_ref, remote, spec, update_heads, head_ref)) < 0)
1524 1525 1526 1527 1528 1529 1530 1531
				goto cleanup;
	} else {
		/* If we're fetching a single refspec, that's the only thing that should be in FETCH_HEAD. */
		if ((error = remote_head_for_fetchspec_src(&merge_remote_ref, update_heads, git_refspec_src(spec))) < 0)
			goto cleanup;
	}

	/* Create the FETCH_HEAD file */
nulltoken committed
1532
	git_vector_foreach(update_heads, i, remote_ref) {
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
		int merge_this_fetchhead = (merge_remote_ref == remote_ref);

		if (!include_all_fetchheads &&
			!git_refspec_src_matches(spec, remote_ref->name) &&
			!merge_this_fetchhead)
			continue;

		if (git_fetchhead_ref_create(&fetchhead_ref,
			&remote_ref->oid,
			merge_this_fetchhead,
			remote_ref->name,
			git_remote_url(remote)) < 0)
			goto cleanup;

		if (git_vector_insert(&fetchhead_refs, fetchhead_ref) < 0)
			goto cleanup;
	}

	git_fetchhead_write(remote->repo, &fetchhead_refs);

cleanup:
	for (i = 0; i < fetchhead_refs.length; ++i)
		git_fetchhead_ref_free(fetchhead_refs.contents[i]);

	git_vector_free(&fetchhead_refs);
	git_reference_free(head_ref);

	return error;
}

1563 1564 1565 1566 1567
/**
 * Generate a list of candidates for pruning by getting a list of
 * references which match the rhs of an active refspec.
 */
static int prune_candidates(git_vector *candidates, git_remote *remote)
1568 1569
{
	git_strarray arr = { 0 };
1570
	size_t i;
1571 1572 1573 1574 1575
	int error;

	if ((error = git_reference_list(&arr, remote->repo)) < 0)
		return error;

1576 1577 1578 1579 1580 1581 1582 1583
	for (i = 0; i < arr.count; i++) {
		const char *refname = arr.strings[i];
		char *refname_dup;

		if (!git_remote__matching_dst_refspec(remote, refname))
			continue;

		refname_dup = git__strdup(refname);
1584
		GIT_ERROR_CHECK_ALLOC(refname_dup);
1585 1586 1587 1588 1589 1590

		if ((error = git_vector_insert(candidates, refname_dup)) < 0)
			goto out;
	}

out:
1591
	git_strarray_dispose(&arr);
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
	return error;
}

static int find_head(const void *_a, const void *_b)
{
	git_remote_head *a = (git_remote_head *) _a;
	git_remote_head *b = (git_remote_head *) _b;

	return strcmp(a->name, b->name);
}

1603
int git_remote_prune(git_remote *remote, const git_remote_callbacks *callbacks)
1604 1605 1606 1607 1608 1609 1610 1611 1612
{
	size_t i, j;
	git_vector remote_refs = GIT_VECTOR_INIT;
	git_vector candidates = GIT_VECTOR_INIT;
	const git_refspec *spec;
	const char *refname;
	int error;
	git_oid zero_id = {{ 0 }};

1613
	if (callbacks)
1614
		GIT_ERROR_CHECK_VERSION(callbacks, GIT_REMOTE_CALLBACKS_VERSION, "git_remote_callbacks");
1615

1616 1617 1618
	if ((error = ls_to_vector(&remote_refs, remote)) < 0)
		goto cleanup;

1619
	git_vector_set_cmp(&remote_refs, find_head);
1620

1621 1622
	if ((error = prune_candidates(&candidates, remote)) < 0)
		goto cleanup;
1623

1624 1625 1626 1627 1628 1629
	/*
	 * Remove those entries from the candidate list for which we
	 * can find a remote reference in at least one refspec.
	 */
	git_vector_foreach(&candidates, i, refname) {
		git_vector_foreach(&remote->active_refspecs, j, spec) {
1630
			git_str buf = GIT_STR_INIT;
1631 1632 1633 1634 1635
			size_t pos;
			char *src_name;
			git_remote_head key = {0};

			if (!git_refspec_dst_matches(spec, refname))
1636 1637
				continue;

1638
			if ((error = git_refspec__rtransform(&buf, spec, refname)) < 0)
1639
				goto cleanup;
1640

1641
			key.name = (char *) git_str_cstr(&buf);
1642
			error = git_vector_bsearch(&pos, &remote_refs, &key);
1643
			git_str_dispose(&buf);
1644

1645 1646
			if (error < 0 && error != GIT_ENOTFOUND)
				goto cleanup;
1647

1648
			if (error == GIT_ENOTFOUND)
1649 1650
				continue;

Aaron Franke committed
1651
			/* If we did find a source, remove it from the candidates. */
1652 1653 1654 1655 1656
			if ((error = git_vector_set((void **) &src_name, &candidates, i, NULL)) < 0)
				goto cleanup;

			git__free(src_name);
			break;
1657 1658 1659
		}
	}

1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
	/*
	 * For those candidates still left in the list, we need to
	 * remove them. We do not remove symrefs, as those are for
	 * stuff like origin/HEAD which will never match, but we do
	 * not want to remove them.
	 */
	git_vector_foreach(&candidates, i, refname) {
		git_reference *ref;
		git_oid id;

		if (refname == NULL)
			continue;

		error = git_reference_lookup(&ref, remote->repo, refname);
		/* as we want it gone, let's not consider this an error */
		if (error == GIT_ENOTFOUND)
			continue;

		if (error < 0)
			goto cleanup;

1681
		if (git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) {
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
			git_reference_free(ref);
			continue;
		}

		git_oid_cpy(&id, git_reference_target(ref));
		error = git_reference_delete(ref);
		git_reference_free(ref);
		if (error < 0)
			goto cleanup;

1692 1693
		if (callbacks && callbacks->update_tips)
			error = callbacks->update_tips(refname, &id, &zero_id, callbacks->payload);
1694 1695 1696 1697 1698

		if (error < 0)
			goto cleanup;
	}

1699 1700
cleanup:
	git_vector_free(&remote_refs);
1701
	git_vector_free_deep(&candidates);
1702 1703 1704
	return error;
}

1705 1706
static int update_tips_for_spec(
		git_remote *remote,
1707
		const git_remote_callbacks *callbacks,
1708
		int update_fetchhead,
1709
		git_remote_autotag_option_t tagopt,
1710 1711 1712
		git_refspec *spec,
		git_vector *refs,
		const char *log_message)
1713
{
1714
	int error = 0, autotag, valid;
1715
	unsigned int i = 0;
1716
	git_str refname = GIT_STR_INIT;
1717
	git_oid old;
1718
	git_odb *odb;
1719 1720
	git_remote_head *head;
	git_reference *ref;
1721
	git_refspec tagspec;
1722
	git_vector update_heads;
1723

1724
	GIT_ASSERT_ARG(remote);
1725

1726
	if (git_repository_odb__weakptr(&odb, remote->repo) < 0)
1727 1728
		return -1;

1729
	if (git_refspec__parse(&tagspec, GIT_REFSPEC_TAGS, true) < 0)
1730 1731
		return -1;

1732
	/* Make a copy of the transport's refs */
1733
	if (git_vector_init(&update_heads, 16, NULL) < 0)
1734
		return -1;
1735

1736 1737
	for (; i < refs->length; ++i) {
		head = git_vector_get(refs, i);
1738
		autotag = 0;
1739
		git_str_clear(&refname);
1740

1741
		/* Ignore malformed ref names (which also saves us from tag^{} */
1742 1743 1744 1745
		if (git_reference_name_is_valid(&valid, head->name) < 0)
			goto on_error;

		if (!valid)
1746 1747
			continue;

1748
		/* If we have a tag, see if the auto-follow rules say to update it */
1749
		if (git_refspec_src_matches(&tagspec, head->name)) {
1750
			if (tagopt != GIT_REMOTE_DOWNLOAD_TAGS_NONE) {
1751

1752
				if (tagopt == GIT_REMOTE_DOWNLOAD_TAGS_AUTO)
1753
					autotag = 1;
1754

1755 1756
				git_str_clear(&refname);
				if (git_str_puts(&refname, head->name) < 0)
1757 1758
					goto on_error;
			}
1759 1760 1761 1762
		}

		/* If we didn't want to auto-follow the tag, check if the refspec matches */
		if (!autotag && git_refspec_src_matches(spec, head->name)) {
1763
			if (spec->dst) {
1764
				if (git_refspec__transform(&refname, spec, head->name) < 0)
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
					goto on_error;
			} else {
				/*
				 * no rhs mans store it in FETCH_HEAD, even if we don't
				 update anything else.
				 */
				if ((error = git_vector_insert(&update_heads, head)) < 0)
					goto on_error;

				continue;
			}
1776 1777 1778
		}

		/* If we still don't have a refname, we don't want it */
1779
		if (git_str_len(&refname) == 0) {
1780 1781 1782
			continue;
		}

1783
		/* In autotag mode, only create tags for objects already in db */
1784 1785
		if (autotag && !git_odb_exists(odb, &head->oid))
			continue;
1786

1787
		if (!autotag && git_vector_insert(&update_heads, head) < 0)
1788 1789
			goto on_error;

1790
		error = git_reference_name_to_id(&old, remote->repo, refname.ptr);
1791
		if (error < 0 && error != GIT_ENOTFOUND)
1792 1793
			goto on_error;

1794 1795 1796
		if (!(error || error == GIT_ENOTFOUND)
				&& !spec->force
				&& !git_graph_descendant_of(remote->repo, &head->oid, &old))
1797 1798
			continue;

1799
		if (error == GIT_ENOTFOUND) {
1800 1801
			memset(&old, 0, GIT_OID_RAWSZ);

1802 1803 1804 1805
			if (autotag && git_vector_insert(&update_heads, head) < 0)
				goto on_error;
		}

1806
		if (!git_oid__cmp(&old, &head->oid))
1807
			continue;
1808

1809
		/* In autotag mode, don't overwrite any locally-existing tags */
1810
		error = git_reference_create(&ref, remote->repo, refname.ptr, &head->oid, !autotag,
1811
				log_message);
1812 1813 1814 1815 1816

		if (error == GIT_EEXISTS)
			continue;

		if (error < 0)
1817
			goto on_error;
1818 1819

		git_reference_free(ref);
1820

1821 1822
		if (callbacks && callbacks->update_tips != NULL) {
			if (callbacks->update_tips(refname.ptr, &old, &head->oid, callbacks->payload) < 0)
1823 1824
				goto on_error;
		}
1825 1826
	}

1827
	if (update_fetchhead &&
1828
	    (error = git_remote_write_fetchhead(remote, spec, &update_heads)) < 0)
1829 1830 1831
		goto on_error;

	git_vector_free(&update_heads);
1832
	git_refspec__dispose(&tagspec);
1833
	git_str_dispose(&refname);
1834 1835 1836
	return 0;

on_error:
1837
	git_vector_free(&update_heads);
1838
	git_refspec__dispose(&tagspec);
1839
	git_str_dispose(&refname);
1840
	return -1;
1841

1842 1843
}

1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
/**
 * Iteration over the three vectors, with a pause whenever we find a match
 *
 * On each stop, we store the iteration stat in the inout i,j,k
 * parameters, and return the currently matching passive refspec as
 * well as the head which we matched.
 */
static int next_head(const git_remote *remote, git_vector *refs,
		     git_refspec **out_spec, git_remote_head **out_head,
		     size_t *out_i, size_t *out_j, size_t *out_k)
{
	const git_vector *active, *passive;
	git_remote_head *head;
	git_refspec *spec, *passive_spec;
	size_t i, j, k;
1859
	int valid;
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870

	active = &remote->active_refspecs;
	passive = &remote->passive_refspecs;

	i = *out_i;
	j = *out_j;
	k = *out_k;

	for (; i < refs->length; i++) {
		head = git_vector_get(refs, i);

1871 1872 1873 1874
		if (git_reference_name_is_valid(&valid, head->name) < 0)
			return -1;

		if (!valid)
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
			continue;

		for (; j < active->length; j++) {
			spec = git_vector_get(active, j);

			if (!git_refspec_src_matches(spec, head->name))
				continue;

			for (; k < passive->length; k++) {
				passive_spec = git_vector_get(passive, k);

				if (!git_refspec_src_matches(passive_spec, head->name))
				    continue;

				*out_spec = passive_spec;
				*out_head = head;
				*out_i = i;
				*out_j = j;
				*out_k = k + 1;
				return 0;

			}
			k = 0;
		}
		j = 0;
	}

	return GIT_ITEROVER;
}

1905 1906
static int opportunistic_updates(const git_remote *remote, const git_remote_callbacks *callbacks,
				 git_vector *refs, const char *msg)
1907 1908 1909 1910 1911
{
	size_t i, j, k;
	git_refspec *spec;
	git_remote_head *head;
	git_reference *ref;
1912
	git_str refname = GIT_STR_INIT;
1913
	int error = 0;
1914 1915 1916 1917

	i = j = k = 0;

	while ((error = next_head(remote, refs, &spec, &head, &i, &j, &k)) == 0) {
1918
		git_oid old = {{ 0 }};
1919 1920 1921 1922 1923 1924 1925 1926
		/*
		 * If we got here, there is a refspec which was used
		 * for fetching which matches the source of one of the
		 * passive refspecs, so we should update that
		 * remote-tracking branch, but not add it to
		 * FETCH_HEAD
		 */

1927 1928
		git_str_clear(&refname);
		if ((error = git_refspec__transform(&refname, spec, head->name)) < 0)
1929
			goto cleanup;
1930

1931 1932 1933 1934 1935 1936
		error = git_reference_name_to_id(&old, remote->repo, refname.ptr);
		if (error < 0 && error != GIT_ENOTFOUND)
			goto cleanup;

		if (!git_oid_cmp(&old, &head->oid))
			continue;
1937

1938 1939 1940 1941 1942 1943
		/* If we did find a current reference, make sure we haven't lost a race */
		if (error)
			error = git_reference_create(&ref, remote->repo, refname.ptr, &head->oid, true, msg);
		else
			error = git_reference_create_matching(&ref, remote->repo, refname.ptr, &head->oid, true, &old, msg);
		git_reference_free(ref);
1944
		if (error < 0)
1945 1946 1947 1948 1949 1950
			goto cleanup;

		if (callbacks && callbacks->update_tips != NULL) {
			if (callbacks->update_tips(refname.ptr, &old, &head->oid, callbacks->payload) < 0)
				goto cleanup;
		}
1951 1952
	}

1953 1954 1955 1956
	if (error == GIT_ITEROVER)
		error = 0;

cleanup:
1957
	git_str_dispose(&refname);
1958
	return error;
1959 1960
}

1961 1962
static int truncate_fetch_head(const char *gitdir)
{
1963
	git_str path = GIT_STR_INIT;
1964 1965
	int error;

1966
	if ((error = git_str_joinpath(&path, gitdir, GIT_FETCH_HEAD_FILE)) < 0)
1967 1968 1969
		return error;

	error = git_futils_truncate(path.ptr, GIT_REFS_FILE_MODE);
1970
	git_str_dispose(&path);
1971 1972 1973 1974

	return error;
}

1975 1976
int git_remote_update_tips(
		git_remote *remote,
1977
		const git_remote_callbacks *callbacks,
1978
		int update_fetchhead,
1979
		git_remote_autotag_option_t download_tags,
1980
		const char *reflog_message)
1981
{
1982
	git_refspec *spec, tagspec;
1983
	git_vector refs = GIT_VECTOR_INIT;
1984
	git_remote_autotag_option_t tagopt;
1985
	int error;
1986 1987
	size_t i;

1988 1989
	/* push has its own logic hidden away in the push object */
	if (remote->push) {
1990
		return git_push_update_tips(remote->push, callbacks);
1991 1992
	}

1993 1994 1995
	if (git_refspec__parse(&tagspec, GIT_REFSPEC_TAGS, true) < 0)
		return -1;

1996 1997

	if ((error = ls_to_vector(&refs, remote)) < 0)
1998 1999
		goto out;

2000
	if (download_tags == GIT_REMOTE_DOWNLOAD_TAGS_UNSPECIFIED)
2001 2002 2003 2004
		tagopt = remote->download_tags;
	else
		tagopt = download_tags;

2005 2006 2007
	if ((error = truncate_fetch_head(git_repository_path(remote->repo))) < 0)
		goto out;

2008 2009
	if (tagopt == GIT_REMOTE_DOWNLOAD_TAGS_ALL) {
		if ((error = update_tips_for_spec(remote, callbacks, update_fetchhead, tagopt, &tagspec, &refs, reflog_message)) < 0)
2010
			goto out;
2011
	}
2012

2013
	git_vector_foreach(&remote->active_refspecs, i, spec) {
2014 2015 2016
		if (spec->push)
			continue;

2017
		if ((error = update_tips_for_spec(remote, callbacks, update_fetchhead, tagopt, spec, &refs, reflog_message)) < 0)
2018
			goto out;
2019 2020
	}

Aaron Franke committed
2021
	/* Only try to do opportunistic updates if the refpec lists differ. */
2022
	if (remote->passed_refspecs)
2023
		error = opportunistic_updates(remote, callbacks, &refs, reflog_message);
2024

2025
out:
2026
	git_vector_free(&refs);
2027
	git_refspec__dispose(&tagspec);
2028
	return error;
2029 2030
}

2031
int git_remote_connected(const git_remote *remote)
2032
{
2033
	GIT_ASSERT_ARG(remote);
2034 2035 2036 2037 2038

	if (!remote->transport || !remote->transport->is_connected)
		return 0;

	/* Ask the transport if it's connected. */
2039
	return remote->transport->is_connected(remote->transport);
2040 2041
}

2042
int git_remote_stop(git_remote *remote)
2043
{
2044
	GIT_ASSERT_ARG(remote);
2045 2046

	if (remote->transport && remote->transport->cancel)
2047
		remote->transport->cancel(remote->transport);
2048 2049

	return 0;
2050 2051
}

2052
int git_remote_disconnect(git_remote *remote)
2053
{
2054
	GIT_ASSERT_ARG(remote);
2055

2056 2057
	if (git_remote_connected(remote))
		remote->transport->close(remote->transport);
2058 2059

	return 0;
2060 2061
}

Carlos Martín Nieto committed
2062 2063
void git_remote_free(git_remote *remote)
{
2064 2065 2066
	if (remote == NULL)
		return;

2067 2068 2069 2070 2071 2072 2073 2074 2075
	if (remote->transport != NULL) {
		git_remote_disconnect(remote);

		remote->transport->free(remote->transport);
		remote->transport = NULL;
	}

	git_vector_free(&remote->refs);

2076
	free_refspecs(&remote->refspecs);
2077 2078
	git_vector_free(&remote->refspecs);

2079 2080 2081
	free_refspecs(&remote->active_refspecs);
	git_vector_free(&remote->active_refspecs);

2082 2083 2084
	free_refspecs(&remote->passive_refspecs);
	git_vector_free(&remote->passive_refspecs);

2085
	git_push_free(remote->push);
2086
	git__free(remote->url);
2087
	git__free(remote->pushurl);
2088 2089
	git__free(remote->name);
	git__free(remote);
Carlos Martín Nieto committed
2090
}
2091

2092
static int remote_list_cb(const git_config_entry *entry, void *payload)
2093
{
2094
	git_vector *list = payload;
2095 2096 2097
	const char *name = entry->name + strlen("remote.");
	size_t namelen = strlen(name);
	char *remote_name;
2098

2099
	/* we know name matches "remote.<stuff>.(push)?url" */
2100

2101 2102 2103 2104
	if (!strcmp(&name[namelen - 4], ".url"))
		remote_name = git__strndup(name, namelen - 4); /* strip ".url" */
	else
		remote_name = git__strndup(name, namelen - 8); /* strip ".pushurl" */
2105
	GIT_ERROR_CHECK_ALLOC(remote_name);
2106

2107
	return git_vector_insert(list, remote_name);
2108 2109 2110 2111 2112
}

int git_remote_list(git_strarray *remotes_list, git_repository *repo)
{
	int error;
2113
	git_config *cfg;
2114
	git_vector list = GIT_VECTOR_INIT;
2115

2116 2117
	if ((error = git_repository_config__weakptr(&cfg, repo)) < 0)
		return error;
2118

2119
	if ((error = git_vector_init(&list, 4, git__strcmp_cb)) < 0)
2120
		return error;
2121

2122
	error = git_config_foreach_match(
2123
		cfg, "^remote\\..*\\.(push)?url$", remote_list_cb, &list);
2124

2125
	if (error < 0) {
2126
		git_vector_free_deep(&list);
2127 2128 2129
		return error;
	}

2130
	git_vector_uniq(&list, git__free);
2131

2132 2133
	remotes_list->strings =
		(char **)git_vector_detach(&remotes_list->count, NULL, &list);
2134

2135
	return 0;
2136
}
2137

2138
const git_indexer_progress *git_remote_stats(git_remote *remote)
2139
{
2140
	GIT_ASSERT_ARG_WITH_RETVAL(remote, NULL);
2141 2142 2143
	return &remote->stats;
}

2144
git_remote_autotag_option_t git_remote_autotag(const git_remote *remote)
2145 2146 2147 2148
{
	return remote->download_tags;
}

2149
int git_remote_set_autotag(git_repository *repo, const char *remote, git_remote_autotag_option_t value)
2150
{
2151
	git_str var = GIT_STR_INIT;
2152 2153 2154
	git_config *config;
	int error;

2155
	GIT_ASSERT_ARG(repo && remote);
2156 2157 2158 2159 2160 2161 2162

	if ((error = ensure_remote_name_is_valid(remote)) < 0)
		return error;

	if ((error = git_repository_config__weakptr(&config, repo)) < 0)
		return error;

2163
	if ((error = git_str_printf(&var, CONFIG_TAGOPT_FMT, remote)))
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
		return error;

	switch (value) {
	case GIT_REMOTE_DOWNLOAD_TAGS_NONE:
		error = git_config_set_string(config, var.ptr, "--no-tags");
		break;
	case GIT_REMOTE_DOWNLOAD_TAGS_ALL:
		error = git_config_set_string(config, var.ptr, "--tags");
		break;
	case GIT_REMOTE_DOWNLOAD_TAGS_AUTO:
		error = git_config_delete_entry(config, var.ptr);
		if (error == GIT_ENOTFOUND)
			error = 0;
		break;
	default:
2179
		git_error_set(GIT_ERROR_INVALID, "invalid value for the tagopt setting");
2180 2181 2182
		error = -1;
	}

2183
	git_str_dispose(&var);
2184
	return error;
2185
}
2186

2187 2188 2189 2190 2191
int git_remote_prune_refs(const git_remote *remote)
{
	return remote->prune_refs;
}

2192 2193 2194 2195 2196
static int rename_remote_config_section(
	git_repository *repo,
	const char *old_name,
	const char *new_name)
{
2197 2198
	git_str old_section_name = GIT_STR_INIT,
		new_section_name = GIT_STR_INIT;
2199 2200
	int error = -1;

2201
	if (git_str_printf(&old_section_name, "remote.%s", old_name) < 0)
2202 2203
		goto cleanup;

2204
	if (new_name &&
2205
		(git_str_printf(&new_section_name, "remote.%s", new_name) < 0))
2206
			goto cleanup;
2207 2208 2209

	error = git_config_rename_section(
		repo,
2210 2211
		git_str_cstr(&old_section_name),
		new_name ? git_str_cstr(&new_section_name) : NULL);
2212 2213

cleanup:
2214 2215
	git_str_dispose(&old_section_name);
	git_str_dispose(&new_section_name);
2216 2217 2218 2219

	return error;
}

2220
struct update_data {
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
	git_config *config;
	const char *old_remote_name;
	const char *new_remote_name;
};

static int update_config_entries_cb(
	const git_config_entry *entry,
	void *payload)
{
	struct update_data *data = (struct update_data *)payload;

	if (strcmp(entry->value, data->old_remote_name))
		return 0;

2235 2236
	return git_config_set_string(
		data->config, entry->name, data->new_remote_name);
2237 2238 2239 2240 2241 2242 2243
}

static int update_branch_remote_config_entry(
	git_repository *repo,
	const char *old_name,
	const char *new_name)
{
2244 2245
	int error;
	struct update_data data = { NULL };
2246

2247 2248
	if ((error = git_repository_config__weakptr(&data.config, repo)) < 0)
		return error;
2249 2250 2251 2252

	data.old_remote_name = old_name;
	data.new_remote_name = new_name;

2253
	return git_config_foreach_match(
2254
		data.config, "branch\\..+\\.remote", update_config_entries_cb, &data);
2255 2256 2257
}

static int rename_one_remote_reference(
2258
	git_reference *reference_in,
2259 2260 2261
	const char *old_remote_name,
	const char *new_remote_name)
{
2262
	int error;
2263
	git_reference *ref = NULL, *dummy = NULL;
2264 2265 2266
	git_str namespace = GIT_STR_INIT, old_namespace = GIT_STR_INIT;
	git_str new_name = GIT_STR_INIT;
	git_str log_message = GIT_STR_INIT;
2267 2268
	size_t pfx_len;
	const char *target;
2269

2270
	if ((error = git_str_printf(&namespace, GIT_REFS_REMOTES_DIR "%s/", new_remote_name)) < 0)
2271 2272 2273
		return error;

	pfx_len = strlen(GIT_REFS_REMOTES_DIR) + strlen(old_remote_name) + 1;
2274 2275
	git_str_puts(&new_name, namespace.ptr);
	if ((error = git_str_puts(&new_name, git_reference_name(reference_in) + pfx_len)) < 0)
2276
		goto cleanup;
2277

2278
	if ((error = git_str_printf(&log_message,
2279 2280 2281
					"renamed remote %s to %s",
					old_remote_name, new_remote_name)) < 0)
		goto cleanup;
2282

2283 2284
	if ((error = git_reference_rename(&ref, reference_in, git_str_cstr(&new_name), 1,
					  git_str_cstr(&log_message))) < 0)
2285 2286
		goto cleanup;

2287
	if (git_reference_type(ref) != GIT_REFERENCE_SYMBOLIC)
2288 2289 2290 2291
		goto cleanup;

	/* Handle refs like origin/HEAD -> origin/master */
	target = git_reference_symbolic_target(ref);
2292
	if ((error = git_str_printf(&old_namespace, GIT_REFS_REMOTES_DIR "%s/", old_remote_name)) < 0)
2293 2294 2295 2296 2297
		goto cleanup;

	if (git__prefixcmp(target, old_namespace.ptr))
		goto cleanup;

2298 2299 2300
	git_str_clear(&new_name);
	git_str_puts(&new_name, namespace.ptr);
	if ((error = git_str_puts(&new_name, target + pfx_len)) < 0)
2301 2302
		goto cleanup;

2303 2304
	error = git_reference_symbolic_set_target(&dummy, ref, git_str_cstr(&new_name),
						  git_str_cstr(&log_message));
2305 2306

	git_reference_free(dummy);
2307 2308

cleanup:
2309 2310
	git_reference_free(reference_in);
	git_reference_free(ref);
2311 2312 2313 2314
	git_str_dispose(&namespace);
	git_str_dispose(&old_namespace);
	git_str_dispose(&new_name);
	git_str_dispose(&log_message);
2315 2316 2317 2318 2319 2320 2321 2322
	return error;
}

static int rename_remote_references(
	git_repository *repo,
	const char *old_name,
	const char *new_name)
{
2323
	int error;
2324
	git_str buf = GIT_STR_INIT;
Vicent Marti committed
2325
	git_reference *ref;
2326
	git_reference_iterator *iter;
2327

2328
	if ((error = git_str_printf(&buf, GIT_REFS_REMOTES_DIR "%s/*", old_name)) < 0)
2329
		return error;
2330

2331 2332
	error = git_reference_iterator_glob_new(&iter, repo, git_str_cstr(&buf));
	git_str_dispose(&buf);
2333

2334 2335 2336 2337
	if (error < 0)
		return error;

	while ((error = git_reference_next(&ref, iter)) == 0) {
2338 2339
		if ((error = rename_one_remote_reference(ref, old_name, new_name)) < 0)
			break;
2340 2341 2342
	}

	git_reference_iterator_free(iter);
2343

2344
	return (error == GIT_ITEROVER) ? 0 : error;
2345 2346
}

2347
static int rename_fetch_refspecs(git_vector *problems, git_remote *remote, const char *new_name)
2348 2349
{
	git_config *config;
2350
	git_str base = GIT_STR_INIT, var = GIT_STR_INIT, val = GIT_STR_INIT;
2351
	const git_refspec *spec;
2352
	size_t i;
2353
	int error = 0;
2354

2355
	if ((error = git_repository_config__weakptr(&config, remote->repo)) < 0)
2356 2357
		return error;

2358 2359 2360
	if ((error = git_vector_init(problems, 1, NULL)) < 0)
		return error;

2361
	if ((error = default_fetchspec_for_name(&base, remote->name)) < 0)
2362
		return error;
2363

2364
	git_vector_foreach(&remote->refspecs, i, spec) {
2365 2366
		if (spec->push)
			continue;
2367

2368
		/* Does the dst part of the refspec follow the expected format? */
2369
		if (strcmp(git_str_cstr(&base), spec->string)) {
2370
			char *dup;
2371

2372
			dup = git__strdup(spec->string);
2373
			GIT_ERROR_CHECK_ALLOC(dup);
2374 2375

			if ((error = git_vector_insert(problems, dup)) < 0)
2376
				break;
2377

2378 2379
			continue;
		}
2380

2381
		/* If we do want to move it to the new section */
2382

2383 2384
		git_str_clear(&val);
		git_str_clear(&var);
2385

2386
		if (default_fetchspec_for_name(&val, new_name) < 0 ||
2387
			git_str_printf(&var, "remote.%s.fetch", new_name) < 0)
2388 2389
		{
			error = -1;
2390
			break;
2391
		}
2392

2393
		if ((error = git_config_set_string(
2394
				config, git_str_cstr(&var), git_str_cstr(&val))) < 0)
2395
			break;
2396
	}
2397

2398 2399 2400
	git_str_dispose(&base);
	git_str_dispose(&var);
	git_str_dispose(&val);
2401 2402 2403 2404 2405 2406 2407 2408 2409

	if (error < 0) {
		char *str;
		git_vector_foreach(problems, i, str)
			git__free(str);

		git_vector_free(problems);
	}

2410 2411 2412
	return error;
}

2413
int git_remote_rename(git_strarray *out, git_repository *repo, const char *name, const char *new_name)
2414 2415
{
	int error;
2416
	git_vector problem_refspecs = GIT_VECTOR_INIT;
2417
	git_remote *remote = NULL;
2418

2419
	GIT_ASSERT_ARG(out && repo && name && new_name);
2420

2421
	if ((error = git_remote_lookup(&remote, repo, name)) < 0)
2422
		return error;
2423

2424
	if ((error = ensure_remote_name_is_valid(new_name)) < 0)
2425
		goto cleanup;
2426

2427 2428
	if ((error = ensure_remote_doesnot_exist(repo, new_name)) < 0)
		goto cleanup;
2429

2430 2431
	if ((error = rename_remote_config_section(repo, name, new_name)) < 0)
		goto cleanup;
2432

2433 2434
	if ((error = update_branch_remote_config_entry(repo, name, new_name)) < 0)
		goto cleanup;
2435

2436 2437
	if ((error = rename_remote_references(repo, name, new_name)) < 0)
		goto cleanup;
2438

2439
	if ((error = rename_fetch_refspecs(&problem_refspecs, remote, new_name)) < 0)
2440
		goto cleanup;
2441

2442 2443 2444
	out->count = problem_refspecs.length;
	out->strings = (char **) problem_refspecs.contents;

2445 2446 2447
cleanup:
	if (error < 0)
		git_vector_free(&problem_refspecs);
2448

2449 2450
	git_remote_free(remote);
	return error;
2451
}
2452

2453
int git_remote_name_is_valid(int *valid, const char *remote_name)
2454
{
2455
	git_str buf = GIT_STR_INIT;
2456 2457 2458 2459 2460 2461
	git_refspec refspec = {0};
	int error;

	GIT_ASSERT(valid);

	*valid = 0;
2462 2463 2464 2465

	if (!remote_name || *remote_name == '\0')
		return 0;

2466
	if ((error = git_str_printf(&buf, "refs/heads/test:refs/remotes/%s/test", remote_name)) < 0)
2467 2468
		goto done;

2469
	error = git_refspec__parse(&refspec, git_str_cstr(&buf), true);
2470

2471 2472 2473 2474 2475 2476
	if (!error)
		*valid = 1;
	else if (error == GIT_EINVALIDSPEC)
		error = 0;

done:
2477
	git_str_dispose(&buf);
2478
	git_refspec__dispose(&refspec);
2479

2480 2481 2482
	return error;
}

2483 2484 2485 2486 2487
git_refspec *git_remote__matching_refspec(git_remote *remote, const char *refname)
{
	git_refspec *spec;
	size_t i;

2488
	git_vector_foreach(&remote->active_refspecs, i, spec) {
2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
		if (spec->push)
			continue;

		if (git_refspec_src_matches(spec, refname))
			return spec;
	}

	return NULL;
}

git_refspec *git_remote__matching_dst_refspec(git_remote *remote, const char *refname)
{
	git_refspec *spec;
	size_t i;

2504
	git_vector_foreach(&remote->active_refspecs, i, spec) {
2505 2506 2507 2508 2509 2510 2511 2512 2513 2514
		if (spec->push)
			continue;

		if (git_refspec_dst_matches(spec, refname))
			return spec;
	}

	return NULL;
}

2515
int git_remote_add_fetch(git_repository *repo, const char *remote, const char *refspec)
2516
{
2517
	return write_add_refspec(repo, remote, refspec, true);
2518 2519
}

2520
int git_remote_add_push(git_repository *repo, const char *remote, const char *refspec)
2521
{
2522
	return write_add_refspec(repo, remote, refspec, false);
2523 2524
}

2525
static int copy_refspecs(git_strarray *array, const git_remote *remote, unsigned int push)
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
{
	size_t i;
	git_vector refspecs;
	git_refspec *spec;
	char *dup;

	if (git_vector_init(&refspecs, remote->refspecs.length, NULL) < 0)
		return -1;

	git_vector_foreach(&remote->refspecs, i, spec) {
		if (spec->push != push)
			continue;

2539
		if ((dup = git__strdup(spec->string)) == NULL)
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
			goto on_error;

		if (git_vector_insert(&refspecs, dup) < 0) {
			git__free(dup);
			goto on_error;
		}
	}

	array->strings = (char **)refspecs.contents;
	array->count = refspecs.length;

	return 0;

on_error:
2554
	git_vector_free_deep(&refspecs);
2555 2556 2557 2558

	return -1;
}

2559
int git_remote_get_fetch_refspecs(git_strarray *array, const git_remote *remote)
2560 2561 2562 2563
{
	return copy_refspecs(array, remote, false);
}

2564
int git_remote_get_push_refspecs(git_strarray *array, const git_remote *remote)
2565 2566 2567
{
	return copy_refspecs(array, remote, true);
}
2568

2569
size_t git_remote_refspec_count(const git_remote *remote)
2570 2571 2572 2573
{
	return remote->refspecs.length;
}

2574
const git_refspec *git_remote_get_refspec(const git_remote *remote, size_t n)
2575 2576 2577
{
	return git_vector_get(&remote->refspecs, n);
}
2578

2579
int git_remote_init_callbacks(git_remote_callbacks *opts, unsigned int version)
2580
{
2581 2582 2583
	GIT_INIT_STRUCTURE_FROM_TEMPLATE(
		opts, version, git_remote_callbacks, GIT_REMOTE_CALLBACKS_INIT);
	return 0;
2584
}
2585

2586 2587
/* asserts a branch.<foo>.remote format */
static const char *name_offset(size_t *len_out, const char *name)
2588
{
2589 2590
	size_t prefix_len;
	const char *dot;
2591

2592 2593
	prefix_len = strlen("remote.");
	dot = strchr(name + prefix_len, '.');
2594

2595
	GIT_ASSERT_ARG_WITH_RETVAL(dot, NULL);
2596

2597 2598
	*len_out = dot - name - prefix_len;
	return name + prefix_len;
2599 2600 2601 2602 2603 2604 2605 2606
}

static int remove_branch_config_related_entries(
	git_repository *repo,
	const char *remote_name)
{
	int error;
	git_config *config;
2607 2608
	git_config_entry *entry;
	git_config_iterator *iter;
2609
	git_str buf = GIT_STR_INIT;
2610 2611 2612 2613

	if ((error = git_repository_config__weakptr(&config, repo)) < 0)
		return error;

2614
	if ((error = git_config_iterator_glob_new(&iter, config, "branch\\..+\\.remote")) < 0)
2615 2616
		return error;

2617 2618 2619 2620
	/* find any branches with us as upstream and remove that config */
	while ((error = git_config_next(&entry, iter)) == 0) {
		const char *branch;
		size_t branch_len;
2621

2622 2623
		if (strcmp(remote_name, entry->value))
			continue;
2624

2625 2626 2627 2628
		if ((branch = name_offset(&branch_len, entry->name)) == NULL) {
			error = -1;
			break;
		}
2629

2630 2631
		git_str_clear(&buf);
		if ((error = git_str_printf(&buf, "branch.%.*s.merge", (int)branch_len, branch)) < 0)
2632 2633
			break;

2634
		if ((error = git_config_delete_entry(config, git_str_cstr(&buf))) < 0) {
2635 2636
			if (error != GIT_ENOTFOUND)
				break;
2637
			git_error_clear();
2638
		}
2639

2640 2641
		git_str_clear(&buf);
		if ((error = git_str_printf(&buf, "branch.%.*s.remote", (int)branch_len, branch)) < 0)
2642 2643
			break;

2644
		if ((error = git_config_delete_entry(config, git_str_cstr(&buf))) < 0) {
2645 2646
			if (error != GIT_ENOTFOUND)
				break;
2647
			git_error_clear();
2648
		}
2649 2650
	}

2651 2652 2653
	if (error == GIT_ITEROVER)
		error = 0;

2654
	git_str_dispose(&buf);
2655
	git_config_iterator_free(iter);
2656 2657 2658
	return error;
}

2659
static int remove_refs(git_repository *repo, const git_refspec *spec)
2660
{
2661 2662
	git_reference_iterator *iter = NULL;
	git_vector refs;
2663
	const char *name;
2664
	char *dup;
2665
	int error;
2666
	size_t i;
2667

2668
	if ((error = git_vector_init(&refs, 8, NULL)) < 0)
2669 2670
		return error;

2671 2672 2673
	if ((error = git_reference_iterator_new(&iter, repo)) < 0)
		goto cleanup;

2674
	while ((error = git_reference_next_name(&name, iter)) == 0) {
2675 2676 2677 2678 2679 2680 2681 2682
		if (!git_refspec_dst_matches(spec, name))
			continue;

		dup = git__strdup(name);
		if (!dup) {
			error = -1;
			goto cleanup;
		}
2683

2684 2685 2686
		if ((error = git_vector_insert(&refs, dup)) < 0)
			goto cleanup;
	}
2687 2688
	if (error == GIT_ITEROVER)
		error = 0;
2689 2690 2691 2692 2693 2694 2695
	if (error < 0)
		goto cleanup;

	git_vector_foreach(&refs, i, name) {
		if ((error = git_reference_remove(repo, name)) < 0)
			break;
	}
2696

2697 2698 2699 2700 2701 2702
cleanup:
	git_reference_iterator_free(iter);
	git_vector_foreach(&refs, i, dup) {
		git__free(dup);
	}
	git_vector_free(&refs);
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
	return error;
}

static int remove_remote_tracking(git_repository *repo, const char *remote_name)
{
	git_remote *remote;
	int error;
	size_t i, count;

	/* we want to use what's on the config, regardless of changes to the instance in memory */
2713
	if ((error = git_remote_lookup(&remote, repo, remote_name)) < 0)
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723
		return error;

	count = git_remote_refspec_count(remote);
	for (i = 0; i < count; i++) {
		const git_refspec *refspec = git_remote_get_refspec(remote, i);

		/* shouldn't ever actually happen */
		if (refspec == NULL)
			continue;

2724
		if ((error = remove_refs(repo, refspec)) < 0)
2725 2726 2727 2728 2729 2730 2731
			break;
	}

	git_remote_free(remote);
	return error;
}

2732
int git_remote_delete(git_repository *repo, const char *name)
2733 2734 2735
{
	int error;

2736 2737
	GIT_ASSERT_ARG(repo);
	GIT_ASSERT_ARG(name);
2738

2739 2740 2741
	if ((error = remove_branch_config_related_entries(repo, name)) < 0 ||
	    (error = remove_remote_tracking(repo, name)) < 0 ||
	    (error = rename_remote_config_section(repo, name, NULL)) < 0)
2742 2743
		return error;

2744 2745
	return 0;
}
2746 2747 2748

int git_remote_default_branch(git_buf *out, git_remote *remote)
{
2749 2750 2751 2752 2753
	GIT_BUF_WRAP_PRIVATE(out, git_remote__default_branch, remote);
}

int git_remote__default_branch(git_str *out, git_remote *remote)
{
2754 2755 2756 2757
	const git_remote_head **heads;
	const git_remote_head *guess = NULL;
	const git_oid *head_id;
	size_t heads_len, i;
2758
	git_str local_default = GIT_STR_INIT;
2759 2760
	int error;

2761
	GIT_ASSERT_ARG(out);
2762

2763
	if ((error = git_remote_ls(&heads, &heads_len, remote)) < 0)
2764
		goto done;
2765

2766 2767 2768 2769
	if (heads_len == 0 || strcmp(heads[0]->name, GIT_HEAD_FILE)) {
		error = GIT_ENOTFOUND;
		goto done;
	}
2770

2771
	/* the first one must be HEAD so if that has the symref info, we're done */
2772
	if (heads[0]->symref_target) {
2773
		error = git_str_puts(out, heads[0]->symref_target);
2774 2775
		goto done;
	}
2776 2777 2778

	/*
	 * If there's no symref information, we have to look over them
2779 2780
	 * and guess. We return the first match unless the default
	 * branch is a candidate. Then we return the default branch.
2781
	 */
2782 2783 2784 2785

	if ((error = git_repository_initialbranch(&local_default, remote->repo)) < 0)
		goto done;

2786 2787 2788 2789 2790 2791
	head_id = &heads[0]->oid;

	for (i = 1; i < heads_len; i++) {
		if (git_oid_cmp(head_id, &heads[i]->oid))
			continue;

2792 2793 2794
		if (git__prefixcmp(heads[i]->name, GIT_REFS_HEADS_DIR))
			continue;

2795 2796 2797 2798 2799
		if (!guess) {
			guess = heads[i];
			continue;
		}

2800
		if (!git__strcmp(local_default.ptr, heads[i]->name)) {
2801 2802 2803 2804 2805
			guess = heads[i];
			break;
		}
	}

2806 2807 2808 2809 2810
	if (!guess) {
		error = GIT_ENOTFOUND;
		goto done;
	}

2811
	error = git_str_puts(out, guess->name);
2812

2813
done:
2814
	git_str_dispose(&local_default);
2815
	return error;
2816
}
2817

2818 2819
GIT_INLINE(int) connect_opts_from_push_opts(
	git_remote_connect_options *out,
2820
	git_remote *remote,
2821
	const git_push_options *push_opts)
2822
{
2823 2824
	git_remote_connect_options tmp = GIT_REMOTE_CONNECT_OPTIONS_INIT;
	copy_opts(&tmp, push_opts);
2825
	return git_remote_connect_options_normalize(out, remote->repo, &tmp);
2826 2827 2828 2829 2830 2831 2832 2833
}

int git_remote_upload(
	git_remote *remote,
	const git_strarray *refspecs,
	const git_push_options *opts)
{
	git_remote_connect_options connect_opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
2834
	git_push *push;
2835
	git_refspec *spec;
2836 2837
	size_t i;
	int error;
2838

2839
	GIT_ASSERT_ARG(remote);
2840

2841
	if (!remote->repo) {
2842
		git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
2843 2844 2845
		return -1;
	}

2846
	if ((error = connect_opts_from_push_opts(&connect_opts, remote, opts)) < 0)
2847
		goto cleanup;
2848

2849
	if ((error = connect_or_reset_options(remote, GIT_DIRECTION_PUSH, &connect_opts)) < 0)
2850 2851
		goto cleanup;

2852
	free_refspecs(&remote->active_refspecs);
Leo Yang committed
2853
	if ((error = dwim_refspecs(&remote->active_refspecs, &remote->refspecs, &remote->refs)) < 0)
2854 2855
		goto cleanup;

2856 2857 2858 2859 2860
	if (remote->push) {
		git_push_free(remote->push);
		remote->push = NULL;
	}

2861 2862
	if ((error = git_push_new(&remote->push, remote, opts)) < 0)
		goto cleanup;
2863

2864
	push = remote->push;
2865

2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877
	if (refspecs && refspecs->count > 0) {
		for (i = 0; i < refspecs->count; i++) {
			if ((error = git_push_add_refspec(push, refspecs->strings[i])) < 0)
				goto cleanup;
		}
	} else {
		git_vector_foreach(&remote->refspecs, i, spec) {
			if (!spec->push)
				continue;
			if ((error = git_push_add_refspec(push, spec->string)) < 0)
				goto cleanup;
		}
2878 2879
	}

2880
	if ((error = git_push_finish(push)) < 0)
2881 2882
		goto cleanup;

2883 2884
	if (connect_opts.callbacks.push_update_reference &&
	    (error = git_push_status_foreach(push, connect_opts.callbacks.push_update_reference, connect_opts.callbacks.payload)) < 0)
2885 2886 2887
		goto cleanup;

cleanup:
2888
	git_remote_connect_options_dispose(&connect_opts);
2889 2890 2891
	return error;
}

2892 2893 2894 2895
int git_remote_push(
	git_remote *remote,
	const git_strarray *refspecs,
	const git_push_options *opts)
2896
{
2897
	git_remote_connect_options connect_opts = GIT_REMOTE_CONNECT_OPTIONS_INIT;
2898
	int error;
2899

2900
	GIT_ASSERT_ARG(remote);
2901 2902

	if (!remote->repo) {
2903
		git_error_set(GIT_ERROR_INVALID, "cannot download detached remote");
2904 2905 2906
		return -1;
	}

2907
	if (connect_opts_from_push_opts(&connect_opts, remote, opts) < 0)
2908
		return -1;
2909 2910

	if ((error = git_remote_upload(remote, refspecs, opts)) < 0)
2911
		goto done;
2912

2913
	error = git_remote_update_tips(remote, &connect_opts.callbacks, 0, 0, NULL);
2914

2915
done:
2916
	git_remote_disconnect(remote);
2917
	git_remote_connect_options_dispose(&connect_opts);
2918 2919
	return error;
}
2920 2921 2922 2923 2924

#define PREFIX "url"
#define SUFFIX_FETCH "insteadof"
#define SUFFIX_PUSH "pushinsteadof"

2925
static int apply_insteadof(char **out, git_config *config, const char *url, int direction, bool use_default_if_empty)
2926 2927 2928 2929 2930
{
	size_t match_length, prefix_length, suffix_length;
	char *replacement = NULL;
	const char *regexp;

2931
	git_str result = GIT_STR_INIT;
2932 2933 2934
	git_config_entry *entry;
	git_config_iterator *iter;

2935 2936 2937 2938
	GIT_ASSERT_ARG(out);
	GIT_ASSERT_ARG(config);
	GIT_ASSERT_ARG(url);
	GIT_ASSERT_ARG(direction == GIT_DIRECTION_FETCH || direction == GIT_DIRECTION_PUSH);
2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949

	/* Add 1 to prefix/suffix length due to the additional escaped dot */
	prefix_length = strlen(PREFIX) + 1;
	if (direction == GIT_DIRECTION_FETCH) {
		regexp = PREFIX "\\..*\\." SUFFIX_FETCH;
		suffix_length = strlen(SUFFIX_FETCH) + 1;
	} else {
		regexp = PREFIX "\\..*\\." SUFFIX_PUSH;
		suffix_length = strlen(SUFFIX_PUSH) + 1;
	}

2950
	if (git_config_iterator_glob_new(&iter, config, regexp) < 0)
2951
		return -1;
2952 2953 2954 2955 2956 2957 2958 2959

	match_length = 0;
	while (git_config_next(&entry, iter) == 0) {
		size_t n, replacement_length;

		/* Check if entry value is a prefix of URL */
		if (git__prefixcmp(url, entry->value))
			continue;
2960

2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977
		/* Check if entry value is longer than previous
		 * prefixes */
		if ((n = strlen(entry->value)) <= match_length)
			continue;

		git__free(replacement);
		match_length = n;

		/* Cut off prefix and suffix of the value */
		replacement_length =
		    strlen(entry->name) - (prefix_length + suffix_length);
		replacement = git__strndup(entry->name + prefix_length,
				replacement_length);
	}

	git_config_iterator_free(iter);

2978 2979 2980 2981 2982 2983 2984
	if (match_length == 0 && use_default_if_empty) {
		*out = git__strdup(url);
		return *out ? 0 : -1;
	} else if (match_length == 0) {
		*out = NULL;
		return 0;
	}
2985

2986
	git_str_printf(&result, "%s%s", replacement, url + match_length);
2987 2988 2989

	git__free(replacement);

2990 2991
	*out = git_str_detach(&result);
	return 0;
2992
}
2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006

/* Deprecated functions */

#ifndef GIT_DEPRECATE_HARD

int git_remote_is_valid_name(const char *remote_name)
{
	int valid = 0;

	git_remote_name_is_valid(&valid, remote_name);
	return valid;
}

#endif