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