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