connect: pass full packet reader when parsing v2 refs
[git.git] / connect.c
blob1d05bc56eda2e61af069bd8200f6e1a9f082be3f
1 #include "git-compat-util.h"
2 #include "cache.h"
3 #include "config.h"
4 #include "pkt-line.h"
5 #include "quote.h"
6 #include "refs.h"
7 #include "run-command.h"
8 #include "remote.h"
9 #include "connect.h"
10 #include "url.h"
11 #include "string-list.h"
12 #include "oid-array.h"
13 #include "transport.h"
14 #include "strbuf.h"
15 #include "version.h"
16 #include "protocol.h"
17 #include "alias.h"
19 static char *server_capabilities_v1;
20 static struct argv_array server_capabilities_v2 = ARGV_ARRAY_INIT;
21 static const char *next_server_feature_value(const char *feature, int *len, int *offset);
23 static int check_ref(const char *name, unsigned int flags)
25 if (!flags)
26 return 1;
28 if (!skip_prefix(name, "refs/", &name))
29 return 0;
31 /* REF_NORMAL means that we don't want the magic fake tag refs */
32 if ((flags & REF_NORMAL) && check_refname_format(name, 0))
33 return 0;
35 /* REF_HEADS means that we want regular branch heads */
36 if ((flags & REF_HEADS) && starts_with(name, "heads/"))
37 return 1;
39 /* REF_TAGS means that we want tags */
40 if ((flags & REF_TAGS) && starts_with(name, "tags/"))
41 return 1;
43 /* All type bits clear means that we are ok with anything */
44 return !(flags & ~REF_NORMAL);
47 int check_ref_type(const struct ref *ref, int flags)
49 return check_ref(ref->name, flags);
52 static NORETURN void die_initial_contact(int unexpected)
55 * A hang-up after seeing some response from the other end
56 * means that it is unexpected, as we know the other end is
57 * willing to talk to us. A hang-up before seeing any
58 * response does not necessarily mean an ACL problem, though.
60 if (unexpected)
61 die(_("the remote end hung up upon initial contact"));
62 else
63 die(_("Could not read from remote repository.\n\n"
64 "Please make sure you have the correct access rights\n"
65 "and the repository exists."));
68 /* Checks if the server supports the capability 'c' */
69 int server_supports_v2(const char *c, int die_on_error)
71 int i;
73 for (i = 0; i < server_capabilities_v2.argc; i++) {
74 const char *out;
75 if (skip_prefix(server_capabilities_v2.argv[i], c, &out) &&
76 (!*out || *out == '='))
77 return 1;
80 if (die_on_error)
81 die(_("server doesn't support '%s'"), c);
83 return 0;
86 int server_feature_v2(const char *c, const char **v)
88 int i;
90 for (i = 0; i < server_capabilities_v2.argc; i++) {
91 const char *out;
92 if (skip_prefix(server_capabilities_v2.argv[i], c, &out) &&
93 (*out == '=')) {
94 *v = out + 1;
95 return 1;
98 return 0;
101 int server_supports_feature(const char *c, const char *feature,
102 int die_on_error)
104 int i;
106 for (i = 0; i < server_capabilities_v2.argc; i++) {
107 const char *out;
108 if (skip_prefix(server_capabilities_v2.argv[i], c, &out) &&
109 (!*out || *(out++) == '=')) {
110 if (parse_feature_request(out, feature))
111 return 1;
112 else
113 break;
117 if (die_on_error)
118 die(_("server doesn't support feature '%s'"), feature);
120 return 0;
123 static void process_capabilities_v2(struct packet_reader *reader)
125 while (packet_reader_read(reader) == PACKET_READ_NORMAL)
126 argv_array_push(&server_capabilities_v2, reader->line);
128 if (reader->status != PACKET_READ_FLUSH)
129 die(_("expected flush after capabilities"));
132 enum protocol_version discover_version(struct packet_reader *reader)
134 enum protocol_version version = protocol_unknown_version;
137 * Peek the first line of the server's response to
138 * determine the protocol version the server is speaking.
140 switch (packet_reader_peek(reader)) {
141 case PACKET_READ_EOF:
142 die_initial_contact(0);
143 case PACKET_READ_FLUSH:
144 case PACKET_READ_DELIM:
145 version = protocol_v0;
146 break;
147 case PACKET_READ_NORMAL:
148 version = determine_protocol_version_client(reader->line);
149 break;
152 switch (version) {
153 case protocol_v2:
154 process_capabilities_v2(reader);
155 break;
156 case protocol_v1:
157 /* Read the peeked version line */
158 packet_reader_read(reader);
159 break;
160 case protocol_v0:
161 break;
162 case protocol_unknown_version:
163 BUG("unknown protocol version");
166 return version;
169 static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
171 char *sym, *target;
172 struct string_list_item *item;
174 if (!len)
175 return; /* just "symref" */
176 /* e.g. "symref=HEAD:refs/heads/master" */
177 sym = xmemdupz(val, len);
178 target = strchr(sym, ':');
179 if (!target)
180 /* just "symref=something" */
181 goto reject;
182 *(target++) = '\0';
183 if (check_refname_format(sym, REFNAME_ALLOW_ONELEVEL) ||
184 check_refname_format(target, REFNAME_ALLOW_ONELEVEL))
185 /* "symref=bogus:pair */
186 goto reject;
187 item = string_list_append_nodup(symref, sym);
188 item->util = target;
189 return;
190 reject:
191 free(sym);
192 return;
195 static void annotate_refs_with_symref_info(struct ref *ref)
197 struct string_list symref = STRING_LIST_INIT_DUP;
198 int offset = 0;
200 while (1) {
201 int len;
202 const char *val;
204 val = next_server_feature_value("symref", &len, &offset);
205 if (!val)
206 break;
207 parse_one_symref_info(&symref, val, len);
209 string_list_sort(&symref);
211 for (; ref; ref = ref->next) {
212 struct string_list_item *item;
213 item = string_list_lookup(&symref, ref->name);
214 if (!item)
215 continue;
216 ref->symref = xstrdup((char *)item->util);
218 string_list_clear(&symref, 0);
221 static void process_capabilities(struct packet_reader *reader, int *linelen)
223 const char *feat_val;
224 int feat_len;
225 const char *line = reader->line;
226 int nul_location = strlen(line);
227 if (nul_location == *linelen)
228 return;
229 server_capabilities_v1 = xstrdup(line + nul_location + 1);
230 *linelen = nul_location;
232 feat_val = server_feature_value("object-format", &feat_len);
233 if (feat_val) {
234 char *hash_name = xstrndup(feat_val, feat_len);
235 int hash_algo = hash_algo_by_name(hash_name);
236 if (hash_algo != GIT_HASH_UNKNOWN)
237 reader->hash_algo = &hash_algos[hash_algo];
238 free(hash_name);
239 } else {
240 reader->hash_algo = &hash_algos[GIT_HASH_SHA1];
244 static int process_dummy_ref(const struct packet_reader *reader)
246 const char *line = reader->line;
247 struct object_id oid;
248 const char *name;
250 if (parse_oid_hex_algop(line, &oid, &name, reader->hash_algo))
251 return 0;
252 if (*name != ' ')
253 return 0;
254 name++;
256 return oideq(&null_oid, &oid) && !strcmp(name, "capabilities^{}");
259 static void check_no_capabilities(const char *line, int len)
261 if (strlen(line) != len)
262 warning(_("ignoring capabilities after first line '%s'"),
263 line + strlen(line));
266 static int process_ref(const struct packet_reader *reader, int len,
267 struct ref ***list, unsigned int flags,
268 struct oid_array *extra_have)
270 const char *line = reader->line;
271 struct object_id old_oid;
272 const char *name;
274 if (parse_oid_hex_algop(line, &old_oid, &name, reader->hash_algo))
275 return 0;
276 if (*name != ' ')
277 return 0;
278 name++;
280 if (extra_have && !strcmp(name, ".have")) {
281 oid_array_append(extra_have, &old_oid);
282 } else if (!strcmp(name, "capabilities^{}")) {
283 die(_("protocol error: unexpected capabilities^{}"));
284 } else if (check_ref(name, flags)) {
285 struct ref *ref = alloc_ref(name);
286 memcpy(ref->old_oid.hash, old_oid.hash, reader->hash_algo->rawsz);
287 **list = ref;
288 *list = &ref->next;
290 check_no_capabilities(line, len);
291 return 1;
294 static int process_shallow(const struct packet_reader *reader, int len,
295 struct oid_array *shallow_points)
297 const char *line = reader->line;
298 const char *arg;
299 struct object_id old_oid;
301 if (!skip_prefix(line, "shallow ", &arg))
302 return 0;
304 if (get_oid_hex_algop(arg, &old_oid, reader->hash_algo))
305 die(_("protocol error: expected shallow sha-1, got '%s'"), arg);
306 if (!shallow_points)
307 die(_("repository on the other end cannot be shallow"));
308 oid_array_append(shallow_points, &old_oid);
309 check_no_capabilities(line, len);
310 return 1;
313 enum get_remote_heads_state {
314 EXPECTING_FIRST_REF = 0,
315 EXPECTING_REF,
316 EXPECTING_SHALLOW,
317 EXPECTING_DONE,
321 * Read all the refs from the other end
323 struct ref **get_remote_heads(struct packet_reader *reader,
324 struct ref **list, unsigned int flags,
325 struct oid_array *extra_have,
326 struct oid_array *shallow_points)
328 struct ref **orig_list = list;
329 int len = 0;
330 enum get_remote_heads_state state = EXPECTING_FIRST_REF;
332 *list = NULL;
334 while (state != EXPECTING_DONE) {
335 switch (packet_reader_read(reader)) {
336 case PACKET_READ_EOF:
337 die_initial_contact(1);
338 case PACKET_READ_NORMAL:
339 len = reader->pktlen;
340 break;
341 case PACKET_READ_FLUSH:
342 state = EXPECTING_DONE;
343 break;
344 case PACKET_READ_DELIM:
345 die(_("invalid packet"));
348 switch (state) {
349 case EXPECTING_FIRST_REF:
350 process_capabilities(reader, &len);
351 if (process_dummy_ref(reader)) {
352 state = EXPECTING_SHALLOW;
353 break;
355 state = EXPECTING_REF;
356 /* fallthrough */
357 case EXPECTING_REF:
358 if (process_ref(reader, len, &list, flags, extra_have))
359 break;
360 state = EXPECTING_SHALLOW;
361 /* fallthrough */
362 case EXPECTING_SHALLOW:
363 if (process_shallow(reader, len, shallow_points))
364 break;
365 die(_("protocol error: unexpected '%s'"), reader->line);
366 case EXPECTING_DONE:
367 break;
371 annotate_refs_with_symref_info(*orig_list);
373 return list;
376 /* Returns 1 when a valid ref has been added to `list`, 0 otherwise */
377 static int process_ref_v2(struct packet_reader *reader, struct ref ***list)
379 int ret = 1;
380 int i = 0;
381 struct object_id old_oid;
382 struct ref *ref;
383 struct string_list line_sections = STRING_LIST_INIT_DUP;
384 const char *end;
385 const char *line = reader->line;
388 * Ref lines have a number of fields which are space deliminated. The
389 * first field is the OID of the ref. The second field is the ref
390 * name. Subsequent fields (symref-target and peeled) are optional and
391 * don't have a particular order.
393 if (string_list_split(&line_sections, line, ' ', -1) < 2) {
394 ret = 0;
395 goto out;
398 if (parse_oid_hex(line_sections.items[i++].string, &old_oid, &end) ||
399 *end) {
400 ret = 0;
401 goto out;
404 ref = alloc_ref(line_sections.items[i++].string);
406 oidcpy(&ref->old_oid, &old_oid);
407 **list = ref;
408 *list = &ref->next;
410 for (; i < line_sections.nr; i++) {
411 const char *arg = line_sections.items[i].string;
412 if (skip_prefix(arg, "symref-target:", &arg))
413 ref->symref = xstrdup(arg);
415 if (skip_prefix(arg, "peeled:", &arg)) {
416 struct object_id peeled_oid;
417 char *peeled_name;
418 struct ref *peeled;
419 if (parse_oid_hex(arg, &peeled_oid, &end) || *end) {
420 ret = 0;
421 goto out;
424 peeled_name = xstrfmt("%s^{}", ref->name);
425 peeled = alloc_ref(peeled_name);
427 oidcpy(&peeled->old_oid, &peeled_oid);
428 **list = peeled;
429 *list = &peeled->next;
431 free(peeled_name);
435 out:
436 string_list_clear(&line_sections, 0);
437 return ret;
440 struct ref **get_remote_refs(int fd_out, struct packet_reader *reader,
441 struct ref **list, int for_push,
442 const struct argv_array *ref_prefixes,
443 const struct string_list *server_options)
445 int i;
446 *list = NULL;
448 if (server_supports_v2("ls-refs", 1))
449 packet_write_fmt(fd_out, "command=ls-refs\n");
451 if (server_supports_v2("agent", 0))
452 packet_write_fmt(fd_out, "agent=%s", git_user_agent_sanitized());
454 if (server_options && server_options->nr &&
455 server_supports_v2("server-option", 1))
456 for (i = 0; i < server_options->nr; i++)
457 packet_write_fmt(fd_out, "server-option=%s",
458 server_options->items[i].string);
460 packet_delim(fd_out);
461 /* When pushing we don't want to request the peeled tags */
462 if (!for_push)
463 packet_write_fmt(fd_out, "peel\n");
464 packet_write_fmt(fd_out, "symrefs\n");
465 for (i = 0; ref_prefixes && i < ref_prefixes->argc; i++) {
466 packet_write_fmt(fd_out, "ref-prefix %s\n",
467 ref_prefixes->argv[i]);
469 packet_flush(fd_out);
471 /* Process response from server */
472 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
473 if (!process_ref_v2(reader, &list))
474 die(_("invalid ls-refs response: %s"), reader->line);
477 if (reader->status != PACKET_READ_FLUSH)
478 die(_("expected flush after ref listing"));
480 return list;
483 const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp, int *offset)
485 int len;
487 if (!feature_list)
488 return NULL;
490 len = strlen(feature);
491 if (offset)
492 feature_list += *offset;
493 while (*feature_list) {
494 const char *found = strstr(feature_list, feature);
495 if (!found)
496 return NULL;
497 if (feature_list == found || isspace(found[-1])) {
498 const char *value = found + len;
499 /* feature with no value (e.g., "thin-pack") */
500 if (!*value || isspace(*value)) {
501 if (lenp)
502 *lenp = 0;
503 return value;
505 /* feature with a value (e.g., "agent=git/1.2.3") */
506 else if (*value == '=') {
507 int end;
509 value++;
510 end = strcspn(value, " \t\n");
511 if (lenp)
512 *lenp = end;
513 if (offset)
514 *offset = value + end - feature_list;
515 return value;
518 * otherwise we matched a substring of another feature;
519 * keep looking
522 feature_list = found + 1;
524 return NULL;
527 int server_supports_hash(const char *desired, int *feature_supported)
529 int offset = 0;
530 int len;
531 const char *hash;
533 hash = next_server_feature_value("object-format", &len, &offset);
534 if (feature_supported)
535 *feature_supported = !!hash;
536 if (!hash) {
537 hash = hash_algos[GIT_HASH_SHA1].name;
538 len = strlen(hash);
540 while (hash) {
541 if (!xstrncmpz(desired, hash, len))
542 return 1;
544 hash = next_server_feature_value("object-format", &len, &offset);
546 return 0;
549 int parse_feature_request(const char *feature_list, const char *feature)
551 return !!parse_feature_value(feature_list, feature, NULL, NULL);
554 static const char *next_server_feature_value(const char *feature, int *len, int *offset)
556 return parse_feature_value(server_capabilities_v1, feature, len, offset);
559 const char *server_feature_value(const char *feature, int *len)
561 return parse_feature_value(server_capabilities_v1, feature, len, NULL);
564 int server_supports(const char *feature)
566 return !!server_feature_value(feature, NULL);
569 enum protocol {
570 PROTO_LOCAL = 1,
571 PROTO_FILE,
572 PROTO_SSH,
573 PROTO_GIT
576 int url_is_local_not_ssh(const char *url)
578 const char *colon = strchr(url, ':');
579 const char *slash = strchr(url, '/');
580 return !colon || (slash && slash < colon) ||
581 (has_dos_drive_prefix(url) && is_valid_path(url));
584 static const char *prot_name(enum protocol protocol)
586 switch (protocol) {
587 case PROTO_LOCAL:
588 case PROTO_FILE:
589 return "file";
590 case PROTO_SSH:
591 return "ssh";
592 case PROTO_GIT:
593 return "git";
594 default:
595 return "unknown protocol";
599 static enum protocol get_protocol(const char *name)
601 if (!strcmp(name, "ssh"))
602 return PROTO_SSH;
603 if (!strcmp(name, "git"))
604 return PROTO_GIT;
605 if (!strcmp(name, "git+ssh")) /* deprecated - do not use */
606 return PROTO_SSH;
607 if (!strcmp(name, "ssh+git")) /* deprecated - do not use */
608 return PROTO_SSH;
609 if (!strcmp(name, "file"))
610 return PROTO_FILE;
611 die(_("protocol '%s' is not supported"), name);
614 static char *host_end(char **hoststart, int removebrackets)
616 char *host = *hoststart;
617 char *end;
618 char *start = strstr(host, "@[");
619 if (start)
620 start++; /* Jump over '@' */
621 else
622 start = host;
623 if (start[0] == '[') {
624 end = strchr(start + 1, ']');
625 if (end) {
626 if (removebrackets) {
627 *end = 0;
628 memmove(start, start + 1, end - start);
629 end++;
631 } else
632 end = host;
633 } else
634 end = host;
635 return end;
638 #define STR_(s) # s
639 #define STR(s) STR_(s)
641 static void get_host_and_port(char **host, const char **port)
643 char *colon, *end;
644 end = host_end(host, 1);
645 colon = strchr(end, ':');
646 if (colon) {
647 long portnr = strtol(colon + 1, &end, 10);
648 if (end != colon + 1 && *end == '\0' && 0 <= portnr && portnr < 65536) {
649 *colon = 0;
650 *port = colon + 1;
651 } else if (!colon[1]) {
652 *colon = 0;
657 static void enable_keepalive(int sockfd)
659 int ka = 1;
661 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
662 error_errno(_("unable to set SO_KEEPALIVE on socket"));
665 #ifndef NO_IPV6
667 static const char *ai_name(const struct addrinfo *ai)
669 static char addr[NI_MAXHOST];
670 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
671 NI_NUMERICHOST) != 0)
672 xsnprintf(addr, sizeof(addr), "(unknown)");
674 return addr;
678 * Returns a connected socket() fd, or else die()s.
680 static int git_tcp_connect_sock(char *host, int flags)
682 struct strbuf error_message = STRBUF_INIT;
683 int sockfd = -1;
684 const char *port = STR(DEFAULT_GIT_PORT);
685 struct addrinfo hints, *ai0, *ai;
686 int gai;
687 int cnt = 0;
689 get_host_and_port(&host, &port);
690 if (!*port)
691 port = "<none>";
693 memset(&hints, 0, sizeof(hints));
694 if (flags & CONNECT_IPV4)
695 hints.ai_family = AF_INET;
696 else if (flags & CONNECT_IPV6)
697 hints.ai_family = AF_INET6;
698 hints.ai_socktype = SOCK_STREAM;
699 hints.ai_protocol = IPPROTO_TCP;
701 if (flags & CONNECT_VERBOSE)
702 fprintf(stderr, _("Looking up %s ... "), host);
704 gai = getaddrinfo(host, port, &hints, &ai);
705 if (gai)
706 die(_("unable to look up %s (port %s) (%s)"), host, port, gai_strerror(gai));
708 if (flags & CONNECT_VERBOSE)
709 /* TRANSLATORS: this is the end of "Looking up %s ... " */
710 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
712 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
713 sockfd = socket(ai->ai_family,
714 ai->ai_socktype, ai->ai_protocol);
715 if ((sockfd < 0) ||
716 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
717 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
718 host, cnt, ai_name(ai), strerror(errno));
719 if (0 <= sockfd)
720 close(sockfd);
721 sockfd = -1;
722 continue;
724 if (flags & CONNECT_VERBOSE)
725 fprintf(stderr, "%s ", ai_name(ai));
726 break;
729 freeaddrinfo(ai0);
731 if (sockfd < 0)
732 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
734 enable_keepalive(sockfd);
736 if (flags & CONNECT_VERBOSE)
737 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
738 fprintf_ln(stderr, _("done."));
740 strbuf_release(&error_message);
742 return sockfd;
745 #else /* NO_IPV6 */
748 * Returns a connected socket() fd, or else die()s.
750 static int git_tcp_connect_sock(char *host, int flags)
752 struct strbuf error_message = STRBUF_INIT;
753 int sockfd = -1;
754 const char *port = STR(DEFAULT_GIT_PORT);
755 char *ep;
756 struct hostent *he;
757 struct sockaddr_in sa;
758 char **ap;
759 unsigned int nport;
760 int cnt;
762 get_host_and_port(&host, &port);
764 if (flags & CONNECT_VERBOSE)
765 fprintf(stderr, _("Looking up %s ... "), host);
767 he = gethostbyname(host);
768 if (!he)
769 die(_("unable to look up %s (%s)"), host, hstrerror(h_errno));
770 nport = strtoul(port, &ep, 10);
771 if ( ep == port || *ep ) {
772 /* Not numeric */
773 struct servent *se = getservbyname(port,"tcp");
774 if ( !se )
775 die(_("unknown port %s"), port);
776 nport = se->s_port;
779 if (flags & CONNECT_VERBOSE)
780 /* TRANSLATORS: this is the end of "Looking up %s ... " */
781 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
783 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
784 memset(&sa, 0, sizeof sa);
785 sa.sin_family = he->h_addrtype;
786 sa.sin_port = htons(nport);
787 memcpy(&sa.sin_addr, *ap, he->h_length);
789 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
790 if ((sockfd < 0) ||
791 connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
792 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
793 host,
794 cnt,
795 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
796 strerror(errno));
797 if (0 <= sockfd)
798 close(sockfd);
799 sockfd = -1;
800 continue;
802 if (flags & CONNECT_VERBOSE)
803 fprintf(stderr, "%s ",
804 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
805 break;
808 if (sockfd < 0)
809 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
811 enable_keepalive(sockfd);
813 if (flags & CONNECT_VERBOSE)
814 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
815 fprintf_ln(stderr, _("done."));
817 return sockfd;
820 #endif /* NO_IPV6 */
824 * Dummy child_process returned by git_connect() if the transport protocol
825 * does not need fork(2).
827 static struct child_process no_fork = CHILD_PROCESS_INIT;
829 int git_connection_is_socket(struct child_process *conn)
831 return conn == &no_fork;
834 static struct child_process *git_tcp_connect(int fd[2], char *host, int flags)
836 int sockfd = git_tcp_connect_sock(host, flags);
838 fd[0] = sockfd;
839 fd[1] = dup(sockfd);
841 return &no_fork;
845 static char *git_proxy_command;
847 static int git_proxy_command_options(const char *var, const char *value,
848 void *cb)
850 if (!strcmp(var, "core.gitproxy")) {
851 const char *for_pos;
852 int matchlen = -1;
853 int hostlen;
854 const char *rhost_name = cb;
855 int rhost_len = strlen(rhost_name);
857 if (git_proxy_command)
858 return 0;
859 if (!value)
860 return config_error_nonbool(var);
861 /* [core]
862 * ;# matches www.kernel.org as well
863 * gitproxy = netcatter-1 for kernel.org
864 * gitproxy = netcatter-2 for sample.xz
865 * gitproxy = netcatter-default
867 for_pos = strstr(value, " for ");
868 if (!for_pos)
869 /* matches everybody */
870 matchlen = strlen(value);
871 else {
872 hostlen = strlen(for_pos + 5);
873 if (rhost_len < hostlen)
874 matchlen = -1;
875 else if (!strncmp(for_pos + 5,
876 rhost_name + rhost_len - hostlen,
877 hostlen) &&
878 ((rhost_len == hostlen) ||
879 rhost_name[rhost_len - hostlen -1] == '.'))
880 matchlen = for_pos - value;
881 else
882 matchlen = -1;
884 if (0 <= matchlen) {
885 /* core.gitproxy = none for kernel.org */
886 if (matchlen == 4 &&
887 !memcmp(value, "none", 4))
888 matchlen = 0;
889 git_proxy_command = xmemdupz(value, matchlen);
891 return 0;
894 return git_default_config(var, value, cb);
897 static int git_use_proxy(const char *host)
899 git_proxy_command = getenv("GIT_PROXY_COMMAND");
900 git_config(git_proxy_command_options, (void*)host);
901 return (git_proxy_command && *git_proxy_command);
904 static struct child_process *git_proxy_connect(int fd[2], char *host)
906 const char *port = STR(DEFAULT_GIT_PORT);
907 struct child_process *proxy;
909 get_host_and_port(&host, &port);
911 if (looks_like_command_line_option(host))
912 die(_("strange hostname '%s' blocked"), host);
913 if (looks_like_command_line_option(port))
914 die(_("strange port '%s' blocked"), port);
916 proxy = xmalloc(sizeof(*proxy));
917 child_process_init(proxy);
918 argv_array_push(&proxy->args, git_proxy_command);
919 argv_array_push(&proxy->args, host);
920 argv_array_push(&proxy->args, port);
921 proxy->in = -1;
922 proxy->out = -1;
923 if (start_command(proxy))
924 die(_("cannot start proxy %s"), git_proxy_command);
925 fd[0] = proxy->out; /* read from proxy stdout */
926 fd[1] = proxy->in; /* write to proxy stdin */
927 return proxy;
930 static char *get_port(char *host)
932 char *end;
933 char *p = strchr(host, ':');
935 if (p) {
936 long port = strtol(p + 1, &end, 10);
937 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
938 *p = '\0';
939 return p+1;
943 return NULL;
947 * Extract protocol and relevant parts from the specified connection URL.
948 * The caller must free() the returned strings.
950 static enum protocol parse_connect_url(const char *url_orig, char **ret_host,
951 char **ret_path)
953 char *url;
954 char *host, *path;
955 char *end;
956 int separator = '/';
957 enum protocol protocol = PROTO_LOCAL;
959 if (is_url(url_orig))
960 url = url_decode(url_orig);
961 else
962 url = xstrdup(url_orig);
964 host = strstr(url, "://");
965 if (host) {
966 *host = '\0';
967 protocol = get_protocol(url);
968 host += 3;
969 } else {
970 host = url;
971 if (!url_is_local_not_ssh(url)) {
972 protocol = PROTO_SSH;
973 separator = ':';
978 * Don't do destructive transforms as protocol code does
979 * '[]' unwrapping in get_host_and_port()
981 end = host_end(&host, 0);
983 if (protocol == PROTO_LOCAL)
984 path = end;
985 else if (protocol == PROTO_FILE && *host != '/' &&
986 !has_dos_drive_prefix(host) &&
987 offset_1st_component(host - 2) > 1)
988 path = host - 2; /* include the leading "//" */
989 else if (protocol == PROTO_FILE && has_dos_drive_prefix(end))
990 path = end; /* "file://$(pwd)" may be "file://C:/projects/repo" */
991 else
992 path = strchr(end, separator);
994 if (!path || !*path)
995 die(_("no path specified; see 'git help pull' for valid url syntax"));
998 * null-terminate hostname and point path to ~ for URL's like this:
999 * ssh://host.xz/~user/repo
1002 end = path; /* Need to \0 terminate host here */
1003 if (separator == ':')
1004 path++; /* path starts after ':' */
1005 if (protocol == PROTO_GIT || protocol == PROTO_SSH) {
1006 if (path[1] == '~')
1007 path++;
1010 path = xstrdup(path);
1011 *end = '\0';
1013 *ret_host = xstrdup(host);
1014 *ret_path = path;
1015 free(url);
1016 return protocol;
1019 static const char *get_ssh_command(void)
1021 const char *ssh;
1023 if ((ssh = getenv("GIT_SSH_COMMAND")))
1024 return ssh;
1026 if (!git_config_get_string_const("core.sshcommand", &ssh))
1027 return ssh;
1029 return NULL;
1032 enum ssh_variant {
1033 VARIANT_AUTO,
1034 VARIANT_SIMPLE,
1035 VARIANT_SSH,
1036 VARIANT_PLINK,
1037 VARIANT_PUTTY,
1038 VARIANT_TORTOISEPLINK,
1041 static void override_ssh_variant(enum ssh_variant *ssh_variant)
1043 const char *variant = getenv("GIT_SSH_VARIANT");
1045 if (!variant && git_config_get_string_const("ssh.variant", &variant))
1046 return;
1048 if (!strcmp(variant, "auto"))
1049 *ssh_variant = VARIANT_AUTO;
1050 else if (!strcmp(variant, "plink"))
1051 *ssh_variant = VARIANT_PLINK;
1052 else if (!strcmp(variant, "putty"))
1053 *ssh_variant = VARIANT_PUTTY;
1054 else if (!strcmp(variant, "tortoiseplink"))
1055 *ssh_variant = VARIANT_TORTOISEPLINK;
1056 else if (!strcmp(variant, "simple"))
1057 *ssh_variant = VARIANT_SIMPLE;
1058 else
1059 *ssh_variant = VARIANT_SSH;
1062 static enum ssh_variant determine_ssh_variant(const char *ssh_command,
1063 int is_cmdline)
1065 enum ssh_variant ssh_variant = VARIANT_AUTO;
1066 const char *variant;
1067 char *p = NULL;
1069 override_ssh_variant(&ssh_variant);
1071 if (ssh_variant != VARIANT_AUTO)
1072 return ssh_variant;
1074 if (!is_cmdline) {
1075 p = xstrdup(ssh_command);
1076 variant = basename(p);
1077 } else {
1078 const char **ssh_argv;
1080 p = xstrdup(ssh_command);
1081 if (split_cmdline(p, &ssh_argv) > 0) {
1082 variant = basename((char *)ssh_argv[0]);
1084 * At this point, variant points into the buffer
1085 * referenced by p, hence we do not need ssh_argv
1086 * any longer.
1088 free(ssh_argv);
1089 } else {
1090 free(p);
1091 return ssh_variant;
1095 if (!strcasecmp(variant, "ssh") ||
1096 !strcasecmp(variant, "ssh.exe"))
1097 ssh_variant = VARIANT_SSH;
1098 else if (!strcasecmp(variant, "plink") ||
1099 !strcasecmp(variant, "plink.exe"))
1100 ssh_variant = VARIANT_PLINK;
1101 else if (!strcasecmp(variant, "tortoiseplink") ||
1102 !strcasecmp(variant, "tortoiseplink.exe"))
1103 ssh_variant = VARIANT_TORTOISEPLINK;
1105 free(p);
1106 return ssh_variant;
1110 * Open a connection using Git's native protocol.
1112 * The caller is responsible for freeing hostandport, but this function may
1113 * modify it (for example, to truncate it to remove the port part).
1115 static struct child_process *git_connect_git(int fd[2], char *hostandport,
1116 const char *path, const char *prog,
1117 enum protocol_version version,
1118 int flags)
1120 struct child_process *conn;
1121 struct strbuf request = STRBUF_INIT;
1123 * Set up virtual host information based on where we will
1124 * connect, unless the user has overridden us in
1125 * the environment.
1127 char *target_host = getenv("GIT_OVERRIDE_VIRTUAL_HOST");
1128 if (target_host)
1129 target_host = xstrdup(target_host);
1130 else
1131 target_host = xstrdup(hostandport);
1133 transport_check_allowed("git");
1136 * These underlying connection commands die() if they
1137 * cannot connect.
1139 if (git_use_proxy(hostandport))
1140 conn = git_proxy_connect(fd, hostandport);
1141 else
1142 conn = git_tcp_connect(fd, hostandport, flags);
1144 * Separate original protocol components prog and path
1145 * from extended host header with a NUL byte.
1147 * Note: Do not add any other headers here! Doing so
1148 * will cause older git-daemon servers to crash.
1150 strbuf_addf(&request,
1151 "%s %s%chost=%s%c",
1152 prog, path, 0,
1153 target_host, 0);
1155 /* If using a new version put that stuff here after a second null byte */
1156 if (version > 0) {
1157 strbuf_addch(&request, '\0');
1158 strbuf_addf(&request, "version=%d%c",
1159 version, '\0');
1162 packet_write(fd[1], request.buf, request.len);
1164 free(target_host);
1165 strbuf_release(&request);
1166 return conn;
1170 * Append the appropriate environment variables to `env` and options to
1171 * `args` for running ssh in Git's SSH-tunneled transport.
1173 static void push_ssh_options(struct argv_array *args, struct argv_array *env,
1174 enum ssh_variant variant, const char *port,
1175 enum protocol_version version, int flags)
1177 if (variant == VARIANT_SSH &&
1178 version > 0) {
1179 argv_array_push(args, "-o");
1180 argv_array_push(args, "SendEnv=" GIT_PROTOCOL_ENVIRONMENT);
1181 argv_array_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1182 version);
1185 if (flags & CONNECT_IPV4) {
1186 switch (variant) {
1187 case VARIANT_AUTO:
1188 BUG("VARIANT_AUTO passed to push_ssh_options");
1189 case VARIANT_SIMPLE:
1190 die(_("ssh variant 'simple' does not support -4"));
1191 case VARIANT_SSH:
1192 case VARIANT_PLINK:
1193 case VARIANT_PUTTY:
1194 case VARIANT_TORTOISEPLINK:
1195 argv_array_push(args, "-4");
1197 } else if (flags & CONNECT_IPV6) {
1198 switch (variant) {
1199 case VARIANT_AUTO:
1200 BUG("VARIANT_AUTO passed to push_ssh_options");
1201 case VARIANT_SIMPLE:
1202 die(_("ssh variant 'simple' does not support -6"));
1203 case VARIANT_SSH:
1204 case VARIANT_PLINK:
1205 case VARIANT_PUTTY:
1206 case VARIANT_TORTOISEPLINK:
1207 argv_array_push(args, "-6");
1211 if (variant == VARIANT_TORTOISEPLINK)
1212 argv_array_push(args, "-batch");
1214 if (port) {
1215 switch (variant) {
1216 case VARIANT_AUTO:
1217 BUG("VARIANT_AUTO passed to push_ssh_options");
1218 case VARIANT_SIMPLE:
1219 die(_("ssh variant 'simple' does not support setting port"));
1220 case VARIANT_SSH:
1221 argv_array_push(args, "-p");
1222 break;
1223 case VARIANT_PLINK:
1224 case VARIANT_PUTTY:
1225 case VARIANT_TORTOISEPLINK:
1226 argv_array_push(args, "-P");
1229 argv_array_push(args, port);
1233 /* Prepare a child_process for use by Git's SSH-tunneled transport. */
1234 static void fill_ssh_args(struct child_process *conn, const char *ssh_host,
1235 const char *port, enum protocol_version version,
1236 int flags)
1238 const char *ssh;
1239 enum ssh_variant variant;
1241 if (looks_like_command_line_option(ssh_host))
1242 die(_("strange hostname '%s' blocked"), ssh_host);
1244 ssh = get_ssh_command();
1245 if (ssh) {
1246 variant = determine_ssh_variant(ssh, 1);
1247 } else {
1249 * GIT_SSH is the no-shell version of
1250 * GIT_SSH_COMMAND (and must remain so for
1251 * historical compatibility).
1253 conn->use_shell = 0;
1255 ssh = getenv("GIT_SSH");
1256 if (!ssh)
1257 ssh = "ssh";
1258 variant = determine_ssh_variant(ssh, 0);
1261 if (variant == VARIANT_AUTO) {
1262 struct child_process detect = CHILD_PROCESS_INIT;
1264 detect.use_shell = conn->use_shell;
1265 detect.no_stdin = detect.no_stdout = detect.no_stderr = 1;
1267 argv_array_push(&detect.args, ssh);
1268 argv_array_push(&detect.args, "-G");
1269 push_ssh_options(&detect.args, &detect.env_array,
1270 VARIANT_SSH, port, version, flags);
1271 argv_array_push(&detect.args, ssh_host);
1273 variant = run_command(&detect) ? VARIANT_SIMPLE : VARIANT_SSH;
1276 argv_array_push(&conn->args, ssh);
1277 push_ssh_options(&conn->args, &conn->env_array, variant, port, version, flags);
1278 argv_array_push(&conn->args, ssh_host);
1282 * This returns the dummy child_process `no_fork` if the transport protocol
1283 * does not need fork(2), or a struct child_process object if it does. Once
1284 * done, finish the connection with finish_connect() with the value returned
1285 * from this function (it is safe to call finish_connect() with NULL to
1286 * support the former case).
1288 * If it returns, the connect is successful; it just dies on errors (this
1289 * will hopefully be changed in a libification effort, to return NULL when
1290 * the connection failed).
1292 struct child_process *git_connect(int fd[2], const char *url,
1293 const char *prog, int flags)
1295 char *hostandport, *path;
1296 struct child_process *conn;
1297 enum protocol protocol;
1298 enum protocol_version version = get_protocol_version_config();
1301 * NEEDSWORK: If we are trying to use protocol v2 and we are planning
1302 * to perform a push, then fallback to v0 since the client doesn't know
1303 * how to push yet using v2.
1305 if (version == protocol_v2 && !strcmp("git-receive-pack", prog))
1306 version = protocol_v0;
1308 /* Without this we cannot rely on waitpid() to tell
1309 * what happened to our children.
1311 signal(SIGCHLD, SIG_DFL);
1313 protocol = parse_connect_url(url, &hostandport, &path);
1314 if ((flags & CONNECT_DIAG_URL) && (protocol != PROTO_SSH)) {
1315 printf("Diag: url=%s\n", url ? url : "NULL");
1316 printf("Diag: protocol=%s\n", prot_name(protocol));
1317 printf("Diag: hostandport=%s\n", hostandport ? hostandport : "NULL");
1318 printf("Diag: path=%s\n", path ? path : "NULL");
1319 conn = NULL;
1320 } else if (protocol == PROTO_GIT) {
1321 conn = git_connect_git(fd, hostandport, path, prog, version, flags);
1322 conn->trace2_child_class = "transport/git";
1323 } else {
1324 struct strbuf cmd = STRBUF_INIT;
1325 const char *const *var;
1327 conn = xmalloc(sizeof(*conn));
1328 child_process_init(conn);
1330 if (looks_like_command_line_option(path))
1331 die(_("strange pathname '%s' blocked"), path);
1333 strbuf_addstr(&cmd, prog);
1334 strbuf_addch(&cmd, ' ');
1335 sq_quote_buf(&cmd, path);
1337 /* remove repo-local variables from the environment */
1338 for (var = local_repo_env; *var; var++)
1339 argv_array_push(&conn->env_array, *var);
1341 conn->use_shell = 1;
1342 conn->in = conn->out = -1;
1343 if (protocol == PROTO_SSH) {
1344 char *ssh_host = hostandport;
1345 const char *port = NULL;
1346 transport_check_allowed("ssh");
1347 get_host_and_port(&ssh_host, &port);
1349 if (!port)
1350 port = get_port(ssh_host);
1352 if (flags & CONNECT_DIAG_URL) {
1353 printf("Diag: url=%s\n", url ? url : "NULL");
1354 printf("Diag: protocol=%s\n", prot_name(protocol));
1355 printf("Diag: userandhost=%s\n", ssh_host ? ssh_host : "NULL");
1356 printf("Diag: port=%s\n", port ? port : "NONE");
1357 printf("Diag: path=%s\n", path ? path : "NULL");
1359 free(hostandport);
1360 free(path);
1361 free(conn);
1362 strbuf_release(&cmd);
1363 return NULL;
1365 conn->trace2_child_class = "transport/ssh";
1366 fill_ssh_args(conn, ssh_host, port, version, flags);
1367 } else {
1368 transport_check_allowed("file");
1369 conn->trace2_child_class = "transport/file";
1370 if (version > 0) {
1371 argv_array_pushf(&conn->env_array, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1372 version);
1375 argv_array_push(&conn->args, cmd.buf);
1377 if (start_command(conn))
1378 die(_("unable to fork"));
1380 fd[0] = conn->out; /* read from child's stdout */
1381 fd[1] = conn->in; /* write to child's stdin */
1382 strbuf_release(&cmd);
1384 free(hostandport);
1385 free(path);
1386 return conn;
1389 int finish_connect(struct child_process *conn)
1391 int code;
1392 if (!conn || git_connection_is_socket(conn))
1393 return 0;
1395 code = finish_command(conn);
1396 free(conn);
1397 return code;