t2400: rewrite regex to avoid unintentional PCRE
[git.git] / connect.c
blobc0c8a38178cec786ff4dfc721e0b9e389a3c5888
1 #include "git-compat-util.h"
2 #include "cache.h"
3 #include "config.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "pkt-line.h"
8 #include "quote.h"
9 #include "refs.h"
10 #include "run-command.h"
11 #include "remote.h"
12 #include "connect.h"
13 #include "url.h"
14 #include "string-list.h"
15 #include "oid-array.h"
16 #include "transport.h"
17 #include "strbuf.h"
18 #include "version.h"
19 #include "protocol.h"
20 #include "alias.h"
21 #include "bundle-uri.h"
23 static char *server_capabilities_v1;
24 static struct strvec server_capabilities_v2 = STRVEC_INIT;
25 static const char *next_server_feature_value(const char *feature, int *len, int *offset);
27 static int check_ref(const char *name, unsigned int flags)
29 if (!flags)
30 return 1;
32 if (!skip_prefix(name, "refs/", &name))
33 return 0;
35 /* REF_NORMAL means that we don't want the magic fake tag refs */
36 if ((flags & REF_NORMAL) && check_refname_format(name,
37 REFNAME_ALLOW_ONELEVEL))
38 return 0;
40 /* REF_HEADS means that we want regular branch heads */
41 if ((flags & REF_HEADS) && starts_with(name, "heads/"))
42 return 1;
44 /* REF_TAGS means that we want tags */
45 if ((flags & REF_TAGS) && starts_with(name, "tags/"))
46 return 1;
48 /* All type bits clear means that we are ok with anything */
49 return !(flags & ~REF_NORMAL);
52 int check_ref_type(const struct ref *ref, int flags)
54 return check_ref(ref->name, flags);
57 static NORETURN void die_initial_contact(int unexpected)
60 * A hang-up after seeing some response from the other end
61 * means that it is unexpected, as we know the other end is
62 * willing to talk to us. A hang-up before seeing any
63 * response does not necessarily mean an ACL problem, though.
65 if (unexpected)
66 die(_("the remote end hung up upon initial contact"));
67 else
68 die(_("Could not read from remote repository.\n\n"
69 "Please make sure you have the correct access rights\n"
70 "and the repository exists."));
73 /* Checks if the server supports the capability 'c' */
74 int server_supports_v2(const char *c)
76 int i;
78 for (i = 0; i < server_capabilities_v2.nr; i++) {
79 const char *out;
80 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
81 (!*out || *out == '='))
82 return 1;
84 return 0;
87 void ensure_server_supports_v2(const char *c)
89 if (!server_supports_v2(c))
90 die(_("server doesn't support '%s'"), c);
93 int server_feature_v2(const char *c, const char **v)
95 int i;
97 for (i = 0; i < server_capabilities_v2.nr; i++) {
98 const char *out;
99 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
100 (*out == '=')) {
101 *v = out + 1;
102 return 1;
105 return 0;
108 int server_supports_feature(const char *c, const char *feature,
109 int die_on_error)
111 int i;
113 for (i = 0; i < server_capabilities_v2.nr; i++) {
114 const char *out;
115 if (skip_prefix(server_capabilities_v2.v[i], c, &out) &&
116 (!*out || *(out++) == '=')) {
117 if (parse_feature_request(out, feature))
118 return 1;
119 else
120 break;
124 if (die_on_error)
125 die(_("server doesn't support feature '%s'"), feature);
127 return 0;
130 static void process_capabilities_v2(struct packet_reader *reader)
132 while (packet_reader_read(reader) == PACKET_READ_NORMAL)
133 strvec_push(&server_capabilities_v2, reader->line);
135 if (reader->status != PACKET_READ_FLUSH)
136 die(_("expected flush after capabilities"));
139 enum protocol_version discover_version(struct packet_reader *reader)
141 enum protocol_version version = protocol_unknown_version;
144 * Peek the first line of the server's response to
145 * determine the protocol version the server is speaking.
147 switch (packet_reader_peek(reader)) {
148 case PACKET_READ_EOF:
149 die_initial_contact(0);
150 case PACKET_READ_FLUSH:
151 case PACKET_READ_DELIM:
152 case PACKET_READ_RESPONSE_END:
153 version = protocol_v0;
154 break;
155 case PACKET_READ_NORMAL:
156 version = determine_protocol_version_client(reader->line);
157 break;
160 switch (version) {
161 case protocol_v2:
162 process_capabilities_v2(reader);
163 break;
164 case protocol_v1:
165 /* Read the peeked version line */
166 packet_reader_read(reader);
167 break;
168 case protocol_v0:
169 break;
170 case protocol_unknown_version:
171 BUG("unknown protocol version");
174 trace2_data_intmax("transfer", NULL, "negotiated-version", version);
176 return version;
179 static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
181 char *sym, *target;
182 struct string_list_item *item;
184 if (!len)
185 return; /* just "symref" */
186 /* e.g. "symref=HEAD:refs/heads/master" */
187 sym = xmemdupz(val, len);
188 target = strchr(sym, ':');
189 if (!target)
190 /* just "symref=something" */
191 goto reject;
192 *(target++) = '\0';
193 if (check_refname_format(sym, REFNAME_ALLOW_ONELEVEL) ||
194 check_refname_format(target, REFNAME_ALLOW_ONELEVEL))
195 /* "symref=bogus:pair */
196 goto reject;
197 item = string_list_append_nodup(symref, sym);
198 item->util = target;
199 return;
200 reject:
201 free(sym);
202 return;
205 static void annotate_refs_with_symref_info(struct ref *ref)
207 struct string_list symref = STRING_LIST_INIT_DUP;
208 int offset = 0;
210 while (1) {
211 int len;
212 const char *val;
214 val = next_server_feature_value("symref", &len, &offset);
215 if (!val)
216 break;
217 parse_one_symref_info(&symref, val, len);
219 string_list_sort(&symref);
221 for (; ref; ref = ref->next) {
222 struct string_list_item *item;
223 item = string_list_lookup(&symref, ref->name);
224 if (!item)
225 continue;
226 ref->symref = xstrdup((char *)item->util);
228 string_list_clear(&symref, 0);
231 static void process_capabilities(struct packet_reader *reader, int *linelen)
233 const char *feat_val;
234 int feat_len;
235 const char *line = reader->line;
236 int nul_location = strlen(line);
237 if (nul_location == *linelen)
238 return;
239 server_capabilities_v1 = xstrdup(line + nul_location + 1);
240 *linelen = nul_location;
242 feat_val = server_feature_value("object-format", &feat_len);
243 if (feat_val) {
244 char *hash_name = xstrndup(feat_val, feat_len);
245 int hash_algo = hash_algo_by_name(hash_name);
246 if (hash_algo != GIT_HASH_UNKNOWN)
247 reader->hash_algo = &hash_algos[hash_algo];
248 free(hash_name);
249 } else {
250 reader->hash_algo = &hash_algos[GIT_HASH_SHA1];
254 static int process_dummy_ref(const struct packet_reader *reader)
256 const char *line = reader->line;
257 struct object_id oid;
258 const char *name;
260 if (parse_oid_hex_algop(line, &oid, &name, reader->hash_algo))
261 return 0;
262 if (*name != ' ')
263 return 0;
264 name++;
266 return oideq(null_oid(), &oid) && !strcmp(name, "capabilities^{}");
269 static void check_no_capabilities(const char *line, int len)
271 if (strlen(line) != len)
272 warning(_("ignoring capabilities after first line '%s'"),
273 line + strlen(line));
276 static int process_ref(const struct packet_reader *reader, int len,
277 struct ref ***list, unsigned int flags,
278 struct oid_array *extra_have)
280 const char *line = reader->line;
281 struct object_id old_oid;
282 const char *name;
284 if (parse_oid_hex_algop(line, &old_oid, &name, reader->hash_algo))
285 return 0;
286 if (*name != ' ')
287 return 0;
288 name++;
290 if (extra_have && !strcmp(name, ".have")) {
291 oid_array_append(extra_have, &old_oid);
292 } else if (!strcmp(name, "capabilities^{}")) {
293 die(_("protocol error: unexpected capabilities^{}"));
294 } else if (check_ref(name, flags)) {
295 struct ref *ref = alloc_ref(name);
296 oidcpy(&ref->old_oid, &old_oid);
297 **list = ref;
298 *list = &ref->next;
300 check_no_capabilities(line, len);
301 return 1;
304 static int process_shallow(const struct packet_reader *reader, int len,
305 struct oid_array *shallow_points)
307 const char *line = reader->line;
308 const char *arg;
309 struct object_id old_oid;
311 if (!skip_prefix(line, "shallow ", &arg))
312 return 0;
314 if (get_oid_hex_algop(arg, &old_oid, reader->hash_algo))
315 die(_("protocol error: expected shallow sha-1, got '%s'"), arg);
316 if (!shallow_points)
317 die(_("repository on the other end cannot be shallow"));
318 oid_array_append(shallow_points, &old_oid);
319 check_no_capabilities(line, len);
320 return 1;
323 enum get_remote_heads_state {
324 EXPECTING_FIRST_REF = 0,
325 EXPECTING_REF,
326 EXPECTING_SHALLOW,
327 EXPECTING_DONE,
331 * Read all the refs from the other end
333 struct ref **get_remote_heads(struct packet_reader *reader,
334 struct ref **list, unsigned int flags,
335 struct oid_array *extra_have,
336 struct oid_array *shallow_points)
338 struct ref **orig_list = list;
339 int len = 0;
340 enum get_remote_heads_state state = EXPECTING_FIRST_REF;
342 *list = NULL;
344 while (state != EXPECTING_DONE) {
345 switch (packet_reader_read(reader)) {
346 case PACKET_READ_EOF:
347 die_initial_contact(1);
348 case PACKET_READ_NORMAL:
349 len = reader->pktlen;
350 break;
351 case PACKET_READ_FLUSH:
352 state = EXPECTING_DONE;
353 break;
354 case PACKET_READ_DELIM:
355 case PACKET_READ_RESPONSE_END:
356 die(_("invalid packet"));
359 switch (state) {
360 case EXPECTING_FIRST_REF:
361 process_capabilities(reader, &len);
362 if (process_dummy_ref(reader)) {
363 state = EXPECTING_SHALLOW;
364 break;
366 state = EXPECTING_REF;
367 /* fallthrough */
368 case EXPECTING_REF:
369 if (process_ref(reader, len, &list, flags, extra_have))
370 break;
371 state = EXPECTING_SHALLOW;
372 /* fallthrough */
373 case EXPECTING_SHALLOW:
374 if (process_shallow(reader, len, shallow_points))
375 break;
376 die(_("protocol error: unexpected '%s'"), reader->line);
377 case EXPECTING_DONE:
378 break;
382 annotate_refs_with_symref_info(*orig_list);
384 return list;
387 /* Returns 1 when a valid ref has been added to `list`, 0 otherwise */
388 static int process_ref_v2(struct packet_reader *reader, struct ref ***list,
389 const char **unborn_head_target)
391 int ret = 1;
392 int i = 0;
393 struct object_id old_oid;
394 struct ref *ref;
395 struct string_list line_sections = STRING_LIST_INIT_DUP;
396 const char *end;
397 const char *line = reader->line;
400 * Ref lines have a number of fields which are space deliminated. The
401 * first field is the OID of the ref. The second field is the ref
402 * name. Subsequent fields (symref-target and peeled) are optional and
403 * don't have a particular order.
405 if (string_list_split(&line_sections, line, ' ', -1) < 2) {
406 ret = 0;
407 goto out;
410 if (!strcmp("unborn", line_sections.items[i].string)) {
411 i++;
412 if (unborn_head_target &&
413 !strcmp("HEAD", line_sections.items[i++].string)) {
415 * Look for the symref target (if any). If found,
416 * return it to the caller.
418 for (; i < line_sections.nr; i++) {
419 const char *arg = line_sections.items[i].string;
421 if (skip_prefix(arg, "symref-target:", &arg)) {
422 *unborn_head_target = xstrdup(arg);
423 break;
427 goto out;
429 if (parse_oid_hex_algop(line_sections.items[i++].string, &old_oid, &end, reader->hash_algo) ||
430 *end) {
431 ret = 0;
432 goto out;
435 ref = alloc_ref(line_sections.items[i++].string);
437 memcpy(ref->old_oid.hash, old_oid.hash, reader->hash_algo->rawsz);
438 **list = ref;
439 *list = &ref->next;
441 for (; i < line_sections.nr; i++) {
442 const char *arg = line_sections.items[i].string;
443 if (skip_prefix(arg, "symref-target:", &arg))
444 ref->symref = xstrdup(arg);
446 if (skip_prefix(arg, "peeled:", &arg)) {
447 struct object_id peeled_oid;
448 char *peeled_name;
449 struct ref *peeled;
450 if (parse_oid_hex_algop(arg, &peeled_oid, &end,
451 reader->hash_algo) || *end) {
452 ret = 0;
453 goto out;
456 peeled_name = xstrfmt("%s^{}", ref->name);
457 peeled = alloc_ref(peeled_name);
459 memcpy(peeled->old_oid.hash, peeled_oid.hash,
460 reader->hash_algo->rawsz);
461 **list = peeled;
462 *list = &peeled->next;
464 free(peeled_name);
468 out:
469 string_list_clear(&line_sections, 0);
470 return ret;
473 void check_stateless_delimiter(int stateless_rpc,
474 struct packet_reader *reader,
475 const char *error)
477 if (!stateless_rpc)
478 return; /* not in stateless mode, no delimiter expected */
479 if (packet_reader_read(reader) != PACKET_READ_RESPONSE_END)
480 die("%s", error);
483 static void send_capabilities(int fd_out, struct packet_reader *reader)
485 const char *hash_name;
487 if (server_supports_v2("agent"))
488 packet_write_fmt(fd_out, "agent=%s", git_user_agent_sanitized());
490 if (server_feature_v2("object-format", &hash_name)) {
491 int hash_algo = hash_algo_by_name(hash_name);
492 if (hash_algo == GIT_HASH_UNKNOWN)
493 die(_("unknown object format '%s' specified by server"), hash_name);
494 reader->hash_algo = &hash_algos[hash_algo];
495 packet_write_fmt(fd_out, "object-format=%s", reader->hash_algo->name);
496 } else {
497 reader->hash_algo = &hash_algos[GIT_HASH_SHA1];
501 int get_remote_bundle_uri(int fd_out, struct packet_reader *reader,
502 struct bundle_list *bundles, int stateless_rpc)
504 int line_nr = 1;
506 /* Assert bundle-uri support */
507 ensure_server_supports_v2("bundle-uri");
509 /* (Re-)send capabilities */
510 send_capabilities(fd_out, reader);
512 /* Send command */
513 packet_write_fmt(fd_out, "command=bundle-uri\n");
514 packet_delim(fd_out);
516 packet_flush(fd_out);
518 /* Process response from server */
519 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
520 const char *line = reader->line;
521 line_nr++;
523 if (!bundle_uri_parse_line(bundles, line))
524 continue;
526 return error(_("error on bundle-uri response line %d: %s"),
527 line_nr, line);
530 if (reader->status != PACKET_READ_FLUSH)
531 return error(_("expected flush after bundle-uri listing"));
534 * Might die(), but obscure enough that that's OK, e.g. in
535 * serve.c we'll call BUG() on its equivalent (the
536 * PACKET_READ_RESPONSE_END check).
538 check_stateless_delimiter(stateless_rpc, reader,
539 _("expected response end packet after ref listing"));
541 return 0;
544 struct ref **get_remote_refs(int fd_out, struct packet_reader *reader,
545 struct ref **list, int for_push,
546 struct transport_ls_refs_options *transport_options,
547 const struct string_list *server_options,
548 int stateless_rpc)
550 int i;
551 struct strvec *ref_prefixes = transport_options ?
552 &transport_options->ref_prefixes : NULL;
553 const char **unborn_head_target = transport_options ?
554 &transport_options->unborn_head_target : NULL;
555 *list = NULL;
557 ensure_server_supports_v2("ls-refs");
558 packet_write_fmt(fd_out, "command=ls-refs\n");
560 /* Send capabilities */
561 send_capabilities(fd_out, reader);
563 if (server_options && server_options->nr) {
564 ensure_server_supports_v2("server-option");
565 for (i = 0; i < server_options->nr; i++)
566 packet_write_fmt(fd_out, "server-option=%s",
567 server_options->items[i].string);
570 packet_delim(fd_out);
571 /* When pushing we don't want to request the peeled tags */
572 if (!for_push)
573 packet_write_fmt(fd_out, "peel\n");
574 packet_write_fmt(fd_out, "symrefs\n");
575 if (server_supports_feature("ls-refs", "unborn", 0))
576 packet_write_fmt(fd_out, "unborn\n");
577 for (i = 0; ref_prefixes && i < ref_prefixes->nr; i++) {
578 packet_write_fmt(fd_out, "ref-prefix %s\n",
579 ref_prefixes->v[i]);
581 packet_flush(fd_out);
583 /* Process response from server */
584 while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
585 if (!process_ref_v2(reader, &list, unborn_head_target))
586 die(_("invalid ls-refs response: %s"), reader->line);
589 if (reader->status != PACKET_READ_FLUSH)
590 die(_("expected flush after ref listing"));
592 check_stateless_delimiter(stateless_rpc, reader,
593 _("expected response end packet after ref listing"));
595 return list;
598 const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp, int *offset)
600 int len;
602 if (!feature_list)
603 return NULL;
605 len = strlen(feature);
606 if (offset)
607 feature_list += *offset;
608 while (*feature_list) {
609 const char *found = strstr(feature_list, feature);
610 if (!found)
611 return NULL;
612 if (feature_list == found || isspace(found[-1])) {
613 const char *value = found + len;
614 /* feature with no value (e.g., "thin-pack") */
615 if (!*value || isspace(*value)) {
616 if (lenp)
617 *lenp = 0;
618 if (offset)
619 *offset = found + len - feature_list;
620 return value;
622 /* feature with a value (e.g., "agent=git/1.2.3") */
623 else if (*value == '=') {
624 int end;
626 value++;
627 end = strcspn(value, " \t\n");
628 if (lenp)
629 *lenp = end;
630 if (offset)
631 *offset = value + end - feature_list;
632 return value;
635 * otherwise we matched a substring of another feature;
636 * keep looking
639 feature_list = found + 1;
641 return NULL;
644 int server_supports_hash(const char *desired, int *feature_supported)
646 int offset = 0;
647 int len;
648 const char *hash;
650 hash = next_server_feature_value("object-format", &len, &offset);
651 if (feature_supported)
652 *feature_supported = !!hash;
653 if (!hash) {
654 hash = hash_algos[GIT_HASH_SHA1].name;
655 len = strlen(hash);
657 while (hash) {
658 if (!xstrncmpz(desired, hash, len))
659 return 1;
661 hash = next_server_feature_value("object-format", &len, &offset);
663 return 0;
666 int parse_feature_request(const char *feature_list, const char *feature)
668 return !!parse_feature_value(feature_list, feature, NULL, NULL);
671 static const char *next_server_feature_value(const char *feature, int *len, int *offset)
673 return parse_feature_value(server_capabilities_v1, feature, len, offset);
676 const char *server_feature_value(const char *feature, int *len)
678 return parse_feature_value(server_capabilities_v1, feature, len, NULL);
681 int server_supports(const char *feature)
683 return !!server_feature_value(feature, NULL);
686 enum protocol {
687 PROTO_LOCAL = 1,
688 PROTO_FILE,
689 PROTO_SSH,
690 PROTO_GIT
693 int url_is_local_not_ssh(const char *url)
695 const char *colon = strchr(url, ':');
696 const char *slash = strchr(url, '/');
697 return !colon || (slash && slash < colon) ||
698 (has_dos_drive_prefix(url) && is_valid_path(url));
701 static const char *prot_name(enum protocol protocol)
703 switch (protocol) {
704 case PROTO_LOCAL:
705 case PROTO_FILE:
706 return "file";
707 case PROTO_SSH:
708 return "ssh";
709 case PROTO_GIT:
710 return "git";
711 default:
712 return "unknown protocol";
716 static enum protocol get_protocol(const char *name)
718 if (!strcmp(name, "ssh"))
719 return PROTO_SSH;
720 if (!strcmp(name, "git"))
721 return PROTO_GIT;
722 if (!strcmp(name, "git+ssh")) /* deprecated - do not use */
723 return PROTO_SSH;
724 if (!strcmp(name, "ssh+git")) /* deprecated - do not use */
725 return PROTO_SSH;
726 if (!strcmp(name, "file"))
727 return PROTO_FILE;
728 die(_("protocol '%s' is not supported"), name);
731 static char *host_end(char **hoststart, int removebrackets)
733 char *host = *hoststart;
734 char *end;
735 char *start = strstr(host, "@[");
736 if (start)
737 start++; /* Jump over '@' */
738 else
739 start = host;
740 if (start[0] == '[') {
741 end = strchr(start + 1, ']');
742 if (end) {
743 if (removebrackets) {
744 *end = 0;
745 memmove(start, start + 1, end - start);
746 end++;
748 } else
749 end = host;
750 } else
751 end = host;
752 return end;
755 #define STR_(s) # s
756 #define STR(s) STR_(s)
758 static void get_host_and_port(char **host, const char **port)
760 char *colon, *end;
761 end = host_end(host, 1);
762 colon = strchr(end, ':');
763 if (colon) {
764 long portnr = strtol(colon + 1, &end, 10);
765 if (end != colon + 1 && *end == '\0' && 0 <= portnr && portnr < 65536) {
766 *colon = 0;
767 *port = colon + 1;
768 } else if (!colon[1]) {
769 *colon = 0;
774 static void enable_keepalive(int sockfd)
776 int ka = 1;
778 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
779 error_errno(_("unable to set SO_KEEPALIVE on socket"));
782 #ifndef NO_IPV6
784 static const char *ai_name(const struct addrinfo *ai)
786 static char addr[NI_MAXHOST];
787 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
788 NI_NUMERICHOST) != 0)
789 xsnprintf(addr, sizeof(addr), "(unknown)");
791 return addr;
795 * Returns a connected socket() fd, or else die()s.
797 static int git_tcp_connect_sock(char *host, int flags)
799 struct strbuf error_message = STRBUF_INIT;
800 int sockfd = -1;
801 const char *port = STR(DEFAULT_GIT_PORT);
802 struct addrinfo hints, *ai0, *ai;
803 int gai;
804 int cnt = 0;
806 get_host_and_port(&host, &port);
807 if (!*port)
808 port = "<none>";
810 memset(&hints, 0, sizeof(hints));
811 if (flags & CONNECT_IPV4)
812 hints.ai_family = AF_INET;
813 else if (flags & CONNECT_IPV6)
814 hints.ai_family = AF_INET6;
815 hints.ai_socktype = SOCK_STREAM;
816 hints.ai_protocol = IPPROTO_TCP;
818 if (flags & CONNECT_VERBOSE)
819 fprintf(stderr, _("Looking up %s ... "), host);
821 gai = getaddrinfo(host, port, &hints, &ai);
822 if (gai)
823 die(_("unable to look up %s (port %s) (%s)"), host, port, gai_strerror(gai));
825 if (flags & CONNECT_VERBOSE)
826 /* TRANSLATORS: this is the end of "Looking up %s ... " */
827 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
829 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
830 sockfd = socket(ai->ai_family,
831 ai->ai_socktype, ai->ai_protocol);
832 if ((sockfd < 0) ||
833 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
834 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
835 host, cnt, ai_name(ai), strerror(errno));
836 if (0 <= sockfd)
837 close(sockfd);
838 sockfd = -1;
839 continue;
841 if (flags & CONNECT_VERBOSE)
842 fprintf(stderr, "%s ", ai_name(ai));
843 break;
846 freeaddrinfo(ai0);
848 if (sockfd < 0)
849 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
851 enable_keepalive(sockfd);
853 if (flags & CONNECT_VERBOSE)
854 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
855 fprintf_ln(stderr, _("done."));
857 strbuf_release(&error_message);
859 return sockfd;
862 #else /* NO_IPV6 */
865 * Returns a connected socket() fd, or else die()s.
867 static int git_tcp_connect_sock(char *host, int flags)
869 struct strbuf error_message = STRBUF_INIT;
870 int sockfd = -1;
871 const char *port = STR(DEFAULT_GIT_PORT);
872 char *ep;
873 struct hostent *he;
874 struct sockaddr_in sa;
875 char **ap;
876 unsigned int nport;
877 int cnt;
879 get_host_and_port(&host, &port);
881 if (flags & CONNECT_VERBOSE)
882 fprintf(stderr, _("Looking up %s ... "), host);
884 he = gethostbyname(host);
885 if (!he)
886 die(_("unable to look up %s (%s)"), host, hstrerror(h_errno));
887 nport = strtoul(port, &ep, 10);
888 if ( ep == port || *ep ) {
889 /* Not numeric */
890 struct servent *se = getservbyname(port,"tcp");
891 if ( !se )
892 die(_("unknown port %s"), port);
893 nport = se->s_port;
896 if (flags & CONNECT_VERBOSE)
897 /* TRANSLATORS: this is the end of "Looking up %s ... " */
898 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
900 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
901 memset(&sa, 0, sizeof sa);
902 sa.sin_family = he->h_addrtype;
903 sa.sin_port = htons(nport);
904 memcpy(&sa.sin_addr, *ap, he->h_length);
906 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
907 if ((sockfd < 0) ||
908 connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
909 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
910 host,
911 cnt,
912 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
913 strerror(errno));
914 if (0 <= sockfd)
915 close(sockfd);
916 sockfd = -1;
917 continue;
919 if (flags & CONNECT_VERBOSE)
920 fprintf(stderr, "%s ",
921 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
922 break;
925 if (sockfd < 0)
926 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
928 enable_keepalive(sockfd);
930 if (flags & CONNECT_VERBOSE)
931 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
932 fprintf_ln(stderr, _("done."));
934 return sockfd;
937 #endif /* NO_IPV6 */
941 * Dummy child_process returned by git_connect() if the transport protocol
942 * does not need fork(2).
944 static struct child_process no_fork = CHILD_PROCESS_INIT;
946 int git_connection_is_socket(struct child_process *conn)
948 return conn == &no_fork;
951 static struct child_process *git_tcp_connect(int fd[2], char *host, int flags)
953 int sockfd = git_tcp_connect_sock(host, flags);
955 fd[0] = sockfd;
956 fd[1] = dup(sockfd);
958 return &no_fork;
962 static char *git_proxy_command;
964 static int git_proxy_command_options(const char *var, const char *value,
965 void *cb)
967 if (!strcmp(var, "core.gitproxy")) {
968 const char *for_pos;
969 int matchlen = -1;
970 int hostlen;
971 const char *rhost_name = cb;
972 int rhost_len = strlen(rhost_name);
974 if (git_proxy_command)
975 return 0;
976 if (!value)
977 return config_error_nonbool(var);
978 /* [core]
979 * ;# matches www.kernel.org as well
980 * gitproxy = netcatter-1 for kernel.org
981 * gitproxy = netcatter-2 for sample.xz
982 * gitproxy = netcatter-default
984 for_pos = strstr(value, " for ");
985 if (!for_pos)
986 /* matches everybody */
987 matchlen = strlen(value);
988 else {
989 hostlen = strlen(for_pos + 5);
990 if (rhost_len < hostlen)
991 matchlen = -1;
992 else if (!strncmp(for_pos + 5,
993 rhost_name + rhost_len - hostlen,
994 hostlen) &&
995 ((rhost_len == hostlen) ||
996 rhost_name[rhost_len - hostlen -1] == '.'))
997 matchlen = for_pos - value;
998 else
999 matchlen = -1;
1001 if (0 <= matchlen) {
1002 /* core.gitproxy = none for kernel.org */
1003 if (matchlen == 4 &&
1004 !memcmp(value, "none", 4))
1005 matchlen = 0;
1006 git_proxy_command = xmemdupz(value, matchlen);
1008 return 0;
1011 return git_default_config(var, value, cb);
1014 static int git_use_proxy(const char *host)
1016 git_proxy_command = getenv("GIT_PROXY_COMMAND");
1017 git_config(git_proxy_command_options, (void*)host);
1018 return (git_proxy_command && *git_proxy_command);
1021 static struct child_process *git_proxy_connect(int fd[2], char *host)
1023 const char *port = STR(DEFAULT_GIT_PORT);
1024 struct child_process *proxy;
1026 get_host_and_port(&host, &port);
1028 if (looks_like_command_line_option(host))
1029 die(_("strange hostname '%s' blocked"), host);
1030 if (looks_like_command_line_option(port))
1031 die(_("strange port '%s' blocked"), port);
1033 proxy = xmalloc(sizeof(*proxy));
1034 child_process_init(proxy);
1035 strvec_push(&proxy->args, git_proxy_command);
1036 strvec_push(&proxy->args, host);
1037 strvec_push(&proxy->args, port);
1038 proxy->in = -1;
1039 proxy->out = -1;
1040 if (start_command(proxy))
1041 die(_("cannot start proxy %s"), git_proxy_command);
1042 fd[0] = proxy->out; /* read from proxy stdout */
1043 fd[1] = proxy->in; /* write to proxy stdin */
1044 return proxy;
1047 static char *get_port(char *host)
1049 char *end;
1050 char *p = strchr(host, ':');
1052 if (p) {
1053 long port = strtol(p + 1, &end, 10);
1054 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
1055 *p = '\0';
1056 return p+1;
1060 return NULL;
1064 * Extract protocol and relevant parts from the specified connection URL.
1065 * The caller must free() the returned strings.
1067 static enum protocol parse_connect_url(const char *url_orig, char **ret_host,
1068 char **ret_path)
1070 char *url;
1071 char *host, *path;
1072 char *end;
1073 int separator = '/';
1074 enum protocol protocol = PROTO_LOCAL;
1076 if (is_url(url_orig))
1077 url = url_decode(url_orig);
1078 else
1079 url = xstrdup(url_orig);
1081 host = strstr(url, "://");
1082 if (host) {
1083 *host = '\0';
1084 protocol = get_protocol(url);
1085 host += 3;
1086 } else {
1087 host = url;
1088 if (!url_is_local_not_ssh(url)) {
1089 protocol = PROTO_SSH;
1090 separator = ':';
1095 * Don't do destructive transforms as protocol code does
1096 * '[]' unwrapping in get_host_and_port()
1098 end = host_end(&host, 0);
1100 if (protocol == PROTO_LOCAL)
1101 path = end;
1102 else if (protocol == PROTO_FILE && *host != '/' &&
1103 !has_dos_drive_prefix(host) &&
1104 offset_1st_component(host - 2) > 1)
1105 path = host - 2; /* include the leading "//" */
1106 else if (protocol == PROTO_FILE && has_dos_drive_prefix(end))
1107 path = end; /* "file://$(pwd)" may be "file://C:/projects/repo" */
1108 else
1109 path = strchr(end, separator);
1111 if (!path || !*path)
1112 die(_("no path specified; see 'git help pull' for valid url syntax"));
1115 * null-terminate hostname and point path to ~ for URL's like this:
1116 * ssh://host.xz/~user/repo
1119 end = path; /* Need to \0 terminate host here */
1120 if (separator == ':')
1121 path++; /* path starts after ':' */
1122 if (protocol == PROTO_GIT || protocol == PROTO_SSH) {
1123 if (path[1] == '~')
1124 path++;
1127 path = xstrdup(path);
1128 *end = '\0';
1130 *ret_host = xstrdup(host);
1131 *ret_path = path;
1132 free(url);
1133 return protocol;
1136 static const char *get_ssh_command(void)
1138 const char *ssh;
1140 if ((ssh = getenv("GIT_SSH_COMMAND")))
1141 return ssh;
1143 if (!git_config_get_string_tmp("core.sshcommand", &ssh))
1144 return ssh;
1146 return NULL;
1149 enum ssh_variant {
1150 VARIANT_AUTO,
1151 VARIANT_SIMPLE,
1152 VARIANT_SSH,
1153 VARIANT_PLINK,
1154 VARIANT_PUTTY,
1155 VARIANT_TORTOISEPLINK,
1158 static void override_ssh_variant(enum ssh_variant *ssh_variant)
1160 const char *variant = getenv("GIT_SSH_VARIANT");
1162 if (!variant && git_config_get_string_tmp("ssh.variant", &variant))
1163 return;
1165 if (!strcmp(variant, "auto"))
1166 *ssh_variant = VARIANT_AUTO;
1167 else if (!strcmp(variant, "plink"))
1168 *ssh_variant = VARIANT_PLINK;
1169 else if (!strcmp(variant, "putty"))
1170 *ssh_variant = VARIANT_PUTTY;
1171 else if (!strcmp(variant, "tortoiseplink"))
1172 *ssh_variant = VARIANT_TORTOISEPLINK;
1173 else if (!strcmp(variant, "simple"))
1174 *ssh_variant = VARIANT_SIMPLE;
1175 else
1176 *ssh_variant = VARIANT_SSH;
1179 static enum ssh_variant determine_ssh_variant(const char *ssh_command,
1180 int is_cmdline)
1182 enum ssh_variant ssh_variant = VARIANT_AUTO;
1183 const char *variant;
1184 char *p = NULL;
1186 override_ssh_variant(&ssh_variant);
1188 if (ssh_variant != VARIANT_AUTO)
1189 return ssh_variant;
1191 if (!is_cmdline) {
1192 p = xstrdup(ssh_command);
1193 variant = basename(p);
1194 } else {
1195 const char **ssh_argv;
1197 p = xstrdup(ssh_command);
1198 if (split_cmdline(p, &ssh_argv) > 0) {
1199 variant = basename((char *)ssh_argv[0]);
1201 * At this point, variant points into the buffer
1202 * referenced by p, hence we do not need ssh_argv
1203 * any longer.
1205 free(ssh_argv);
1206 } else {
1207 free(p);
1208 return ssh_variant;
1212 if (!strcasecmp(variant, "ssh") ||
1213 !strcasecmp(variant, "ssh.exe"))
1214 ssh_variant = VARIANT_SSH;
1215 else if (!strcasecmp(variant, "plink") ||
1216 !strcasecmp(variant, "plink.exe"))
1217 ssh_variant = VARIANT_PLINK;
1218 else if (!strcasecmp(variant, "tortoiseplink") ||
1219 !strcasecmp(variant, "tortoiseplink.exe"))
1220 ssh_variant = VARIANT_TORTOISEPLINK;
1222 free(p);
1223 return ssh_variant;
1227 * Open a connection using Git's native protocol.
1229 * The caller is responsible for freeing hostandport, but this function may
1230 * modify it (for example, to truncate it to remove the port part).
1232 static struct child_process *git_connect_git(int fd[2], char *hostandport,
1233 const char *path, const char *prog,
1234 enum protocol_version version,
1235 int flags)
1237 struct child_process *conn;
1238 struct strbuf request = STRBUF_INIT;
1240 * Set up virtual host information based on where we will
1241 * connect, unless the user has overridden us in
1242 * the environment.
1244 char *target_host = getenv("GIT_OVERRIDE_VIRTUAL_HOST");
1245 if (target_host)
1246 target_host = xstrdup(target_host);
1247 else
1248 target_host = xstrdup(hostandport);
1250 transport_check_allowed("git");
1251 if (strchr(target_host, '\n') || strchr(path, '\n'))
1252 die(_("newline is forbidden in git:// hosts and repo paths"));
1255 * These underlying connection commands die() if they
1256 * cannot connect.
1258 if (git_use_proxy(hostandport))
1259 conn = git_proxy_connect(fd, hostandport);
1260 else
1261 conn = git_tcp_connect(fd, hostandport, flags);
1263 * Separate original protocol components prog and path
1264 * from extended host header with a NUL byte.
1266 * Note: Do not add any other headers here! Doing so
1267 * will cause older git-daemon servers to crash.
1269 strbuf_addf(&request,
1270 "%s %s%chost=%s%c",
1271 prog, path, 0,
1272 target_host, 0);
1274 /* If using a new version put that stuff here after a second null byte */
1275 if (version > 0) {
1276 strbuf_addch(&request, '\0');
1277 strbuf_addf(&request, "version=%d%c",
1278 version, '\0');
1281 packet_write(fd[1], request.buf, request.len);
1283 free(target_host);
1284 strbuf_release(&request);
1285 return conn;
1289 * Append the appropriate environment variables to `env` and options to
1290 * `args` for running ssh in Git's SSH-tunneled transport.
1292 static void push_ssh_options(struct strvec *args, struct strvec *env,
1293 enum ssh_variant variant, const char *port,
1294 enum protocol_version version, int flags)
1296 if (variant == VARIANT_SSH &&
1297 version > 0) {
1298 strvec_push(args, "-o");
1299 strvec_push(args, "SendEnv=" GIT_PROTOCOL_ENVIRONMENT);
1300 strvec_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1301 version);
1304 if (flags & CONNECT_IPV4) {
1305 switch (variant) {
1306 case VARIANT_AUTO:
1307 BUG("VARIANT_AUTO passed to push_ssh_options");
1308 case VARIANT_SIMPLE:
1309 die(_("ssh variant 'simple' does not support -4"));
1310 case VARIANT_SSH:
1311 case VARIANT_PLINK:
1312 case VARIANT_PUTTY:
1313 case VARIANT_TORTOISEPLINK:
1314 strvec_push(args, "-4");
1316 } else if (flags & CONNECT_IPV6) {
1317 switch (variant) {
1318 case VARIANT_AUTO:
1319 BUG("VARIANT_AUTO passed to push_ssh_options");
1320 case VARIANT_SIMPLE:
1321 die(_("ssh variant 'simple' does not support -6"));
1322 case VARIANT_SSH:
1323 case VARIANT_PLINK:
1324 case VARIANT_PUTTY:
1325 case VARIANT_TORTOISEPLINK:
1326 strvec_push(args, "-6");
1330 if (variant == VARIANT_TORTOISEPLINK)
1331 strvec_push(args, "-batch");
1333 if (port) {
1334 switch (variant) {
1335 case VARIANT_AUTO:
1336 BUG("VARIANT_AUTO passed to push_ssh_options");
1337 case VARIANT_SIMPLE:
1338 die(_("ssh variant 'simple' does not support setting port"));
1339 case VARIANT_SSH:
1340 strvec_push(args, "-p");
1341 break;
1342 case VARIANT_PLINK:
1343 case VARIANT_PUTTY:
1344 case VARIANT_TORTOISEPLINK:
1345 strvec_push(args, "-P");
1348 strvec_push(args, port);
1352 /* Prepare a child_process for use by Git's SSH-tunneled transport. */
1353 static void fill_ssh_args(struct child_process *conn, const char *ssh_host,
1354 const char *port, enum protocol_version version,
1355 int flags)
1357 const char *ssh;
1358 enum ssh_variant variant;
1360 if (looks_like_command_line_option(ssh_host))
1361 die(_("strange hostname '%s' blocked"), ssh_host);
1363 ssh = get_ssh_command();
1364 if (ssh) {
1365 variant = determine_ssh_variant(ssh, 1);
1366 } else {
1368 * GIT_SSH is the no-shell version of
1369 * GIT_SSH_COMMAND (and must remain so for
1370 * historical compatibility).
1372 conn->use_shell = 0;
1374 ssh = getenv("GIT_SSH");
1375 if (!ssh)
1376 ssh = "ssh";
1377 variant = determine_ssh_variant(ssh, 0);
1380 if (variant == VARIANT_AUTO) {
1381 struct child_process detect = CHILD_PROCESS_INIT;
1383 detect.use_shell = conn->use_shell;
1384 detect.no_stdin = detect.no_stdout = detect.no_stderr = 1;
1386 strvec_push(&detect.args, ssh);
1387 strvec_push(&detect.args, "-G");
1388 push_ssh_options(&detect.args, &detect.env,
1389 VARIANT_SSH, port, version, flags);
1390 strvec_push(&detect.args, ssh_host);
1392 variant = run_command(&detect) ? VARIANT_SIMPLE : VARIANT_SSH;
1395 strvec_push(&conn->args, ssh);
1396 push_ssh_options(&conn->args, &conn->env, variant, port, version,
1397 flags);
1398 strvec_push(&conn->args, ssh_host);
1402 * This returns the dummy child_process `no_fork` if the transport protocol
1403 * does not need fork(2), or a struct child_process object if it does. Once
1404 * done, finish the connection with finish_connect() with the value returned
1405 * from this function (it is safe to call finish_connect() with NULL to
1406 * support the former case).
1408 * If it returns, the connect is successful; it just dies on errors (this
1409 * will hopefully be changed in a libification effort, to return NULL when
1410 * the connection failed).
1412 struct child_process *git_connect(int fd[2], const char *url,
1413 const char *name,
1414 const char *prog, int flags)
1416 char *hostandport, *path;
1417 struct child_process *conn;
1418 enum protocol protocol;
1419 enum protocol_version version = get_protocol_version_config();
1422 * NEEDSWORK: If we are trying to use protocol v2 and we are planning
1423 * to perform any operation that doesn't involve upload-pack (i.e., a
1424 * fetch, ls-remote, etc), then fallback to v0 since we don't know how
1425 * to do anything else (like push or remote archive) via v2.
1427 if (version == protocol_v2 && strcmp("git-upload-pack", name))
1428 version = protocol_v0;
1430 /* Without this we cannot rely on waitpid() to tell
1431 * what happened to our children.
1433 signal(SIGCHLD, SIG_DFL);
1435 protocol = parse_connect_url(url, &hostandport, &path);
1436 if ((flags & CONNECT_DIAG_URL) && (protocol != PROTO_SSH)) {
1437 printf("Diag: url=%s\n", url ? url : "NULL");
1438 printf("Diag: protocol=%s\n", prot_name(protocol));
1439 printf("Diag: hostandport=%s\n", hostandport ? hostandport : "NULL");
1440 printf("Diag: path=%s\n", path ? path : "NULL");
1441 conn = NULL;
1442 } else if (protocol == PROTO_GIT) {
1443 conn = git_connect_git(fd, hostandport, path, prog, version, flags);
1444 conn->trace2_child_class = "transport/git";
1445 } else {
1446 struct strbuf cmd = STRBUF_INIT;
1447 const char *const *var;
1449 conn = xmalloc(sizeof(*conn));
1450 child_process_init(conn);
1452 if (looks_like_command_line_option(path))
1453 die(_("strange pathname '%s' blocked"), path);
1455 strbuf_addstr(&cmd, prog);
1456 strbuf_addch(&cmd, ' ');
1457 sq_quote_buf(&cmd, path);
1459 /* remove repo-local variables from the environment */
1460 for (var = local_repo_env; *var; var++)
1461 strvec_push(&conn->env, *var);
1463 conn->use_shell = 1;
1464 conn->in = conn->out = -1;
1465 if (protocol == PROTO_SSH) {
1466 char *ssh_host = hostandport;
1467 const char *port = NULL;
1468 transport_check_allowed("ssh");
1469 get_host_and_port(&ssh_host, &port);
1471 if (!port)
1472 port = get_port(ssh_host);
1474 if (flags & CONNECT_DIAG_URL) {
1475 printf("Diag: url=%s\n", url ? url : "NULL");
1476 printf("Diag: protocol=%s\n", prot_name(protocol));
1477 printf("Diag: userandhost=%s\n", ssh_host ? ssh_host : "NULL");
1478 printf("Diag: port=%s\n", port ? port : "NONE");
1479 printf("Diag: path=%s\n", path ? path : "NULL");
1481 free(hostandport);
1482 free(path);
1483 free(conn);
1484 strbuf_release(&cmd);
1485 return NULL;
1487 conn->trace2_child_class = "transport/ssh";
1488 fill_ssh_args(conn, ssh_host, port, version, flags);
1489 } else {
1490 transport_check_allowed("file");
1491 conn->trace2_child_class = "transport/file";
1492 if (version > 0) {
1493 strvec_pushf(&conn->env,
1494 GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1495 version);
1498 strvec_push(&conn->args, cmd.buf);
1500 if (start_command(conn))
1501 die(_("unable to fork"));
1503 fd[0] = conn->out; /* read from child's stdout */
1504 fd[1] = conn->in; /* write to child's stdin */
1505 strbuf_release(&cmd);
1507 free(hostandport);
1508 free(path);
1509 return conn;
1512 int finish_connect(struct child_process *conn)
1514 int code;
1515 if (!conn || git_connection_is_socket(conn))
1516 return 0;
1518 code = finish_command(conn);
1519 free(conn);
1520 return code;