Merge commit '520d7e278cfd25057e883575060b7378dfab61dc'
[git/mingw.git] / connect.c
blob26c5173636aebdf529514e408da52de1df5c36d0
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 "spawn-pipe.h"
9 static char *server_capabilities;
11 static int check_ref(const char *name, int len, unsigned int flags)
13 if (!flags)
14 return 1;
16 if (len < 5 || memcmp(name, "refs/", 5))
17 return 0;
19 /* Skip the "refs/" part */
20 name += 5;
21 len -= 5;
23 /* REF_NORMAL means that we don't want the magic fake tag refs */
24 if ((flags & REF_NORMAL) && check_ref_format(name) < 0)
25 return 0;
27 /* REF_HEADS means that we want regular branch heads */
28 if ((flags & REF_HEADS) && !memcmp(name, "heads/", 6))
29 return 1;
31 /* REF_TAGS means that we want tags */
32 if ((flags & REF_TAGS) && !memcmp(name, "tags/", 5))
33 return 1;
35 /* All type bits clear means that we are ok with anything */
36 return !(flags & ~REF_NORMAL);
40 * Read all the refs from the other end
42 struct ref **get_remote_heads(int in, struct ref **list,
43 int nr_match, char **match,
44 unsigned int flags)
46 *list = NULL;
47 for (;;) {
48 struct ref *ref;
49 unsigned char old_sha1[20];
50 static char buffer[1000];
51 char *name;
52 int len, name_len;
54 len = packet_read_line(in, buffer, sizeof(buffer));
55 if (!len)
56 break;
57 if (buffer[len-1] == '\n')
58 buffer[--len] = 0;
60 if (len < 42 || get_sha1_hex(buffer, old_sha1) || buffer[40] != ' ')
61 die("protocol error: expected sha/ref, got '%s'", buffer);
62 name = buffer + 41;
64 name_len = strlen(name);
65 if (len != name_len + 41) {
66 if (server_capabilities)
67 free(server_capabilities);
68 server_capabilities = xstrdup(name + name_len + 1);
71 if (!check_ref(name, name_len, flags))
72 continue;
73 if (nr_match && !path_match(name, nr_match, match))
74 continue;
75 ref = xcalloc(1, sizeof(*ref) + len - 40);
76 hashcpy(ref->old_sha1, old_sha1);
77 memcpy(ref->name, buffer + 41, len - 40);
78 *list = ref;
79 list = &ref->next;
81 return list;
84 int server_supports(const char *feature)
86 return server_capabilities &&
87 strstr(server_capabilities, feature) != NULL;
90 int get_ack(int fd, unsigned char *result_sha1)
92 static char line[1000];
93 int len = packet_read_line(fd, line, sizeof(line));
95 if (!len)
96 die("git-fetch-pack: expected ACK/NAK, got EOF");
97 if (line[len-1] == '\n')
98 line[--len] = 0;
99 if (!strcmp(line, "NAK"))
100 return 0;
101 if (!prefixcmp(line, "ACK ")) {
102 if (!get_sha1_hex(line+4, result_sha1)) {
103 if (strstr(line+45, "continue"))
104 return 2;
105 return 1;
108 die("git-fetch_pack: expected ACK/NAK, got '%s'", line);
111 int path_match(const char *path, int nr, char **match)
113 int i;
114 int pathlen = strlen(path);
116 for (i = 0; i < nr; i++) {
117 char *s = match[i];
118 int len = strlen(s);
120 if (!len || len > pathlen)
121 continue;
122 if (memcmp(path + pathlen - len, s, len))
123 continue;
124 if (pathlen > len && path[pathlen - len - 1] != '/')
125 continue;
126 *s = 0;
127 return (i + 1);
129 return 0;
132 struct refspec {
133 char *src;
134 char *dst;
135 char force;
139 * A:B means fast forward remote B with local A.
140 * +A:B means overwrite remote B with local A.
141 * +A is a shorthand for +A:A.
142 * A is a shorthand for A:A.
143 * :B means delete remote B.
145 static struct refspec *parse_ref_spec(int nr_refspec, char **refspec)
147 int i;
148 struct refspec *rs = xcalloc(sizeof(*rs), (nr_refspec + 1));
149 for (i = 0; i < nr_refspec; i++) {
150 char *sp, *dp, *ep;
151 sp = refspec[i];
152 if (*sp == '+') {
153 rs[i].force = 1;
154 sp++;
156 ep = strchr(sp, ':');
157 if (ep) {
158 dp = ep + 1;
159 *ep = 0;
161 else
162 dp = sp;
163 rs[i].src = sp;
164 rs[i].dst = dp;
166 rs[nr_refspec].src = rs[nr_refspec].dst = NULL;
167 return rs;
170 static int count_refspec_match(const char *pattern,
171 struct ref *refs,
172 struct ref **matched_ref)
174 int patlen = strlen(pattern);
175 struct ref *matched_weak = NULL;
176 struct ref *matched = NULL;
177 int weak_match = 0;
178 int match = 0;
180 for (weak_match = match = 0; refs; refs = refs->next) {
181 char *name = refs->name;
182 int namelen = strlen(name);
183 int weak_match;
185 if (namelen < patlen ||
186 memcmp(name + namelen - patlen, pattern, patlen))
187 continue;
188 if (namelen != patlen && name[namelen - patlen - 1] != '/')
189 continue;
191 /* A match is "weak" if it is with refs outside
192 * heads or tags, and did not specify the pattern
193 * in full (e.g. "refs/remotes/origin/master") or at
194 * least from the toplevel (e.g. "remotes/origin/master");
195 * otherwise "git push $URL master" would result in
196 * ambiguity between remotes/origin/master and heads/master
197 * at the remote site.
199 if (namelen != patlen &&
200 patlen != namelen - 5 &&
201 prefixcmp(name, "refs/heads/") &&
202 prefixcmp(name, "refs/tags/")) {
203 /* We want to catch the case where only weak
204 * matches are found and there are multiple
205 * matches, and where more than one strong
206 * matches are found, as ambiguous. One
207 * strong match with zero or more weak matches
208 * are acceptable as a unique match.
210 matched_weak = refs;
211 weak_match++;
213 else {
214 matched = refs;
215 match++;
218 if (!matched) {
219 *matched_ref = matched_weak;
220 return weak_match;
222 else {
223 *matched_ref = matched;
224 return match;
228 static void link_dst_tail(struct ref *ref, struct ref ***tail)
230 **tail = ref;
231 *tail = &ref->next;
232 **tail = NULL;
235 static struct ref *try_explicit_object_name(const char *name)
237 unsigned char sha1[20];
238 struct ref *ref;
239 int len;
241 if (!*name) {
242 ref = xcalloc(1, sizeof(*ref) + 20);
243 strcpy(ref->name, "(delete)");
244 hashclr(ref->new_sha1);
245 return ref;
247 if (get_sha1(name, sha1))
248 return NULL;
249 len = strlen(name) + 1;
250 ref = xcalloc(1, sizeof(*ref) + len);
251 memcpy(ref->name, name, len);
252 hashcpy(ref->new_sha1, sha1);
253 return ref;
256 static int match_explicit_refs(struct ref *src, struct ref *dst,
257 struct ref ***dst_tail, struct refspec *rs)
259 int i, errs;
260 for (i = errs = 0; rs[i].src; i++) {
261 struct ref *matched_src, *matched_dst;
263 matched_src = matched_dst = NULL;
264 switch (count_refspec_match(rs[i].src, src, &matched_src)) {
265 case 1:
266 break;
267 case 0:
268 /* The source could be in the get_sha1() format
269 * not a reference name. :refs/other is a
270 * way to delete 'other' ref at the remote end.
272 matched_src = try_explicit_object_name(rs[i].src);
273 if (matched_src)
274 break;
275 errs = 1;
276 error("src refspec %s does not match any.",
277 rs[i].src);
278 break;
279 default:
280 errs = 1;
281 error("src refspec %s matches more than one.",
282 rs[i].src);
283 break;
285 switch (count_refspec_match(rs[i].dst, dst, &matched_dst)) {
286 case 1:
287 break;
288 case 0:
289 if (!memcmp(rs[i].dst, "refs/", 5)) {
290 int len = strlen(rs[i].dst) + 1;
291 matched_dst = xcalloc(1, sizeof(*dst) + len);
292 memcpy(matched_dst->name, rs[i].dst, len);
293 link_dst_tail(matched_dst, dst_tail);
295 else if (!strcmp(rs[i].src, rs[i].dst) &&
296 matched_src) {
297 /* pushing "master:master" when
298 * remote does not have master yet.
300 int len = strlen(matched_src->name) + 1;
301 matched_dst = xcalloc(1, sizeof(*dst) + len);
302 memcpy(matched_dst->name, matched_src->name,
303 len);
304 link_dst_tail(matched_dst, dst_tail);
306 else {
307 errs = 1;
308 error("dst refspec %s does not match any "
309 "existing ref on the remote and does "
310 "not start with refs/.", rs[i].dst);
312 break;
313 default:
314 errs = 1;
315 error("dst refspec %s matches more than one.",
316 rs[i].dst);
317 break;
319 if (errs)
320 continue;
321 if (matched_dst->peer_ref) {
322 errs = 1;
323 error("dst ref %s receives from more than one src.",
324 matched_dst->name);
326 else {
327 matched_dst->peer_ref = matched_src;
328 matched_dst->force = rs[i].force;
331 return -errs;
334 static struct ref *find_ref_by_name(struct ref *list, const char *name)
336 for ( ; list; list = list->next)
337 if (!strcmp(list->name, name))
338 return list;
339 return NULL;
342 int match_refs(struct ref *src, struct ref *dst, struct ref ***dst_tail,
343 int nr_refspec, char **refspec, int all)
345 struct refspec *rs = parse_ref_spec(nr_refspec, refspec);
347 if (nr_refspec)
348 return match_explicit_refs(src, dst, dst_tail, rs);
350 /* pick the remainder */
351 for ( ; src; src = src->next) {
352 struct ref *dst_peer;
353 if (src->peer_ref)
354 continue;
355 dst_peer = find_ref_by_name(dst, src->name);
356 if ((dst_peer && dst_peer->peer_ref) || (!dst_peer && !all))
357 continue;
358 if (!dst_peer) {
359 /* Create a new one and link it */
360 int len = strlen(src->name) + 1;
361 dst_peer = xcalloc(1, sizeof(*dst_peer) + len);
362 memcpy(dst_peer->name, src->name, len);
363 hashcpy(dst_peer->new_sha1, src->new_sha1);
364 link_dst_tail(dst_peer, dst_tail);
366 dst_peer->peer_ref = src;
368 return 0;
371 enum protocol {
372 PROTO_LOCAL = 1,
373 PROTO_SSH,
374 PROTO_GIT,
377 static enum protocol get_protocol(const char *name)
379 if (!strcmp(name, "ssh"))
380 return PROTO_SSH;
381 if (!strcmp(name, "git"))
382 return PROTO_GIT;
383 if (!strcmp(name, "git+ssh"))
384 return PROTO_SSH;
385 if (!strcmp(name, "ssh+git"))
386 return PROTO_SSH;
387 die("I don't handle protocol '%s'", name);
390 #define STR_(s) # s
391 #define STR(s) STR_(s)
393 #ifndef NO_IPV6
396 * Returns a connected socket() fd, or else die()s.
398 static int git_tcp_connect_sock(char *host)
400 int sockfd = -1, saved_errno = 0;
401 char *colon, *end;
402 const char *port = STR(DEFAULT_GIT_PORT);
403 struct addrinfo hints, *ai0, *ai;
404 int gai;
406 if (host[0] == '[') {
407 end = strchr(host + 1, ']');
408 if (end) {
409 *end = 0;
410 end++;
411 host++;
412 } else
413 end = host;
414 } else
415 end = host;
416 colon = strchr(end, ':');
418 if (colon) {
419 *colon = 0;
420 port = colon + 1;
421 if (!*port)
422 port = "<none>";
425 memset(&hints, 0, sizeof(hints));
426 hints.ai_socktype = SOCK_STREAM;
427 hints.ai_protocol = IPPROTO_TCP;
429 gai = getaddrinfo(host, port, &hints, &ai);
430 if (gai)
431 die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
433 for (ai0 = ai; ai; ai = ai->ai_next) {
434 sockfd = socket(ai->ai_family,
435 ai->ai_socktype, ai->ai_protocol);
436 if (sockfd < 0) {
437 saved_errno = errno;
438 continue;
440 if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
441 saved_errno = errno;
442 close(sockfd);
443 sockfd = -1;
444 continue;
446 break;
449 freeaddrinfo(ai0);
451 if (sockfd < 0)
452 die("unable to connect a socket (%s)", strerror(saved_errno));
454 return sockfd;
457 #else /* NO_IPV6 */
460 * Returns a connected socket() fd, or else die()s.
462 static int git_tcp_connect_sock(char *host)
464 int sockfd = -1, saved_errno = 0;
465 char *colon, *end;
466 char *port = STR(DEFAULT_GIT_PORT), *ep;
467 struct hostent *he;
468 struct sockaddr_in sa;
469 char **ap;
470 unsigned int nport;
472 if (host[0] == '[') {
473 end = strchr(host + 1, ']');
474 if (end) {
475 *end = 0;
476 end++;
477 host++;
478 } else
479 end = host;
480 } else
481 end = host;
482 colon = strchr(end, ':');
484 if (colon) {
485 *colon = 0;
486 port = colon + 1;
489 he = gethostbyname(host);
490 if (!he)
491 die("Unable to look up %s (%s)", host, hstrerror(h_errno));
492 nport = strtoul(port, &ep, 10);
493 if ( ep == port || *ep ) {
494 /* Not numeric */
495 struct servent *se = getservbyname(port,"tcp");
496 if ( !se )
497 die("Unknown port %s\n", port);
498 nport = se->s_port;
501 for (ap = he->h_addr_list; *ap; ap++) {
502 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
503 if (sockfd < 0) {
504 saved_errno = errno;
505 continue;
508 memset(&sa, 0, sizeof sa);
509 sa.sin_family = he->h_addrtype;
510 sa.sin_port = htons(nport);
511 memcpy(&sa.sin_addr, *ap, he->h_length);
513 if (connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
514 saved_errno = errno;
515 close(sockfd);
516 sockfd = -1;
517 continue;
519 break;
522 if (sockfd < 0)
523 die("unable to connect a socket (%s)", strerror(saved_errno));
525 return sockfd;
528 #endif /* NO_IPV6 */
531 static void git_tcp_connect(int fd[2], char *host)
533 #ifndef __MINGW32__
534 int sockfd = git_tcp_connect_sock(host);
535 #else
536 int sockfd;
537 WSADATA wsa;
539 if (WSAStartup(MAKEWORD(2,2), &wsa))
540 die("unable to initialize winsock subsystem, error %d",
541 WSAGetLastError());
542 atexit((void(*)(void)) WSACleanup);
544 sockfd = git_tcp_connect_sock(host);
545 /* convert into a file descriptor */
546 if ((sockfd = _open_osfhandle(sockfd, O_RDWR|O_BINARY)) < 0)
547 die("unable to make a socket file descriptor: %s",
548 strerror(errno));
549 #endif
551 fd[0] = sockfd;
552 fd[1] = dup(sockfd);
556 static char *git_proxy_command;
557 static const char *rhost_name;
558 static int rhost_len;
560 static int git_proxy_command_options(const char *var, const char *value)
562 if (!strcmp(var, "core.gitproxy")) {
563 const char *for_pos;
564 int matchlen = -1;
565 int hostlen;
567 if (git_proxy_command)
568 return 0;
569 /* [core]
570 * ;# matches www.kernel.org as well
571 * gitproxy = netcatter-1 for kernel.org
572 * gitproxy = netcatter-2 for sample.xz
573 * gitproxy = netcatter-default
575 for_pos = strstr(value, " for ");
576 if (!for_pos)
577 /* matches everybody */
578 matchlen = strlen(value);
579 else {
580 hostlen = strlen(for_pos + 5);
581 if (rhost_len < hostlen)
582 matchlen = -1;
583 else if (!strncmp(for_pos + 5,
584 rhost_name + rhost_len - hostlen,
585 hostlen) &&
586 ((rhost_len == hostlen) ||
587 rhost_name[rhost_len - hostlen -1] == '.'))
588 matchlen = for_pos - value;
589 else
590 matchlen = -1;
592 if (0 <= matchlen) {
593 /* core.gitproxy = none for kernel.org */
594 if (matchlen == 4 &&
595 !memcmp(value, "none", 4))
596 matchlen = 0;
597 git_proxy_command = xmalloc(matchlen + 1);
598 memcpy(git_proxy_command, value, matchlen);
599 git_proxy_command[matchlen] = 0;
601 return 0;
604 return git_default_config(var, value);
607 static int git_use_proxy(const char *host)
609 rhost_name = host;
610 rhost_len = strlen(host);
611 git_proxy_command = getenv("GIT_PROXY_COMMAND");
612 git_config(git_proxy_command_options);
613 rhost_name = NULL;
614 return (git_proxy_command && *git_proxy_command);
617 static void git_proxy_connect(int fd[2], char *host)
619 const char *port = STR(DEFAULT_GIT_PORT);
620 char *colon, *end;
621 const char *argv[4];
622 struct child_process proxy;
624 if (host[0] == '[') {
625 end = strchr(host + 1, ']');
626 if (end) {
627 *end = 0;
628 end++;
629 host++;
630 } else
631 end = host;
632 } else
633 end = host;
634 colon = strchr(end, ':');
636 if (colon) {
637 *colon = 0;
638 port = colon + 1;
641 argv[0] = git_proxy_command;
642 argv[1] = host;
643 argv[2] = port;
644 argv[3] = NULL;
645 memset(&proxy, 0, sizeof(proxy));
646 proxy.argv = argv;
647 proxy.in = -1;
648 proxy.out = -1;
649 if (start_command(&proxy))
650 die("cannot start proxy %s", argv[0]);
651 fd[0] = proxy.out; /* read from proxy stdout */
652 fd[1] = proxy.in; /* write to proxy stdin */
655 #define MAX_CMD_LEN 1024
658 * This returns 0 if the transport protocol does not need fork(2),
659 * or a process id if it does. Once done, finish the connection
660 * with finish_connect() with the value returned from this function
661 * (it is safe to call finish_connect() with 0 to support the former
662 * case).
664 * Does not return a negative value on error; it just dies.
666 pid_t git_connect(int fd[2], char *url, const char *prog)
668 char *host, *path = url;
669 char *end;
670 int c;
671 int pipefd[2][2];
672 pid_t pid;
673 enum protocol protocol = PROTO_LOCAL;
674 int free_path = 0;
676 /* Without this we cannot rely on waitpid() to tell
677 * what happened to our children.
679 signal(SIGCHLD, SIG_DFL);
681 host = strstr(url, "://");
682 if(host) {
683 *host = '\0';
684 protocol = get_protocol(url);
685 host += 3;
686 c = '/';
687 } else {
688 host = url;
689 c = ':';
692 if (host[0] == '[') {
693 end = strchr(host + 1, ']');
694 if (end) {
695 *end = 0;
696 end++;
697 host++;
698 } else
699 end = host;
700 } else
701 end = host;
703 path = strchr(end, c);
704 if (c == ':') {
705 /* host must have at least 2 chars to catch DOS C:/path */
706 if (path && path - end > 1) {
707 protocol = PROTO_SSH;
708 *path++ = '\0';
709 } else
710 path = host;
713 if (!path || !*path)
714 die("No path specified. See 'man git-pull' for valid url syntax");
717 * null-terminate hostname and point path to ~ for URL's like this:
718 * ssh://host.xz/~user/repo
720 if (protocol != PROTO_LOCAL && host != url) {
721 char *ptr = path;
722 if (path[1] == '~')
723 path++;
724 else {
725 path = xstrdup(ptr);
726 free_path = 1;
729 *ptr = '\0';
732 if (protocol == PROTO_GIT) {
733 /* These underlying connection commands die() if they
734 * cannot connect.
736 char *target_host = xstrdup(host);
737 if (git_use_proxy(host))
738 git_proxy_connect(fd, host);
739 else
740 git_tcp_connect(fd, host);
742 * Separate original protocol components prog and path
743 * from extended components with a NUL byte.
745 packet_write(fd[1],
746 "%s %s%chost=%s%c",
747 prog, path, 0,
748 target_host, 0);
749 free(target_host);
750 if (free_path)
751 free(path);
752 return 0;
755 if (pipe(pipefd[0]) < 0 || pipe(pipefd[1]) < 0)
756 die("unable to create pipe pair for communication");
758 char command[MAX_CMD_LEN];
759 char *posn = command;
760 int size = MAX_CMD_LEN;
761 int of = 0;
763 of |= add_to_string(&posn, &size, prog, 0);
764 of |= add_to_string(&posn, &size, " ", 0);
765 of |= add_to_string(&posn, &size, path, 1);
767 if (of)
768 die("command line too long");
770 if (protocol == PROTO_SSH) {
771 const char *argv[] = { NULL, host, command, NULL };
772 const char *ssh = getenv("GIT_SSH");
773 if (!ssh) ssh = "ssh";
774 pid = spawnvpe_pipe(ssh, argv, environ, pipefd[1], pipefd[0]);
776 else {
777 const char *argv[] = { NULL, "-c", command, NULL };
778 const char **env = copy_environ();
779 env_unsetenv(env, ALTERNATE_DB_ENVIRONMENT);
780 env_unsetenv(env, DB_ENVIRONMENT);
781 env_unsetenv(env, GIT_DIR_ENVIRONMENT);
782 env_unsetenv(env, GRAFT_ENVIRONMENT);
783 env_unsetenv(env, INDEX_ENVIRONMENT);
784 pid = spawnvpe_pipe("sh", argv, env, pipefd[1], pipefd[0]);
786 if (pid < 0)
787 die("unable to fork");
788 fd[0] = pipefd[0][0];
789 fd[1] = pipefd[1][1];
790 if (free_path)
791 free(path);
792 return pid;
795 int finish_connect(pid_t pid)
797 if (pid == 0)
798 return 0;
800 while (waitpid(pid, NULL, 0) < 0) {
801 if (errno != EINTR)
802 return -1;
804 return 0;