Merge branch 'ab/avoid-losing-exit-codes-in-tests'
[git/debian.git] / connect.c
blob134069574a2cc02f9be201c9677cd03c25f125aa
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, 0))
35 return 0;
37 /* REF_HEADS means that we want regular branch heads */
38 if ((flags & REF_HEADS) && starts_with(name, "heads/"))
39 return 1;
41 /* REF_TAGS means that we want tags */
42 if ((flags & REF_TAGS) && starts_with(name, "tags/"))
43 return 1;
45 /* All type bits clear means that we are ok with anything */
46 return !(flags & ~REF_NORMAL);
49 int check_ref_type(const struct ref *ref, int flags)
51 return check_ref(ref->name, flags);
54 static NORETURN void die_initial_contact(int unexpected)
57 * A hang-up after seeing some response from the other end
58 * means that it is unexpected, as we know the other end is
59 * willing to talk to us. A hang-up before seeing any
60 * response does not necessarily mean an ACL problem, though.
62 if (unexpected)
63 die(_("the remote end hung up upon initial contact"));
64 else
65 die(_("Could not read from remote repository.\n\n"
66 "Please make sure you have the correct access rights\n"
67 "and the repository exists."));
70 /* Checks if the server supports the capability 'c' */
71 int server_supports_v2(const char *c)
73 int i;
75 for (i = 0; i < server_capabilities_v2.nr; i++) {
76 const char *out;
77 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
78 (!*out || *out == '='))
79 return 1;
81 return 0;
84 void ensure_server_supports_v2(const char *c)
86 if (!server_supports_v2(c))
87 die(_("server doesn't support '%s'"), c);
90 int server_feature_v2(const char *c, const char **v)
92 int i;
94 for (i = 0; i < server_capabilities_v2.nr; i++) {
95 const char *out;
96 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
97 (*out == '=')) {
98 *v = out + 1;
99 return 1;
102 return 0;
105 int server_supports_feature(const char *c, const char *feature,
106 int die_on_error)
108 int i;
110 for (i = 0; i < server_capabilities_v2.nr; i++) {
111 const char *out;
112 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
113 (!*out || *(out++) == '=')) {
114 if (parse_feature_request(out, feature))
115 return 1;
116 else
117 break;
121 if (die_on_error)
122 die(_("server doesn't support feature '%s'"), feature);
124 return 0;
127 static void process_capabilities_v2(struct packet_reader *reader)
129 while (packet_reader_read(reader) == PACKET_READ_NORMAL)
130 strvec_push(&server_capabilities_v2, reader->line);
132 if (reader->status != PACKET_READ_FLUSH)
133 die(_("expected flush after capabilities"));
136 enum protocol_version discover_version(struct packet_reader *reader)
138 enum protocol_version version = protocol_unknown_version;
141 * Peek the first line of the server's response to
142 * determine the protocol version the server is speaking.
144 switch (packet_reader_peek(reader)) {
145 case PACKET_READ_EOF:
146 die_initial_contact(0);
147 case PACKET_READ_FLUSH:
148 case PACKET_READ_DELIM:
149 case PACKET_READ_RESPONSE_END:
150 version = protocol_v0;
151 break;
152 case PACKET_READ_NORMAL:
153 version = determine_protocol_version_client(reader->line);
154 break;
157 switch (version) {
158 case protocol_v2:
159 process_capabilities_v2(reader);
160 break;
161 case protocol_v1:
162 /* Read the peeked version line */
163 packet_reader_read(reader);
164 break;
165 case protocol_v0:
166 break;
167 case protocol_unknown_version:
168 BUG("unknown protocol version");
171 trace2_data_intmax("transfer", NULL, "negotiated-version", version);
173 return version;
176 static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
178 char *sym, *target;
179 struct string_list_item *item;
181 if (!len)
182 return; /* just "symref" */
183 /* e.g. "symref=HEAD:refs/heads/master" */
184 sym = xmemdupz(val, len);
185 target = strchr(sym, ':');
186 if (!target)
187 /* just "symref=something" */
188 goto reject;
189 *(target++) = '\0';
190 if (check_refname_format(sym, REFNAME_ALLOW_ONELEVEL) ||
191 check_refname_format(target, REFNAME_ALLOW_ONELEVEL))
192 /* "symref=bogus:pair */
193 goto reject;
194 item = string_list_append_nodup(symref, sym);
195 item->util = target;
196 return;
197 reject:
198 free(sym);
199 return;
202 static void annotate_refs_with_symref_info(struct ref *ref)
204 struct string_list symref = STRING_LIST_INIT_DUP;
205 int offset = 0;
207 while (1) {
208 int len;
209 const char *val;
211 val = next_server_feature_value("symref", &len, &offset);
212 if (!val)
213 break;
214 parse_one_symref_info(&symref, val, len);
216 string_list_sort(&symref);
218 for (; ref; ref = ref->next) {
219 struct string_list_item *item;
220 item = string_list_lookup(&symref, ref->name);
221 if (!item)
222 continue;
223 ref->symref = xstrdup((char *)item->util);
225 string_list_clear(&symref, 0);
228 static void process_capabilities(struct packet_reader *reader, int *linelen)
230 const char *feat_val;
231 int feat_len;
232 const char *line = reader->line;
233 int nul_location = strlen(line);
234 if (nul_location == *linelen)
235 return;
236 server_capabilities_v1 = xstrdup(line + nul_location + 1);
237 *linelen = nul_location;
239 feat_val = server_feature_value("object-format", &feat_len);
240 if (feat_val) {
241 char *hash_name = xstrndup(feat_val, feat_len);
242 int hash_algo = hash_algo_by_name(hash_name);
243 if (hash_algo != GIT_HASH_UNKNOWN)
244 reader->hash_algo = &hash_algos[hash_algo];
245 free(hash_name);
246 } else {
247 reader->hash_algo = &hash_algos[GIT_HASH_SHA1];
251 static int process_dummy_ref(const struct packet_reader *reader)
253 const char *line = reader->line;
254 struct object_id oid;
255 const char *name;
257 if (parse_oid_hex_algop(line, &oid, &name, reader->hash_algo))
258 return 0;
259 if (*name != ' ')
260 return 0;
261 name++;
263 return oideq(null_oid(), &oid) && !strcmp(name, "capabilities^{}");
266 static void check_no_capabilities(const char *line, int len)
268 if (strlen(line) != len)
269 warning(_("ignoring capabilities after first line '%s'"),
270 line + strlen(line));
273 static int process_ref(const struct packet_reader *reader, int len,
274 struct ref ***list, unsigned int flags,
275 struct oid_array *extra_have)
277 const char *line = reader->line;
278 struct object_id old_oid;
279 const char *name;
281 if (parse_oid_hex_algop(line, &old_oid, &name, reader->hash_algo))
282 return 0;
283 if (*name != ' ')
284 return 0;
285 name++;
287 if (extra_have && !strcmp(name, ".have")) {
288 oid_array_append(extra_have, &old_oid);
289 } else if (!strcmp(name, "capabilities^{}")) {
290 die(_("protocol error: unexpected capabilities^{}"));
291 } else if (check_ref(name, flags)) {
292 struct ref *ref = alloc_ref(name);
293 oidcpy(&ref->old_oid, &old_oid);
294 **list = ref;
295 *list = &ref->next;
297 check_no_capabilities(line, len);
298 return 1;
301 static int process_shallow(const struct packet_reader *reader, int len,
302 struct oid_array *shallow_points)
304 const char *line = reader->line;
305 const char *arg;
306 struct object_id old_oid;
308 if (!skip_prefix(line, "shallow ", &arg))
309 return 0;
311 if (get_oid_hex_algop(arg, &old_oid, reader->hash_algo))
312 die(_("protocol error: expected shallow sha-1, got '%s'"), arg);
313 if (!shallow_points)
314 die(_("repository on the other end cannot be shallow"));
315 oid_array_append(shallow_points, &old_oid);
316 check_no_capabilities(line, len);
317 return 1;
320 enum get_remote_heads_state {
321 EXPECTING_FIRST_REF = 0,
322 EXPECTING_REF,
323 EXPECTING_SHALLOW,
324 EXPECTING_DONE,
328 * Read all the refs from the other end
330 struct ref **get_remote_heads(struct packet_reader *reader,
331 struct ref **list, unsigned int flags,
332 struct oid_array *extra_have,
333 struct oid_array *shallow_points)
335 struct ref **orig_list = list;
336 int len = 0;
337 enum get_remote_heads_state state = EXPECTING_FIRST_REF;
339 *list = NULL;
341 while (state != EXPECTING_DONE) {
342 switch (packet_reader_read(reader)) {
343 case PACKET_READ_EOF:
344 die_initial_contact(1);
345 case PACKET_READ_NORMAL:
346 len = reader->pktlen;
347 break;
348 case PACKET_READ_FLUSH:
349 state = EXPECTING_DONE;
350 break;
351 case PACKET_READ_DELIM:
352 case PACKET_READ_RESPONSE_END:
353 die(_("invalid packet"));
356 switch (state) {
357 case EXPECTING_FIRST_REF:
358 process_capabilities(reader, &len);
359 if (process_dummy_ref(reader)) {
360 state = EXPECTING_SHALLOW;
361 break;
363 state = EXPECTING_REF;
364 /* fallthrough */
365 case EXPECTING_REF:
366 if (process_ref(reader, len, &list, flags, extra_have))
367 break;
368 state = EXPECTING_SHALLOW;
369 /* fallthrough */
370 case EXPECTING_SHALLOW:
371 if (process_shallow(reader, len, shallow_points))
372 break;
373 die(_("protocol error: unexpected '%s'"), reader->line);
374 case EXPECTING_DONE:
375 break;
379 annotate_refs_with_symref_info(*orig_list);
381 return list;
384 /* Returns 1 when a valid ref has been added to `list`, 0 otherwise */
385 static int process_ref_v2(struct packet_reader *reader, struct ref ***list,
386 const char **unborn_head_target)
388 int ret = 1;
389 int i = 0;
390 struct object_id old_oid;
391 struct ref *ref;
392 struct string_list line_sections = STRING_LIST_INIT_DUP;
393 const char *end;
394 const char *line = reader->line;
397 * Ref lines have a number of fields which are space deliminated. The
398 * first field is the OID of the ref. The second field is the ref
399 * name. Subsequent fields (symref-target and peeled) are optional and
400 * don't have a particular order.
402 if (string_list_split(&line_sections, line, ' ', -1) < 2) {
403 ret = 0;
404 goto out;
407 if (!strcmp("unborn", line_sections.items[i].string)) {
408 i++;
409 if (unborn_head_target &&
410 !strcmp("HEAD", line_sections.items[i++].string)) {
412 * Look for the symref target (if any). If found,
413 * return it to the caller.
415 for (; i < line_sections.nr; i++) {
416 const char *arg = line_sections.items[i].string;
418 if (skip_prefix(arg, "symref-target:", &arg)) {
419 *unborn_head_target = xstrdup(arg);
420 break;
424 goto out;
426 if (parse_oid_hex_algop(line_sections.items[i++].string, &old_oid, &end, reader->hash_algo) ||
427 *end) {
428 ret = 0;
429 goto out;
432 ref = alloc_ref(line_sections.items[i++].string);
434 memcpy(ref->old_oid.hash, old_oid.hash, reader->hash_algo->rawsz);
435 **list = ref;
436 *list = &ref->next;
438 for (; i < line_sections.nr; i++) {
439 const char *arg = line_sections.items[i].string;
440 if (skip_prefix(arg, "symref-target:", &arg))
441 ref->symref = xstrdup(arg);
443 if (skip_prefix(arg, "peeled:", &arg)) {
444 struct object_id peeled_oid;
445 char *peeled_name;
446 struct ref *peeled;
447 if (parse_oid_hex_algop(arg, &peeled_oid, &end,
448 reader->hash_algo) || *end) {
449 ret = 0;
450 goto out;
453 peeled_name = xstrfmt("%s^{}", ref->name);
454 peeled = alloc_ref(peeled_name);
456 memcpy(peeled->old_oid.hash, peeled_oid.hash,
457 reader->hash_algo->rawsz);
458 **list = peeled;
459 *list = &peeled->next;
461 free(peeled_name);
465 out:
466 string_list_clear(&line_sections, 0);
467 return ret;
470 void check_stateless_delimiter(int stateless_rpc,
471 struct packet_reader *reader,
472 const char *error)
474 if (!stateless_rpc)
475 return; /* not in stateless mode, no delimiter expected */
476 if (packet_reader_read(reader) != PACKET_READ_RESPONSE_END)
477 die("%s", error);
480 static void send_capabilities(int fd_out, struct packet_reader *reader)
482 const char *hash_name;
484 if (server_supports_v2("agent"))
485 packet_write_fmt(fd_out, "agent=%s", git_user_agent_sanitized());
487 if (server_feature_v2("object-format", &hash_name)) {
488 int hash_algo = hash_algo_by_name(hash_name);
489 if (hash_algo == GIT_HASH_UNKNOWN)
490 die(_("unknown object format '%s' specified by server"), hash_name);
491 reader->hash_algo = &hash_algos[hash_algo];
492 packet_write_fmt(fd_out, "object-format=%s", reader->hash_algo->name);
493 } else {
494 reader->hash_algo = &hash_algos[GIT_HASH_SHA1];
498 int get_remote_bundle_uri(int fd_out, struct packet_reader *reader,
499 struct bundle_list *bundles, int stateless_rpc)
501 int line_nr = 1;
503 /* Assert bundle-uri support */
504 ensure_server_supports_v2("bundle-uri");
506 /* (Re-)send capabilities */
507 send_capabilities(fd_out, reader);
509 /* Send command */
510 packet_write_fmt(fd_out, "command=bundle-uri\n");
511 packet_delim(fd_out);
513 packet_flush(fd_out);
515 /* Process response from server */
516 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
517 const char *line = reader->line;
518 line_nr++;
520 if (!bundle_uri_parse_line(bundles, line))
521 continue;
523 return error(_("error on bundle-uri response line %d: %s"),
524 line_nr, line);
527 if (reader->status != PACKET_READ_FLUSH)
528 return error(_("expected flush after bundle-uri listing"));
531 * Might die(), but obscure enough that that's OK, e.g. in
532 * serve.c we'll call BUG() on its equivalent (the
533 * PACKET_READ_RESPONSE_END check).
535 check_stateless_delimiter(stateless_rpc, reader,
536 _("expected response end packet after ref listing"));
538 return 0;
541 struct ref **get_remote_refs(int fd_out, struct packet_reader *reader,
542 struct ref **list, int for_push,
543 struct transport_ls_refs_options *transport_options,
544 const struct string_list *server_options,
545 int stateless_rpc)
547 int i;
548 struct strvec *ref_prefixes = transport_options ?
549 &transport_options->ref_prefixes : NULL;
550 const char **unborn_head_target = transport_options ?
551 &transport_options->unborn_head_target : NULL;
552 *list = NULL;
554 ensure_server_supports_v2("ls-refs");
555 packet_write_fmt(fd_out, "command=ls-refs\n");
557 /* Send capabilities */
558 send_capabilities(fd_out, reader);
560 if (server_options && server_options->nr) {
561 ensure_server_supports_v2("server-option");
562 for (i = 0; i < server_options->nr; i++)
563 packet_write_fmt(fd_out, "server-option=%s",
564 server_options->items[i].string);
567 packet_delim(fd_out);
568 /* When pushing we don't want to request the peeled tags */
569 if (!for_push)
570 packet_write_fmt(fd_out, "peel\n");
571 packet_write_fmt(fd_out, "symrefs\n");
572 if (server_supports_feature("ls-refs", "unborn", 0))
573 packet_write_fmt(fd_out, "unborn\n");
574 for (i = 0; ref_prefixes && i < ref_prefixes->nr; i++) {
575 packet_write_fmt(fd_out, "ref-prefix %s\n",
576 ref_prefixes->v[i]);
578 packet_flush(fd_out);
580 /* Process response from server */
581 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
582 if (!process_ref_v2(reader, &list, unborn_head_target))
583 die(_("invalid ls-refs response: %s"), reader->line);
586 if (reader->status != PACKET_READ_FLUSH)
587 die(_("expected flush after ref listing"));
589 check_stateless_delimiter(stateless_rpc, reader,
590 _("expected response end packet after ref listing"));
592 return list;
595 const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp, int *offset)
597 int len;
599 if (!feature_list)
600 return NULL;
602 len = strlen(feature);
603 if (offset)
604 feature_list += *offset;
605 while (*feature_list) {
606 const char *found = strstr(feature_list, feature);
607 if (!found)
608 return NULL;
609 if (feature_list == found || isspace(found[-1])) {
610 const char *value = found + len;
611 /* feature with no value (e.g., "thin-pack") */
612 if (!*value || isspace(*value)) {
613 if (lenp)
614 *lenp = 0;
615 if (offset)
616 *offset = found + len - feature_list;
617 return value;
619 /* feature with a value (e.g., "agent=git/1.2.3") */
620 else if (*value == '=') {
621 int end;
623 value++;
624 end = strcspn(value, " \t\n");
625 if (lenp)
626 *lenp = end;
627 if (offset)
628 *offset = value + end - feature_list;
629 return value;
632 * otherwise we matched a substring of another feature;
633 * keep looking
636 feature_list = found + 1;
638 return NULL;
641 int server_supports_hash(const char *desired, int *feature_supported)
643 int offset = 0;
644 int len;
645 const char *hash;
647 hash = next_server_feature_value("object-format", &len, &offset);
648 if (feature_supported)
649 *feature_supported = !!hash;
650 if (!hash) {
651 hash = hash_algos[GIT_HASH_SHA1].name;
652 len = strlen(hash);
654 while (hash) {
655 if (!xstrncmpz(desired, hash, len))
656 return 1;
658 hash = next_server_feature_value("object-format", &len, &offset);
660 return 0;
663 int parse_feature_request(const char *feature_list, const char *feature)
665 return !!parse_feature_value(feature_list, feature, NULL, NULL);
668 static const char *next_server_feature_value(const char *feature, int *len, int *offset)
670 return parse_feature_value(server_capabilities_v1, feature, len, offset);
673 const char *server_feature_value(const char *feature, int *len)
675 return parse_feature_value(server_capabilities_v1, feature, len, NULL);
678 int server_supports(const char *feature)
680 return !!server_feature_value(feature, NULL);
683 enum protocol {
684 PROTO_LOCAL = 1,
685 PROTO_FILE,
686 PROTO_SSH,
687 PROTO_GIT
690 int url_is_local_not_ssh(const char *url)
692 const char *colon = strchr(url, ':');
693 const char *slash = strchr(url, '/');
694 return !colon || (slash && slash < colon) ||
695 (has_dos_drive_prefix(url) && is_valid_path(url));
698 static const char *prot_name(enum protocol protocol)
700 switch (protocol) {
701 case PROTO_LOCAL:
702 case PROTO_FILE:
703 return "file";
704 case PROTO_SSH:
705 return "ssh";
706 case PROTO_GIT:
707 return "git";
708 default:
709 return "unknown protocol";
713 static enum protocol get_protocol(const char *name)
715 if (!strcmp(name, "ssh"))
716 return PROTO_SSH;
717 if (!strcmp(name, "git"))
718 return PROTO_GIT;
719 if (!strcmp(name, "git+ssh")) /* deprecated - do not use */
720 return PROTO_SSH;
721 if (!strcmp(name, "ssh+git")) /* deprecated - do not use */
722 return PROTO_SSH;
723 if (!strcmp(name, "file"))
724 return PROTO_FILE;
725 die(_("protocol '%s' is not supported"), name);
728 static char *host_end(char **hoststart, int removebrackets)
730 char *host = *hoststart;
731 char *end;
732 char *start = strstr(host, "@[");
733 if (start)
734 start++; /* Jump over '@' */
735 else
736 start = host;
737 if (start[0] == '[') {
738 end = strchr(start + 1, ']');
739 if (end) {
740 if (removebrackets) {
741 *end = 0;
742 memmove(start, start + 1, end - start);
743 end++;
745 } else
746 end = host;
747 } else
748 end = host;
749 return end;
752 #define STR_(s) # s
753 #define STR(s) STR_(s)
755 static void get_host_and_port(char **host, const char **port)
757 char *colon, *end;
758 end = host_end(host, 1);
759 colon = strchr(end, ':');
760 if (colon) {
761 long portnr = strtol(colon + 1, &end, 10);
762 if (end != colon + 1 && *end == '\0' && 0 <= portnr && portnr < 65536) {
763 *colon = 0;
764 *port = colon + 1;
765 } else if (!colon[1]) {
766 *colon = 0;
771 static void enable_keepalive(int sockfd)
773 int ka = 1;
775 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
776 error_errno(_("unable to set SO_KEEPALIVE on socket"));
779 #ifndef NO_IPV6
781 static const char *ai_name(const struct addrinfo *ai)
783 static char addr[NI_MAXHOST];
784 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
785 NI_NUMERICHOST) != 0)
786 xsnprintf(addr, sizeof(addr), "(unknown)");
788 return addr;
792 * Returns a connected socket() fd, or else die()s.
794 static int git_tcp_connect_sock(char *host, int flags)
796 struct strbuf error_message = STRBUF_INIT;
797 int sockfd = -1;
798 const char *port = STR(DEFAULT_GIT_PORT);
799 struct addrinfo hints, *ai0, *ai;
800 int gai;
801 int cnt = 0;
803 get_host_and_port(&host, &port);
804 if (!*port)
805 port = "<none>";
807 memset(&hints, 0, sizeof(hints));
808 if (flags & CONNECT_IPV4)
809 hints.ai_family = AF_INET;
810 else if (flags & CONNECT_IPV6)
811 hints.ai_family = AF_INET6;
812 hints.ai_socktype = SOCK_STREAM;
813 hints.ai_protocol = IPPROTO_TCP;
815 if (flags & CONNECT_VERBOSE)
816 fprintf(stderr, _("Looking up %s ... "), host);
818 gai = getaddrinfo(host, port, &hints, &ai);
819 if (gai)
820 die(_("unable to look up %s (port %s) (%s)"), host, port, gai_strerror(gai));
822 if (flags & CONNECT_VERBOSE)
823 /* TRANSLATORS: this is the end of "Looking up %s ... " */
824 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
826 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
827 sockfd = socket(ai->ai_family,
828 ai->ai_socktype, ai->ai_protocol);
829 if ((sockfd < 0) ||
830 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
831 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
832 host, cnt, ai_name(ai), strerror(errno));
833 if (0 <= sockfd)
834 close(sockfd);
835 sockfd = -1;
836 continue;
838 if (flags & CONNECT_VERBOSE)
839 fprintf(stderr, "%s ", ai_name(ai));
840 break;
843 freeaddrinfo(ai0);
845 if (sockfd < 0)
846 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
848 enable_keepalive(sockfd);
850 if (flags & CONNECT_VERBOSE)
851 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
852 fprintf_ln(stderr, _("done."));
854 strbuf_release(&error_message);
856 return sockfd;
859 #else /* NO_IPV6 */
862 * Returns a connected socket() fd, or else die()s.
864 static int git_tcp_connect_sock(char *host, int flags)
866 struct strbuf error_message = STRBUF_INIT;
867 int sockfd = -1;
868 const char *port = STR(DEFAULT_GIT_PORT);
869 char *ep;
870 struct hostent *he;
871 struct sockaddr_in sa;
872 char **ap;
873 unsigned int nport;
874 int cnt;
876 get_host_and_port(&host, &port);
878 if (flags & CONNECT_VERBOSE)
879 fprintf(stderr, _("Looking up %s ... "), host);
881 he = gethostbyname(host);
882 if (!he)
883 die(_("unable to look up %s (%s)"), host, hstrerror(h_errno));
884 nport = strtoul(port, &ep, 10);
885 if ( ep == port || *ep ) {
886 /* Not numeric */
887 struct servent *se = getservbyname(port,"tcp");
888 if ( !se )
889 die(_("unknown port %s"), port);
890 nport = se->s_port;
893 if (flags & CONNECT_VERBOSE)
894 /* TRANSLATORS: this is the end of "Looking up %s ... " */
895 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
897 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
898 memset(&sa, 0, sizeof sa);
899 sa.sin_family = he->h_addrtype;
900 sa.sin_port = htons(nport);
901 memcpy(&sa.sin_addr, *ap, he->h_length);
903 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
904 if ((sockfd < 0) ||
905 connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
906 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
907 host,
908 cnt,
909 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
910 strerror(errno));
911 if (0 <= sockfd)
912 close(sockfd);
913 sockfd = -1;
914 continue;
916 if (flags & CONNECT_VERBOSE)
917 fprintf(stderr, "%s ",
918 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
919 break;
922 if (sockfd < 0)
923 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
925 enable_keepalive(sockfd);
927 if (flags & CONNECT_VERBOSE)
928 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
929 fprintf_ln(stderr, _("done."));
931 return sockfd;
934 #endif /* NO_IPV6 */
938 * Dummy child_process returned by git_connect() if the transport protocol
939 * does not need fork(2).
941 static struct child_process no_fork = CHILD_PROCESS_INIT;
943 int git_connection_is_socket(struct child_process *conn)
945 return conn == &no_fork;
948 static struct child_process *git_tcp_connect(int fd[2], char *host, int flags)
950 int sockfd = git_tcp_connect_sock(host, flags);
952 fd[0] = sockfd;
953 fd[1] = dup(sockfd);
955 return &no_fork;
959 static char *git_proxy_command;
961 static int git_proxy_command_options(const char *var, const char *value,
962 void *cb)
964 if (!strcmp(var, "core.gitproxy")) {
965 const char *for_pos;
966 int matchlen = -1;
967 int hostlen;
968 const char *rhost_name = cb;
969 int rhost_len = strlen(rhost_name);
971 if (git_proxy_command)
972 return 0;
973 if (!value)
974 return config_error_nonbool(var);
975 /* [core]
976 * ;# matches www.kernel.org as well
977 * gitproxy = netcatter-1 for kernel.org
978 * gitproxy = netcatter-2 for sample.xz
979 * gitproxy = netcatter-default
981 for_pos = strstr(value, " for ");
982 if (!for_pos)
983 /* matches everybody */
984 matchlen = strlen(value);
985 else {
986 hostlen = strlen(for_pos + 5);
987 if (rhost_len < hostlen)
988 matchlen = -1;
989 else if (!strncmp(for_pos + 5,
990 rhost_name + rhost_len - hostlen,
991 hostlen) &&
992 ((rhost_len == hostlen) ||
993 rhost_name[rhost_len - hostlen -1] == '.'))
994 matchlen = for_pos - value;
995 else
996 matchlen = -1;
998 if (0 <= matchlen) {
999 /* core.gitproxy = none for kernel.org */
1000 if (matchlen == 4 &&
1001 !memcmp(value, "none", 4))
1002 matchlen = 0;
1003 git_proxy_command = xmemdupz(value, matchlen);
1005 return 0;
1008 return git_default_config(var, value, cb);
1011 static int git_use_proxy(const char *host)
1013 git_proxy_command = getenv("GIT_PROXY_COMMAND");
1014 git_config(git_proxy_command_options, (void*)host);
1015 return (git_proxy_command && *git_proxy_command);
1018 static struct child_process *git_proxy_connect(int fd[2], char *host)
1020 const char *port = STR(DEFAULT_GIT_PORT);
1021 struct child_process *proxy;
1023 get_host_and_port(&host, &port);
1025 if (looks_like_command_line_option(host))
1026 die(_("strange hostname '%s' blocked"), host);
1027 if (looks_like_command_line_option(port))
1028 die(_("strange port '%s' blocked"), port);
1030 proxy = xmalloc(sizeof(*proxy));
1031 child_process_init(proxy);
1032 strvec_push(&proxy->args, git_proxy_command);
1033 strvec_push(&proxy->args, host);
1034 strvec_push(&proxy->args, port);
1035 proxy->in = -1;
1036 proxy->out = -1;
1037 if (start_command(proxy))
1038 die(_("cannot start proxy %s"), git_proxy_command);
1039 fd[0] = proxy->out; /* read from proxy stdout */
1040 fd[1] = proxy->in; /* write to proxy stdin */
1041 return proxy;
1044 static char *get_port(char *host)
1046 char *end;
1047 char *p = strchr(host, ':');
1049 if (p) {
1050 long port = strtol(p + 1, &end, 10);
1051 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
1052 *p = '\0';
1053 return p+1;
1057 return NULL;
1061 * Extract protocol and relevant parts from the specified connection URL.
1062 * The caller must free() the returned strings.
1064 static enum protocol parse_connect_url(const char *url_orig, char **ret_host,
1065 char **ret_path)
1067 char *url;
1068 char *host, *path;
1069 char *end;
1070 int separator = '/';
1071 enum protocol protocol = PROTO_LOCAL;
1073 if (is_url(url_orig))
1074 url = url_decode(url_orig);
1075 else
1076 url = xstrdup(url_orig);
1078 host = strstr(url, "://");
1079 if (host) {
1080 *host = '\0';
1081 protocol = get_protocol(url);
1082 host += 3;
1083 } else {
1084 host = url;
1085 if (!url_is_local_not_ssh(url)) {
1086 protocol = PROTO_SSH;
1087 separator = ':';
1092 * Don't do destructive transforms as protocol code does
1093 * '[]' unwrapping in get_host_and_port()
1095 end = host_end(&host, 0);
1097 if (protocol == PROTO_LOCAL)
1098 path = end;
1099 else if (protocol == PROTO_FILE && *host != '/' &&
1100 !has_dos_drive_prefix(host) &&
1101 offset_1st_component(host - 2) > 1)
1102 path = host - 2; /* include the leading "//" */
1103 else if (protocol == PROTO_FILE && has_dos_drive_prefix(end))
1104 path = end; /* "file://$(pwd)" may be "file://C:/projects/repo" */
1105 else
1106 path = strchr(end, separator);
1108 if (!path || !*path)
1109 die(_("no path specified; see 'git help pull' for valid url syntax"));
1112 * null-terminate hostname and point path to ~ for URL's like this:
1113 * ssh://host.xz/~user/repo
1116 end = path; /* Need to \0 terminate host here */
1117 if (separator == ':')
1118 path++; /* path starts after ':' */
1119 if (protocol == PROTO_GIT || protocol == PROTO_SSH) {
1120 if (path[1] == '~')
1121 path++;
1124 path = xstrdup(path);
1125 *end = '\0';
1127 *ret_host = xstrdup(host);
1128 *ret_path = path;
1129 free(url);
1130 return protocol;
1133 static const char *get_ssh_command(void)
1135 const char *ssh;
1137 if ((ssh = getenv("GIT_SSH_COMMAND")))
1138 return ssh;
1140 if (!git_config_get_string_tmp("core.sshcommand", &ssh))
1141 return ssh;
1143 return NULL;
1146 enum ssh_variant {
1147 VARIANT_AUTO,
1148 VARIANT_SIMPLE,
1149 VARIANT_SSH,
1150 VARIANT_PLINK,
1151 VARIANT_PUTTY,
1152 VARIANT_TORTOISEPLINK,
1155 static void override_ssh_variant(enum ssh_variant *ssh_variant)
1157 const char *variant = getenv("GIT_SSH_VARIANT");
1159 if (!variant && git_config_get_string_tmp("ssh.variant", &variant))
1160 return;
1162 if (!strcmp(variant, "auto"))
1163 *ssh_variant = VARIANT_AUTO;
1164 else if (!strcmp(variant, "plink"))
1165 *ssh_variant = VARIANT_PLINK;
1166 else if (!strcmp(variant, "putty"))
1167 *ssh_variant = VARIANT_PUTTY;
1168 else if (!strcmp(variant, "tortoiseplink"))
1169 *ssh_variant = VARIANT_TORTOISEPLINK;
1170 else if (!strcmp(variant, "simple"))
1171 *ssh_variant = VARIANT_SIMPLE;
1172 else
1173 *ssh_variant = VARIANT_SSH;
1176 static enum ssh_variant determine_ssh_variant(const char *ssh_command,
1177 int is_cmdline)
1179 enum ssh_variant ssh_variant = VARIANT_AUTO;
1180 const char *variant;
1181 char *p = NULL;
1183 override_ssh_variant(&ssh_variant);
1185 if (ssh_variant != VARIANT_AUTO)
1186 return ssh_variant;
1188 if (!is_cmdline) {
1189 p = xstrdup(ssh_command);
1190 variant = basename(p);
1191 } else {
1192 const char **ssh_argv;
1194 p = xstrdup(ssh_command);
1195 if (split_cmdline(p, &ssh_argv) > 0) {
1196 variant = basename((char *)ssh_argv[0]);
1198 * At this point, variant points into the buffer
1199 * referenced by p, hence we do not need ssh_argv
1200 * any longer.
1202 free(ssh_argv);
1203 } else {
1204 free(p);
1205 return ssh_variant;
1209 if (!strcasecmp(variant, "ssh") ||
1210 !strcasecmp(variant, "ssh.exe"))
1211 ssh_variant = VARIANT_SSH;
1212 else if (!strcasecmp(variant, "plink") ||
1213 !strcasecmp(variant, "plink.exe"))
1214 ssh_variant = VARIANT_PLINK;
1215 else if (!strcasecmp(variant, "tortoiseplink") ||
1216 !strcasecmp(variant, "tortoiseplink.exe"))
1217 ssh_variant = VARIANT_TORTOISEPLINK;
1219 free(p);
1220 return ssh_variant;
1224 * Open a connection using Git's native protocol.
1226 * The caller is responsible for freeing hostandport, but this function may
1227 * modify it (for example, to truncate it to remove the port part).
1229 static struct child_process *git_connect_git(int fd[2], char *hostandport,
1230 const char *path, const char *prog,
1231 enum protocol_version version,
1232 int flags)
1234 struct child_process *conn;
1235 struct strbuf request = STRBUF_INIT;
1237 * Set up virtual host information based on where we will
1238 * connect, unless the user has overridden us in
1239 * the environment.
1241 char *target_host = getenv("GIT_OVERRIDE_VIRTUAL_HOST");
1242 if (target_host)
1243 target_host = xstrdup(target_host);
1244 else
1245 target_host = xstrdup(hostandport);
1247 transport_check_allowed("git");
1248 if (strchr(target_host, '\n') || strchr(path, '\n'))
1249 die(_("newline is forbidden in git:// hosts and repo paths"));
1252 * These underlying connection commands die() if they
1253 * cannot connect.
1255 if (git_use_proxy(hostandport))
1256 conn = git_proxy_connect(fd, hostandport);
1257 else
1258 conn = git_tcp_connect(fd, hostandport, flags);
1260 * Separate original protocol components prog and path
1261 * from extended host header with a NUL byte.
1263 * Note: Do not add any other headers here! Doing so
1264 * will cause older git-daemon servers to crash.
1266 strbuf_addf(&request,
1267 "%s %s%chost=%s%c",
1268 prog, path, 0,
1269 target_host, 0);
1271 /* If using a new version put that stuff here after a second null byte */
1272 if (version > 0) {
1273 strbuf_addch(&request, '\0');
1274 strbuf_addf(&request, "version=%d%c",
1275 version, '\0');
1278 packet_write(fd[1], request.buf, request.len);
1280 free(target_host);
1281 strbuf_release(&request);
1282 return conn;
1286 * Append the appropriate environment variables to `env` and options to
1287 * `args` for running ssh in Git's SSH-tunneled transport.
1289 static void push_ssh_options(struct strvec *args, struct strvec *env,
1290 enum ssh_variant variant, const char *port,
1291 enum protocol_version version, int flags)
1293 if (variant == VARIANT_SSH &&
1294 version > 0) {
1295 strvec_push(args, "-o");
1296 strvec_push(args, "SendEnv=" GIT_PROTOCOL_ENVIRONMENT);
1297 strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1298 version);
1301 if (flags & CONNECT_IPV4) {
1302 switch (variant) {
1303 case VARIANT_AUTO:
1304 BUG("VARIANT_AUTO passed to push_ssh_options");
1305 case VARIANT_SIMPLE:
1306 die(_("ssh variant 'simple' does not support -4"));
1307 case VARIANT_SSH:
1308 case VARIANT_PLINK:
1309 case VARIANT_PUTTY:
1310 case VARIANT_TORTOISEPLINK:
1311 strvec_push(args, "-4");
1313 } else if (flags & CONNECT_IPV6) {
1314 switch (variant) {
1315 case VARIANT_AUTO:
1316 BUG("VARIANT_AUTO passed to push_ssh_options");
1317 case VARIANT_SIMPLE:
1318 die(_("ssh variant 'simple' does not support -6"));
1319 case VARIANT_SSH:
1320 case VARIANT_PLINK:
1321 case VARIANT_PUTTY:
1322 case VARIANT_TORTOISEPLINK:
1323 strvec_push(args, "-6");
1327 if (variant == VARIANT_TORTOISEPLINK)
1328 strvec_push(args, "-batch");
1330 if (port) {
1331 switch (variant) {
1332 case VARIANT_AUTO:
1333 BUG("VARIANT_AUTO passed to push_ssh_options");
1334 case VARIANT_SIMPLE:
1335 die(_("ssh variant 'simple' does not support setting port"));
1336 case VARIANT_SSH:
1337 strvec_push(args, "-p");
1338 break;
1339 case VARIANT_PLINK:
1340 case VARIANT_PUTTY:
1341 case VARIANT_TORTOISEPLINK:
1342 strvec_push(args, "-P");
1345 strvec_push(args, port);
1349 /* Prepare a child_process for use by Git's SSH-tunneled transport. */
1350 static void fill_ssh_args(struct child_process *conn, const char *ssh_host,
1351 const char *port, enum protocol_version version,
1352 int flags)
1354 const char *ssh;
1355 enum ssh_variant variant;
1357 if (looks_like_command_line_option(ssh_host))
1358 die(_("strange hostname '%s' blocked"), ssh_host);
1360 ssh = get_ssh_command();
1361 if (ssh) {
1362 variant = determine_ssh_variant(ssh, 1);
1363 } else {
1365 * GIT_SSH is the no-shell version of
1366 * GIT_SSH_COMMAND (and must remain so for
1367 * historical compatibility).
1369 conn->use_shell = 0;
1371 ssh = getenv("GIT_SSH");
1372 if (!ssh)
1373 ssh = "ssh";
1374 variant = determine_ssh_variant(ssh, 0);
1377 if (variant == VARIANT_AUTO) {
1378 struct child_process detect = CHILD_PROCESS_INIT;
1380 detect.use_shell = conn->use_shell;
1381 detect.no_stdin = detect.no_stdout = detect.no_stderr = 1;
1383 strvec_push(&detect.args, ssh);
1384 strvec_push(&detect.args, "-G");
1385 push_ssh_options(&detect.args, &detect.env,
1386 VARIANT_SSH, port, version, flags);
1387 strvec_push(&detect.args, ssh_host);
1389 variant = run_command(&detect) ? VARIANT_SIMPLE : VARIANT_SSH;
1392 strvec_push(&conn->args, ssh);
1393 push_ssh_options(&conn->args, &conn->env, variant, port, version,
1394 flags);
1395 strvec_push(&conn->args, ssh_host);
1399 * This returns the dummy child_process `no_fork` if the transport protocol
1400 * does not need fork(2), or a struct child_process object if it does. Once
1401 * done, finish the connection with finish_connect() with the value returned
1402 * from this function (it is safe to call finish_connect() with NULL to
1403 * support the former case).
1405 * If it returns, the connect is successful; it just dies on errors (this
1406 * will hopefully be changed in a libification effort, to return NULL when
1407 * the connection failed).
1409 struct child_process *git_connect(int fd[2], const char *url,
1410 const char *prog, int flags)
1412 char *hostandport, *path;
1413 struct child_process *conn;
1414 enum protocol protocol;
1415 enum protocol_version version = get_protocol_version_config();
1418 * NEEDSWORK: If we are trying to use protocol v2 and we are planning
1419 * to perform a push, then fallback to v0 since the client doesn't know
1420 * how to push yet using v2.
1422 if (version == protocol_v2 && !strcmp("git-receive-pack", prog))
1423 version = protocol_v0;
1425 /* Without this we cannot rely on waitpid() to tell
1426 * what happened to our children.
1428 signal(SIGCHLD, SIG_DFL);
1430 protocol = parse_connect_url(url, &hostandport, &path);
1431 if ((flags & CONNECT_DIAG_URL) && (protocol != PROTO_SSH)) {
1432 printf("Diag: url=%s\n", url ? url : "NULL");
1433 printf("Diag: protocol=%s\n", prot_name(protocol));
1434 printf("Diag: hostandport=%s\n", hostandport ? hostandport : "NULL");
1435 printf("Diag: path=%s\n", path ? path : "NULL");
1436 conn = NULL;
1437 } else if (protocol == PROTO_GIT) {
1438 conn = git_connect_git(fd, hostandport, path, prog, version, flags);
1439 conn->trace2_child_class = "transport/git";
1440 } else {
1441 struct strbuf cmd = STRBUF_INIT;
1442 const char *const *var;
1444 conn = xmalloc(sizeof(*conn));
1445 child_process_init(conn);
1447 if (looks_like_command_line_option(path))
1448 die(_("strange pathname '%s' blocked"), path);
1450 strbuf_addstr(&cmd, prog);
1451 strbuf_addch(&cmd, ' ');
1452 sq_quote_buf(&cmd, path);
1454 /* remove repo-local variables from the environment */
1455 for (var = local_repo_env; *var; var++)
1456 strvec_push(&conn->env, *var);
1458 conn->use_shell = 1;
1459 conn->in = conn->out = -1;
1460 if (protocol == PROTO_SSH) {
1461 char *ssh_host = hostandport;
1462 const char *port = NULL;
1463 transport_check_allowed("ssh");
1464 get_host_and_port(&ssh_host, &port);
1466 if (!port)
1467 port = get_port(ssh_host);
1469 if (flags & CONNECT_DIAG_URL) {
1470 printf("Diag: url=%s\n", url ? url : "NULL");
1471 printf("Diag: protocol=%s\n", prot_name(protocol));
1472 printf("Diag: userandhost=%s\n", ssh_host ? ssh_host : "NULL");
1473 printf("Diag: port=%s\n", port ? port : "NONE");
1474 printf("Diag: path=%s\n", path ? path : "NULL");
1476 free(hostandport);
1477 free(path);
1478 free(conn);
1479 strbuf_release(&cmd);
1480 return NULL;
1482 conn->trace2_child_class = "transport/ssh";
1483 fill_ssh_args(conn, ssh_host, port, version, flags);
1484 } else {
1485 transport_check_allowed("file");
1486 conn->trace2_child_class = "transport/file";
1487 if (version > 0) {
1488 strvec_pushf(&conn->env,
1489 GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1490 version);
1493 strvec_push(&conn->args, cmd.buf);
1495 if (start_command(conn))
1496 die(_("unable to fork"));
1498 fd[0] = conn->out; /* read from child's stdout */
1499 fd[1] = conn->in; /* write to child's stdin */
1500 strbuf_release(&cmd);
1502 free(hostandport);
1503 free(path);
1504 return conn;
1507 int finish_connect(struct child_process *conn)
1509 int code;
1510 if (!conn || git_connection_is_socket(conn))
1511 return 0;
1513 code = finish_command(conn);
1514 free(conn);
1515 return code;