connect.c 14.7 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
		return 0;

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

	/* REF_NORMAL means that we don't want the magic fake tag refs */
25
	if ((flags & REF_NORMAL) && check_refname_format(name, 0))
L
Linus Torvalds 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39
		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 55 56 57 58 59 60 61
static void die_initial_contact(int got_at_least_one_head)
{
	if (got_at_least_one_head)
		die("The remote end hung up upon initial contact");
	else
		die("Could not read from remote repository.\n\n"
		    "Please make sure you have the correct access rights\n"
		    "and the repository exists.");
}

62 63 64
/*
 * Read all the refs from the other end
 */
65
struct ref **get_remote_heads(int in, struct ref **list,
66 67
			      unsigned int flags,
			      struct extra_have_objects *extra_have)
68
{
69 70
	int got_at_least_one_head = 0;

71 72 73 74 75 76
	*list = NULL;
	for (;;) {
		struct ref *ref;
		unsigned char old_sha1[20];
		static char buffer[1000];
		char *name;
77
		int len, name_len;
78

79
		len = packet_read(in, buffer, sizeof(buffer),
80 81
				  PACKET_READ_GENTLE_ON_EOF |
				  PACKET_READ_CHOMP_NEWLINE);
82 83 84
		if (len < 0)
			die_initial_contact(got_at_least_one_head);

85 86 87
		if (!len)
			break;

88 89 90
		if (len > 4 && !prefixcmp(buffer, "ERR "))
			die("remote error: %s", buffer + 4);

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

95 96
		name_len = strlen(name);
		if (len != name_len + 41) {
97
			free(server_capabilities);
98
			server_capabilities = xstrdup(name + name_len + 1);
99 100
		}

101 102 103 104 105 106
		if (extra_have &&
		    name_len == 5 && !memcmp(".have", name, 5)) {
			add_extra_have(extra_have, old_sha1);
			continue;
		}

L
Linus Torvalds 已提交
107
		if (!check_ref(name, name_len, flags))
108
			continue;
109
		ref = alloc_ref(buffer + 41);
110
		hashcpy(ref->old_sha1, old_sha1);
111 112
		*list = ref;
		list = &ref->next;
113
		got_at_least_one_head = 1;
114 115 116 117
	}
	return list;
}

118
const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp)
119 120 121 122 123 124 125 126 127 128 129
{
	int len;

	if (!feature_list)
		return NULL;

	len = strlen(feature);
	while (*feature_list) {
		const char *found = strstr(feature_list, feature);
		if (!found)
			return NULL;
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
		if (feature_list == found || isspace(found[-1])) {
			const char *value = found + len;
			/* feature with no value (e.g., "thin-pack") */
			if (!*value || isspace(*value)) {
				if (lenp)
					*lenp = 0;
				return value;
			}
			/* feature with a value (e.g., "agent=git/1.2.3") */
			else if (*value == '=') {
				value++;
				if (lenp)
					*lenp = strcspn(value, " \t\n");
				return value;
			}
			/*
			 * otherwise we matched a substring of another feature;
			 * keep looking
			 */
		}
150 151 152
		feature_list = found + 1;
	}
	return NULL;
153 154
}

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
int parse_feature_request(const char *feature_list, const char *feature)
{
	return !!parse_feature_value(feature_list, feature, NULL);
}

const char *server_feature_value(const char *feature, int *len)
{
	return parse_feature_value(server_capabilities, feature, len);
}

int server_supports(const char *feature)
{
	return !!server_feature_value(feature, NULL);
}

170 171 172
enum protocol {
	PROTO_LOCAL = 1,
	PROTO_SSH,
173
	PROTO_GIT
174 175 176 177 178 179 180 181
};

static enum protocol get_protocol(const char *name)
{
	if (!strcmp(name, "ssh"))
		return PROTO_SSH;
	if (!strcmp(name, "git"))
		return PROTO_GIT;
182 183 184 185
	if (!strcmp(name, "git+ssh"))
		return PROTO_SSH;
	if (!strcmp(name, "ssh+git"))
		return PROTO_SSH;
186 187
	if (!strcmp(name, "file"))
		return PROTO_LOCAL;
188 189 190
	die("I don't handle protocol '%s'", name);
}

191 192
#define STR_(s)	# s
#define STR(s)	STR_(s)
193

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
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;
	}
}

216 217 218 219 220 221 222 223 224
static void enable_keepalive(int sockfd)
{
	int ka = 1;

	if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
		fprintf(stderr, "unable to set SO_KEEPALIVE on socket: %s\n",
			strerror(errno));
}

225
#ifndef NO_IPV6
226

227 228
static const char *ai_name(const struct addrinfo *ai)
{
229 230 231
	static char addr[NI_MAXHOST];
	if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
			NI_NUMERICHOST) != 0)
232
		strcpy(addr, "(unknown)");
233

234 235 236
	return addr;
}

237 238 239
/*
 * Returns a connected socket() fd, or else die()s.
 */
240
static int git_tcp_connect_sock(char *host, int flags)
241
{
242 243
	struct strbuf error_message = STRBUF_INIT;
	int sockfd = -1;
T
Timo Hirvonen 已提交
244
	const char *port = STR(DEFAULT_GIT_PORT);
245 246
	struct addrinfo hints, *ai0, *ai;
	int gai;
247
	int cnt = 0;
248

249 250 251
	get_host_and_port(&host, &port);
	if (!*port)
		port = "<none>";
252 253 254 255 256

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

257 258 259
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "Looking up %s ... ", host);

260 261
	gai = getaddrinfo(host, port, &hints, &ai);
	if (gai)
L
Linus Torvalds 已提交
262
		die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
263

264 265 266
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);

267
	for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
268 269
		sockfd = socket(ai->ai_family,
				ai->ai_socktype, ai->ai_protocol);
270 271 272 273 274 275
		if ((sockfd < 0) ||
		    (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
			strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
				    host, cnt, ai_name(ai), strerror(errno));
			if (0 <= sockfd)
				close(sockfd);
276 277
			sockfd = -1;
			continue;
278
		}
279 280
		if (flags & CONNECT_VERBOSE)
			fprintf(stderr, "%s ", ai_name(ai));
281
		break;
282 283
	}

284
	freeaddrinfo(ai0);
285 286

	if (sockfd < 0)
287
		die("unable to connect to %s:\n%s", host, error_message.buf);
288

289 290
	enable_keepalive(sockfd);

291 292 293
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\n");

294 295
	strbuf_release(&error_message);

296
	return sockfd;
297 298
}

299
#else /* NO_IPV6 */
300

301 302 303
/*
 * Returns a connected socket() fd, or else die()s.
 */
304
static int git_tcp_connect_sock(char *host, int flags)
305
{
306 307
	struct strbuf error_message = STRBUF_INIT;
	int sockfd = -1;
308 309
	const char *port = STR(DEFAULT_GIT_PORT);
	char *ep;
310 311 312 313
	struct hostent *he;
	struct sockaddr_in sa;
	char **ap;
	unsigned int nport;
314
	int cnt;
315

316
	get_host_and_port(&host, &port);
317

318 319 320
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "Looking up %s ... ", host);

321 322 323 324 325 326 327 328
	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 )
329
			die("Unknown port %s", port);
330 331 332
		nport = se->s_port;
	}

333 334 335
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);

336
	for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
337 338
		memset(&sa, 0, sizeof sa);
		sa.sin_family = he->h_addrtype;
P
Peter Anvin 已提交
339
		sa.sin_port = htons(nport);
340
		memcpy(&sa.sin_addr, *ap, he->h_length);
341

342 343 344 345
		sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
		if ((sockfd < 0) ||
		    connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
			strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
346 347 348
				host,
				cnt,
				inet_ntoa(*(struct in_addr *)&sa.sin_addr),
349 350 351
				strerror(errno));
			if (0 <= sockfd)
				close(sockfd);
352 353 354
			sockfd = -1;
			continue;
		}
355 356 357
		if (flags & CONNECT_VERBOSE)
			fprintf(stderr, "%s ",
				inet_ntoa(*(struct in_addr *)&sa.sin_addr));
358 359 360 361
		break;
	}

	if (sockfd < 0)
362
		die("unable to connect to %s:\n%s", host, error_message.buf);
363

364 365
	enable_keepalive(sockfd);

366 367 368
	if (flags & CONNECT_VERBOSE)
		fprintf(stderr, "done.\n");

369 370 371 372 373 374
	return sockfd;
}

#endif /* NO_IPV6 */


375
static void git_tcp_connect(int fd[2], char *host, int flags)
376
{
377
	int sockfd = git_tcp_connect_sock(host, flags);
378

379
	fd[0] = sockfd;
380
	fd[1] = dup(sockfd);
381 382 383
}


384
static char *git_proxy_command;
P
Paul Collins 已提交
385

386 387
static int git_proxy_command_options(const char *var, const char *value,
		void *cb)
P
Paul Collins 已提交
388
{
J
Junio C Hamano 已提交
389
	if (!strcmp(var, "core.gitproxy")) {
390 391 392
		const char *for_pos;
		int matchlen = -1;
		int hostlen;
393 394
		const char *rhost_name = cb;
		int rhost_len = strlen(rhost_name);
395

J
Junio C Hamano 已提交
396
		if (git_proxy_command)
P
Paul Collins 已提交
397
			return 0;
398 399
		if (!value)
			return config_error_nonbool(var);
J
Junio C Hamano 已提交
400 401 402 403 404 405
		/* [core]
		 * ;# matches www.kernel.org as well
		 * gitproxy = netcatter-1 for kernel.org
		 * gitproxy = netcatter-2 for sample.xz
		 * gitproxy = netcatter-default
		 */
406
		for_pos = strstr(value, " for ");
J
Junio C Hamano 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
		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 已提交
425
			if (matchlen == 4 &&
J
Junio C Hamano 已提交
426 427
			    !memcmp(value, "none", 4))
				matchlen = 0;
P
Pierre Habouzit 已提交
428
			git_proxy_command = xmemdupz(value, matchlen);
P
Paul Collins 已提交
429
		}
J
Junio C Hamano 已提交
430
		return 0;
P
Paul Collins 已提交
431 432
	}

433
	return git_default_config(var, value, cb);
P
Paul Collins 已提交
434 435
}

J
Junio C Hamano 已提交
436
static int git_use_proxy(const char *host)
P
Paul Collins 已提交
437 438
{
	git_proxy_command = getenv("GIT_PROXY_COMMAND");
439
	git_config(git_proxy_command_options, (void*)host);
J
Junio C Hamano 已提交
440
	return (git_proxy_command && *git_proxy_command);
P
Paul Collins 已提交
441 442
}

443
static struct child_process *git_proxy_connect(int fd[2], char *host)
P
Paul Collins 已提交
444
{
T
Timo Hirvonen 已提交
445
	const char *port = STR(DEFAULT_GIT_PORT);
446 447
	const char **argv;
	struct child_process *proxy;
P
Paul Collins 已提交
448

449
	get_host_and_port(&host, &port);
P
Paul Collins 已提交
450

451
	argv = xmalloc(sizeof(*argv) * 4);
452 453 454 455
	argv[0] = git_proxy_command;
	argv[1] = host;
	argv[2] = port;
	argv[3] = NULL;
456 457 458 459 460
	proxy = xcalloc(1, sizeof(*proxy));
	proxy->argv = argv;
	proxy->in = -1;
	proxy->out = -1;
	if (start_command(proxy))
461
		die("cannot start proxy %s", argv[0]);
462 463 464
	fd[0] = proxy->out; /* read from proxy stdout */
	fd[1] = proxy->in;  /* write to proxy stdin */
	return proxy;
P
Paul Collins 已提交
465 466
}

467 468
#define MAX_CMD_LEN 1024

469
static char *get_port(char *host)
470 471 472 473 474
{
	char *end;
	char *p = strchr(host, ':');

	if (p) {
475 476
		long port = strtol(p + 1, &end, 10);
		if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
477 478 479 480 481 482 483 484
			*p = '\0';
			return p+1;
		}
	}

	return NULL;
}

485 486
static struct child_process no_fork;

487
/*
488 489 490 491 492
 * 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).
493
 *
494 495 496
 * 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).
497
 */
498
struct child_process *git_connect(int fd[2], const char *url_orig,
499
				  const char *prog, int flags)
500
{
J
Jeff King 已提交
501
	char *url;
B
Benjamin Kramer 已提交
502
	char *host, *path;
503 504
	char *end;
	int c;
505
	struct child_process *conn = &no_fork;
506
	enum protocol protocol = PROTO_LOCAL;
507
	int free_path = 0;
508
	char *port = NULL;
509 510
	const char **arg;
	struct strbuf cmd;
511

512 513 514 515 516
	/* Without this we cannot rely on waitpid() to tell
	 * what happened to our children.
	 */
	signal(SIGCHLD, SIG_DFL);

J
Jeff King 已提交
517 518 519 520 521
	if (is_url(url_orig))
		url = url_decode(url_orig);
	else
		url = xstrdup(url_orig);

522
	host = strstr(url, "://");
523
	if (host) {
524 525 526
		*host = '\0';
		protocol = get_protocol(url);
		host += 3;
527 528
		c = '/';
	} else {
529
		host = url;
530 531 532
		c = ':';
	}

533 534
	/*
	 * Don't do destructive transforms with git:// as that
535
	 * protocol code does '[]' unwrapping of its own.
536
	 */
537 538 539
	if (host[0] == '[') {
		end = strchr(host + 1, ']');
		if (end) {
540 541 542 543
			if (protocol != PROTO_GIT) {
				*end = 0;
				host++;
			}
544 545 546 547 548 549 550
			end++;
		} else
			end = host;
	} else
		end = host;

	path = strchr(end, c);
551
	if (path && !has_dos_drive_prefix(end)) {
552
		if (c == ':') {
553
			protocol = PROTO_SSH;
554
			*path++ = '\0';
555 556 557
		}
	} else
		path = end;
558

559 560 561 562 563 564 565 566 567 568 569
	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++;
570
		else {
571
			path = xstrdup(ptr);
572 573
			free_path = 1;
		}
574 575 576 577

		*ptr = '\0';
	}

578 579 580 581
	/*
	 * Add support for ssh port: ssh://host.xy:<port>/...
	 */
	if (protocol == PROTO_SSH && host != url)
582
		port = get_port(end);
583

P
Paul Collins 已提交
584
	if (protocol == PROTO_GIT) {
585 586 587
		/* These underlying connection commands die() if they
		 * cannot connect.
		 */
588
		char *target_host = xstrdup(host);
J
Junio C Hamano 已提交
589
		if (git_use_proxy(host))
590
			conn = git_proxy_connect(fd, host);
591
		else
592
			git_tcp_connect(fd, host, flags);
593 594
		/*
		 * Separate original protocol components prog and path
595 596 597 598
		 * 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.
599 600 601 602 603 604
		 */
		packet_write(fd[1],
			     "%s %s%chost=%s%c",
			     prog, path, 0,
			     target_host, 0);
		free(target_host);
605
		free(url);
606 607
		if (free_path)
			free(path);
608
		return conn;
P
Paul Collins 已提交
609
	}
610

611
	conn = xcalloc(1, sizeof(*conn));
612

613 614 615 616 617 618 619 620
	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;
621
	conn->argv = arg = xcalloc(7, sizeof(*arg));
622 623
	if (protocol == PROTO_SSH) {
		const char *ssh = getenv("GIT_SSH");
624
		int putty = ssh && strcasestr(ssh, "plink");
625 626 627
		if (!ssh) ssh = "ssh";

		*arg++ = ssh;
628 629
		if (putty && !strcasestr(ssh, "tortoiseplink"))
			*arg++ = "-batch";
630
		if (port) {
631 632
			/* P is for PuTTY, p is for OpenSSH */
			*arg++ = putty ? "-P" : "-p";
633
			*arg++ = port;
634
		}
635 636 637
		*arg++ = host;
	}
	else {
638 639
		/* remove repo-local variables from the environment */
		conn->env = local_repo_env;
640
		conn->use_shell = 1;
M
Matt Draisey 已提交
641
	}
642 643 644 645 646 647 648 649 650
	*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);
651
	free(url);
652 653
	if (free_path)
		free(path);
654
	return conn;
655 656
}

657 658 659 660 661
int git_connection_is_socket(struct child_process *conn)
{
	return conn == &no_fork;
}

662
int finish_connect(struct child_process *conn)
663
{
664
	int code;
665
	if (!conn || git_connection_is_socket(conn))
666 667
		return 0;

668 669
	code = finish_command(conn);
	free(conn->argv);
670
	free(conn);
671
	return code;
672
}