Merge branch 'pw/wildmatch-fixes'
[git.git] / connect.c
blobed486116ee1e5f36c5fa42031e5b656d67ed5d5a
1 #include "git-compat-util.h"
2 #include "cache.h"
3 #include "config.h"
4 #include "hex.h"
5 #include "pkt-line.h"
6 #include "quote.h"
7 #include "refs.h"
8 #include "run-command.h"
9 #include "remote.h"
10 #include "connect.h"
11 #include "url.h"
12 #include "string-list.h"
13 #include "oid-array.h"
14 #include "transport.h"
15 #include "strbuf.h"
16 #include "version.h"
17 #include "protocol.h"
18 #include "alias.h"
19 #include "bundle-uri.h"
21 static char *server_capabilities_v1;
22 static struct strvec server_capabilities_v2 = STRVEC_INIT;
23 static const char *next_server_feature_value(const char *feature, int *len, int *offset);
25 static int check_ref(const char *name, unsigned int flags)
27 if (!flags)
28 return 1;
30 if (!skip_prefix(name, "refs/", &name))
31 return 0;
33 /* REF_NORMAL means that we don't want the magic fake tag refs */
34 if ((flags & REF_NORMAL) && check_refname_format(name,
35 REFNAME_ALLOW_ONELEVEL))
36 return 0;
38 /* REF_HEADS means that we want regular branch heads */
39 if ((flags & REF_HEADS) && starts_with(name, "heads/"))
40 return 1;
42 /* REF_TAGS means that we want tags */
43 if ((flags & REF_TAGS) && starts_with(name, "tags/"))
44 return 1;
46 /* All type bits clear means that we are ok with anything */
47 return !(flags & ~REF_NORMAL);
50 int check_ref_type(const struct ref *ref, int flags)
52 return check_ref(ref->name, flags);
55 static NORETURN void die_initial_contact(int unexpected)
58 * A hang-up after seeing some response from the other end
59 * means that it is unexpected, as we know the other end is
60 * willing to talk to us. A hang-up before seeing any
61 * response does not necessarily mean an ACL problem, though.
63 if (unexpected)
64 die(_("the remote end hung up upon initial contact"));
65 else
66 die(_("Could not read from remote repository.\n\n"
67 "Please make sure you have the correct access rights\n"
68 "and the repository exists."));
71 /* Checks if the server supports the capability 'c' */
72 int server_supports_v2(const char *c)
74 int i;
76 for (i = 0; i < server_capabilities_v2.nr; i++) {
77 const char *out;
78 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
79 (!*out || *out == '='))
80 return 1;
82 return 0;
85 void ensure_server_supports_v2(const char *c)
87 if (!server_supports_v2(c))
88 die(_("server doesn't support '%s'"), c);
91 int server_feature_v2(const char *c, const char **v)
93 int i;
95 for (i = 0; i < server_capabilities_v2.nr; i++) {
96 const char *out;
97 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
98 (*out == '=')) {
99 *v = out + 1;
100 return 1;
103 return 0;
106 int server_supports_feature(const char *c, const char *feature,
107 int die_on_error)
109 int i;
111 for (i = 0; i < server_capabilities_v2.nr; i++) {
112 const char *out;
113 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
114 (!*out || *(out++) == '=')) {
115 if (parse_feature_request(out, feature))
116 return 1;
117 else
118 break;
122 if (die_on_error)
123 die(_("server doesn't support feature '%s'"), feature);
125 return 0;
128 static void process_capabilities_v2(struct packet_reader *reader)
130 while (packet_reader_read(reader) == PACKET_READ_NORMAL)
131 strvec_push(&server_capabilities_v2, reader->line);
133 if (reader->status != PACKET_READ_FLUSH)
134 die(_("expected flush after capabilities"));
137 enum protocol_version discover_version(struct packet_reader *reader)
139 enum protocol_version version = protocol_unknown_version;
142 * Peek the first line of the server's response to
143 * determine the protocol version the server is speaking.
145 switch (packet_reader_peek(reader)) {
146 case PACKET_READ_EOF:
147 die_initial_contact(0);
148 case PACKET_READ_FLUSH:
149 case PACKET_READ_DELIM:
150 case PACKET_READ_RESPONSE_END:
151 version = protocol_v0;
152 break;
153 case PACKET_READ_NORMAL:
154 version = determine_protocol_version_client(reader->line);
155 break;
158 switch (version) {
159 case protocol_v2:
160 process_capabilities_v2(reader);
161 break;
162 case protocol_v1:
163 /* Read the peeked version line */
164 packet_reader_read(reader);
165 break;
166 case protocol_v0:
167 break;
168 case protocol_unknown_version:
169 BUG("unknown protocol version");
172 trace2_data_intmax("transfer", NULL, "negotiated-version", version);
174 return version;
177 static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
179 char *sym, *target;
180 struct string_list_item *item;
182 if (!len)
183 return; /* just "symref" */
184 /* e.g. "symref=HEAD:refs/heads/master" */
185 sym = xmemdupz(val, len);
186 target = strchr(sym, ':');
187 if (!target)
188 /* just "symref=something" */
189 goto reject;
190 *(target++) = '\0';
191 if (check_refname_format(sym, REFNAME_ALLOW_ONELEVEL) ||
192 check_refname_format(target, REFNAME_ALLOW_ONELEVEL))
193 /* "symref=bogus:pair */
194 goto reject;
195 item = string_list_append_nodup(symref, sym);
196 item->util = target;
197 return;
198 reject:
199 free(sym);
200 return;
203 static void annotate_refs_with_symref_info(struct ref *ref)
205 struct string_list symref = STRING_LIST_INIT_DUP;
206 int offset = 0;
208 while (1) {
209 int len;
210 const char *val;
212 val = next_server_feature_value("symref", &len, &offset);
213 if (!val)
214 break;
215 parse_one_symref_info(&symref, val, len);
217 string_list_sort(&symref);
219 for (; ref; ref = ref->next) {
220 struct string_list_item *item;
221 item = string_list_lookup(&symref, ref->name);
222 if (!item)
223 continue;
224 ref->symref = xstrdup((char *)item->util);
226 string_list_clear(&symref, 0);
229 static void process_capabilities(struct packet_reader *reader, int *linelen)
231 const char *feat_val;
232 int feat_len;
233 const char *line = reader->line;
234 int nul_location = strlen(line);
235 if (nul_location == *linelen)
236 return;
237 server_capabilities_v1 = xstrdup(line + nul_location + 1);
238 *linelen = nul_location;
240 feat_val = server_feature_value("object-format", &feat_len);
241 if (feat_val) {
242 char *hash_name = xstrndup(feat_val, feat_len);
243 int hash_algo = hash_algo_by_name(hash_name);
244 if (hash_algo != GIT_HASH_UNKNOWN)
245 reader->hash_algo = &hash_algos[hash_algo];
246 free(hash_name);
247 } else {
248 reader->hash_algo = &hash_algos[GIT_HASH_SHA1];
252 static int process_dummy_ref(const struct packet_reader *reader)
254 const char *line = reader->line;
255 struct object_id oid;
256 const char *name;
258 if (parse_oid_hex_algop(line, &oid, &name, reader->hash_algo))
259 return 0;
260 if (*name != ' ')
261 return 0;
262 name++;
264 return oideq(null_oid(), &oid) && !strcmp(name, "capabilities^{}");
267 static void check_no_capabilities(const char *line, int len)
269 if (strlen(line) != len)
270 warning(_("ignoring capabilities after first line '%s'"),
271 line + strlen(line));
274 static int process_ref(const struct packet_reader *reader, int len,
275 struct ref ***list, unsigned int flags,
276 struct oid_array *extra_have)
278 const char *line = reader->line;
279 struct object_id old_oid;
280 const char *name;
282 if (parse_oid_hex_algop(line, &old_oid, &name, reader->hash_algo))
283 return 0;
284 if (*name != ' ')
285 return 0;
286 name++;
288 if (extra_have && !strcmp(name, ".have")) {
289 oid_array_append(extra_have, &old_oid);
290 } else if (!strcmp(name, "capabilities^{}")) {
291 die(_("protocol error: unexpected capabilities^{}"));
292 } else if (check_ref(name, flags)) {
293 struct ref *ref = alloc_ref(name);
294 oidcpy(&ref->old_oid, &old_oid);
295 **list = ref;
296 *list = &ref->next;
298 check_no_capabilities(line, len);
299 return 1;
302 static int process_shallow(const struct packet_reader *reader, int len,
303 struct oid_array *shallow_points)
305 const char *line = reader->line;
306 const char *arg;
307 struct object_id old_oid;
309 if (!skip_prefix(line, "shallow ", &arg))
310 return 0;
312 if (get_oid_hex_algop(arg, &old_oid, reader->hash_algo))
313 die(_("protocol error: expected shallow sha-1, got '%s'"), arg);
314 if (!shallow_points)
315 die(_("repository on the other end cannot be shallow"));
316 oid_array_append(shallow_points, &old_oid);
317 check_no_capabilities(line, len);
318 return 1;
321 enum get_remote_heads_state {
322 EXPECTING_FIRST_REF = 0,
323 EXPECTING_REF,
324 EXPECTING_SHALLOW,
325 EXPECTING_DONE,
329 * Read all the refs from the other end
331 struct ref **get_remote_heads(struct packet_reader *reader,
332 struct ref **list, unsigned int flags,
333 struct oid_array *extra_have,
334 struct oid_array *shallow_points)
336 struct ref **orig_list = list;
337 int len = 0;
338 enum get_remote_heads_state state = EXPECTING_FIRST_REF;
340 *list = NULL;
342 while (state != EXPECTING_DONE) {
343 switch (packet_reader_read(reader)) {
344 case PACKET_READ_EOF:
345 die_initial_contact(1);
346 case PACKET_READ_NORMAL:
347 len = reader->pktlen;
348 break;
349 case PACKET_READ_FLUSH:
350 state = EXPECTING_DONE;
351 break;
352 case PACKET_READ_DELIM:
353 case PACKET_READ_RESPONSE_END:
354 die(_("invalid packet"));
357 switch (state) {
358 case EXPECTING_FIRST_REF:
359 process_capabilities(reader, &len);
360 if (process_dummy_ref(reader)) {
361 state = EXPECTING_SHALLOW;
362 break;
364 state = EXPECTING_REF;
365 /* fallthrough */
366 case EXPECTING_REF:
367 if (process_ref(reader, len, &list, flags, extra_have))
368 break;
369 state = EXPECTING_SHALLOW;
370 /* fallthrough */
371 case EXPECTING_SHALLOW:
372 if (process_shallow(reader, len, shallow_points))
373 break;
374 die(_("protocol error: unexpected '%s'"), reader->line);
375 case EXPECTING_DONE:
376 break;
380 annotate_refs_with_symref_info(*orig_list);
382 return list;
385 /* Returns 1 when a valid ref has been added to `list`, 0 otherwise */
386 static int process_ref_v2(struct packet_reader *reader, struct ref ***list,
387 const char **unborn_head_target)
389 int ret = 1;
390 int i = 0;
391 struct object_id old_oid;
392 struct ref *ref;
393 struct string_list line_sections = STRING_LIST_INIT_DUP;
394 const char *end;
395 const char *line = reader->line;
398 * Ref lines have a number of fields which are space deliminated. The
399 * first field is the OID of the ref. The second field is the ref
400 * name. Subsequent fields (symref-target and peeled) are optional and
401 * don't have a particular order.
403 if (string_list_split(&line_sections, line, ' ', -1) < 2) {
404 ret = 0;
405 goto out;
408 if (!strcmp("unborn", line_sections.items[i].string)) {
409 i++;
410 if (unborn_head_target &&
411 !strcmp("HEAD", line_sections.items[i++].string)) {
413 * Look for the symref target (if any). If found,
414 * return it to the caller.
416 for (; i < line_sections.nr; i++) {
417 const char *arg = line_sections.items[i].string;
419 if (skip_prefix(arg, "symref-target:", &arg)) {
420 *unborn_head_target = xstrdup(arg);
421 break;
425 goto out;
427 if (parse_oid_hex_algop(line_sections.items[i++].string, &old_oid, &end, reader->hash_algo) ||
428 *end) {
429 ret = 0;
430 goto out;
433 ref = alloc_ref(line_sections.items[i++].string);
435 memcpy(ref->old_oid.hash, old_oid.hash, reader->hash_algo->rawsz);
436 **list = ref;
437 *list = &ref->next;
439 for (; i < line_sections.nr; i++) {
440 const char *arg = line_sections.items[i].string;
441 if (skip_prefix(arg, "symref-target:", &arg))
442 ref->symref = xstrdup(arg);
444 if (skip_prefix(arg, "peeled:", &arg)) {
445 struct object_id peeled_oid;
446 char *peeled_name;
447 struct ref *peeled;
448 if (parse_oid_hex_algop(arg, &peeled_oid, &end,
449 reader->hash_algo) || *end) {
450 ret = 0;
451 goto out;
454 peeled_name = xstrfmt("%s^{}", ref->name);
455 peeled = alloc_ref(peeled_name);
457 memcpy(peeled->old_oid.hash, peeled_oid.hash,
458 reader->hash_algo->rawsz);
459 **list = peeled;
460 *list = &peeled->next;
462 free(peeled_name);
466 out:
467 string_list_clear(&line_sections, 0);
468 return ret;
471 void check_stateless_delimiter(int stateless_rpc,
472 struct packet_reader *reader,
473 const char *error)
475 if (!stateless_rpc)
476 return; /* not in stateless mode, no delimiter expected */
477 if (packet_reader_read(reader) != PACKET_READ_RESPONSE_END)
478 die("%s", error);
481 static void send_capabilities(int fd_out, struct packet_reader *reader)
483 const char *hash_name;
485 if (server_supports_v2("agent"))
486 packet_write_fmt(fd_out, "agent=%s", git_user_agent_sanitized());
488 if (server_feature_v2("object-format", &hash_name)) {
489 int hash_algo = hash_algo_by_name(hash_name);
490 if (hash_algo == GIT_HASH_UNKNOWN)
491 die(_("unknown object format '%s' specified by server"), hash_name);
492 reader->hash_algo = &hash_algos[hash_algo];
493 packet_write_fmt(fd_out, "object-format=%s", reader->hash_algo->name);
494 } else {
495 reader->hash_algo = &hash_algos[GIT_HASH_SHA1];
499 int get_remote_bundle_uri(int fd_out, struct packet_reader *reader,
500 struct bundle_list *bundles, int stateless_rpc)
502 int line_nr = 1;
504 /* Assert bundle-uri support */
505 ensure_server_supports_v2("bundle-uri");
507 /* (Re-)send capabilities */
508 send_capabilities(fd_out, reader);
510 /* Send command */
511 packet_write_fmt(fd_out, "command=bundle-uri\n");
512 packet_delim(fd_out);
514 packet_flush(fd_out);
516 /* Process response from server */
517 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
518 const char *line = reader->line;
519 line_nr++;
521 if (!bundle_uri_parse_line(bundles, line))
522 continue;
524 return error(_("error on bundle-uri response line %d: %s"),
525 line_nr, line);
528 if (reader->status != PACKET_READ_FLUSH)
529 return error(_("expected flush after bundle-uri listing"));
532 * Might die(), but obscure enough that that's OK, e.g. in
533 * serve.c we'll call BUG() on its equivalent (the
534 * PACKET_READ_RESPONSE_END check).
536 check_stateless_delimiter(stateless_rpc, reader,
537 _("expected response end packet after ref listing"));
539 return 0;
542 struct ref **get_remote_refs(int fd_out, struct packet_reader *reader,
543 struct ref **list, int for_push,
544 struct transport_ls_refs_options *transport_options,
545 const struct string_list *server_options,
546 int stateless_rpc)
548 int i;
549 struct strvec *ref_prefixes = transport_options ?
550 &transport_options->ref_prefixes : NULL;
551 const char **unborn_head_target = transport_options ?
552 &transport_options->unborn_head_target : NULL;
553 *list = NULL;
555 ensure_server_supports_v2("ls-refs");
556 packet_write_fmt(fd_out, "command=ls-refs\n");
558 /* Send capabilities */
559 send_capabilities(fd_out, reader);
561 if (server_options && server_options->nr) {
562 ensure_server_supports_v2("server-option");
563 for (i = 0; i < server_options->nr; i++)
564 packet_write_fmt(fd_out, "server-option=%s",
565 server_options->items[i].string);
568 packet_delim(fd_out);
569 /* When pushing we don't want to request the peeled tags */
570 if (!for_push)
571 packet_write_fmt(fd_out, "peel\n");
572 packet_write_fmt(fd_out, "symrefs\n");
573 if (server_supports_feature("ls-refs", "unborn", 0))
574 packet_write_fmt(fd_out, "unborn\n");
575 for (i = 0; ref_prefixes && i < ref_prefixes->nr; i++) {
576 packet_write_fmt(fd_out, "ref-prefix %s\n",
577 ref_prefixes->v[i]);
579 packet_flush(fd_out);
581 /* Process response from server */
582 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
583 if (!process_ref_v2(reader, &list, unborn_head_target))
584 die(_("invalid ls-refs response: %s"), reader->line);
587 if (reader->status != PACKET_READ_FLUSH)
588 die(_("expected flush after ref listing"));
590 check_stateless_delimiter(stateless_rpc, reader,
591 _("expected response end packet after ref listing"));
593 return list;
596 const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp, int *offset)
598 int len;
600 if (!feature_list)
601 return NULL;
603 len = strlen(feature);
604 if (offset)
605 feature_list += *offset;
606 while (*feature_list) {
607 const char *found = strstr(feature_list, feature);
608 if (!found)
609 return NULL;
610 if (feature_list == found || isspace(found[-1])) {
611 const char *value = found + len;
612 /* feature with no value (e.g., "thin-pack") */
613 if (!*value || isspace(*value)) {
614 if (lenp)
615 *lenp = 0;
616 if (offset)
617 *offset = found + len - feature_list;
618 return value;
620 /* feature with a value (e.g., "agent=git/1.2.3") */
621 else if (*value == '=') {
622 int end;
624 value++;
625 end = strcspn(value, " \t\n");
626 if (lenp)
627 *lenp = end;
628 if (offset)
629 *offset = value + end - feature_list;
630 return value;
633 * otherwise we matched a substring of another feature;
634 * keep looking
637 feature_list = found + 1;
639 return NULL;
642 int server_supports_hash(const char *desired, int *feature_supported)
644 int offset = 0;
645 int len;
646 const char *hash;
648 hash = next_server_feature_value("object-format", &len, &offset);
649 if (feature_supported)
650 *feature_supported = !!hash;
651 if (!hash) {
652 hash = hash_algos[GIT_HASH_SHA1].name;
653 len = strlen(hash);
655 while (hash) {
656 if (!xstrncmpz(desired, hash, len))
657 return 1;
659 hash = next_server_feature_value("object-format", &len, &offset);
661 return 0;
664 int parse_feature_request(const char *feature_list, const char *feature)
666 return !!parse_feature_value(feature_list, feature, NULL, NULL);
669 static const char *next_server_feature_value(const char *feature, int *len, int *offset)
671 return parse_feature_value(server_capabilities_v1, feature, len, offset);
674 const char *server_feature_value(const char *feature, int *len)
676 return parse_feature_value(server_capabilities_v1, feature, len, NULL);
679 int server_supports(const char *feature)
681 return !!server_feature_value(feature, NULL);
684 enum protocol {
685 PROTO_LOCAL = 1,
686 PROTO_FILE,
687 PROTO_SSH,
688 PROTO_GIT
691 int url_is_local_not_ssh(const char *url)
693 const char *colon = strchr(url, ':');
694 const char *slash = strchr(url, '/');
695 return !colon || (slash && slash < colon) ||
696 (has_dos_drive_prefix(url) && is_valid_path(url));
699 static const char *prot_name(enum protocol protocol)
701 switch (protocol) {
702 case PROTO_LOCAL:
703 case PROTO_FILE:
704 return "file";
705 case PROTO_SSH:
706 return "ssh";
707 case PROTO_GIT:
708 return "git";
709 default:
710 return "unknown protocol";
714 static enum protocol get_protocol(const char *name)
716 if (!strcmp(name, "ssh"))
717 return PROTO_SSH;
718 if (!strcmp(name, "git"))
719 return PROTO_GIT;
720 if (!strcmp(name, "git+ssh")) /* deprecated - do not use */
721 return PROTO_SSH;
722 if (!strcmp(name, "ssh+git")) /* deprecated - do not use */
723 return PROTO_SSH;
724 if (!strcmp(name, "file"))
725 return PROTO_FILE;
726 die(_("protocol '%s' is not supported"), name);
729 static char *host_end(char **hoststart, int removebrackets)
731 char *host = *hoststart;
732 char *end;
733 char *start = strstr(host, "@[");
734 if (start)
735 start++; /* Jump over '@' */
736 else
737 start = host;
738 if (start[0] == '[') {
739 end = strchr(start + 1, ']');
740 if (end) {
741 if (removebrackets) {
742 *end = 0;
743 memmove(start, start + 1, end - start);
744 end++;
746 } else
747 end = host;
748 } else
749 end = host;
750 return end;
753 #define STR_(s) # s
754 #define STR(s) STR_(s)
756 static void get_host_and_port(char **host, const char **port)
758 char *colon, *end;
759 end = host_end(host, 1);
760 colon = strchr(end, ':');
761 if (colon) {
762 long portnr = strtol(colon + 1, &end, 10);
763 if (end != colon + 1 && *end == '\0' && 0 <= portnr && portnr < 65536) {
764 *colon = 0;
765 *port = colon + 1;
766 } else if (!colon[1]) {
767 *colon = 0;
772 static void enable_keepalive(int sockfd)
774 int ka = 1;
776 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
777 error_errno(_("unable to set SO_KEEPALIVE on socket"));
780 #ifndef NO_IPV6
782 static const char *ai_name(const struct addrinfo *ai)
784 static char addr[NI_MAXHOST];
785 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
786 NI_NUMERICHOST) != 0)
787 xsnprintf(addr, sizeof(addr), "(unknown)");
789 return addr;
793 * Returns a connected socket() fd, or else die()s.
795 static int git_tcp_connect_sock(char *host, int flags)
797 struct strbuf error_message = STRBUF_INIT;
798 int sockfd = -1;
799 const char *port = STR(DEFAULT_GIT_PORT);
800 struct addrinfo hints, *ai0, *ai;
801 int gai;
802 int cnt = 0;
804 get_host_and_port(&host, &port);
805 if (!*port)
806 port = "<none>";
808 memset(&hints, 0, sizeof(hints));
809 if (flags & CONNECT_IPV4)
810 hints.ai_family = AF_INET;
811 else if (flags & CONNECT_IPV6)
812 hints.ai_family = AF_INET6;
813 hints.ai_socktype = SOCK_STREAM;
814 hints.ai_protocol = IPPROTO_TCP;
816 if (flags & CONNECT_VERBOSE)
817 fprintf(stderr, _("Looking up %s ... "), host);
819 gai = getaddrinfo(host, port, &hints, &ai);
820 if (gai)
821 die(_("unable to look up %s (port %s) (%s)"), host, port, gai_strerror(gai));
823 if (flags & CONNECT_VERBOSE)
824 /* TRANSLATORS: this is the end of "Looking up %s ... " */
825 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
827 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
828 sockfd = socket(ai->ai_family,
829 ai->ai_socktype, ai->ai_protocol);
830 if ((sockfd < 0) ||
831 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
832 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
833 host, cnt, ai_name(ai), strerror(errno));
834 if (0 <= sockfd)
835 close(sockfd);
836 sockfd = -1;
837 continue;
839 if (flags & CONNECT_VERBOSE)
840 fprintf(stderr, "%s ", ai_name(ai));
841 break;
844 freeaddrinfo(ai0);
846 if (sockfd < 0)
847 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
849 enable_keepalive(sockfd);
851 if (flags & CONNECT_VERBOSE)
852 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
853 fprintf_ln(stderr, _("done."));
855 strbuf_release(&error_message);
857 return sockfd;
860 #else /* NO_IPV6 */
863 * Returns a connected socket() fd, or else die()s.
865 static int git_tcp_connect_sock(char *host, int flags)
867 struct strbuf error_message = STRBUF_INIT;
868 int sockfd = -1;
869 const char *port = STR(DEFAULT_GIT_PORT);
870 char *ep;
871 struct hostent *he;
872 struct sockaddr_in sa;
873 char **ap;
874 unsigned int nport;
875 int cnt;
877 get_host_and_port(&host, &port);
879 if (flags & CONNECT_VERBOSE)
880 fprintf(stderr, _("Looking up %s ... "), host);
882 he = gethostbyname(host);
883 if (!he)
884 die(_("unable to look up %s (%s)"), host, hstrerror(h_errno));
885 nport = strtoul(port, &ep, 10);
886 if ( ep == port || *ep ) {
887 /* Not numeric */
888 struct servent *se = getservbyname(port,"tcp");
889 if ( !se )
890 die(_("unknown port %s"), port);
891 nport = se->s_port;
894 if (flags & CONNECT_VERBOSE)
895 /* TRANSLATORS: this is the end of "Looking up %s ... " */
896 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
898 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
899 memset(&sa, 0, sizeof sa);
900 sa.sin_family = he->h_addrtype;
901 sa.sin_port = htons(nport);
902 memcpy(&sa.sin_addr, *ap, he->h_length);
904 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
905 if ((sockfd < 0) ||
906 connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
907 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
908 host,
909 cnt,
910 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
911 strerror(errno));
912 if (0 <= sockfd)
913 close(sockfd);
914 sockfd = -1;
915 continue;
917 if (flags & CONNECT_VERBOSE)
918 fprintf(stderr, "%s ",
919 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
920 break;
923 if (sockfd < 0)
924 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
926 enable_keepalive(sockfd);
928 if (flags & CONNECT_VERBOSE)
929 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
930 fprintf_ln(stderr, _("done."));
932 return sockfd;
935 #endif /* NO_IPV6 */
939 * Dummy child_process returned by git_connect() if the transport protocol
940 * does not need fork(2).
942 static struct child_process no_fork = CHILD_PROCESS_INIT;
944 int git_connection_is_socket(struct child_process *conn)
946 return conn == &no_fork;
949 static struct child_process *git_tcp_connect(int fd[2], char *host, int flags)
951 int sockfd = git_tcp_connect_sock(host, flags);
953 fd[0] = sockfd;
954 fd[1] = dup(sockfd);
956 return &no_fork;
960 static char *git_proxy_command;
962 static int git_proxy_command_options(const char *var, const char *value,
963 void *cb)
965 if (!strcmp(var, "core.gitproxy")) {
966 const char *for_pos;
967 int matchlen = -1;
968 int hostlen;
969 const char *rhost_name = cb;
970 int rhost_len = strlen(rhost_name);
972 if (git_proxy_command)
973 return 0;
974 if (!value)
975 return config_error_nonbool(var);
976 /* [core]
977 * ;# matches www.kernel.org as well
978 * gitproxy = netcatter-1 for kernel.org
979 * gitproxy = netcatter-2 for sample.xz
980 * gitproxy = netcatter-default
982 for_pos = strstr(value, " for ");
983 if (!for_pos)
984 /* matches everybody */
985 matchlen = strlen(value);
986 else {
987 hostlen = strlen(for_pos + 5);
988 if (rhost_len < hostlen)
989 matchlen = -1;
990 else if (!strncmp(for_pos + 5,
991 rhost_name + rhost_len - hostlen,
992 hostlen) &&
993 ((rhost_len == hostlen) ||
994 rhost_name[rhost_len - hostlen -1] == '.'))
995 matchlen = for_pos - value;
996 else
997 matchlen = -1;
999 if (0 <= matchlen) {
1000 /* core.gitproxy = none for kernel.org */
1001 if (matchlen == 4 &&
1002 !memcmp(value, "none", 4))
1003 matchlen = 0;
1004 git_proxy_command = xmemdupz(value, matchlen);
1006 return 0;
1009 return git_default_config(var, value, cb);
1012 static int git_use_proxy(const char *host)
1014 git_proxy_command = getenv("GIT_PROXY_COMMAND");
1015 git_config(git_proxy_command_options, (void*)host);
1016 return (git_proxy_command && *git_proxy_command);
1019 static struct child_process *git_proxy_connect(int fd[2], char *host)
1021 const char *port = STR(DEFAULT_GIT_PORT);
1022 struct child_process *proxy;
1024 get_host_and_port(&host, &port);
1026 if (looks_like_command_line_option(host))
1027 die(_("strange hostname '%s' blocked"), host);
1028 if (looks_like_command_line_option(port))
1029 die(_("strange port '%s' blocked"), port);
1031 proxy = xmalloc(sizeof(*proxy));
1032 child_process_init(proxy);
1033 strvec_push(&proxy->args, git_proxy_command);
1034 strvec_push(&proxy->args, host);
1035 strvec_push(&proxy->args, port);
1036 proxy->in = -1;
1037 proxy->out = -1;
1038 if (start_command(proxy))
1039 die(_("cannot start proxy %s"), git_proxy_command);
1040 fd[0] = proxy->out; /* read from proxy stdout */
1041 fd[1] = proxy->in; /* write to proxy stdin */
1042 return proxy;
1045 static char *get_port(char *host)
1047 char *end;
1048 char *p = strchr(host, ':');
1050 if (p) {
1051 long port = strtol(p + 1, &end, 10);
1052 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
1053 *p = '\0';
1054 return p+1;
1058 return NULL;
1062 * Extract protocol and relevant parts from the specified connection URL.
1063 * The caller must free() the returned strings.
1065 static enum protocol parse_connect_url(const char *url_orig, char **ret_host,
1066 char **ret_path)
1068 char *url;
1069 char *host, *path;
1070 char *end;
1071 int separator = '/';
1072 enum protocol protocol = PROTO_LOCAL;
1074 if (is_url(url_orig))
1075 url = url_decode(url_orig);
1076 else
1077 url = xstrdup(url_orig);
1079 host = strstr(url, "://");
1080 if (host) {
1081 *host = '\0';
1082 protocol = get_protocol(url);
1083 host += 3;
1084 } else {
1085 host = url;
1086 if (!url_is_local_not_ssh(url)) {
1087 protocol = PROTO_SSH;
1088 separator = ':';
1093 * Don't do destructive transforms as protocol code does
1094 * '[]' unwrapping in get_host_and_port()
1096 end = host_end(&host, 0);
1098 if (protocol == PROTO_LOCAL)
1099 path = end;
1100 else if (protocol == PROTO_FILE && *host != '/' &&
1101 !has_dos_drive_prefix(host) &&
1102 offset_1st_component(host - 2) > 1)
1103 path = host - 2; /* include the leading "//" */
1104 else if (protocol == PROTO_FILE && has_dos_drive_prefix(end))
1105 path = end; /* "file://$(pwd)" may be "file://C:/projects/repo" */
1106 else
1107 path = strchr(end, separator);
1109 if (!path || !*path)
1110 die(_("no path specified; see 'git help pull' for valid url syntax"));
1113 * null-terminate hostname and point path to ~ for URL's like this:
1114 * ssh://host.xz/~user/repo
1117 end = path; /* Need to \0 terminate host here */
1118 if (separator == ':')
1119 path++; /* path starts after ':' */
1120 if (protocol == PROTO_GIT || protocol == PROTO_SSH) {
1121 if (path[1] == '~')
1122 path++;
1125 path = xstrdup(path);
1126 *end = '\0';
1128 *ret_host = xstrdup(host);
1129 *ret_path = path;
1130 free(url);
1131 return protocol;
1134 static const char *get_ssh_command(void)
1136 const char *ssh;
1138 if ((ssh = getenv("GIT_SSH_COMMAND")))
1139 return ssh;
1141 if (!git_config_get_string_tmp("core.sshcommand", &ssh))
1142 return ssh;
1144 return NULL;
1147 enum ssh_variant {
1148 VARIANT_AUTO,
1149 VARIANT_SIMPLE,
1150 VARIANT_SSH,
1151 VARIANT_PLINK,
1152 VARIANT_PUTTY,
1153 VARIANT_TORTOISEPLINK,
1156 static void override_ssh_variant(enum ssh_variant *ssh_variant)
1158 const char *variant = getenv("GIT_SSH_VARIANT");
1160 if (!variant && git_config_get_string_tmp("ssh.variant", &variant))
1161 return;
1163 if (!strcmp(variant, "auto"))
1164 *ssh_variant = VARIANT_AUTO;
1165 else if (!strcmp(variant, "plink"))
1166 *ssh_variant = VARIANT_PLINK;
1167 else if (!strcmp(variant, "putty"))
1168 *ssh_variant = VARIANT_PUTTY;
1169 else if (!strcmp(variant, "tortoiseplink"))
1170 *ssh_variant = VARIANT_TORTOISEPLINK;
1171 else if (!strcmp(variant, "simple"))
1172 *ssh_variant = VARIANT_SIMPLE;
1173 else
1174 *ssh_variant = VARIANT_SSH;
1177 static enum ssh_variant determine_ssh_variant(const char *ssh_command,
1178 int is_cmdline)
1180 enum ssh_variant ssh_variant = VARIANT_AUTO;
1181 const char *variant;
1182 char *p = NULL;
1184 override_ssh_variant(&ssh_variant);
1186 if (ssh_variant != VARIANT_AUTO)
1187 return ssh_variant;
1189 if (!is_cmdline) {
1190 p = xstrdup(ssh_command);
1191 variant = basename(p);
1192 } else {
1193 const char **ssh_argv;
1195 p = xstrdup(ssh_command);
1196 if (split_cmdline(p, &ssh_argv) > 0) {
1197 variant = basename((char *)ssh_argv[0]);
1199 * At this point, variant points into the buffer
1200 * referenced by p, hence we do not need ssh_argv
1201 * any longer.
1203 free(ssh_argv);
1204 } else {
1205 free(p);
1206 return ssh_variant;
1210 if (!strcasecmp(variant, "ssh") ||
1211 !strcasecmp(variant, "ssh.exe"))
1212 ssh_variant = VARIANT_SSH;
1213 else if (!strcasecmp(variant, "plink") ||
1214 !strcasecmp(variant, "plink.exe"))
1215 ssh_variant = VARIANT_PLINK;
1216 else if (!strcasecmp(variant, "tortoiseplink") ||
1217 !strcasecmp(variant, "tortoiseplink.exe"))
1218 ssh_variant = VARIANT_TORTOISEPLINK;
1220 free(p);
1221 return ssh_variant;
1225 * Open a connection using Git's native protocol.
1227 * The caller is responsible for freeing hostandport, but this function may
1228 * modify it (for example, to truncate it to remove the port part).
1230 static struct child_process *git_connect_git(int fd[2], char *hostandport,
1231 const char *path, const char *prog,
1232 enum protocol_version version,
1233 int flags)
1235 struct child_process *conn;
1236 struct strbuf request = STRBUF_INIT;
1238 * Set up virtual host information based on where we will
1239 * connect, unless the user has overridden us in
1240 * the environment.
1242 char *target_host = getenv("GIT_OVERRIDE_VIRTUAL_HOST");
1243 if (target_host)
1244 target_host = xstrdup(target_host);
1245 else
1246 target_host = xstrdup(hostandport);
1248 transport_check_allowed("git");
1249 if (strchr(target_host, '\n') || strchr(path, '\n'))
1250 die(_("newline is forbidden in git:// hosts and repo paths"));
1253 * These underlying connection commands die() if they
1254 * cannot connect.
1256 if (git_use_proxy(hostandport))
1257 conn = git_proxy_connect(fd, hostandport);
1258 else
1259 conn = git_tcp_connect(fd, hostandport, flags);
1261 * Separate original protocol components prog and path
1262 * from extended host header with a NUL byte.
1264 * Note: Do not add any other headers here! Doing so
1265 * will cause older git-daemon servers to crash.
1267 strbuf_addf(&request,
1268 "%s %s%chost=%s%c",
1269 prog, path, 0,
1270 target_host, 0);
1272 /* If using a new version put that stuff here after a second null byte */
1273 if (version > 0) {
1274 strbuf_addch(&request, '\0');
1275 strbuf_addf(&request, "version=%d%c",
1276 version, '\0');
1279 packet_write(fd[1], request.buf, request.len);
1281 free(target_host);
1282 strbuf_release(&request);
1283 return conn;
1287 * Append the appropriate environment variables to `env` and options to
1288 * `args` for running ssh in Git's SSH-tunneled transport.
1290 static void push_ssh_options(struct strvec *args, struct strvec *env,
1291 enum ssh_variant variant, const char *port,
1292 enum protocol_version version, int flags)
1294 if (variant == VARIANT_SSH &&
1295 version > 0) {
1296 strvec_push(args, "-o");
1297 strvec_push(args, "SendEnv=" GIT_PROTOCOL_ENVIRONMENT);
1298 strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1299 version);
1302 if (flags & CONNECT_IPV4) {
1303 switch (variant) {
1304 case VARIANT_AUTO:
1305 BUG("VARIANT_AUTO passed to push_ssh_options");
1306 case VARIANT_SIMPLE:
1307 die(_("ssh variant 'simple' does not support -4"));
1308 case VARIANT_SSH:
1309 case VARIANT_PLINK:
1310 case VARIANT_PUTTY:
1311 case VARIANT_TORTOISEPLINK:
1312 strvec_push(args, "-4");
1314 } else if (flags & CONNECT_IPV6) {
1315 switch (variant) {
1316 case VARIANT_AUTO:
1317 BUG("VARIANT_AUTO passed to push_ssh_options");
1318 case VARIANT_SIMPLE:
1319 die(_("ssh variant 'simple' does not support -6"));
1320 case VARIANT_SSH:
1321 case VARIANT_PLINK:
1322 case VARIANT_PUTTY:
1323 case VARIANT_TORTOISEPLINK:
1324 strvec_push(args, "-6");
1328 if (variant == VARIANT_TORTOISEPLINK)
1329 strvec_push(args, "-batch");
1331 if (port) {
1332 switch (variant) {
1333 case VARIANT_AUTO:
1334 BUG("VARIANT_AUTO passed to push_ssh_options");
1335 case VARIANT_SIMPLE:
1336 die(_("ssh variant 'simple' does not support setting port"));
1337 case VARIANT_SSH:
1338 strvec_push(args, "-p");
1339 break;
1340 case VARIANT_PLINK:
1341 case VARIANT_PUTTY:
1342 case VARIANT_TORTOISEPLINK:
1343 strvec_push(args, "-P");
1346 strvec_push(args, port);
1350 /* Prepare a child_process for use by Git's SSH-tunneled transport. */
1351 static void fill_ssh_args(struct child_process *conn, const char *ssh_host,
1352 const char *port, enum protocol_version version,
1353 int flags)
1355 const char *ssh;
1356 enum ssh_variant variant;
1358 if (looks_like_command_line_option(ssh_host))
1359 die(_("strange hostname '%s' blocked"), ssh_host);
1361 ssh = get_ssh_command();
1362 if (ssh) {
1363 variant = determine_ssh_variant(ssh, 1);
1364 } else {
1366 * GIT_SSH is the no-shell version of
1367 * GIT_SSH_COMMAND (and must remain so for
1368 * historical compatibility).
1370 conn->use_shell = 0;
1372 ssh = getenv("GIT_SSH");
1373 if (!ssh)
1374 ssh = "ssh";
1375 variant = determine_ssh_variant(ssh, 0);
1378 if (variant == VARIANT_AUTO) {
1379 struct child_process detect = CHILD_PROCESS_INIT;
1381 detect.use_shell = conn->use_shell;
1382 detect.no_stdin = detect.no_stdout = detect.no_stderr = 1;
1384 strvec_push(&detect.args, ssh);
1385 strvec_push(&detect.args, "-G");
1386 push_ssh_options(&detect.args, &detect.env,
1387 VARIANT_SSH, port, version, flags);
1388 strvec_push(&detect.args, ssh_host);
1390 variant = run_command(&detect) ? VARIANT_SIMPLE : VARIANT_SSH;
1393 strvec_push(&conn->args, ssh);
1394 push_ssh_options(&conn->args, &conn->env, variant, port, version,
1395 flags);
1396 strvec_push(&conn->args, ssh_host);
1400 * This returns the dummy child_process `no_fork` if the transport protocol
1401 * does not need fork(2), or a struct child_process object if it does. Once
1402 * done, finish the connection with finish_connect() with the value returned
1403 * from this function (it is safe to call finish_connect() with NULL to
1404 * support the former case).
1406 * If it returns, the connect is successful; it just dies on errors (this
1407 * will hopefully be changed in a libification effort, to return NULL when
1408 * the connection failed).
1410 struct child_process *git_connect(int fd[2], const char *url,
1411 const char *name,
1412 const char *prog, int flags)
1414 char *hostandport, *path;
1415 struct child_process *conn;
1416 enum protocol protocol;
1417 enum protocol_version version = get_protocol_version_config();
1420 * NEEDSWORK: If we are trying to use protocol v2 and we are planning
1421 * to perform any operation that doesn't involve upload-pack (i.e., a
1422 * fetch, ls-remote, etc), then fallback to v0 since we don't know how
1423 * to do anything else (like push or remote archive) via v2.
1425 if (version == protocol_v2 && strcmp("git-upload-pack", name))
1426 version = protocol_v0;
1428 /* Without this we cannot rely on waitpid() to tell
1429 * what happened to our children.
1431 signal(SIGCHLD, SIG_DFL);
1433 protocol = parse_connect_url(url, &hostandport, &path);
1434 if ((flags & CONNECT_DIAG_URL) && (protocol != PROTO_SSH)) {
1435 printf("Diag: url=%s\n", url ? url : "NULL");
1436 printf("Diag: protocol=%s\n", prot_name(protocol));
1437 printf("Diag: hostandport=%s\n", hostandport ? hostandport : "NULL");
1438 printf("Diag: path=%s\n", path ? path : "NULL");
1439 conn = NULL;
1440 } else if (protocol == PROTO_GIT) {
1441 conn = git_connect_git(fd, hostandport, path, prog, version, flags);
1442 conn->trace2_child_class = "transport/git";
1443 } else {
1444 struct strbuf cmd = STRBUF_INIT;
1445 const char *const *var;
1447 conn = xmalloc(sizeof(*conn));
1448 child_process_init(conn);
1450 if (looks_like_command_line_option(path))
1451 die(_("strange pathname '%s' blocked"), path);
1453 strbuf_addstr(&cmd, prog);
1454 strbuf_addch(&cmd, ' ');
1455 sq_quote_buf(&cmd, path);
1457 /* remove repo-local variables from the environment */
1458 for (var = local_repo_env; *var; var++)
1459 strvec_push(&conn->env, *var);
1461 conn->use_shell = 1;
1462 conn->in = conn->out = -1;
1463 if (protocol == PROTO_SSH) {
1464 char *ssh_host = hostandport;
1465 const char *port = NULL;
1466 transport_check_allowed("ssh");
1467 get_host_and_port(&ssh_host, &port);
1469 if (!port)
1470 port = get_port(ssh_host);
1472 if (flags & CONNECT_DIAG_URL) {
1473 printf("Diag: url=%s\n", url ? url : "NULL");
1474 printf("Diag: protocol=%s\n", prot_name(protocol));
1475 printf("Diag: userandhost=%s\n", ssh_host ? ssh_host : "NULL");
1476 printf("Diag: port=%s\n", port ? port : "NONE");
1477 printf("Diag: path=%s\n", path ? path : "NULL");
1479 free(hostandport);
1480 free(path);
1481 free(conn);
1482 strbuf_release(&cmd);
1483 return NULL;
1485 conn->trace2_child_class = "transport/ssh";
1486 fill_ssh_args(conn, ssh_host, port, version, flags);
1487 } else {
1488 transport_check_allowed("file");
1489 conn->trace2_child_class = "transport/file";
1490 if (version > 0) {
1491 strvec_pushf(&conn->env,
1492 GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1493 version);
1496 strvec_push(&conn->args, cmd.buf);
1498 if (start_command(conn))
1499 die(_("unable to fork"));
1501 fd[0] = conn->out; /* read from child's stdout */
1502 fd[1] = conn->in; /* write to child's stdin */
1503 strbuf_release(&cmd);
1505 free(hostandport);
1506 free(path);
1507 return conn;
1510 int finish_connect(struct child_process *conn)
1512 int code;
1513 if (!conn || git_connection_is_socket(conn))
1514 return 0;
1516 code = finish_command(conn);
1517 free(conn);
1518 return code;