connect.c 14.1 KB
Newer Older
J
Jason Riedy 已提交
1
#include "git-compat-util.h"
2
#include "cache.h"
3
#include "pkt-line.h"
4
#include "quote.h"
5
#include "refs.h"
6
#include "run-command.h"
7
#include "remote.h"
J
Jeff King 已提交
8
#include "url.h"
9

10
static char *server_capabilities;
11

L
Linus Torvalds 已提交
12 13 14 15 16
static int check_ref(const char *name, int len, unsigned int flags)
{
	if (!flags)
		return 1;

17
	if (len < 5 || memcmp(name, "refs/", 5))
L
Linus Torvalds 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
		return 0;

	/* Skip the "refs/" part */
	name += 5;
	len -= 5;

	/* REF_NORMAL means that we don't want the magic fake tag refs */
	if ((flags & REF_NORMAL) && check_ref_format(name) < 0)
		return 0;

	/* REF_HEADS means that we want regular branch heads */
	if ((flags & REF_HEADS) && !memcmp(name, "heads/", 6))
		return 1;

	/* REF_TAGS means that we want tags */
	if ((flags & REF_TAGS) && !memcmp(name, "tags/", 5))
		return 1;

	/* All type bits clear means that we are ok with anything */
	return !(flags & ~REF_NORMAL);
}

40 41 42 43 44
int check_ref_type(const struct ref *ref, int flags)
{
	return check_ref(ref->name, strlen(ref->name), flags);
}

45 46 47 48 49 50 51
static void add_extra_have(struct extra_have_objects *extra, unsigned char *sha1)
{
	ALLOC_GROW(extra->array, extra->nr + 1, extra->alloc);
	hashcpy(&(extra->array[extra->nr][0]), sha1);
	extra->nr++;
}

52 53 54
/*
 * Read all the refs from the other end
 */
55
struct ref **get_remote_heads(int in, struct ref **list,
L
Linus Torvalds 已提交
56
			      int nr_match, char **match,
57 58
			      unsigned int flags,
			      struct extra_have_objects *extra_have)
59 60 61 62 63 64 65
{
	*list = NULL;
	for (;;) {
		struct ref *ref;
		unsigned char old_sha1[20];
		static char buffer[1000];
		char *name;
66
		int len, name_len;
67 68 69 70 71 72 73

		len = packet_read_line(in, buffer, sizeof(buffer));
		if (!len)
			break;
		if (buffer[len-1] == '\n')
			buffer[--len] = 0;

74 75 76
		if (len > 4 && !prefixcmp(buffer, "ERR "))
			die("remote error: %s", buffer + 4);

77 78 79
		if (len < 42 || get_sha1_hex(buffer, old_sha1) || buffer[40] != ' ')
			die("protocol error: expected sha/ref, got '%s'", buffer);
		name = buffer + 41;
80

81 82
		name_len = strlen(name);
		if (len != name_len + 41) {
83
			free(server_capabilities);
84
			server_capabilities = xstrdup(name + name_len + 1);
85 86
		}

87 88 89 90 91 92
		if (extra_have &&
		    name_len == 5 && !memcmp(".have", name, 5)) {
			add_extra_have(extra_have, old_sha1);
			continue;
		}

L
Linus Torvalds 已提交
93
		if (!check_ref(name, name_len, flags))
94
			continue;
95 96
		if (nr_match && !path_match(name, nr_match, match))
			continue;
97
		ref = alloc_ref(buffer + 41);
98
		hashcpy(ref->old_sha1, old_sha1);
99 100 101 102 103 104
		*list = ref;
		list = &ref->next;
	}
	return list;
}

105 106
int server_supports(const char *feature)
{
J
Johannes Schindelin 已提交
107 108
	return server_capabilities &&
		strstr(server_capabilities, feature) != NULL;
109 110
}

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
int path_match(const char *path, int nr, char **match)
{
	int i;
	int pathlen = strlen(path);

	for (i = 0; i < nr; i++) {
		char *s = match[i];
		int len = strlen(s);

		if (!len || len > pathlen)
			continue;
		if (memcmp(path + pathlen - len, s, len))
			continue;
		if (pathlen > len && path[pathlen - len - 1] != '/')
			continue;
		*s = 0;
127
		return (i + 1);
128 129 130 131
	}
	return 0;
}

132 133 134
enum protocol {
	PROTO_LOCAL = 1,
	PROTO_SSH,
135
	PROTO_GIT
136 137 138 139 140 141 142 143
};

static enum protocol get_protocol(const char *name)
{
	if (!strcmp(name, "ssh"))
		return PROTO_SSH;
	if (!strcmp(name, "git"))
		return PROTO_GIT;
144 145 146 147
	if (!strcmp(name, "git+ssh"))
		return PROTO_SSH;
	if (!strcmp(name, "ssh+git"))
		return PROTO_SSH;
148 149
	if (!strcmp(name, "file"))
		return PROTO_LOCAL;
150 151 152
	die("I don't handle protocol '%s'", name);
}

153 154
#define STR_(s)	# s
#define STR(s)	STR_(s)
155

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
static void get_host_and_port(char **host, const char **port)
{
	char *colon, *end;

	if (*host[0] == '[') {
		end = strchr(*host + 1, ']');
		if (end) {
			*end = 0;
			end++;
			(*host)++;
		} else
			end = *host;
	} else
		end = *host;
	colon = strchr(end, ':');

	if (colon) {
		*colon = 0;
		*port = colon + 1;
	}
}

178
#ifndef NO_IPV6
179

180 181
static const char *ai_name(const struct addrinfo *ai)
{
182 183 184
	static char addr[NI_MAXHOST];
	if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
			NI_NUMERICHOST) != 0)
185
		strcpy(addr, "(unknown)");
186

187 188 189
	return addr;
}

190 191 192
/*
 * Returns a connected socket() fd, or else die()s.
 */
193
static int git_tcp_connect_sock(char *host, int flags)
194
{
P
Petr Baudis 已提交
195
	int sockfd = -1, saved_errno = 0;
T
Timo Hirvonen 已提交
196
	const char *port = STR(DEFAULT_GIT_PORT);
197 198
	struct addrinfo hints, *ai0, *ai;
	int gai;
199
	int cnt = 0;
200

201 202 203
	get_host_and_port(&host, &port);
	if (!*port)
		port = "<none>";
204 205 206 207 208

	memset(&hints, 0, sizeof(hints));
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

209 210 211
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "Looking up %s ... ", host);

212 213
	gai = getaddrinfo(host, port, &hints, &ai);
	if (gai)
L
Linus Torvalds 已提交
214
		die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
215

216 217 218
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);

219
	for (ai0 = ai; ai; ai = ai->ai_next) {
220 221
		sockfd = socket(ai->ai_family,
				ai->ai_socktype, ai->ai_protocol);
P
Petr Baudis 已提交
222 223
		if (sockfd < 0) {
			saved_errno = errno;
224
			continue;
P
Petr Baudis 已提交
225
		}
226
		if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
P
Petr Baudis 已提交
227
			saved_errno = errno;
228
			fprintf(stderr, "%s[%d: %s]: errno=%s\n",
229 230 231 232
				host,
				cnt,
				ai_name(ai),
				strerror(saved_errno));
233 234 235
			close(sockfd);
			sockfd = -1;
			continue;
236
		}
237 238
		if (flags & CONNECT_VERBOSE)
			fprintf(stderr, "%s ", ai_name(ai));
239
		break;
240 241
	}

242
	freeaddrinfo(ai0);
243 244

	if (sockfd < 0)
P
Petr Baudis 已提交
245
		die("unable to connect a socket (%s)", strerror(saved_errno));
246

247 248 249
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\n");

250
	return sockfd;
251 252
}

253
#else /* NO_IPV6 */
254

255 256 257
/*
 * Returns a connected socket() fd, or else die()s.
 */
258
static int git_tcp_connect_sock(char *host, int flags)
259
{
P
Petr Baudis 已提交
260
	int sockfd = -1, saved_errno = 0;
261 262
	const char *port = STR(DEFAULT_GIT_PORT);
	char *ep;
263 264 265 266
	struct hostent *he;
	struct sockaddr_in sa;
	char **ap;
	unsigned int nport;
267
	int cnt;
268

269
	get_host_and_port(&host, &port);
270

271 272 273
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "Looking up %s ... ", host);

274 275 276 277 278 279 280 281
	he = gethostbyname(host);
	if (!he)
		die("Unable to look up %s (%s)", host, hstrerror(h_errno));
	nport = strtoul(port, &ep, 10);
	if ( ep == port || *ep ) {
		/* Not numeric */
		struct servent *se = getservbyname(port,"tcp");
		if ( !se )
282
			die("Unknown port %s", port);
283 284 285
		nport = se->s_port;
	}

286 287 288
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);

289
	for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
290
		sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
P
Petr Baudis 已提交
291 292
		if (sockfd < 0) {
			saved_errno = errno;
293
			continue;
P
Petr Baudis 已提交
294
		}
295 296 297

		memset(&sa, 0, sizeof sa);
		sa.sin_family = he->h_addrtype;
P
Peter Anvin 已提交
298
		sa.sin_port = htons(nport);
299
		memcpy(&sa.sin_addr, *ap, he->h_length);
300 301

		if (connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
P
Petr Baudis 已提交
302
			saved_errno = errno;
303
			fprintf(stderr, "%s[%d: %s]: errno=%s\n",
304 305 306 307
				host,
				cnt,
				inet_ntoa(*(struct in_addr *)&sa.sin_addr),
				strerror(saved_errno));
308 309 310 311
			close(sockfd);
			sockfd = -1;
			continue;
		}
312 313 314
		if (flags & CONNECT_VERBOSE)
			fprintf(stderr, "%s ",
				inet_ntoa(*(struct in_addr *)&sa.sin_addr));
315 316 317 318
		break;
	}

	if (sockfd < 0)
P
Petr Baudis 已提交
319
		die("unable to connect a socket (%s)", strerror(saved_errno));
320

321 322 323
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\n");

324 325 326 327 328 329
	return sockfd;
}

#endif /* NO_IPV6 */


330
static void git_tcp_connect(int fd[2], char *host, int flags)
331
{
332
	int sockfd = git_tcp_connect_sock(host, flags);
333

334
	fd[0] = sockfd;
335
	fd[1] = dup(sockfd);
336 337 338
}


339
static char *git_proxy_command;
P
Paul Collins 已提交
340

341 342
static int git_proxy_command_options(const char *var, const char *value,
		void *cb)
P
Paul Collins 已提交
343
{
J
Junio C Hamano 已提交
344
	if (!strcmp(var, "core.gitproxy")) {
345 346 347
		const char *for_pos;
		int matchlen = -1;
		int hostlen;
348 349
		const char *rhost_name = cb;
		int rhost_len = strlen(rhost_name);
350

J
Junio C Hamano 已提交
351
		if (git_proxy_command)
P
Paul Collins 已提交
352
			return 0;
353 354
		if (!value)
			return config_error_nonbool(var);
J
Junio C Hamano 已提交
355 356 357 358 359 360
		/* [core]
		 * ;# matches www.kernel.org as well
		 * gitproxy = netcatter-1 for kernel.org
		 * gitproxy = netcatter-2 for sample.xz
		 * gitproxy = netcatter-default
		 */
361
		for_pos = strstr(value, " for ");
J
Junio C Hamano 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
		if (!for_pos)
			/* matches everybody */
			matchlen = strlen(value);
		else {
			hostlen = strlen(for_pos + 5);
			if (rhost_len < hostlen)
				matchlen = -1;
			else if (!strncmp(for_pos + 5,
					  rhost_name + rhost_len - hostlen,
					  hostlen) &&
				 ((rhost_len == hostlen) ||
				  rhost_name[rhost_len - hostlen -1] == '.'))
				matchlen = for_pos - value;
			else
				matchlen = -1;
		}
		if (0 <= matchlen) {
			/* core.gitproxy = none for kernel.org */
J
Junio C Hamano 已提交
380
			if (matchlen == 4 &&
J
Junio C Hamano 已提交
381 382
			    !memcmp(value, "none", 4))
				matchlen = 0;
P
Pierre Habouzit 已提交
383
			git_proxy_command = xmemdupz(value, matchlen);
P
Paul Collins 已提交
384
		}
J
Junio C Hamano 已提交
385
		return 0;
P
Paul Collins 已提交
386 387
	}

388
	return git_default_config(var, value, cb);
P
Paul Collins 已提交
389 390
}

J
Junio C Hamano 已提交
391
static int git_use_proxy(const char *host)
P
Paul Collins 已提交
392 393
{
	git_proxy_command = getenv("GIT_PROXY_COMMAND");
394
	git_config(git_proxy_command_options, (void*)host);
J
Junio C Hamano 已提交
395
	return (git_proxy_command && *git_proxy_command);
P
Paul Collins 已提交
396 397
}

398
static void git_proxy_connect(int fd[2], char *host)
P
Paul Collins 已提交
399
{
T
Timo Hirvonen 已提交
400
	const char *port = STR(DEFAULT_GIT_PORT);
401 402
	const char *argv[4];
	struct child_process proxy;
P
Paul Collins 已提交
403

404
	get_host_and_port(&host, &port);
P
Paul Collins 已提交
405

406 407 408 409 410 411 412 413 414 415 416 417
	argv[0] = git_proxy_command;
	argv[1] = host;
	argv[2] = port;
	argv[3] = NULL;
	memset(&proxy, 0, sizeof(proxy));
	proxy.argv = argv;
	proxy.in = -1;
	proxy.out = -1;
	if (start_command(&proxy))
		die("cannot start proxy %s", argv[0]);
	fd[0] = proxy.out; /* read from proxy stdout */
	fd[1] = proxy.in;  /* write to proxy stdin */
P
Paul Collins 已提交
418 419
}

420 421
#define MAX_CMD_LEN 1024

422
static char *get_port(char *host)
423 424 425 426 427
{
	char *end;
	char *p = strchr(host, ':');

	if (p) {
428 429
		long port = strtol(p + 1, &end, 10);
		if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
430 431 432 433 434 435 436 437
			*p = '\0';
			return p+1;
		}
	}

	return NULL;
}

438 439
static struct child_process no_fork;

440
/*
441 442 443 444 445
 * This returns a dummy child_process if the transport protocol does not
 * need fork(2), or a struct child_process object if it does.  Once done,
 * finish the connection with finish_connect() with the value returned from
 * this function (it is safe to call finish_connect() with NULL to support
 * the former case).
446
 *
447 448 449
 * If it returns, the connect is successful; it just dies on errors (this
 * will hopefully be changed in a libification effort, to return NULL when
 * the connection failed).
450
 */
451
struct child_process *git_connect(int fd[2], const char *url_orig,
452
				  const char *prog, int flags)
453
{
J
Jeff King 已提交
454
	char *url;
B
Benjamin Kramer 已提交
455
	char *host, *path;
456 457
	char *end;
	int c;
458
	struct child_process *conn;
459
	enum protocol protocol = PROTO_LOCAL;
460
	int free_path = 0;
461
	char *port = NULL;
462 463
	const char **arg;
	struct strbuf cmd;
464

465 466 467 468 469
	/* Without this we cannot rely on waitpid() to tell
	 * what happened to our children.
	 */
	signal(SIGCHLD, SIG_DFL);

J
Jeff King 已提交
470 471 472 473 474
	if (is_url(url_orig))
		url = url_decode(url_orig);
	else
		url = xstrdup(url_orig);

475
	host = strstr(url, "://");
476
	if (host) {
477 478 479
		*host = '\0';
		protocol = get_protocol(url);
		host += 3;
480 481
		c = '/';
	} else {
482
		host = url;
483 484 485
		c = ':';
	}

486 487
	/*
	 * Don't do destructive transforms with git:// as that
488
	 * protocol code does '[]' unwrapping of its own.
489
	 */
490 491 492
	if (host[0] == '[') {
		end = strchr(host + 1, ']');
		if (end) {
493 494 495 496
			if (protocol != PROTO_GIT) {
				*end = 0;
				host++;
			}
497 498 499 500 501 502 503
			end++;
		} else
			end = host;
	} else
		end = host;

	path = strchr(end, c);
504
	if (path && !has_dos_drive_prefix(end)) {
505
		if (c == ':') {
506
			protocol = PROTO_SSH;
507
			*path++ = '\0';
508 509 510
		}
	} else
		path = end;
511

512 513 514 515 516 517 518 519 520 521 522
	if (!path || !*path)
		die("No path specified. See 'man git-pull' for valid url syntax");

	/*
	 * null-terminate hostname and point path to ~ for URL's like this:
	 *    ssh://host.xz/~user/repo
	 */
	if (protocol != PROTO_LOCAL && host != url) {
		char *ptr = path;
		if (path[1] == '~')
			path++;
523
		else {
524
			path = xstrdup(ptr);
525 526
			free_path = 1;
		}
527 528 529 530

		*ptr = '\0';
	}

531 532 533 534 535 536
	/*
	 * Add support for ssh port: ssh://host.xy:<port>/...
	 */
	if (protocol == PROTO_SSH && host != url)
		port = get_port(host);

P
Paul Collins 已提交
537
	if (protocol == PROTO_GIT) {
538 539 540
		/* These underlying connection commands die() if they
		 * cannot connect.
		 */
541
		char *target_host = xstrdup(host);
J
Junio C Hamano 已提交
542
		if (git_use_proxy(host))
543
			git_proxy_connect(fd, host);
544
		else
545
			git_tcp_connect(fd, host, flags);
546 547
		/*
		 * Separate original protocol components prog and path
548 549 550 551
		 * from extended host header with a NUL byte.
		 *
		 * Note: Do not add any other headers here!  Doing so
		 * will cause older git-daemon servers to crash.
552 553 554 555 556 557
		 */
		packet_write(fd[1],
			     "%s %s%chost=%s%c",
			     prog, path, 0,
			     target_host, 0);
		free(target_host);
558
		free(url);
559 560
		if (free_path)
			free(path);
561
		return &no_fork;
P
Paul Collins 已提交
562
	}
563

564
	conn = xcalloc(1, sizeof(*conn));
565

566 567 568 569 570 571 572 573
	strbuf_init(&cmd, MAX_CMD_LEN);
	strbuf_addstr(&cmd, prog);
	strbuf_addch(&cmd, ' ');
	sq_quote_buf(&cmd, path);
	if (cmd.len >= MAX_CMD_LEN)
		die("command line too long");

	conn->in = conn->out = -1;
574
	conn->argv = arg = xcalloc(7, sizeof(*arg));
575 576
	if (protocol == PROTO_SSH) {
		const char *ssh = getenv("GIT_SSH");
577
		int putty = ssh && strcasestr(ssh, "plink");
578 579 580
		if (!ssh) ssh = "ssh";

		*arg++ = ssh;
581 582
		if (putty && !strcasestr(ssh, "tortoiseplink"))
			*arg++ = "-batch";
583
		if (port) {
584 585
			/* P is for PuTTY, p is for OpenSSH */
			*arg++ = putty ? "-P" : "-p";
586
			*arg++ = port;
587
		}
588 589 590
		*arg++ = host;
	}
	else {
591 592
		/* remove repo-local variables from the environment */
		conn->env = local_repo_env;
593
		conn->use_shell = 1;
M
Matt Draisey 已提交
594
	}
595 596 597 598 599 600 601 602 603
	*arg++ = cmd.buf;
	*arg = NULL;

	if (start_command(conn))
		die("unable to fork");

	fd[0] = conn->out; /* read from child's stdout */
	fd[1] = conn->in;  /* write to child's stdin */
	strbuf_release(&cmd);
604
	free(url);
605 606
	if (free_path)
		free(path);
607
	return conn;
608 609
}

610
int finish_connect(struct child_process *conn)
611
{
612
	int code;
613
	if (!conn || conn == &no_fork)
614 615
		return 0;

616 617
	code = finish_command(conn);
	free(conn->argv);
618
	free(conn);
619
	return code;
620
}
621 622 623

char *git_getpass(const char *prompt)
{
A
Anselm Kruis 已提交
624
	const char *askpass;
625 626 627 628 629
	struct child_process pass;
	const char *args[3];
	static struct strbuf buffer = STRBUF_INIT;

	askpass = getenv("GIT_ASKPASS");
A
Anselm Kruis 已提交
630 631
	if (!askpass)
		askpass = askpass_program;
632 633
	if (!askpass)
		askpass = getenv("SSH_ASKPASS");
634 635 636 637 638 639
	if (!askpass || !(*askpass)) {
		char *result = getpass(prompt);
		if (!result)
			die_errno("Could not read password");
		return result;
	}
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664

	args[0] = askpass;
	args[1]	= prompt;
	args[2] = NULL;

	memset(&pass, 0, sizeof(pass));
	pass.argv = args;
	pass.out = -1;

	if (start_command(&pass))
		exit(1);

	strbuf_reset(&buffer);
	if (strbuf_read(&buffer, pass.out, 20) < 0)
		die("failed to read password from %s\n", askpass);

	close(pass.out);

	if (finish_command(&pass))
		exit(1);

	strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));

	return buffer.buf;
}