README.MinGW: push works now locally and via ssh!
[git/mingw.git] / connect.c
blobd3964b80595893dc7a43998e2c7573ee5eebf44f
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 "spawn-pipe.h"
8 static char *server_capabilities;
10 static int check_ref(const char *name, int len, unsigned int flags)
12 if (!flags)
13 return 1;
15 if (len < 5 || memcmp(name, "refs/", 5))
16 return 0;
18 /* Skip the "refs/" part */
19 name += 5;
20 len -= 5;
22 /* REF_NORMAL means that we don't want the magic fake tag refs */
23 if ((flags & REF_NORMAL) && check_ref_format(name) < 0)
24 return 0;
26 /* REF_HEADS means that we want regular branch heads */
27 if ((flags & REF_HEADS) && !memcmp(name, "heads/", 6))
28 return 1;
30 /* REF_TAGS means that we want tags */
31 if ((flags & REF_TAGS) && !memcmp(name, "tags/", 5))
32 return 1;
34 /* All type bits clear means that we are ok with anything */
35 return !(flags & ~REF_NORMAL);
39 * Read all the refs from the other end
41 struct ref **get_remote_heads(int in, struct ref **list,
42 int nr_match, char **match,
43 unsigned int flags)
45 *list = NULL;
46 for (;;) {
47 struct ref *ref;
48 unsigned char old_sha1[20];
49 static char buffer[1000];
50 char *name;
51 int len, name_len;
53 len = packet_read_line(in, buffer, sizeof(buffer));
54 if (!len)
55 break;
56 if (buffer[len-1] == '\n')
57 buffer[--len] = 0;
59 if (len < 42 || get_sha1_hex(buffer, old_sha1) || buffer[40] != ' ')
60 die("protocol error: expected sha/ref, got '%s'", buffer);
61 name = buffer + 41;
63 name_len = strlen(name);
64 if (len != name_len + 41) {
65 if (server_capabilities)
66 free(server_capabilities);
67 server_capabilities = xstrdup(name + name_len + 1);
70 if (!check_ref(name, name_len, flags))
71 continue;
72 if (nr_match && !path_match(name, nr_match, match))
73 continue;
74 ref = xcalloc(1, sizeof(*ref) + len - 40);
75 hashcpy(ref->old_sha1, old_sha1);
76 memcpy(ref->name, buffer + 41, len - 40);
77 *list = ref;
78 list = &ref->next;
80 return list;
83 int server_supports(const char *feature)
85 return server_capabilities &&
86 strstr(server_capabilities, feature) != NULL;
89 int get_ack(int fd, unsigned char *result_sha1)
91 static char line[1000];
92 int len = packet_read_line(fd, line, sizeof(line));
94 if (!len)
95 die("git-fetch-pack: expected ACK/NAK, got EOF");
96 if (line[len-1] == '\n')
97 line[--len] = 0;
98 if (!strcmp(line, "NAK"))
99 return 0;
100 if (!strncmp(line, "ACK ", 4)) {
101 if (!get_sha1_hex(line+4, result_sha1)) {
102 if (strstr(line+45, "continue"))
103 return 2;
104 return 1;
107 die("git-fetch_pack: expected ACK/NAK, got '%s'", line);
110 int path_match(const char *path, int nr, char **match)
112 int i;
113 int pathlen = strlen(path);
115 for (i = 0; i < nr; i++) {
116 char *s = match[i];
117 int len = strlen(s);
119 if (!len || len > pathlen)
120 continue;
121 if (memcmp(path + pathlen - len, s, len))
122 continue;
123 if (pathlen > len && path[pathlen - len - 1] != '/')
124 continue;
125 *s = 0;
126 return (i + 1);
128 return 0;
131 struct refspec {
132 char *src;
133 char *dst;
134 char force;
138 * A:B means fast forward remote B with local A.
139 * +A:B means overwrite remote B with local A.
140 * +A is a shorthand for +A:A.
141 * A is a shorthand for A:A.
142 * :B means delete remote B.
144 static struct refspec *parse_ref_spec(int nr_refspec, char **refspec)
146 int i;
147 struct refspec *rs = xcalloc(sizeof(*rs), (nr_refspec + 1));
148 for (i = 0; i < nr_refspec; i++) {
149 char *sp, *dp, *ep;
150 sp = refspec[i];
151 if (*sp == '+') {
152 rs[i].force = 1;
153 sp++;
155 ep = strchr(sp, ':');
156 if (ep) {
157 dp = ep + 1;
158 *ep = 0;
160 else
161 dp = sp;
162 rs[i].src = sp;
163 rs[i].dst = dp;
165 rs[nr_refspec].src = rs[nr_refspec].dst = NULL;
166 return rs;
169 static int count_refspec_match(const char *pattern,
170 struct ref *refs,
171 struct ref **matched_ref)
173 int patlen = strlen(pattern);
174 struct ref *matched_weak = NULL;
175 struct ref *matched = NULL;
176 int weak_match = 0;
177 int match = 0;
179 for (weak_match = match = 0; refs; refs = refs->next) {
180 char *name = refs->name;
181 int namelen = strlen(name);
182 int weak_match;
184 if (namelen < patlen ||
185 memcmp(name + namelen - patlen, pattern, patlen))
186 continue;
187 if (namelen != patlen && name[namelen - patlen - 1] != '/')
188 continue;
190 /* A match is "weak" if it is with refs outside
191 * heads or tags, and did not specify the pattern
192 * in full (e.g. "refs/remotes/origin/master") or at
193 * least from the toplevel (e.g. "remotes/origin/master");
194 * otherwise "git push $URL master" would result in
195 * ambiguity between remotes/origin/master and heads/master
196 * at the remote site.
198 if (namelen != patlen &&
199 patlen != namelen - 5 &&
200 strncmp(name, "refs/heads/", 11) &&
201 strncmp(name, "refs/tags/", 10)) {
202 /* We want to catch the case where only weak
203 * matches are found and there are multiple
204 * matches, and where more than one strong
205 * matches are found, as ambiguous. One
206 * strong match with zero or more weak matches
207 * are acceptable as a unique match.
209 matched_weak = refs;
210 weak_match++;
212 else {
213 matched = refs;
214 match++;
217 if (!matched) {
218 *matched_ref = matched_weak;
219 return weak_match;
221 else {
222 *matched_ref = matched;
223 return match;
227 static void link_dst_tail(struct ref *ref, struct ref ***tail)
229 **tail = ref;
230 *tail = &ref->next;
231 **tail = NULL;
234 static struct ref *try_explicit_object_name(const char *name)
236 unsigned char sha1[20];
237 struct ref *ref;
238 int len;
240 if (!*name) {
241 ref = xcalloc(1, sizeof(*ref) + 20);
242 strcpy(ref->name, "(delete)");
243 hashclr(ref->new_sha1);
244 return ref;
246 if (get_sha1(name, sha1))
247 return NULL;
248 len = strlen(name) + 1;
249 ref = xcalloc(1, sizeof(*ref) + len);
250 memcpy(ref->name, name, len);
251 hashcpy(ref->new_sha1, sha1);
252 return ref;
255 static int match_explicit_refs(struct ref *src, struct ref *dst,
256 struct ref ***dst_tail, struct refspec *rs)
258 int i, errs;
259 for (i = errs = 0; rs[i].src; i++) {
260 struct ref *matched_src, *matched_dst;
262 matched_src = matched_dst = NULL;
263 switch (count_refspec_match(rs[i].src, src, &matched_src)) {
264 case 1:
265 break;
266 case 0:
267 /* The source could be in the get_sha1() format
268 * not a reference name. :refs/other is a
269 * way to delete 'other' ref at the remote end.
271 matched_src = try_explicit_object_name(rs[i].src);
272 if (matched_src)
273 break;
274 errs = 1;
275 error("src refspec %s does not match any.",
276 rs[i].src);
277 break;
278 default:
279 errs = 1;
280 error("src refspec %s matches more than one.",
281 rs[i].src);
282 break;
284 switch (count_refspec_match(rs[i].dst, dst, &matched_dst)) {
285 case 1:
286 break;
287 case 0:
288 if (!memcmp(rs[i].dst, "refs/", 5)) {
289 int len = strlen(rs[i].dst) + 1;
290 matched_dst = xcalloc(1, sizeof(*dst) + len);
291 memcpy(matched_dst->name, rs[i].dst, len);
292 link_dst_tail(matched_dst, dst_tail);
294 else if (!strcmp(rs[i].src, rs[i].dst) &&
295 matched_src) {
296 /* pushing "master:master" when
297 * remote does not have master yet.
299 int len = strlen(matched_src->name) + 1;
300 matched_dst = xcalloc(1, sizeof(*dst) + len);
301 memcpy(matched_dst->name, matched_src->name,
302 len);
303 link_dst_tail(matched_dst, dst_tail);
305 else {
306 errs = 1;
307 error("dst refspec %s does not match any "
308 "existing ref on the remote and does "
309 "not start with refs/.", rs[i].dst);
311 break;
312 default:
313 errs = 1;
314 error("dst refspec %s matches more than one.",
315 rs[i].dst);
316 break;
318 if (errs)
319 continue;
320 if (matched_dst->peer_ref) {
321 errs = 1;
322 error("dst ref %s receives from more than one src.",
323 matched_dst->name);
325 else {
326 matched_dst->peer_ref = matched_src;
327 matched_dst->force = rs[i].force;
330 return -errs;
333 static struct ref *find_ref_by_name(struct ref *list, const char *name)
335 for ( ; list; list = list->next)
336 if (!strcmp(list->name, name))
337 return list;
338 return NULL;
341 int match_refs(struct ref *src, struct ref *dst, struct ref ***dst_tail,
342 int nr_refspec, char **refspec, int all)
344 struct refspec *rs = parse_ref_spec(nr_refspec, refspec);
346 if (nr_refspec)
347 return match_explicit_refs(src, dst, dst_tail, rs);
349 /* pick the remainder */
350 for ( ; src; src = src->next) {
351 struct ref *dst_peer;
352 if (src->peer_ref)
353 continue;
354 dst_peer = find_ref_by_name(dst, src->name);
355 if ((dst_peer && dst_peer->peer_ref) || (!dst_peer && !all))
356 continue;
357 if (!dst_peer) {
358 /* Create a new one and link it */
359 int len = strlen(src->name) + 1;
360 dst_peer = xcalloc(1, sizeof(*dst_peer) + len);
361 memcpy(dst_peer->name, src->name, len);
362 hashcpy(dst_peer->new_sha1, src->new_sha1);
363 link_dst_tail(dst_peer, dst_tail);
365 dst_peer->peer_ref = src;
367 return 0;
370 enum protocol {
371 PROTO_LOCAL = 1,
372 PROTO_SSH,
373 PROTO_GIT,
376 static enum protocol get_protocol(const char *name)
378 if (!strcmp(name, "ssh"))
379 return PROTO_SSH;
380 if (!strcmp(name, "git"))
381 return PROTO_GIT;
382 if (!strcmp(name, "git+ssh"))
383 return PROTO_SSH;
384 if (!strcmp(name, "ssh+git"))
385 return PROTO_SSH;
386 die("I don't handle protocol '%s'", name);
389 #define STR_(s) # s
390 #define STR(s) STR_(s)
392 #ifndef NO_IPV6
395 * Returns a connected socket() fd, or else die()s.
397 static int git_tcp_connect_sock(char *host)
399 int sockfd = -1, saved_errno = 0;
400 char *colon, *end;
401 const char *port = STR(DEFAULT_GIT_PORT);
402 struct addrinfo hints, *ai0, *ai;
403 int gai;
405 if (host[0] == '[') {
406 end = strchr(host + 1, ']');
407 if (end) {
408 *end = 0;
409 end++;
410 host++;
411 } else
412 end = host;
413 } else
414 end = host;
415 colon = strchr(end, ':');
417 if (colon) {
418 *colon = 0;
419 port = colon + 1;
422 memset(&hints, 0, sizeof(hints));
423 hints.ai_socktype = SOCK_STREAM;
424 hints.ai_protocol = IPPROTO_TCP;
426 gai = getaddrinfo(host, port, &hints, &ai);
427 if (gai)
428 die("Unable to look up %s (%s)", host, gai_strerror(gai));
430 for (ai0 = ai; ai; ai = ai->ai_next) {
431 sockfd = socket(ai->ai_family,
432 ai->ai_socktype, ai->ai_protocol);
433 if (sockfd < 0) {
434 saved_errno = errno;
435 continue;
437 if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
438 saved_errno = errno;
439 close(sockfd);
440 sockfd = -1;
441 continue;
443 break;
446 freeaddrinfo(ai0);
448 if (sockfd < 0)
449 die("unable to connect a socket (%s)", strerror(saved_errno));
451 return sockfd;
454 #else /* NO_IPV6 */
457 * Returns a connected socket() fd, or else die()s.
459 static int git_tcp_connect_sock(char *host)
461 int sockfd = -1, saved_errno = 0;
462 char *colon, *end;
463 char *port = STR(DEFAULT_GIT_PORT), *ep;
464 struct hostent *he;
465 struct sockaddr_in sa;
466 char **ap;
467 unsigned int nport;
469 if (host[0] == '[') {
470 end = strchr(host + 1, ']');
471 if (end) {
472 *end = 0;
473 end++;
474 host++;
475 } else
476 end = host;
477 } else
478 end = host;
479 colon = strchr(end, ':');
481 if (colon) {
482 *colon = 0;
483 port = colon + 1;
486 he = gethostbyname(host);
487 if (!he)
488 die("Unable to look up %s (%s)", host, hstrerror(h_errno));
489 nport = strtoul(port, &ep, 10);
490 if ( ep == port || *ep ) {
491 /* Not numeric */
492 struct servent *se = getservbyname(port,"tcp");
493 if ( !se )
494 die("Unknown port %s\n", port);
495 nport = se->s_port;
498 for (ap = he->h_addr_list; *ap; ap++) {
499 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
500 if (sockfd < 0) {
501 saved_errno = errno;
502 continue;
505 memset(&sa, 0, sizeof sa);
506 sa.sin_family = he->h_addrtype;
507 sa.sin_port = htons(nport);
508 memcpy(&sa.sin_addr, *ap, he->h_length);
510 if (connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
511 saved_errno = errno;
512 close(sockfd);
513 sockfd = -1;
514 continue;
516 break;
519 if (sockfd < 0)
520 die("unable to connect a socket (%s)", strerror(saved_errno));
522 return sockfd;
525 #endif /* NO_IPV6 */
528 static void git_tcp_connect(int fd[2], char *host)
530 int sockfd = git_tcp_connect_sock(host);
532 fd[0] = sockfd;
533 fd[1] = sockfd;
537 static char *git_proxy_command;
538 static const char *rhost_name;
539 static int rhost_len;
541 static int git_proxy_command_options(const char *var, const char *value)
543 if (!strcmp(var, "core.gitproxy")) {
544 const char *for_pos;
545 int matchlen = -1;
546 int hostlen;
548 if (git_proxy_command)
549 return 0;
550 /* [core]
551 * ;# matches www.kernel.org as well
552 * gitproxy = netcatter-1 for kernel.org
553 * gitproxy = netcatter-2 for sample.xz
554 * gitproxy = netcatter-default
556 for_pos = strstr(value, " for ");
557 if (!for_pos)
558 /* matches everybody */
559 matchlen = strlen(value);
560 else {
561 hostlen = strlen(for_pos + 5);
562 if (rhost_len < hostlen)
563 matchlen = -1;
564 else if (!strncmp(for_pos + 5,
565 rhost_name + rhost_len - hostlen,
566 hostlen) &&
567 ((rhost_len == hostlen) ||
568 rhost_name[rhost_len - hostlen -1] == '.'))
569 matchlen = for_pos - value;
570 else
571 matchlen = -1;
573 if (0 <= matchlen) {
574 /* core.gitproxy = none for kernel.org */
575 if (matchlen == 4 &&
576 !memcmp(value, "none", 4))
577 matchlen = 0;
578 git_proxy_command = xmalloc(matchlen + 1);
579 memcpy(git_proxy_command, value, matchlen);
580 git_proxy_command[matchlen] = 0;
582 return 0;
585 return git_default_config(var, value);
588 static int git_use_proxy(const char *host)
590 rhost_name = host;
591 rhost_len = strlen(host);
592 git_proxy_command = getenv("GIT_PROXY_COMMAND");
593 git_config(git_proxy_command_options);
594 rhost_name = NULL;
595 return (git_proxy_command && *git_proxy_command);
598 static void git_proxy_connect(int fd[2], char *host)
600 const char *port = STR(DEFAULT_GIT_PORT);
601 char *colon, *end;
602 int pipefd[2][2];
603 pid_t pid;
605 if (host[0] == '[') {
606 end = strchr(host + 1, ']');
607 if (end) {
608 *end = 0;
609 end++;
610 host++;
611 } else
612 end = host;
613 } else
614 end = host;
615 colon = strchr(end, ':');
617 if (colon) {
618 *colon = 0;
619 port = colon + 1;
622 if (pipe(pipefd[0]) < 0 || pipe(pipefd[1]) < 0)
623 die("unable to create pipe pair for communication");
626 const char *argv[] = { NULL, host, port, NULL };
627 spawnvpe_pipe(git_proxy_command, argv, environ, pipefd[1], pipefd[0]);
629 fd[0] = pipefd[0][0];
630 fd[1] = pipefd[1][1];
633 #define MAX_CMD_LEN 1024
636 * This returns 0 if the transport protocol does not need fork(2),
637 * or a process id if it does. Once done, finish the connection
638 * with finish_connect() with the value returned from this function
639 * (it is safe to call finish_connect() with 0 to support the former
640 * case).
642 * Does not return a negative value on error; it just dies.
644 pid_t git_connect(int fd[2], char *url, const char *prog)
646 char *host, *path = url;
647 char *end;
648 int c;
649 int pipefd[2][2];
650 pid_t pid;
651 enum protocol protocol = PROTO_LOCAL;
652 int free_path = 0;
654 /* Without this we cannot rely on waitpid() to tell
655 * what happened to our children.
657 signal(SIGCHLD, SIG_DFL);
659 host = strstr(url, "://");
660 if(host) {
661 *host = '\0';
662 protocol = get_protocol(url);
663 host += 3;
664 c = '/';
665 } else {
666 host = url;
667 c = ':';
670 if (host[0] == '[') {
671 end = strchr(host + 1, ']');
672 if (end) {
673 *end = 0;
674 end++;
675 host++;
676 } else
677 end = host;
678 } else
679 end = host;
681 path = strchr(end, c);
682 if (c == ':') {
683 /* host must have at least 2 chars to catch DOS C:/path */
684 if (path && path - end > 1) {
685 protocol = PROTO_SSH;
686 *path++ = '\0';
687 } else
688 path = host;
691 if (!path || !*path)
692 die("No path specified. See 'man git-pull' for valid url syntax");
695 * null-terminate hostname and point path to ~ for URL's like this:
696 * ssh://host.xz/~user/repo
698 if (protocol != PROTO_LOCAL && host != url) {
699 char *ptr = path;
700 if (path[1] == '~')
701 path++;
702 else {
703 path = xstrdup(ptr);
704 free_path = 1;
707 *ptr = '\0';
710 if (protocol == PROTO_GIT) {
711 /* These underlying connection commands die() if they
712 * cannot connect.
714 char *target_host = xstrdup(host);
715 if (git_use_proxy(host))
716 git_proxy_connect(fd, host);
717 else
718 git_tcp_connect(fd, host);
720 * Separate original protocol components prog and path
721 * from extended components with a NUL byte.
723 packet_write(fd[1],
724 "%s %s%chost=%s%c",
725 prog, path, 0,
726 target_host, 0);
727 free(target_host);
728 if (free_path)
729 free(path);
730 return 0;
733 if (pipe(pipefd[0]) < 0 || pipe(pipefd[1]) < 0)
734 die("unable to create pipe pair for communication");
736 char command[MAX_CMD_LEN];
737 char *posn = command;
738 int size = MAX_CMD_LEN;
739 int of = 0;
741 of |= add_to_string(&posn, &size, prog, 0);
742 of |= add_to_string(&posn, &size, " ", 0);
743 of |= add_to_string(&posn, &size, path, 1);
745 if (of)
746 die("command line too long");
748 if (protocol == PROTO_SSH) {
749 const char *argv[] = { NULL, host, command, NULL };
750 const char *ssh = getenv("GIT_SSH");
751 if (!ssh) ssh = "ssh";
752 pid = spawnvpe_pipe(ssh, argv, environ, pipefd[1], pipefd[0]);
754 else {
755 const char *argv[] = { NULL, "-c", command, NULL };
756 const char **env = copy_environ();
757 env_unsetenv(env, ALTERNATE_DB_ENVIRONMENT);
758 env_unsetenv(env, DB_ENVIRONMENT);
759 env_unsetenv(env, GIT_DIR_ENVIRONMENT);
760 env_unsetenv(env, GRAFT_ENVIRONMENT);
761 env_unsetenv(env, INDEX_ENVIRONMENT);
762 pid = spawnvpe_pipe("sh", argv, env, pipefd[1], pipefd[0]);
764 fd[0] = pipefd[0][0];
765 fd[1] = pipefd[1][1];
766 if (free_path)
767 free(path);
768 return pid;
771 int finish_connect(pid_t pid)
773 if (pid == 0)
774 return 0;
776 while (waitpid(pid, NULL, 0) < 0) {
777 if (errno != EINTR)
778 return -1;
780 return 0;