t5562: pass object-format in synthesized test data
[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                 memcpy(ref->old_oid.hash, old_oid.hash, reader->hash_algo->rawsz);
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(const char *line, 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
386         /*
387          * Ref lines have a number of fields which are space deliminated.  The
388          * first field is the OID of the ref.  The second field is the ref
389          * name.  Subsequent fields (symref-target and peeled) are optional and
390          * don't have a particular order.
391          */
392         if (string_list_split(&line_sections, line, ' ', -1) < 2) {
393                 ret = 0;
394                 goto out;
395         }
396
397         if (parse_oid_hex(line_sections.items[i++].string, &old_oid, &end) ||
398             *end) {
399                 ret = 0;
400                 goto out;
401         }
402
403         ref = alloc_ref(line_sections.items[i++].string);
404
405         oidcpy(&ref->old_oid, &old_oid);
406         **list = ref;
407         *list = &ref->next;
408
409         for (; i < line_sections.nr; i++) {
410                 const char *arg = line_sections.items[i].string;
411                 if (skip_prefix(arg, "symref-target:", &arg))
412                         ref->symref = xstrdup(arg);
413
414                 if (skip_prefix(arg, "peeled:", &arg)) {
415                         struct object_id peeled_oid;
416                         char *peeled_name;
417                         struct ref *peeled;
418                         if (parse_oid_hex(arg, &peeled_oid, &end) || *end) {
419                                 ret = 0;
420                                 goto out;
421                         }
422
423                         peeled_name = xstrfmt("%s^{}", ref->name);
424                         peeled = alloc_ref(peeled_name);
425
426                         oidcpy(&peeled->old_oid, &peeled_oid);
427                         **list = peeled;
428                         *list = &peeled->next;
429
430                         free(peeled_name);
431                 }
432         }
433
434 out:
435         string_list_clear(&line_sections, 0);
436         return ret;
437 }
438
439 struct ref **get_remote_refs(int fd_out, struct packet_reader *reader,
440                              struct ref **list, int for_push,
441                              const struct argv_array *ref_prefixes,
442                              const struct string_list *server_options)
443 {
444         int i;
445         *list = NULL;
446
447         if (server_supports_v2("ls-refs", 1))
448                 packet_write_fmt(fd_out, "command=ls-refs\n");
449
450         if (server_supports_v2("agent", 0))
451                 packet_write_fmt(fd_out, "agent=%s", git_user_agent_sanitized());
452
453         if (server_options && server_options->nr &&
454             server_supports_v2("server-option", 1))
455                 for (i = 0; i < server_options->nr; i++)
456                         packet_write_fmt(fd_out, "server-option=%s",
457                                          server_options->items[i].string);
458
459         packet_delim(fd_out);
460         /* When pushing we don't want to request the peeled tags */
461         if (!for_push)
462                 packet_write_fmt(fd_out, "peel\n");
463         packet_write_fmt(fd_out, "symrefs\n");
464         for (i = 0; ref_prefixes && i < ref_prefixes->argc; i++) {
465                 packet_write_fmt(fd_out, "ref-prefix %s\n",
466                                  ref_prefixes->argv[i]);
467         }
468         packet_flush(fd_out);
469
470         /* Process response from server */
471         while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
472                 if (!process_ref_v2(reader->line, &list))
473                         die(_("invalid ls-refs response: %s"), reader->line);
474         }
475
476         if (reader->status != PACKET_READ_FLUSH)
477                 die(_("expected flush after ref listing"));
478
479         return list;
480 }
481
482 const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp, int *offset)
483 {
484         int len;
485
486         if (!feature_list)
487                 return NULL;
488
489         len = strlen(feature);
490         if (offset)
491                 feature_list += *offset;
492         while (*feature_list) {
493                 const char *found = strstr(feature_list, feature);
494                 if (!found)
495                         return NULL;
496                 if (feature_list == found || isspace(found[-1])) {
497                         const char *value = found + len;
498                         /* feature with no value (e.g., "thin-pack") */
499                         if (!*value || isspace(*value)) {
500                                 if (lenp)
501                                         *lenp = 0;
502                                 return value;
503                         }
504                         /* feature with a value (e.g., "agent=git/1.2.3") */
505                         else if (*value == '=') {
506                                 int end;
507
508                                 value++;
509                                 end = strcspn(value, " \t\n");
510                                 if (lenp)
511                                         *lenp = end;
512                                 if (offset)
513                                         *offset = value + end - feature_list;
514                                 return value;
515                         }
516                         /*
517                          * otherwise we matched a substring of another feature;
518                          * keep looking
519                          */
520                 }
521                 feature_list = found + 1;
522         }
523         return NULL;
524 }
525
526 int server_supports_hash(const char *desired, int *feature_supported)
527 {
528         int offset = 0;
529         int len;
530         const char *hash;
531
532         hash = next_server_feature_value("object-format", &len, &offset);
533         if (feature_supported)
534                 *feature_supported = !!hash;
535         if (!hash) {
536                 hash = hash_algos[GIT_HASH_SHA1].name;
537                 len = strlen(hash);
538         }
539         while (hash) {
540                 if (!xstrncmpz(desired, hash, len))
541                         return 1;
542
543                 hash = next_server_feature_value("object-format", &len, &offset);
544         }
545         return 0;
546 }
547
548 int parse_feature_request(const char *feature_list, const char *feature)
549 {
550         return !!parse_feature_value(feature_list, feature, NULL, NULL);
551 }
552
553 static const char *next_server_feature_value(const char *feature, int *len, int *offset)
554 {
555         return parse_feature_value(server_capabilities_v1, feature, len, offset);
556 }
557
558 const char *server_feature_value(const char *feature, int *len)
559 {
560         return parse_feature_value(server_capabilities_v1, feature, len, NULL);
561 }
562
563 int server_supports(const char *feature)
564 {
565         return !!server_feature_value(feature, NULL);
566 }
567
568 enum protocol {
569         PROTO_LOCAL = 1,
570         PROTO_FILE,
571         PROTO_SSH,
572         PROTO_GIT
573 };
574
575 int url_is_local_not_ssh(const char *url)
576 {
577         const char *colon = strchr(url, ':');
578         const char *slash = strchr(url, '/');
579         return !colon || (slash && slash < colon) ||
580                 (has_dos_drive_prefix(url) && is_valid_path(url));
581 }
582
583 static const char *prot_name(enum protocol protocol)
584 {
585         switch (protocol) {
586                 case PROTO_LOCAL:
587                 case PROTO_FILE:
588                         return "file";
589                 case PROTO_SSH:
590                         return "ssh";
591                 case PROTO_GIT:
592                         return "git";
593                 default:
594                         return "unknown protocol";
595         }
596 }
597
598 static enum protocol get_protocol(const char *name)
599 {
600         if (!strcmp(name, "ssh"))
601                 return PROTO_SSH;
602         if (!strcmp(name, "git"))
603                 return PROTO_GIT;
604         if (!strcmp(name, "git+ssh")) /* deprecated - do not use */
605                 return PROTO_SSH;
606         if (!strcmp(name, "ssh+git")) /* deprecated - do not use */
607                 return PROTO_SSH;
608         if (!strcmp(name, "file"))
609                 return PROTO_FILE;
610         die(_("protocol '%s' is not supported"), name);
611 }
612
613 static char *host_end(char **hoststart, int removebrackets)
614 {
615         char *host = *hoststart;
616         char *end;
617         char *start = strstr(host, "@[");
618         if (start)
619                 start++; /* Jump over '@' */
620         else
621                 start = host;
622         if (start[0] == '[') {
623                 end = strchr(start + 1, ']');
624                 if (end) {
625                         if (removebrackets) {
626                                 *end = 0;
627                                 memmove(start, start + 1, end - start);
628                                 end++;
629                         }
630                 } else
631                         end = host;
632         } else
633                 end = host;
634         return end;
635 }
636
637 #define STR_(s) # s
638 #define STR(s)  STR_(s)
639
640 static void get_host_and_port(char **host, const char **port)
641 {
642         char *colon, *end;
643         end = host_end(host, 1);
644         colon = strchr(end, ':');
645         if (colon) {
646                 long portnr = strtol(colon + 1, &end, 10);
647                 if (end != colon + 1 && *end == '\0' && 0 <= portnr && portnr < 65536) {
648                         *colon = 0;
649                         *port = colon + 1;
650                 } else if (!colon[1]) {
651                         *colon = 0;
652                 }
653         }
654 }
655
656 static void enable_keepalive(int sockfd)
657 {
658         int ka = 1;
659
660         if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
661                 error_errno(_("unable to set SO_KEEPALIVE on socket"));
662 }
663
664 #ifndef NO_IPV6
665
666 static const char *ai_name(const struct addrinfo *ai)
667 {
668         static char addr[NI_MAXHOST];
669         if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
670                         NI_NUMERICHOST) != 0)
671                 xsnprintf(addr, sizeof(addr), "(unknown)");
672
673         return addr;
674 }
675
676 /*
677  * Returns a connected socket() fd, or else die()s.
678  */
679 static int git_tcp_connect_sock(char *host, int flags)
680 {
681         struct strbuf error_message = STRBUF_INIT;
682         int sockfd = -1;
683         const char *port = STR(DEFAULT_GIT_PORT);
684         struct addrinfo hints, *ai0, *ai;
685         int gai;
686         int cnt = 0;
687
688         get_host_and_port(&host, &port);
689         if (!*port)
690                 port = "<none>";
691
692         memset(&hints, 0, sizeof(hints));
693         if (flags & CONNECT_IPV4)
694                 hints.ai_family = AF_INET;
695         else if (flags & CONNECT_IPV6)
696                 hints.ai_family = AF_INET6;
697         hints.ai_socktype = SOCK_STREAM;
698         hints.ai_protocol = IPPROTO_TCP;
699
700         if (flags & CONNECT_VERBOSE)
701                 fprintf(stderr, _("Looking up %s ... "), host);
702
703         gai = getaddrinfo(host, port, &hints, &ai);
704         if (gai)
705                 die(_("unable to look up %s (port %s) (%s)"), host, port, gai_strerror(gai));
706
707         if (flags & CONNECT_VERBOSE)
708                 /* TRANSLATORS: this is the end of "Looking up %s ... " */
709                 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
710
711         for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
712                 sockfd = socket(ai->ai_family,
713                                 ai->ai_socktype, ai->ai_protocol);
714                 if ((sockfd < 0) ||
715                     (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
716                         strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
717                                     host, cnt, ai_name(ai), strerror(errno));
718                         if (0 <= sockfd)
719                                 close(sockfd);
720                         sockfd = -1;
721                         continue;
722                 }
723                 if (flags & CONNECT_VERBOSE)
724                         fprintf(stderr, "%s ", ai_name(ai));
725                 break;
726         }
727
728         freeaddrinfo(ai0);
729
730         if (sockfd < 0)
731                 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
732
733         enable_keepalive(sockfd);
734
735         if (flags & CONNECT_VERBOSE)
736                 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
737                 fprintf_ln(stderr, _("done."));
738
739         strbuf_release(&error_message);
740
741         return sockfd;
742 }
743
744 #else /* NO_IPV6 */
745
746 /*
747  * Returns a connected socket() fd, or else die()s.
748  */
749 static int git_tcp_connect_sock(char *host, int flags)
750 {
751         struct strbuf error_message = STRBUF_INIT;
752         int sockfd = -1;
753         const char *port = STR(DEFAULT_GIT_PORT);
754         char *ep;
755         struct hostent *he;
756         struct sockaddr_in sa;
757         char **ap;
758         unsigned int nport;
759         int cnt;
760
761         get_host_and_port(&host, &port);
762
763         if (flags & CONNECT_VERBOSE)
764                 fprintf(stderr, _("Looking up %s ... "), host);
765
766         he = gethostbyname(host);
767         if (!he)
768                 die(_("unable to look up %s (%s)"), host, hstrerror(h_errno));
769         nport = strtoul(port, &ep, 10);
770         if ( ep == port || *ep ) {
771                 /* Not numeric */
772                 struct servent *se = getservbyname(port,"tcp");
773                 if ( !se )
774                         die(_("unknown port %s"), port);
775                 nport = se->s_port;
776         }
777
778         if (flags & CONNECT_VERBOSE)
779                 /* TRANSLATORS: this is the end of "Looking up %s ... " */
780                 fprintf(stderr, _("done.\nConnecting to %s (port %s) ... "), host, port);
781
782         for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
783                 memset(&sa, 0, sizeof sa);
784                 sa.sin_family = he->h_addrtype;
785                 sa.sin_port = htons(nport);
786                 memcpy(&sa.sin_addr, *ap, he->h_length);
787
788                 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
789                 if ((sockfd < 0) ||
790                     connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
791                         strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
792                                 host,
793                                 cnt,
794                                 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
795                                 strerror(errno));
796                         if (0 <= sockfd)
797                                 close(sockfd);
798                         sockfd = -1;
799                         continue;
800                 }
801                 if (flags & CONNECT_VERBOSE)
802                         fprintf(stderr, "%s ",
803                                 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
804                 break;
805         }
806
807         if (sockfd < 0)
808                 die(_("unable to connect to %s:\n%s"), host, error_message.buf);
809
810         enable_keepalive(sockfd);
811
812         if (flags & CONNECT_VERBOSE)
813                 /* TRANSLATORS: this is the end of "Connecting to %s (port %s) ... " */
814                 fprintf_ln(stderr, _("done."));
815
816         return sockfd;
817 }
818
819 #endif /* NO_IPV6 */
820
821
822 /*
823  * Dummy child_process returned by git_connect() if the transport protocol
824  * does not need fork(2).
825  */
826 static struct child_process no_fork = CHILD_PROCESS_INIT;
827
828 int git_connection_is_socket(struct child_process *conn)
829 {
830         return conn == &no_fork;
831 }
832
833 static struct child_process *git_tcp_connect(int fd[2], char *host, int flags)
834 {
835         int sockfd = git_tcp_connect_sock(host, flags);
836
837         fd[0] = sockfd;
838         fd[1] = dup(sockfd);
839
840         return &no_fork;
841 }
842
843
844 static char *git_proxy_command;
845
846 static int git_proxy_command_options(const char *var, const char *value,
847                 void *cb)
848 {
849         if (!strcmp(var, "core.gitproxy")) {
850                 const char *for_pos;
851                 int matchlen = -1;
852                 int hostlen;
853                 const char *rhost_name = cb;
854                 int rhost_len = strlen(rhost_name);
855
856                 if (git_proxy_command)
857                         return 0;
858                 if (!value)
859                         return config_error_nonbool(var);
860                 /* [core]
861                  * ;# matches www.kernel.org as well
862                  * gitproxy = netcatter-1 for kernel.org
863                  * gitproxy = netcatter-2 for sample.xz
864                  * gitproxy = netcatter-default
865                  */
866                 for_pos = strstr(value, " for ");
867                 if (!for_pos)
868                         /* matches everybody */
869                         matchlen = strlen(value);
870                 else {
871                         hostlen = strlen(for_pos + 5);
872                         if (rhost_len < hostlen)
873                                 matchlen = -1;
874                         else if (!strncmp(for_pos + 5,
875                                           rhost_name + rhost_len - hostlen,
876                                           hostlen) &&
877                                  ((rhost_len == hostlen) ||
878                                   rhost_name[rhost_len - hostlen -1] == '.'))
879                                 matchlen = for_pos - value;
880                         else
881                                 matchlen = -1;
882                 }
883                 if (0 <= matchlen) {
884                         /* core.gitproxy = none for kernel.org */
885                         if (matchlen == 4 &&
886                             !memcmp(value, "none", 4))
887                                 matchlen = 0;
888                         git_proxy_command = xmemdupz(value, matchlen);
889                 }
890                 return 0;
891         }
892
893         return git_default_config(var, value, cb);
894 }
895
896 static int git_use_proxy(const char *host)
897 {
898         git_proxy_command = getenv("GIT_PROXY_COMMAND");
899         git_config(git_proxy_command_options, (void*)host);
900         return (git_proxy_command && *git_proxy_command);
901 }
902
903 static struct child_process *git_proxy_connect(int fd[2], char *host)
904 {
905         const char *port = STR(DEFAULT_GIT_PORT);
906         struct child_process *proxy;
907
908         get_host_and_port(&host, &port);
909
910         if (looks_like_command_line_option(host))
911                 die(_("strange hostname '%s' blocked"), host);
912         if (looks_like_command_line_option(port))
913                 die(_("strange port '%s' blocked"), port);
914
915         proxy = xmalloc(sizeof(*proxy));
916         child_process_init(proxy);
917         argv_array_push(&proxy->args, git_proxy_command);
918         argv_array_push(&proxy->args, host);
919         argv_array_push(&proxy->args, port);
920         proxy->in = -1;
921         proxy->out = -1;
922         if (start_command(proxy))
923                 die(_("cannot start proxy %s"), git_proxy_command);
924         fd[0] = proxy->out; /* read from proxy stdout */
925         fd[1] = proxy->in;  /* write to proxy stdin */
926         return proxy;
927 }
928
929 static char *get_port(char *host)
930 {
931         char *end;
932         char *p = strchr(host, ':');
933
934         if (p) {
935                 long port = strtol(p + 1, &end, 10);
936                 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
937                         *p = '\0';
938                         return p+1;
939                 }
940         }
941
942         return NULL;
943 }
944
945 /*
946  * Extract protocol and relevant parts from the specified connection URL.
947  * The caller must free() the returned strings.
948  */
949 static enum protocol parse_connect_url(const char *url_orig, char **ret_host,
950                                        char **ret_path)
951 {
952         char *url;
953         char *host, *path;
954         char *end;
955         int separator = '/';
956         enum protocol protocol = PROTO_LOCAL;
957
958         if (is_url(url_orig))
959                 url = url_decode(url_orig);
960         else
961                 url = xstrdup(url_orig);
962
963         host = strstr(url, "://");
964         if (host) {
965                 *host = '\0';
966                 protocol = get_protocol(url);
967                 host += 3;
968         } else {
969                 host = url;
970                 if (!url_is_local_not_ssh(url)) {
971                         protocol = PROTO_SSH;
972                         separator = ':';
973                 }
974         }
975
976         /*
977          * Don't do destructive transforms as protocol code does
978          * '[]' unwrapping in get_host_and_port()
979          */
980         end = host_end(&host, 0);
981
982         if (protocol == PROTO_LOCAL)
983                 path = end;
984         else if (protocol == PROTO_FILE && *host != '/' &&
985                  !has_dos_drive_prefix(host) &&
986                  offset_1st_component(host - 2) > 1)
987                 path = host - 2; /* include the leading "//" */
988         else if (protocol == PROTO_FILE && has_dos_drive_prefix(end))
989                 path = end; /* "file://$(pwd)" may be "file://C:/projects/repo" */
990         else
991                 path = strchr(end, separator);
992
993         if (!path || !*path)
994                 die(_("no path specified; see 'git help pull' for valid url syntax"));
995
996         /*
997          * null-terminate hostname and point path to ~ for URL's like this:
998          *    ssh://host.xz/~user/repo
999          */
1000
1001         end = path; /* Need to \0 terminate host here */
1002         if (separator == ':')
1003                 path++; /* path starts after ':' */
1004         if (protocol == PROTO_GIT || protocol == PROTO_SSH) {
1005                 if (path[1] == '~')
1006                         path++;
1007         }
1008
1009         path = xstrdup(path);
1010         *end = '\0';
1011
1012         *ret_host = xstrdup(host);
1013         *ret_path = path;
1014         free(url);
1015         return protocol;
1016 }
1017
1018 static const char *get_ssh_command(void)
1019 {
1020         const char *ssh;
1021
1022         if ((ssh = getenv("GIT_SSH_COMMAND")))
1023                 return ssh;
1024
1025         if (!git_config_get_string_const("core.sshcommand", &ssh))
1026                 return ssh;
1027
1028         return NULL;
1029 }
1030
1031 enum ssh_variant {
1032         VARIANT_AUTO,
1033         VARIANT_SIMPLE,
1034         VARIANT_SSH,
1035         VARIANT_PLINK,
1036         VARIANT_PUTTY,
1037         VARIANT_TORTOISEPLINK,
1038 };
1039
1040 static void override_ssh_variant(enum ssh_variant *ssh_variant)
1041 {
1042         const char *variant = getenv("GIT_SSH_VARIANT");
1043
1044         if (!variant && git_config_get_string_const("ssh.variant", &variant))
1045                 return;
1046
1047         if (!strcmp(variant, "auto"))
1048                 *ssh_variant = VARIANT_AUTO;
1049         else if (!strcmp(variant, "plink"))
1050                 *ssh_variant = VARIANT_PLINK;
1051         else if (!strcmp(variant, "putty"))
1052                 *ssh_variant = VARIANT_PUTTY;
1053         else if (!strcmp(variant, "tortoiseplink"))
1054                 *ssh_variant = VARIANT_TORTOISEPLINK;
1055         else if (!strcmp(variant, "simple"))
1056                 *ssh_variant = VARIANT_SIMPLE;
1057         else
1058                 *ssh_variant = VARIANT_SSH;
1059 }
1060
1061 static enum ssh_variant determine_ssh_variant(const char *ssh_command,
1062                                               int is_cmdline)
1063 {
1064         enum ssh_variant ssh_variant = VARIANT_AUTO;
1065         const char *variant;
1066         char *p = NULL;
1067
1068         override_ssh_variant(&ssh_variant);
1069
1070         if (ssh_variant != VARIANT_AUTO)
1071                 return ssh_variant;
1072
1073         if (!is_cmdline) {
1074                 p = xstrdup(ssh_command);
1075                 variant = basename(p);
1076         } else {
1077                 const char **ssh_argv;
1078
1079                 p = xstrdup(ssh_command);
1080                 if (split_cmdline(p, &ssh_argv) > 0) {
1081                         variant = basename((char *)ssh_argv[0]);
1082                         /*
1083                          * At this point, variant points into the buffer
1084                          * referenced by p, hence we do not need ssh_argv
1085                          * any longer.
1086                          */
1087                         free(ssh_argv);
1088                 } else {
1089                         free(p);
1090                         return ssh_variant;
1091                 }
1092         }
1093
1094         if (!strcasecmp(variant, "ssh") ||
1095             !strcasecmp(variant, "ssh.exe"))
1096                 ssh_variant = VARIANT_SSH;
1097         else if (!strcasecmp(variant, "plink") ||
1098                  !strcasecmp(variant, "plink.exe"))
1099                 ssh_variant = VARIANT_PLINK;
1100         else if (!strcasecmp(variant, "tortoiseplink") ||
1101                  !strcasecmp(variant, "tortoiseplink.exe"))
1102                 ssh_variant = VARIANT_TORTOISEPLINK;
1103
1104         free(p);
1105         return ssh_variant;
1106 }
1107
1108 /*
1109  * Open a connection using Git's native protocol.
1110  *
1111  * The caller is responsible for freeing hostandport, but this function may
1112  * modify it (for example, to truncate it to remove the port part).
1113  */
1114 static struct child_process *git_connect_git(int fd[2], char *hostandport,
1115                                              const char *path, const char *prog,
1116                                              enum protocol_version version,
1117                                              int flags)
1118 {
1119         struct child_process *conn;
1120         struct strbuf request = STRBUF_INIT;
1121         /*
1122          * Set up virtual host information based on where we will
1123          * connect, unless the user has overridden us in
1124          * the environment.
1125          */
1126         char *target_host = getenv("GIT_OVERRIDE_VIRTUAL_HOST");
1127         if (target_host)
1128                 target_host = xstrdup(target_host);
1129         else
1130                 target_host = xstrdup(hostandport);
1131
1132         transport_check_allowed("git");
1133
1134         /*
1135          * These underlying connection commands die() if they
1136          * cannot connect.
1137          */
1138         if (git_use_proxy(hostandport))
1139                 conn = git_proxy_connect(fd, hostandport);
1140         else
1141                 conn = git_tcp_connect(fd, hostandport, flags);
1142         /*
1143          * Separate original protocol components prog and path
1144          * from extended host header with a NUL byte.
1145          *
1146          * Note: Do not add any other headers here!  Doing so
1147          * will cause older git-daemon servers to crash.
1148          */
1149         strbuf_addf(&request,
1150                     "%s %s%chost=%s%c",
1151                     prog, path, 0,
1152                     target_host, 0);
1153
1154         /* If using a new version put that stuff here after a second null byte */
1155         if (version > 0) {
1156                 strbuf_addch(&request, '\0');
1157                 strbuf_addf(&request, "version=%d%c",
1158                             version, '\0');
1159         }
1160
1161         packet_write(fd[1], request.buf, request.len);
1162
1163         free(target_host);
1164         strbuf_release(&request);
1165         return conn;
1166 }
1167
1168 /*
1169  * Append the appropriate environment variables to `env` and options to
1170  * `args` for running ssh in Git's SSH-tunneled transport.
1171  */
1172 static void push_ssh_options(struct argv_array *args, struct argv_array *env,
1173                              enum ssh_variant variant, const char *port,
1174                              enum protocol_version version, int flags)
1175 {
1176         if (variant == VARIANT_SSH &&
1177             version > 0) {
1178                 argv_array_push(args, "-o");
1179                 argv_array_push(args, "SendEnv=" GIT_PROTOCOL_ENVIRONMENT);
1180                 argv_array_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1181                                  version);
1182         }
1183
1184         if (flags & CONNECT_IPV4) {
1185                 switch (variant) {
1186                 case VARIANT_AUTO:
1187                         BUG("VARIANT_AUTO passed to push_ssh_options");
1188                 case VARIANT_SIMPLE:
1189                         die(_("ssh variant 'simple' does not support -4"));
1190                 case VARIANT_SSH:
1191                 case VARIANT_PLINK:
1192                 case VARIANT_PUTTY:
1193                 case VARIANT_TORTOISEPLINK:
1194                         argv_array_push(args, "-4");
1195                 }
1196         } else if (flags & CONNECT_IPV6) {
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 -6"));
1202                 case VARIANT_SSH:
1203                 case VARIANT_PLINK:
1204                 case VARIANT_PUTTY:
1205                 case VARIANT_TORTOISEPLINK:
1206                         argv_array_push(args, "-6");
1207                 }
1208         }
1209
1210         if (variant == VARIANT_TORTOISEPLINK)
1211                 argv_array_push(args, "-batch");
1212
1213         if (port) {
1214                 switch (variant) {
1215                 case VARIANT_AUTO:
1216                         BUG("VARIANT_AUTO passed to push_ssh_options");
1217                 case VARIANT_SIMPLE:
1218                         die(_("ssh variant 'simple' does not support setting port"));
1219                 case VARIANT_SSH:
1220                         argv_array_push(args, "-p");
1221                         break;
1222                 case VARIANT_PLINK:
1223                 case VARIANT_PUTTY:
1224                 case VARIANT_TORTOISEPLINK:
1225                         argv_array_push(args, "-P");
1226                 }
1227
1228                 argv_array_push(args, port);
1229         }
1230 }
1231
1232 /* Prepare a child_process for use by Git's SSH-tunneled transport. */
1233 static void fill_ssh_args(struct child_process *conn, const char *ssh_host,
1234                           const char *port, enum protocol_version version,
1235                           int flags)
1236 {
1237         const char *ssh;
1238         enum ssh_variant variant;
1239
1240         if (looks_like_command_line_option(ssh_host))
1241                 die(_("strange hostname '%s' blocked"), ssh_host);
1242
1243         ssh = get_ssh_command();
1244         if (ssh) {
1245                 variant = determine_ssh_variant(ssh, 1);
1246         } else {
1247                 /*
1248                  * GIT_SSH is the no-shell version of
1249                  * GIT_SSH_COMMAND (and must remain so for
1250                  * historical compatibility).
1251                  */
1252                 conn->use_shell = 0;
1253
1254                 ssh = getenv("GIT_SSH");
1255                 if (!ssh)
1256                         ssh = "ssh";
1257                 variant = determine_ssh_variant(ssh, 0);
1258         }
1259
1260         if (variant == VARIANT_AUTO) {
1261                 struct child_process detect = CHILD_PROCESS_INIT;
1262
1263                 detect.use_shell = conn->use_shell;
1264                 detect.no_stdin = detect.no_stdout = detect.no_stderr = 1;
1265
1266                 argv_array_push(&detect.args, ssh);
1267                 argv_array_push(&detect.args, "-G");
1268                 push_ssh_options(&detect.args, &detect.env_array,
1269                                  VARIANT_SSH, port, version, flags);
1270                 argv_array_push(&detect.args, ssh_host);
1271
1272                 variant = run_command(&detect) ? VARIANT_SIMPLE : VARIANT_SSH;
1273         }
1274
1275         argv_array_push(&conn->args, ssh);
1276         push_ssh_options(&conn->args, &conn->env_array, variant, port, version, flags);
1277         argv_array_push(&conn->args, ssh_host);
1278 }
1279
1280 /*
1281  * This returns the dummy child_process `no_fork` if the transport protocol
1282  * does not need fork(2), or a struct child_process object if it does.  Once
1283  * done, finish the connection with finish_connect() with the value returned
1284  * from this function (it is safe to call finish_connect() with NULL to
1285  * support the former case).
1286  *
1287  * If it returns, the connect is successful; it just dies on errors (this
1288  * will hopefully be changed in a libification effort, to return NULL when
1289  * the connection failed).
1290  */
1291 struct child_process *git_connect(int fd[2], const char *url,
1292                                   const char *prog, int flags)
1293 {
1294         char *hostandport, *path;
1295         struct child_process *conn;
1296         enum protocol protocol;
1297         enum protocol_version version = get_protocol_version_config();
1298
1299         /*
1300          * NEEDSWORK: If we are trying to use protocol v2 and we are planning
1301          * to perform a push, then fallback to v0 since the client doesn't know
1302          * how to push yet using v2.
1303          */
1304         if (version == protocol_v2 && !strcmp("git-receive-pack", prog))
1305                 version = protocol_v0;
1306
1307         /* Without this we cannot rely on waitpid() to tell
1308          * what happened to our children.
1309          */
1310         signal(SIGCHLD, SIG_DFL);
1311
1312         protocol = parse_connect_url(url, &hostandport, &path);
1313         if ((flags & CONNECT_DIAG_URL) && (protocol != PROTO_SSH)) {
1314                 printf("Diag: url=%s\n", url ? url : "NULL");
1315                 printf("Diag: protocol=%s\n", prot_name(protocol));
1316                 printf("Diag: hostandport=%s\n", hostandport ? hostandport : "NULL");
1317                 printf("Diag: path=%s\n", path ? path : "NULL");
1318                 conn = NULL;
1319         } else if (protocol == PROTO_GIT) {
1320                 conn = git_connect_git(fd, hostandport, path, prog, version, flags);
1321                 conn->trace2_child_class = "transport/git";
1322         } else {
1323                 struct strbuf cmd = STRBUF_INIT;
1324                 const char *const *var;
1325
1326                 conn = xmalloc(sizeof(*conn));
1327                 child_process_init(conn);
1328
1329                 if (looks_like_command_line_option(path))
1330                         die(_("strange pathname '%s' blocked"), path);
1331
1332                 strbuf_addstr(&cmd, prog);
1333                 strbuf_addch(&cmd, ' ');
1334                 sq_quote_buf(&cmd, path);
1335
1336                 /* remove repo-local variables from the environment */
1337                 for (var = local_repo_env; *var; var++)
1338                         argv_array_push(&conn->env_array, *var);
1339
1340                 conn->use_shell = 1;
1341                 conn->in = conn->out = -1;
1342                 if (protocol == PROTO_SSH) {
1343                         char *ssh_host = hostandport;
1344                         const char *port = NULL;
1345                         transport_check_allowed("ssh");
1346                         get_host_and_port(&ssh_host, &port);
1347
1348                         if (!port)
1349                                 port = get_port(ssh_host);
1350
1351                         if (flags & CONNECT_DIAG_URL) {
1352                                 printf("Diag: url=%s\n", url ? url : "NULL");
1353                                 printf("Diag: protocol=%s\n", prot_name(protocol));
1354                                 printf("Diag: userandhost=%s\n", ssh_host ? ssh_host : "NULL");
1355                                 printf("Diag: port=%s\n", port ? port : "NONE");
1356                                 printf("Diag: path=%s\n", path ? path : "NULL");
1357
1358                                 free(hostandport);
1359                                 free(path);
1360                                 free(conn);
1361                                 strbuf_release(&cmd);
1362                                 return NULL;
1363                         }
1364                         conn->trace2_child_class = "transport/ssh";
1365                         fill_ssh_args(conn, ssh_host, port, version, flags);
1366                 } else {
1367                         transport_check_allowed("file");
1368                         conn->trace2_child_class = "transport/file";
1369                         if (version > 0) {
1370                                 argv_array_pushf(&conn->env_array, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1371                                                  version);
1372                         }
1373                 }
1374                 argv_array_push(&conn->args, cmd.buf);
1375
1376                 if (start_command(conn))
1377                         die(_("unable to fork"));
1378
1379                 fd[0] = conn->out; /* read from child's stdout */
1380                 fd[1] = conn->in;  /* write to child's stdin */
1381                 strbuf_release(&cmd);
1382         }
1383         free(hostandport);
1384         free(path);
1385         return conn;
1386 }
1387
1388 int finish_connect(struct child_process *conn)
1389 {
1390         int code;
1391         if (!conn || git_connection_is_socket(conn))
1392                 return 0;
1393
1394         code = finish_command(conn);
1395         free(conn);
1396         return code;
1397 }