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