make the sender advertise shallow commits to the receiver
[alt-git.git] / connect.c
blob48eec414f7e25ffc704b8a394077a3b60c2a1b61
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"
8 #include "connect.h"
9 #include "url.h"
10 #include "string-list.h"
11 #include "sha1-array.h"
13 static char *server_capabilities;
14 static const char *parse_feature_value(const char *, const char *, int *);
16 static int check_ref(const char *name, int len, unsigned int flags)
18 if (!flags)
19 return 1;
21 if (len < 5 || memcmp(name, "refs/", 5))
22 return 0;
24 /* Skip the "refs/" part */
25 name += 5;
26 len -= 5;
28 /* REF_NORMAL means that we don't want the magic fake tag refs */
29 if ((flags & REF_NORMAL) && check_refname_format(name, 0))
30 return 0;
32 /* REF_HEADS means that we want regular branch heads */
33 if ((flags & REF_HEADS) && !memcmp(name, "heads/", 6))
34 return 1;
36 /* REF_TAGS means that we want tags */
37 if ((flags & REF_TAGS) && !memcmp(name, "tags/", 5))
38 return 1;
40 /* All type bits clear means that we are ok with anything */
41 return !(flags & ~REF_NORMAL);
44 int check_ref_type(const struct ref *ref, int flags)
46 return check_ref(ref->name, strlen(ref->name), flags);
49 static void die_initial_contact(int got_at_least_one_head)
51 if (got_at_least_one_head)
52 die("The remote end hung up upon initial contact");
53 else
54 die("Could not read from remote repository.\n\n"
55 "Please make sure you have the correct access rights\n"
56 "and the repository exists.");
59 static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
61 char *sym, *target;
62 struct string_list_item *item;
64 if (!len)
65 return; /* just "symref" */
66 /* e.g. "symref=HEAD:refs/heads/master" */
67 sym = xmalloc(len + 1);
68 memcpy(sym, val, len);
69 sym[len] = '\0';
70 target = strchr(sym, ':');
71 if (!target)
72 /* just "symref=something" */
73 goto reject;
74 *(target++) = '\0';
75 if (check_refname_format(sym, REFNAME_ALLOW_ONELEVEL) ||
76 check_refname_format(target, REFNAME_ALLOW_ONELEVEL))
77 /* "symref=bogus:pair */
78 goto reject;
79 item = string_list_append(symref, sym);
80 item->util = target;
81 return;
82 reject:
83 free(sym);
84 return;
87 static void annotate_refs_with_symref_info(struct ref *ref)
89 struct string_list symref = STRING_LIST_INIT_DUP;
90 const char *feature_list = server_capabilities;
92 while (feature_list) {
93 int len;
94 const char *val;
96 val = parse_feature_value(feature_list, "symref", &len);
97 if (!val)
98 break;
99 parse_one_symref_info(&symref, val, len);
100 feature_list = val + 1;
102 sort_string_list(&symref);
104 for (; ref; ref = ref->next) {
105 struct string_list_item *item;
106 item = string_list_lookup(&symref, ref->name);
107 if (!item)
108 continue;
109 ref->symref = xstrdup((char *)item->util);
111 string_list_clear(&symref, 0);
115 * Read all the refs from the other end
117 struct ref **get_remote_heads(int in, char *src_buf, size_t src_len,
118 struct ref **list, unsigned int flags,
119 struct sha1_array *extra_have)
121 struct ref **orig_list = list;
122 int got_at_least_one_head = 0;
124 *list = NULL;
125 for (;;) {
126 struct ref *ref;
127 unsigned char old_sha1[20];
128 char *name;
129 int len, name_len;
130 char *buffer = packet_buffer;
132 len = packet_read(in, &src_buf, &src_len,
133 packet_buffer, sizeof(packet_buffer),
134 PACKET_READ_GENTLE_ON_EOF |
135 PACKET_READ_CHOMP_NEWLINE);
136 if (len < 0)
137 die_initial_contact(got_at_least_one_head);
139 if (!len)
140 break;
142 if (len > 4 && !prefixcmp(buffer, "ERR "))
143 die("remote error: %s", buffer + 4);
145 if (len < 42 || get_sha1_hex(buffer, old_sha1) || buffer[40] != ' ')
146 die("protocol error: expected sha/ref, got '%s'", buffer);
147 name = buffer + 41;
149 name_len = strlen(name);
150 if (len != name_len + 41) {
151 free(server_capabilities);
152 server_capabilities = xstrdup(name + name_len + 1);
155 if (extra_have &&
156 name_len == 5 && !memcmp(".have", name, 5)) {
157 sha1_array_append(extra_have, old_sha1);
158 continue;
161 if (!check_ref(name, name_len, flags))
162 continue;
163 ref = alloc_ref(buffer + 41);
164 hashcpy(ref->old_sha1, old_sha1);
165 *list = ref;
166 list = &ref->next;
167 got_at_least_one_head = 1;
170 annotate_refs_with_symref_info(*orig_list);
172 return list;
175 static const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp)
177 int len;
179 if (!feature_list)
180 return NULL;
182 len = strlen(feature);
183 while (*feature_list) {
184 const char *found = strstr(feature_list, feature);
185 if (!found)
186 return NULL;
187 if (feature_list == found || isspace(found[-1])) {
188 const char *value = found + len;
189 /* feature with no value (e.g., "thin-pack") */
190 if (!*value || isspace(*value)) {
191 if (lenp)
192 *lenp = 0;
193 return value;
195 /* feature with a value (e.g., "agent=git/1.2.3") */
196 else if (*value == '=') {
197 value++;
198 if (lenp)
199 *lenp = strcspn(value, " \t\n");
200 return value;
203 * otherwise we matched a substring of another feature;
204 * keep looking
207 feature_list = found + 1;
209 return NULL;
212 int parse_feature_request(const char *feature_list, const char *feature)
214 return !!parse_feature_value(feature_list, feature, NULL);
217 const char *server_feature_value(const char *feature, int *len)
219 return parse_feature_value(server_capabilities, feature, len);
222 int server_supports(const char *feature)
224 return !!server_feature_value(feature, NULL);
227 enum protocol {
228 PROTO_LOCAL = 1,
229 PROTO_SSH,
230 PROTO_GIT
233 static enum protocol get_protocol(const char *name)
235 if (!strcmp(name, "ssh"))
236 return PROTO_SSH;
237 if (!strcmp(name, "git"))
238 return PROTO_GIT;
239 if (!strcmp(name, "git+ssh"))
240 return PROTO_SSH;
241 if (!strcmp(name, "ssh+git"))
242 return PROTO_SSH;
243 if (!strcmp(name, "file"))
244 return PROTO_LOCAL;
245 die("I don't handle protocol '%s'", name);
248 #define STR_(s) # s
249 #define STR(s) STR_(s)
251 static void get_host_and_port(char **host, const char **port)
253 char *colon, *end;
255 if (*host[0] == '[') {
256 end = strchr(*host + 1, ']');
257 if (end) {
258 *end = 0;
259 end++;
260 (*host)++;
261 } else
262 end = *host;
263 } else
264 end = *host;
265 colon = strchr(end, ':');
267 if (colon) {
268 *colon = 0;
269 *port = colon + 1;
273 static void enable_keepalive(int sockfd)
275 int ka = 1;
277 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
278 fprintf(stderr, "unable to set SO_KEEPALIVE on socket: %s\n",
279 strerror(errno));
282 #ifndef NO_IPV6
284 static const char *ai_name(const struct addrinfo *ai)
286 static char addr[NI_MAXHOST];
287 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
288 NI_NUMERICHOST) != 0)
289 strcpy(addr, "(unknown)");
291 return addr;
295 * Returns a connected socket() fd, or else die()s.
297 static int git_tcp_connect_sock(char *host, int flags)
299 struct strbuf error_message = STRBUF_INIT;
300 int sockfd = -1;
301 const char *port = STR(DEFAULT_GIT_PORT);
302 struct addrinfo hints, *ai0, *ai;
303 int gai;
304 int cnt = 0;
306 get_host_and_port(&host, &port);
307 if (!*port)
308 port = "<none>";
310 memset(&hints, 0, sizeof(hints));
311 hints.ai_socktype = SOCK_STREAM;
312 hints.ai_protocol = IPPROTO_TCP;
314 if (flags & CONNECT_VERBOSE)
315 fprintf(stderr, "Looking up %s ... ", host);
317 gai = getaddrinfo(host, port, &hints, &ai);
318 if (gai)
319 die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
321 if (flags & CONNECT_VERBOSE)
322 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
324 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
325 sockfd = socket(ai->ai_family,
326 ai->ai_socktype, ai->ai_protocol);
327 if ((sockfd < 0) ||
328 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
329 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
330 host, cnt, ai_name(ai), strerror(errno));
331 if (0 <= sockfd)
332 close(sockfd);
333 sockfd = -1;
334 continue;
336 if (flags & CONNECT_VERBOSE)
337 fprintf(stderr, "%s ", ai_name(ai));
338 break;
341 freeaddrinfo(ai0);
343 if (sockfd < 0)
344 die("unable to connect to %s:\n%s", host, error_message.buf);
346 enable_keepalive(sockfd);
348 if (flags & CONNECT_VERBOSE)
349 fprintf(stderr, "done.\n");
351 strbuf_release(&error_message);
353 return sockfd;
356 #else /* NO_IPV6 */
359 * Returns a connected socket() fd, or else die()s.
361 static int git_tcp_connect_sock(char *host, int flags)
363 struct strbuf error_message = STRBUF_INIT;
364 int sockfd = -1;
365 const char *port = STR(DEFAULT_GIT_PORT);
366 char *ep;
367 struct hostent *he;
368 struct sockaddr_in sa;
369 char **ap;
370 unsigned int nport;
371 int cnt;
373 get_host_and_port(&host, &port);
375 if (flags & CONNECT_VERBOSE)
376 fprintf(stderr, "Looking up %s ... ", host);
378 he = gethostbyname(host);
379 if (!he)
380 die("Unable to look up %s (%s)", host, hstrerror(h_errno));
381 nport = strtoul(port, &ep, 10);
382 if ( ep == port || *ep ) {
383 /* Not numeric */
384 struct servent *se = getservbyname(port,"tcp");
385 if ( !se )
386 die("Unknown port %s", port);
387 nport = se->s_port;
390 if (flags & CONNECT_VERBOSE)
391 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
393 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
394 memset(&sa, 0, sizeof sa);
395 sa.sin_family = he->h_addrtype;
396 sa.sin_port = htons(nport);
397 memcpy(&sa.sin_addr, *ap, he->h_length);
399 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
400 if ((sockfd < 0) ||
401 connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
402 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
403 host,
404 cnt,
405 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
406 strerror(errno));
407 if (0 <= sockfd)
408 close(sockfd);
409 sockfd = -1;
410 continue;
412 if (flags & CONNECT_VERBOSE)
413 fprintf(stderr, "%s ",
414 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
415 break;
418 if (sockfd < 0)
419 die("unable to connect to %s:\n%s", host, error_message.buf);
421 enable_keepalive(sockfd);
423 if (flags & CONNECT_VERBOSE)
424 fprintf(stderr, "done.\n");
426 return sockfd;
429 #endif /* NO_IPV6 */
432 static void git_tcp_connect(int fd[2], char *host, int flags)
434 int sockfd = git_tcp_connect_sock(host, flags);
436 fd[0] = sockfd;
437 fd[1] = dup(sockfd);
441 static char *git_proxy_command;
443 static int git_proxy_command_options(const char *var, const char *value,
444 void *cb)
446 if (!strcmp(var, "core.gitproxy")) {
447 const char *for_pos;
448 int matchlen = -1;
449 int hostlen;
450 const char *rhost_name = cb;
451 int rhost_len = strlen(rhost_name);
453 if (git_proxy_command)
454 return 0;
455 if (!value)
456 return config_error_nonbool(var);
457 /* [core]
458 * ;# matches www.kernel.org as well
459 * gitproxy = netcatter-1 for kernel.org
460 * gitproxy = netcatter-2 for sample.xz
461 * gitproxy = netcatter-default
463 for_pos = strstr(value, " for ");
464 if (!for_pos)
465 /* matches everybody */
466 matchlen = strlen(value);
467 else {
468 hostlen = strlen(for_pos + 5);
469 if (rhost_len < hostlen)
470 matchlen = -1;
471 else if (!strncmp(for_pos + 5,
472 rhost_name + rhost_len - hostlen,
473 hostlen) &&
474 ((rhost_len == hostlen) ||
475 rhost_name[rhost_len - hostlen -1] == '.'))
476 matchlen = for_pos - value;
477 else
478 matchlen = -1;
480 if (0 <= matchlen) {
481 /* core.gitproxy = none for kernel.org */
482 if (matchlen == 4 &&
483 !memcmp(value, "none", 4))
484 matchlen = 0;
485 git_proxy_command = xmemdupz(value, matchlen);
487 return 0;
490 return git_default_config(var, value, cb);
493 static int git_use_proxy(const char *host)
495 git_proxy_command = getenv("GIT_PROXY_COMMAND");
496 git_config(git_proxy_command_options, (void*)host);
497 return (git_proxy_command && *git_proxy_command);
500 static struct child_process *git_proxy_connect(int fd[2], char *host)
502 const char *port = STR(DEFAULT_GIT_PORT);
503 const char **argv;
504 struct child_process *proxy;
506 get_host_and_port(&host, &port);
508 argv = xmalloc(sizeof(*argv) * 4);
509 argv[0] = git_proxy_command;
510 argv[1] = host;
511 argv[2] = port;
512 argv[3] = NULL;
513 proxy = xcalloc(1, sizeof(*proxy));
514 proxy->argv = argv;
515 proxy->in = -1;
516 proxy->out = -1;
517 if (start_command(proxy))
518 die("cannot start proxy %s", argv[0]);
519 fd[0] = proxy->out; /* read from proxy stdout */
520 fd[1] = proxy->in; /* write to proxy stdin */
521 return proxy;
524 #define MAX_CMD_LEN 1024
526 static char *get_port(char *host)
528 char *end;
529 char *p = strchr(host, ':');
531 if (p) {
532 long port = strtol(p + 1, &end, 10);
533 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
534 *p = '\0';
535 return p+1;
539 return NULL;
542 static struct child_process no_fork;
545 * This returns a dummy child_process if the transport protocol does not
546 * need fork(2), or a struct child_process object if it does. Once done,
547 * finish the connection with finish_connect() with the value returned from
548 * this function (it is safe to call finish_connect() with NULL to support
549 * the former case).
551 * If it returns, the connect is successful; it just dies on errors (this
552 * will hopefully be changed in a libification effort, to return NULL when
553 * the connection failed).
555 struct child_process *git_connect(int fd[2], const char *url_orig,
556 const char *prog, int flags)
558 char *url;
559 char *host, *path;
560 char *end;
561 int c;
562 struct child_process *conn = &no_fork;
563 enum protocol protocol = PROTO_LOCAL;
564 int free_path = 0;
565 char *port = NULL;
566 const char **arg;
567 struct strbuf cmd;
569 /* Without this we cannot rely on waitpid() to tell
570 * what happened to our children.
572 signal(SIGCHLD, SIG_DFL);
574 if (is_url(url_orig))
575 url = url_decode(url_orig);
576 else
577 url = xstrdup(url_orig);
579 host = strstr(url, "://");
580 if (host) {
581 *host = '\0';
582 protocol = get_protocol(url);
583 host += 3;
584 c = '/';
585 } else {
586 host = url;
587 c = ':';
591 * Don't do destructive transforms with git:// as that
592 * protocol code does '[]' unwrapping of its own.
594 if (host[0] == '[') {
595 end = strchr(host + 1, ']');
596 if (end) {
597 if (protocol != PROTO_GIT) {
598 *end = 0;
599 host++;
601 end++;
602 } else
603 end = host;
604 } else
605 end = host;
607 path = strchr(end, c);
608 if (path && !has_dos_drive_prefix(end)) {
609 if (c == ':') {
610 if (host != url || path < strchrnul(host, '/')) {
611 protocol = PROTO_SSH;
612 *path++ = '\0';
613 } else /* '/' in the host part, assume local path */
614 path = end;
616 } else
617 path = end;
619 if (!path || !*path)
620 die("No path specified. See 'man git-pull' for valid url syntax");
623 * null-terminate hostname and point path to ~ for URL's like this:
624 * ssh://host.xz/~user/repo
626 if (protocol != PROTO_LOCAL && host != url) {
627 char *ptr = path;
628 if (path[1] == '~')
629 path++;
630 else {
631 path = xstrdup(ptr);
632 free_path = 1;
635 *ptr = '\0';
639 * Add support for ssh port: ssh://host.xy:<port>/...
641 if (protocol == PROTO_SSH && host != url)
642 port = get_port(end);
644 if (protocol == PROTO_GIT) {
645 /* These underlying connection commands die() if they
646 * cannot connect.
648 char *target_host = xstrdup(host);
649 if (git_use_proxy(host))
650 conn = git_proxy_connect(fd, host);
651 else
652 git_tcp_connect(fd, host, flags);
654 * Separate original protocol components prog and path
655 * from extended host header with a NUL byte.
657 * Note: Do not add any other headers here! Doing so
658 * will cause older git-daemon servers to crash.
660 packet_write(fd[1],
661 "%s %s%chost=%s%c",
662 prog, path, 0,
663 target_host, 0);
664 free(target_host);
665 free(url);
666 if (free_path)
667 free(path);
668 return conn;
671 conn = xcalloc(1, sizeof(*conn));
673 strbuf_init(&cmd, MAX_CMD_LEN);
674 strbuf_addstr(&cmd, prog);
675 strbuf_addch(&cmd, ' ');
676 sq_quote_buf(&cmd, path);
677 if (cmd.len >= MAX_CMD_LEN)
678 die("command line too long");
680 conn->in = conn->out = -1;
681 conn->argv = arg = xcalloc(7, sizeof(*arg));
682 if (protocol == PROTO_SSH) {
683 const char *ssh = getenv("GIT_SSH");
684 int putty = ssh && strcasestr(ssh, "plink");
685 if (!ssh) ssh = "ssh";
687 *arg++ = ssh;
688 if (putty && !strcasestr(ssh, "tortoiseplink"))
689 *arg++ = "-batch";
690 if (port) {
691 /* P is for PuTTY, p is for OpenSSH */
692 *arg++ = putty ? "-P" : "-p";
693 *arg++ = port;
695 *arg++ = host;
697 else {
698 /* remove repo-local variables from the environment */
699 conn->env = local_repo_env;
700 conn->use_shell = 1;
702 *arg++ = cmd.buf;
703 *arg = NULL;
705 if (start_command(conn))
706 die("unable to fork");
708 fd[0] = conn->out; /* read from child's stdout */
709 fd[1] = conn->in; /* write to child's stdin */
710 strbuf_release(&cmd);
711 free(url);
712 if (free_path)
713 free(path);
714 return conn;
717 int git_connection_is_socket(struct child_process *conn)
719 return conn == &no_fork;
722 int finish_connect(struct child_process *conn)
724 int code;
725 if (!conn || git_connection_is_socket(conn))
726 return 0;
728 code = finish_command(conn);
729 free(conn->argv);
730 free(conn);
731 return code;