Sync with 2.38.5
[git.git] / connect.c
blobeef752f14b803e4ac770264abe900f250fedb01d
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 strvec server_capabilities_v2 = STRVEC_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)
71 int i;
73 for (i = 0; i < server_capabilities_v2.nr; i++) {
74 const char *out;
75 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
76 (!*out || *out == '='))
77 return 1;
79 return 0;
82 void ensure_server_supports_v2(const char *c)
84 if (!server_supports_v2(c))
85 die(_("server doesn't support '%s'"), c);
88 int server_feature_v2(const char *c, const char **v)
90 int i;
92 for (i = 0; i < server_capabilities_v2.nr; i++) {
93 const char *out;
94 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
95 (*out == '=')) {
96 *v = out + 1;
97 return 1;
100 return 0;
103 int server_supports_feature(const char *c, const char *feature,
104 int die_on_error)
106 int i;
108 for (i = 0; i < server_capabilities_v2.nr; i++) {
109 const char *out;
110 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
111 (!*out || *(out++) == '=')) {
112 if (parse_feature_request(out, feature))
113 return 1;
114 else
115 break;
119 if (die_on_error)
120 die(_("server doesn't support feature '%s'"), feature);
122 return 0;
125 static void process_capabilities_v2(struct packet_reader *reader)
127 while (packet_reader_read(reader) == PACKET_READ_NORMAL)
128 strvec_push(&server_capabilities_v2, reader->line);
130 if (reader->status != PACKET_READ_FLUSH)
131 die(_("expected flush after capabilities"));
134 enum protocol_version discover_version(struct packet_reader *reader)
136 enum protocol_version version = protocol_unknown_version;
139 * Peek the first line of the server's response to
140 * determine the protocol version the server is speaking.
142 switch (packet_reader_peek(reader)) {
143 case PACKET_READ_EOF:
144 die_initial_contact(0);
145 case PACKET_READ_FLUSH:
146 case PACKET_READ_DELIM:
147 case PACKET_READ_RESPONSE_END:
148 version = protocol_v0;
149 break;
150 case PACKET_READ_NORMAL:
151 version = determine_protocol_version_client(reader->line);
152 break;
155 switch (version) {
156 case protocol_v2:
157 process_capabilities_v2(reader);
158 break;
159 case protocol_v1:
160 /* Read the peeked version line */
161 packet_reader_read(reader);
162 break;
163 case protocol_v0:
164 break;
165 case protocol_unknown_version:
166 BUG("unknown protocol version");
169 trace2_data_intmax("transfer", NULL, "negotiated-version", version);
171 return version;
174 static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
176 char *sym, *target;
177 struct string_list_item *item;
179 if (!len)
180 return; /* just "symref" */
181 /* e.g. "symref=HEAD:refs/heads/master" */
182 sym = xmemdupz(val, len);
183 target = strchr(sym, ':');
184 if (!target)
185 /* just "symref=something" */
186 goto reject;
187 *(target++) = '\0';
188 if (check_refname_format(sym, REFNAME_ALLOW_ONELEVEL) ||
189 check_refname_format(target, REFNAME_ALLOW_ONELEVEL))
190 /* "symref=bogus:pair */
191 goto reject;
192 item = string_list_append_nodup(symref, sym);
193 item->util = target;
194 return;
195 reject:
196 free(sym);
197 return;
200 static void annotate_refs_with_symref_info(struct ref *ref)
202 struct string_list symref = STRING_LIST_INIT_DUP;
203 int offset = 0;
205 while (1) {
206 int len;
207 const char *val;
209 val = next_server_feature_value("symref", &len, &offset);
210 if (!val)
211 break;
212 parse_one_symref_info(&symref, val, len);
214 string_list_sort(&symref);
216 for (; ref; ref = ref->next) {
217 struct string_list_item *item;
218 item = string_list_lookup(&symref, ref->name);
219 if (!item)
220 continue;
221 ref->symref = xstrdup((char *)item->util);
223 string_list_clear(&symref, 0);
226 static void process_capabilities(struct packet_reader *reader, int *linelen)
228 const char *feat_val;
229 int feat_len;
230 const char *line = reader->line;
231 int nul_location = strlen(line);
232 if (nul_location == *linelen)
233 return;
234 server_capabilities_v1 = xstrdup(line + nul_location + 1);
235 *linelen = nul_location;
237 feat_val = server_feature_value("object-format", &feat_len);
238 if (feat_val) {
239 char *hash_name = xstrndup(feat_val, feat_len);
240 int hash_algo = hash_algo_by_name(hash_name);
241 if (hash_algo != GIT_HASH_UNKNOWN)
242 reader->hash_algo = &hash_algos[hash_algo];
243 free(hash_name);
244 } else {
245 reader->hash_algo = &hash_algos[GIT_HASH_SHA1];
249 static int process_dummy_ref(const struct packet_reader *reader)
251 const char *line = reader->line;
252 struct object_id oid;
253 const char *name;
255 if (parse_oid_hex_algop(line, &oid, &name, reader->hash_algo))
256 return 0;
257 if (*name != ' ')
258 return 0;
259 name++;
261 return oideq(null_oid(), &oid) && !strcmp(name, "capabilities^{}");
264 static void check_no_capabilities(const char *line, int len)
266 if (strlen(line) != len)
267 warning(_("ignoring capabilities after first line '%s'"),
268 line + strlen(line));
271 static int process_ref(const struct packet_reader *reader, int len,
272 struct ref ***list, unsigned int flags,
273 struct oid_array *extra_have)
275 const char *line = reader->line;
276 struct object_id old_oid;
277 const char *name;
279 if (parse_oid_hex_algop(line, &old_oid, &name, reader->hash_algo))
280 return 0;
281 if (*name != ' ')
282 return 0;
283 name++;
285 if (extra_have && !strcmp(name, ".have")) {
286 oid_array_append(extra_have, &old_oid);
287 } else if (!strcmp(name, "capabilities^{}")) {
288 die(_("protocol error: unexpected capabilities^{}"));
289 } else if (check_ref(name, flags)) {
290 struct ref *ref = alloc_ref(name);
291 oidcpy(&ref->old_oid, &old_oid);
292 **list = ref;
293 *list = &ref->next;
295 check_no_capabilities(line, len);
296 return 1;
299 static int process_shallow(const struct packet_reader *reader, int len,
300 struct oid_array *shallow_points)
302 const char *line = reader->line;
303 const char *arg;
304 struct object_id old_oid;
306 if (!skip_prefix(line, "shallow ", &arg))
307 return 0;
309 if (get_oid_hex_algop(arg, &old_oid, reader->hash_algo))
310 die(_("protocol error: expected shallow sha-1, got '%s'"), arg);
311 if (!shallow_points)
312 die(_("repository on the other end cannot be shallow"));
313 oid_array_append(shallow_points, &old_oid);
314 check_no_capabilities(line, len);
315 return 1;
318 enum get_remote_heads_state {
319 EXPECTING_FIRST_REF = 0,
320 EXPECTING_REF,
321 EXPECTING_SHALLOW,
322 EXPECTING_DONE,
326 * Read all the refs from the other end
328 struct ref **get_remote_heads(struct packet_reader *reader,
329 struct ref **list, unsigned int flags,
330 struct oid_array *extra_have,
331 struct oid_array *shallow_points)
333 struct ref **orig_list = list;
334 int len = 0;
335 enum get_remote_heads_state state = EXPECTING_FIRST_REF;
337 *list = NULL;
339 while (state != EXPECTING_DONE) {
340 switch (packet_reader_read(reader)) {
341 case PACKET_READ_EOF:
342 die_initial_contact(1);
343 case PACKET_READ_NORMAL:
344 len = reader->pktlen;
345 break;
346 case PACKET_READ_FLUSH:
347 state = EXPECTING_DONE;
348 break;
349 case PACKET_READ_DELIM:
350 case PACKET_READ_RESPONSE_END:
351 die(_("invalid packet"));
354 switch (state) {
355 case EXPECTING_FIRST_REF:
356 process_capabilities(reader, &len);
357 if (process_dummy_ref(reader)) {
358 state = EXPECTING_SHALLOW;
359 break;
361 state = EXPECTING_REF;
362 /* fallthrough */
363 case EXPECTING_REF:
364 if (process_ref(reader, len, &list, flags, extra_have))
365 break;
366 state = EXPECTING_SHALLOW;
367 /* fallthrough */
368 case EXPECTING_SHALLOW:
369 if (process_shallow(reader, len, shallow_points))
370 break;
371 die(_("protocol error: unexpected '%s'"), reader->line);
372 case EXPECTING_DONE:
373 break;
377 annotate_refs_with_symref_info(*orig_list);
379 return list;
382 /* Returns 1 when a valid ref has been added to `list`, 0 otherwise */
383 static int process_ref_v2(struct packet_reader *reader, struct ref ***list,
384 const char **unborn_head_target)
386 int ret = 1;
387 int i = 0;
388 struct object_id old_oid;
389 struct ref *ref;
390 struct string_list line_sections = STRING_LIST_INIT_DUP;
391 const char *end;
392 const char *line = reader->line;
395 * Ref lines have a number of fields which are space deliminated. The
396 * first field is the OID of the ref. The second field is the ref
397 * name. Subsequent fields (symref-target and peeled) are optional and
398 * don't have a particular order.
400 if (string_list_split(&line_sections, line, ' ', -1) < 2) {
401 ret = 0;
402 goto out;
405 if (!strcmp("unborn", line_sections.items[i].string)) {
406 i++;
407 if (unborn_head_target &&
408 !strcmp("HEAD", line_sections.items[i++].string)) {
410 * Look for the symref target (if any). If found,
411 * return it to the caller.
413 for (; i < line_sections.nr; i++) {
414 const char *arg = line_sections.items[i].string;
416 if (skip_prefix(arg, "symref-target:", &arg)) {
417 *unborn_head_target = xstrdup(arg);
418 break;
422 goto out;
424 if (parse_oid_hex_algop(line_sections.items[i++].string, &old_oid, &end, reader->hash_algo) ||
425 *end) {
426 ret = 0;
427 goto out;
430 ref = alloc_ref(line_sections.items[i++].string);
432 memcpy(ref->old_oid.hash, old_oid.hash, reader->hash_algo->rawsz);
433 **list = ref;
434 *list = &ref->next;
436 for (; i < line_sections.nr; i++) {
437 const char *arg = line_sections.items[i].string;
438 if (skip_prefix(arg, "symref-target:", &arg))
439 ref->symref = xstrdup(arg);
441 if (skip_prefix(arg, "peeled:", &arg)) {
442 struct object_id peeled_oid;
443 char *peeled_name;
444 struct ref *peeled;
445 if (parse_oid_hex_algop(arg, &peeled_oid, &end,
446 reader->hash_algo) || *end) {
447 ret = 0;
448 goto out;
451 peeled_name = xstrfmt("%s^{}", ref->name);
452 peeled = alloc_ref(peeled_name);
454 memcpy(peeled->old_oid.hash, peeled_oid.hash,
455 reader->hash_algo->rawsz);
456 **list = peeled;
457 *list = &peeled->next;
459 free(peeled_name);
463 out:
464 string_list_clear(&line_sections, 0);
465 return ret;
468 void check_stateless_delimiter(int stateless_rpc,
469 struct packet_reader *reader,
470 const char *error)
472 if (!stateless_rpc)
473 return; /* not in stateless mode, no delimiter expected */
474 if (packet_reader_read(reader) != PACKET_READ_RESPONSE_END)
475 die("%s", error);
478 static void send_capabilities(int fd_out, struct packet_reader *reader)
480 const char *hash_name;
482 if (server_supports_v2("agent"))
483 packet_write_fmt(fd_out, "agent=%s", git_user_agent_sanitized());
485 if (server_feature_v2("object-format", &hash_name)) {
486 int hash_algo = hash_algo_by_name(hash_name);
487 if (hash_algo == GIT_HASH_UNKNOWN)
488 die(_("unknown object format '%s' specified by server"), hash_name);
489 reader->hash_algo = &hash_algos[hash_algo];
490 packet_write_fmt(fd_out, "object-format=%s", reader->hash_algo->name);
491 } else {
492 reader->hash_algo = &hash_algos[GIT_HASH_SHA1];
496 struct ref **get_remote_refs(int fd_out, struct packet_reader *reader,
497 struct ref **list, int for_push,
498 struct transport_ls_refs_options *transport_options,
499 const struct string_list *server_options,
500 int stateless_rpc)
502 int i;
503 struct strvec *ref_prefixes = transport_options ?
504 &transport_options->ref_prefixes : NULL;
505 const char **unborn_head_target = transport_options ?
506 &transport_options->unborn_head_target : NULL;
507 *list = NULL;
509 ensure_server_supports_v2("ls-refs");
510 packet_write_fmt(fd_out, "command=ls-refs\n");
512 /* Send capabilities */
513 send_capabilities(fd_out, reader);
515 if (server_options && server_options->nr) {
516 ensure_server_supports_v2("server-option");
517 for (i = 0; i < server_options->nr; i++)
518 packet_write_fmt(fd_out, "server-option=%s",
519 server_options->items[i].string);
522 packet_delim(fd_out);
523 /* When pushing we don't want to request the peeled tags */
524 if (!for_push)
525 packet_write_fmt(fd_out, "peel\n");
526 packet_write_fmt(fd_out, "symrefs\n");
527 if (server_supports_feature("ls-refs", "unborn", 0))
528 packet_write_fmt(fd_out, "unborn\n");
529 for (i = 0; ref_prefixes && i < ref_prefixes->nr; i++) {
530 packet_write_fmt(fd_out, "ref-prefix %s\n",
531 ref_prefixes->v[i]);
533 packet_flush(fd_out);
535 /* Process response from server */
536 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
537 if (!process_ref_v2(reader, &list, unborn_head_target))
538 die(_("invalid ls-refs response: %s"), reader->line);
541 if (reader->status != PACKET_READ_FLUSH)
542 die(_("expected flush after ref listing"));
544 check_stateless_delimiter(stateless_rpc, reader,
545 _("expected response end packet after ref listing"));
547 return list;
550 const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp, int *offset)
552 int len;
554 if (!feature_list)
555 return NULL;
557 len = strlen(feature);
558 if (offset)
559 feature_list += *offset;
560 while (*feature_list) {
561 const char *found = strstr(feature_list, feature);
562 if (!found)
563 return NULL;
564 if (feature_list == found || isspace(found[-1])) {
565 const char *value = found + len;
566 /* feature with no value (e.g., "thin-pack") */
567 if (!*value || isspace(*value)) {
568 if (lenp)
569 *lenp = 0;
570 if (offset)
571 *offset = found + len - feature_list;
572 return value;
574 /* feature with a value (e.g., "agent=git/1.2.3") */
575 else if (*value == '=') {
576 int end;
578 value++;
579 end = strcspn(value, " \t\n");
580 if (lenp)
581 *lenp = end;
582 if (offset)
583 *offset = value + end - feature_list;
584 return value;
587 * otherwise we matched a substring of another feature;
588 * keep looking
591 feature_list = found + 1;
593 return NULL;
596 int server_supports_hash(const char *desired, int *feature_supported)
598 int offset = 0;
599 int len;
600 const char *hash;
602 hash = next_server_feature_value("object-format", &len, &offset);
603 if (feature_supported)
604 *feature_supported = !!hash;
605 if (!hash) {
606 hash = hash_algos[GIT_HASH_SHA1].name;
607 len = strlen(hash);
609 while (hash) {
610 if (!xstrncmpz(desired, hash, len))
611 return 1;
613 hash = next_server_feature_value("object-format", &len, &offset);
615 return 0;
618 int parse_feature_request(const char *feature_list, const char *feature)
620 return !!parse_feature_value(feature_list, feature, NULL, NULL);
623 static const char *next_server_feature_value(const char *feature, int *len, int *offset)
625 return parse_feature_value(server_capabilities_v1, feature, len, offset);
628 const char *server_feature_value(const char *feature, int *len)
630 return parse_feature_value(server_capabilities_v1, feature, len, NULL);
633 int server_supports(const char *feature)
635 return !!server_feature_value(feature, NULL);
638 enum protocol {
639 PROTO_LOCAL = 1,
640 PROTO_FILE,
641 PROTO_SSH,
642 PROTO_GIT
645 int url_is_local_not_ssh(const char *url)
647 const char *colon = strchr(url, ':');
648 const char *slash = strchr(url, '/');
649 return !colon || (slash && slash < colon) ||
650 (has_dos_drive_prefix(url) && is_valid_path(url));
653 static const char *prot_name(enum protocol protocol)
655 switch (protocol) {
656 case PROTO_LOCAL:
657 case PROTO_FILE:
658 return "file";
659 case PROTO_SSH:
660 return "ssh";
661 case PROTO_GIT:
662 return "git";
663 default:
664 return "unknown protocol";
668 static enum protocol get_protocol(const char *name)
670 if (!strcmp(name, "ssh"))
671 return PROTO_SSH;
672 if (!strcmp(name, "git"))
673 return PROTO_GIT;
674 if (!strcmp(name, "git+ssh")) /* deprecated - do not use */
675 return PROTO_SSH;
676 if (!strcmp(name, "ssh+git")) /* deprecated - do not use */
677 return PROTO_SSH;
678 if (!strcmp(name, "file"))
679 return PROTO_FILE;
680 die(_("protocol '%s' is not supported"), name);
683 static char *host_end(char **hoststart, int removebrackets)
685 char *host = *hoststart;
686 char *end;
687 char *start = strstr(host, "@[");
688 if (start)
689 start++; /* Jump over '@' */
690 else
691 start = host;
692 if (start[0] == '[') {
693 end = strchr(start + 1, ']');
694 if (end) {
695 if (removebrackets) {
696 *end = 0;
697 memmove(start, start + 1, end - start);
698 end++;
700 } else
701 end = host;
702 } else
703 end = host;
704 return end;
707 #define STR_(s) # s
708 #define STR(s) STR_(s)
710 static void get_host_and_port(char **host, const char **port)
712 char *colon, *end;
713 end = host_end(host, 1);
714 colon = strchr(end, ':');
715 if (colon) {
716 long portnr = strtol(colon + 1, &end, 10);
717 if (end != colon + 1 && *end == '\0' && 0 <= portnr && portnr < 65536) {
718 *colon = 0;
719 *port = colon + 1;
720 } else if (!colon[1]) {
721 *colon = 0;
726 static void enable_keepalive(int sockfd)
728 int ka = 1;
730 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
731 error_errno(_("unable to set SO_KEEPALIVE on socket"));
734 #ifndef NO_IPV6
736 static const char *ai_name(const struct addrinfo *ai)
738 static char addr[NI_MAXHOST];
739 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
740 NI_NUMERICHOST) != 0)
741 xsnprintf(addr, sizeof(addr), "(unknown)");
743 return addr;
747 * Returns a connected socket() fd, or else die()s.
749 static int git_tcp_connect_sock(char *host, int flags)
751 struct strbuf error_message = STRBUF_INIT;
752 int sockfd = -1;
753 const char *port = STR(DEFAULT_GIT_PORT);
754 struct addrinfo hints, *ai0, *ai;
755 int gai;
756 int cnt = 0;
758 get_host_and_port(&host, &port);
759 if (!*port)
760 port = "<none>";
762 memset(&hints, 0, sizeof(hints));
763 if (flags & CONNECT_IPV4)
764 hints.ai_family = AF_INET;
765 else if (flags & CONNECT_IPV6)
766 hints.ai_family = AF_INET6;
767 hints.ai_socktype = SOCK_STREAM;
768 hints.ai_protocol = IPPROTO_TCP;
770 if (flags & CONNECT_VERBOSE)
771 fprintf(stderr, _("Looking up %s ... "), host);
773 gai = getaddrinfo(host, port, &hints, &ai);
774 if (gai)
775 die(_("unable to look up %s (port %s) (%s)"), host, port, gai_strerror(gai));
777 if (flags & CONNECT_VERBOSE)
778 /* TRANSLATORS: this is the end of "Looking up %s ... " */
779 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
781 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
782 sockfd = socket(ai->ai_family,
783 ai->ai_socktype, ai->ai_protocol);
784 if ((sockfd < 0) ||
785 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
786 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
787 host, cnt, ai_name(ai), strerror(errno));
788 if (0 <= sockfd)
789 close(sockfd);
790 sockfd = -1;
791 continue;
793 if (flags & CONNECT_VERBOSE)
794 fprintf(stderr, "%s ", ai_name(ai));
795 break;
798 freeaddrinfo(ai0);
800 if (sockfd < 0)
801 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
803 enable_keepalive(sockfd);
805 if (flags & CONNECT_VERBOSE)
806 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
807 fprintf_ln(stderr, _("done."));
809 strbuf_release(&error_message);
811 return sockfd;
814 #else /* NO_IPV6 */
817 * Returns a connected socket() fd, or else die()s.
819 static int git_tcp_connect_sock(char *host, int flags)
821 struct strbuf error_message = STRBUF_INIT;
822 int sockfd = -1;
823 const char *port = STR(DEFAULT_GIT_PORT);
824 char *ep;
825 struct hostent *he;
826 struct sockaddr_in sa;
827 char **ap;
828 unsigned int nport;
829 int cnt;
831 get_host_and_port(&host, &port);
833 if (flags & CONNECT_VERBOSE)
834 fprintf(stderr, _("Looking up %s ... "), host);
836 he = gethostbyname(host);
837 if (!he)
838 die(_("unable to look up %s (%s)"), host, hstrerror(h_errno));
839 nport = strtoul(port, &ep, 10);
840 if ( ep == port || *ep ) {
841 /* Not numeric */
842 struct servent *se = getservbyname(port,"tcp");
843 if ( !se )
844 die(_("unknown port %s"), port);
845 nport = se->s_port;
848 if (flags & CONNECT_VERBOSE)
849 /* TRANSLATORS: this is the end of "Looking up %s ... " */
850 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
852 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
853 memset(&sa, 0, sizeof sa);
854 sa.sin_family = he->h_addrtype;
855 sa.sin_port = htons(nport);
856 memcpy(&sa.sin_addr, *ap, he->h_length);
858 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
859 if ((sockfd < 0) ||
860 connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
861 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
862 host,
863 cnt,
864 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
865 strerror(errno));
866 if (0 <= sockfd)
867 close(sockfd);
868 sockfd = -1;
869 continue;
871 if (flags & CONNECT_VERBOSE)
872 fprintf(stderr, "%s ",
873 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
874 break;
877 if (sockfd < 0)
878 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
880 enable_keepalive(sockfd);
882 if (flags & CONNECT_VERBOSE)
883 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
884 fprintf_ln(stderr, _("done."));
886 return sockfd;
889 #endif /* NO_IPV6 */
893 * Dummy child_process returned by git_connect() if the transport protocol
894 * does not need fork(2).
896 static struct child_process no_fork = CHILD_PROCESS_INIT;
898 int git_connection_is_socket(struct child_process *conn)
900 return conn == &no_fork;
903 static struct child_process *git_tcp_connect(int fd[2], char *host, int flags)
905 int sockfd = git_tcp_connect_sock(host, flags);
907 fd[0] = sockfd;
908 fd[1] = dup(sockfd);
910 return &no_fork;
914 static char *git_proxy_command;
916 static int git_proxy_command_options(const char *var, const char *value,
917 void *cb)
919 if (!strcmp(var, "core.gitproxy")) {
920 const char *for_pos;
921 int matchlen = -1;
922 int hostlen;
923 const char *rhost_name = cb;
924 int rhost_len = strlen(rhost_name);
926 if (git_proxy_command)
927 return 0;
928 if (!value)
929 return config_error_nonbool(var);
930 /* [core]
931 * ;# matches www.kernel.org as well
932 * gitproxy = netcatter-1 for kernel.org
933 * gitproxy = netcatter-2 for sample.xz
934 * gitproxy = netcatter-default
936 for_pos = strstr(value, " for ");
937 if (!for_pos)
938 /* matches everybody */
939 matchlen = strlen(value);
940 else {
941 hostlen = strlen(for_pos + 5);
942 if (rhost_len < hostlen)
943 matchlen = -1;
944 else if (!strncmp(for_pos + 5,
945 rhost_name + rhost_len - hostlen,
946 hostlen) &&
947 ((rhost_len == hostlen) ||
948 rhost_name[rhost_len - hostlen -1] == '.'))
949 matchlen = for_pos - value;
950 else
951 matchlen = -1;
953 if (0 <= matchlen) {
954 /* core.gitproxy = none for kernel.org */
955 if (matchlen == 4 &&
956 !memcmp(value, "none", 4))
957 matchlen = 0;
958 git_proxy_command = xmemdupz(value, matchlen);
960 return 0;
963 return git_default_config(var, value, cb);
966 static int git_use_proxy(const char *host)
968 git_proxy_command = getenv("GIT_PROXY_COMMAND");
969 git_config(git_proxy_command_options, (void*)host);
970 return (git_proxy_command && *git_proxy_command);
973 static struct child_process *git_proxy_connect(int fd[2], char *host)
975 const char *port = STR(DEFAULT_GIT_PORT);
976 struct child_process *proxy;
978 get_host_and_port(&host, &port);
980 if (looks_like_command_line_option(host))
981 die(_("strange hostname '%s' blocked"), host);
982 if (looks_like_command_line_option(port))
983 die(_("strange port '%s' blocked"), port);
985 proxy = xmalloc(sizeof(*proxy));
986 child_process_init(proxy);
987 strvec_push(&proxy->args, git_proxy_command);
988 strvec_push(&proxy->args, host);
989 strvec_push(&proxy->args, port);
990 proxy->in = -1;
991 proxy->out = -1;
992 if (start_command(proxy))
993 die(_("cannot start proxy %s"), git_proxy_command);
994 fd[0] = proxy->out; /* read from proxy stdout */
995 fd[1] = proxy->in; /* write to proxy stdin */
996 return proxy;
999 static char *get_port(char *host)
1001 char *end;
1002 char *p = strchr(host, ':');
1004 if (p) {
1005 long port = strtol(p + 1, &end, 10);
1006 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
1007 *p = '\0';
1008 return p+1;
1012 return NULL;
1016 * Extract protocol and relevant parts from the specified connection URL.
1017 * The caller must free() the returned strings.
1019 static enum protocol parse_connect_url(const char *url_orig, char **ret_host,
1020 char **ret_path)
1022 char *url;
1023 char *host, *path;
1024 char *end;
1025 int separator = '/';
1026 enum protocol protocol = PROTO_LOCAL;
1028 if (is_url(url_orig))
1029 url = url_decode(url_orig);
1030 else
1031 url = xstrdup(url_orig);
1033 host = strstr(url, "://");
1034 if (host) {
1035 *host = '\0';
1036 protocol = get_protocol(url);
1037 host += 3;
1038 } else {
1039 host = url;
1040 if (!url_is_local_not_ssh(url)) {
1041 protocol = PROTO_SSH;
1042 separator = ':';
1047 * Don't do destructive transforms as protocol code does
1048 * '[]' unwrapping in get_host_and_port()
1050 end = host_end(&host, 0);
1052 if (protocol == PROTO_LOCAL)
1053 path = end;
1054 else if (protocol == PROTO_FILE && *host != '/' &&
1055 !has_dos_drive_prefix(host) &&
1056 offset_1st_component(host - 2) > 1)
1057 path = host - 2; /* include the leading "//" */
1058 else if (protocol == PROTO_FILE && has_dos_drive_prefix(end))
1059 path = end; /* "file://$(pwd)" may be "file://C:/projects/repo" */
1060 else
1061 path = strchr(end, separator);
1063 if (!path || !*path)
1064 die(_("no path specified; see 'git help pull' for valid url syntax"));
1067 * null-terminate hostname and point path to ~ for URL's like this:
1068 * ssh://host.xz/~user/repo
1071 end = path; /* Need to \0 terminate host here */
1072 if (separator == ':')
1073 path++; /* path starts after ':' */
1074 if (protocol == PROTO_GIT || protocol == PROTO_SSH) {
1075 if (path[1] == '~')
1076 path++;
1079 path = xstrdup(path);
1080 *end = '\0';
1082 *ret_host = xstrdup(host);
1083 *ret_path = path;
1084 free(url);
1085 return protocol;
1088 static const char *get_ssh_command(void)
1090 const char *ssh;
1092 if ((ssh = getenv("GIT_SSH_COMMAND")))
1093 return ssh;
1095 if (!git_config_get_string_tmp("core.sshcommand", &ssh))
1096 return ssh;
1098 return NULL;
1101 enum ssh_variant {
1102 VARIANT_AUTO,
1103 VARIANT_SIMPLE,
1104 VARIANT_SSH,
1105 VARIANT_PLINK,
1106 VARIANT_PUTTY,
1107 VARIANT_TORTOISEPLINK,
1110 static void override_ssh_variant(enum ssh_variant *ssh_variant)
1112 const char *variant = getenv("GIT_SSH_VARIANT");
1114 if (!variant && git_config_get_string_tmp("ssh.variant", &variant))
1115 return;
1117 if (!strcmp(variant, "auto"))
1118 *ssh_variant = VARIANT_AUTO;
1119 else if (!strcmp(variant, "plink"))
1120 *ssh_variant = VARIANT_PLINK;
1121 else if (!strcmp(variant, "putty"))
1122 *ssh_variant = VARIANT_PUTTY;
1123 else if (!strcmp(variant, "tortoiseplink"))
1124 *ssh_variant = VARIANT_TORTOISEPLINK;
1125 else if (!strcmp(variant, "simple"))
1126 *ssh_variant = VARIANT_SIMPLE;
1127 else
1128 *ssh_variant = VARIANT_SSH;
1131 static enum ssh_variant determine_ssh_variant(const char *ssh_command,
1132 int is_cmdline)
1134 enum ssh_variant ssh_variant = VARIANT_AUTO;
1135 const char *variant;
1136 char *p = NULL;
1138 override_ssh_variant(&ssh_variant);
1140 if (ssh_variant != VARIANT_AUTO)
1141 return ssh_variant;
1143 if (!is_cmdline) {
1144 p = xstrdup(ssh_command);
1145 variant = basename(p);
1146 } else {
1147 const char **ssh_argv;
1149 p = xstrdup(ssh_command);
1150 if (split_cmdline(p, &ssh_argv) > 0) {
1151 variant = basename((char *)ssh_argv[0]);
1153 * At this point, variant points into the buffer
1154 * referenced by p, hence we do not need ssh_argv
1155 * any longer.
1157 free(ssh_argv);
1158 } else {
1159 free(p);
1160 return ssh_variant;
1164 if (!strcasecmp(variant, "ssh") ||
1165 !strcasecmp(variant, "ssh.exe"))
1166 ssh_variant = VARIANT_SSH;
1167 else if (!strcasecmp(variant, "plink") ||
1168 !strcasecmp(variant, "plink.exe"))
1169 ssh_variant = VARIANT_PLINK;
1170 else if (!strcasecmp(variant, "tortoiseplink") ||
1171 !strcasecmp(variant, "tortoiseplink.exe"))
1172 ssh_variant = VARIANT_TORTOISEPLINK;
1174 free(p);
1175 return ssh_variant;
1179 * Open a connection using Git's native protocol.
1181 * The caller is responsible for freeing hostandport, but this function may
1182 * modify it (for example, to truncate it to remove the port part).
1184 static struct child_process *git_connect_git(int fd[2], char *hostandport,
1185 const char *path, const char *prog,
1186 enum protocol_version version,
1187 int flags)
1189 struct child_process *conn;
1190 struct strbuf request = STRBUF_INIT;
1192 * Set up virtual host information based on where we will
1193 * connect, unless the user has overridden us in
1194 * the environment.
1196 char *target_host = getenv("GIT_OVERRIDE_VIRTUAL_HOST");
1197 if (target_host)
1198 target_host = xstrdup(target_host);
1199 else
1200 target_host = xstrdup(hostandport);
1202 transport_check_allowed("git");
1203 if (strchr(target_host, '\n') || strchr(path, '\n'))
1204 die(_("newline is forbidden in git:// hosts and repo paths"));
1207 * These underlying connection commands die() if they
1208 * cannot connect.
1210 if (git_use_proxy(hostandport))
1211 conn = git_proxy_connect(fd, hostandport);
1212 else
1213 conn = git_tcp_connect(fd, hostandport, flags);
1215 * Separate original protocol components prog and path
1216 * from extended host header with a NUL byte.
1218 * Note: Do not add any other headers here! Doing so
1219 * will cause older git-daemon servers to crash.
1221 strbuf_addf(&request,
1222 "%s %s%chost=%s%c",
1223 prog, path, 0,
1224 target_host, 0);
1226 /* If using a new version put that stuff here after a second null byte */
1227 if (version > 0) {
1228 strbuf_addch(&request, '\0');
1229 strbuf_addf(&request, "version=%d%c",
1230 version, '\0');
1233 packet_write(fd[1], request.buf, request.len);
1235 free(target_host);
1236 strbuf_release(&request);
1237 return conn;
1241 * Append the appropriate environment variables to `env` and options to
1242 * `args` for running ssh in Git's SSH-tunneled transport.
1244 static void push_ssh_options(struct strvec *args, struct strvec *env,
1245 enum ssh_variant variant, const char *port,
1246 enum protocol_version version, int flags)
1248 if (variant == VARIANT_SSH &&
1249 version > 0) {
1250 strvec_push(args, "-o");
1251 strvec_push(args, "SendEnv=" GIT_PROTOCOL_ENVIRONMENT);
1252 strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1253 version);
1256 if (flags & CONNECT_IPV4) {
1257 switch (variant) {
1258 case VARIANT_AUTO:
1259 BUG("VARIANT_AUTO passed to push_ssh_options");
1260 case VARIANT_SIMPLE:
1261 die(_("ssh variant 'simple' does not support -4"));
1262 case VARIANT_SSH:
1263 case VARIANT_PLINK:
1264 case VARIANT_PUTTY:
1265 case VARIANT_TORTOISEPLINK:
1266 strvec_push(args, "-4");
1268 } else if (flags & CONNECT_IPV6) {
1269 switch (variant) {
1270 case VARIANT_AUTO:
1271 BUG("VARIANT_AUTO passed to push_ssh_options");
1272 case VARIANT_SIMPLE:
1273 die(_("ssh variant 'simple' does not support -6"));
1274 case VARIANT_SSH:
1275 case VARIANT_PLINK:
1276 case VARIANT_PUTTY:
1277 case VARIANT_TORTOISEPLINK:
1278 strvec_push(args, "-6");
1282 if (variant == VARIANT_TORTOISEPLINK)
1283 strvec_push(args, "-batch");
1285 if (port) {
1286 switch (variant) {
1287 case VARIANT_AUTO:
1288 BUG("VARIANT_AUTO passed to push_ssh_options");
1289 case VARIANT_SIMPLE:
1290 die(_("ssh variant 'simple' does not support setting port"));
1291 case VARIANT_SSH:
1292 strvec_push(args, "-p");
1293 break;
1294 case VARIANT_PLINK:
1295 case VARIANT_PUTTY:
1296 case VARIANT_TORTOISEPLINK:
1297 strvec_push(args, "-P");
1300 strvec_push(args, port);
1304 /* Prepare a child_process for use by Git's SSH-tunneled transport. */
1305 static void fill_ssh_args(struct child_process *conn, const char *ssh_host,
1306 const char *port, enum protocol_version version,
1307 int flags)
1309 const char *ssh;
1310 enum ssh_variant variant;
1312 if (looks_like_command_line_option(ssh_host))
1313 die(_("strange hostname '%s' blocked"), ssh_host);
1315 ssh = get_ssh_command();
1316 if (ssh) {
1317 variant = determine_ssh_variant(ssh, 1);
1318 } else {
1320 * GIT_SSH is the no-shell version of
1321 * GIT_SSH_COMMAND (and must remain so for
1322 * historical compatibility).
1324 conn->use_shell = 0;
1326 ssh = getenv("GIT_SSH");
1327 if (!ssh)
1328 ssh = "ssh";
1329 variant = determine_ssh_variant(ssh, 0);
1332 if (variant == VARIANT_AUTO) {
1333 struct child_process detect = CHILD_PROCESS_INIT;
1335 detect.use_shell = conn->use_shell;
1336 detect.no_stdin = detect.no_stdout = detect.no_stderr = 1;
1338 strvec_push(&detect.args, ssh);
1339 strvec_push(&detect.args, "-G");
1340 push_ssh_options(&detect.args, &detect.env,
1341 VARIANT_SSH, port, version, flags);
1342 strvec_push(&detect.args, ssh_host);
1344 variant = run_command(&detect) ? VARIANT_SIMPLE : VARIANT_SSH;
1347 strvec_push(&conn->args, ssh);
1348 push_ssh_options(&conn->args, &conn->env, variant, port, version,
1349 flags);
1350 strvec_push(&conn->args, ssh_host);
1354 * This returns the dummy child_process `no_fork` if the transport protocol
1355 * does not need fork(2), or a struct child_process object if it does. Once
1356 * done, finish the connection with finish_connect() with the value returned
1357 * from this function (it is safe to call finish_connect() with NULL to
1358 * support the former case).
1360 * If it returns, the connect is successful; it just dies on errors (this
1361 * will hopefully be changed in a libification effort, to return NULL when
1362 * the connection failed).
1364 struct child_process *git_connect(int fd[2], const char *url,
1365 const char *prog, int flags)
1367 char *hostandport, *path;
1368 struct child_process *conn;
1369 enum protocol protocol;
1370 enum protocol_version version = get_protocol_version_config();
1373 * NEEDSWORK: If we are trying to use protocol v2 and we are planning
1374 * to perform a push, then fallback to v0 since the client doesn't know
1375 * how to push yet using v2.
1377 if (version == protocol_v2 && !strcmp("git-receive-pack", prog))
1378 version = protocol_v0;
1380 /* Without this we cannot rely on waitpid() to tell
1381 * what happened to our children.
1383 signal(SIGCHLD, SIG_DFL);
1385 protocol = parse_connect_url(url, &hostandport, &path);
1386 if ((flags & CONNECT_DIAG_URL) && (protocol != PROTO_SSH)) {
1387 printf("Diag: url=%s\n", url ? url : "NULL");
1388 printf("Diag: protocol=%s\n", prot_name(protocol));
1389 printf("Diag: hostandport=%s\n", hostandport ? hostandport : "NULL");
1390 printf("Diag: path=%s\n", path ? path : "NULL");
1391 conn = NULL;
1392 } else if (protocol == PROTO_GIT) {
1393 conn = git_connect_git(fd, hostandport, path, prog, version, flags);
1394 conn->trace2_child_class = "transport/git";
1395 } else {
1396 struct strbuf cmd = STRBUF_INIT;
1397 const char *const *var;
1399 conn = xmalloc(sizeof(*conn));
1400 child_process_init(conn);
1402 if (looks_like_command_line_option(path))
1403 die(_("strange pathname '%s' blocked"), path);
1405 strbuf_addstr(&cmd, prog);
1406 strbuf_addch(&cmd, ' ');
1407 sq_quote_buf(&cmd, path);
1409 /* remove repo-local variables from the environment */
1410 for (var = local_repo_env; *var; var++)
1411 strvec_push(&conn->env, *var);
1413 conn->use_shell = 1;
1414 conn->in = conn->out = -1;
1415 if (protocol == PROTO_SSH) {
1416 char *ssh_host = hostandport;
1417 const char *port = NULL;
1418 transport_check_allowed("ssh");
1419 get_host_and_port(&ssh_host, &port);
1421 if (!port)
1422 port = get_port(ssh_host);
1424 if (flags & CONNECT_DIAG_URL) {
1425 printf("Diag: url=%s\n", url ? url : "NULL");
1426 printf("Diag: protocol=%s\n", prot_name(protocol));
1427 printf("Diag: userandhost=%s\n", ssh_host ? ssh_host : "NULL");
1428 printf("Diag: port=%s\n", port ? port : "NONE");
1429 printf("Diag: path=%s\n", path ? path : "NULL");
1431 free(hostandport);
1432 free(path);
1433 free(conn);
1434 strbuf_release(&cmd);
1435 return NULL;
1437 conn->trace2_child_class = "transport/ssh";
1438 fill_ssh_args(conn, ssh_host, port, version, flags);
1439 } else {
1440 transport_check_allowed("file");
1441 conn->trace2_child_class = "transport/file";
1442 if (version > 0) {
1443 strvec_pushf(&conn->env,
1444 GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1445 version);
1448 strvec_push(&conn->args, cmd.buf);
1450 if (start_command(conn))
1451 die(_("unable to fork"));
1453 fd[0] = conn->out; /* read from child's stdout */
1454 fd[1] = conn->in; /* write to child's stdin */
1455 strbuf_release(&cmd);
1457 free(hostandport);
1458 free(path);
1459 return conn;
1462 int finish_connect(struct child_process *conn)
1464 int code;
1465 if (!conn || git_connection_is_socket(conn))
1466 return 0;
1468 code = finish_command(conn);
1469 free(conn);
1470 return code;