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