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