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