upload-pack, receive-pack: introduce protocol version 1
[git/git.git] / connect.c
CommitLineData
731043fd 1#include "git-compat-util.h"
f7192598 2#include "cache.h"
b2141fc1 3#include "config.h"
41cb7488 4#include "pkt-line.h"
b10d0ec7 5#include "quote.h"
6abf5c0c 6#include "refs.h"
15a1c012 7#include "run-command.h"
6b62816c 8#include "remote.h"
47a59185 9#include "connect.h"
9d2e9420 10#include "url.h"
a45b5f05 11#include "string-list.h"
13eb4626 12#include "sha1-array.h"
a5adaced 13#include "transport.h"
0cd83283 14#include "strbuf.h"
f7192598 15
96f1e58f 16static char *server_capabilities;
5d54cffc 17static const char *parse_feature_value(const char *, const char *, int *);
211b5f9e 18
be0b3f82 19static int check_ref(const char *name, unsigned int flags)
2718ff09
LT
20{
21 if (!flags)
22 return 1;
23
be0b3f82 24 if (!skip_prefix(name, "refs/", &name))
2718ff09
LT
25 return 0;
26
2718ff09 27 /* REF_NORMAL means that we don't want the magic fake tag refs */
8d9c5010 28 if ((flags & REF_NORMAL) && check_refname_format(name, 0))
2718ff09
LT
29 return 0;
30
31 /* REF_HEADS means that we want regular branch heads */
be0b3f82 32 if ((flags & REF_HEADS) && starts_with(name, "heads/"))
2718ff09
LT
33 return 1;
34
35 /* REF_TAGS means that we want tags */
be0b3f82 36 if ((flags & REF_TAGS) && starts_with(name, "tags/"))
2718ff09
LT
37 return 1;
38
39 /* All type bits clear means that we are ok with anything */
40 return !(flags & ~REF_NORMAL);
41}
42
4577370e
DB
43int check_ref_type(const struct ref *ref, int flags)
44{
be0b3f82 45 return check_ref(ref->name, flags);
4577370e
DB
46}
47
55e4f936 48static void die_initial_contact(int unexpected)
46284dd1 49{
55e4f936 50 if (unexpected)
f2b93b38 51 die(_("The remote end hung up upon initial contact"));
46284dd1 52 else
f2b93b38
VA
53 die(_("Could not read from remote repository.\n\n"
54 "Please make sure you have the correct access rights\n"
55 "and the repository exists."));
46284dd1
HV
56}
57
a45b5f05
JH
58static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
59{
60 char *sym, *target;
61 struct string_list_item *item;
62
63 if (!len)
64 return; /* just "symref" */
65 /* e.g. "symref=HEAD:refs/heads/master" */
5c0b13f8 66 sym = xmemdupz(val, len);
a45b5f05
JH
67 target = strchr(sym, ':');
68 if (!target)
69 /* just "symref=something" */
70 goto reject;
71 *(target++) = '\0';
72 if (check_refname_format(sym, REFNAME_ALLOW_ONELEVEL) ||
73 check_refname_format(target, REFNAME_ALLOW_ONELEVEL))
74 /* "symref=bogus:pair */
75 goto reject;
ef4fe561 76 item = string_list_append_nodup(symref, sym);
a45b5f05
JH
77 item->util = target;
78 return;
79reject:
80 free(sym);
81 return;
82}
83
84static void annotate_refs_with_symref_info(struct ref *ref)
85{
86 struct string_list symref = STRING_LIST_INIT_DUP;
87 const char *feature_list = server_capabilities;
88
89 while (feature_list) {
90 int len;
91 const char *val;
92
93 val = parse_feature_value(feature_list, "symref", &len);
94 if (!val)
95 break;
96 parse_one_symref_info(&symref, val, len);
97 feature_list = val + 1;
98 }
3383e199 99 string_list_sort(&symref);
a45b5f05
JH
100
101 for (; ref; ref = ref->next) {
102 struct string_list_item *item;
103 item = string_list_lookup(&symref, ref->name);
104 if (!item)
105 continue;
106 ref->symref = xstrdup((char *)item->util);
107 }
108 string_list_clear(&symref, 0);
109}
110
0cd83283
JT
111/*
112 * Read one line of a server's ref advertisement into packet_buffer.
113 */
114static int read_remote_ref(int in, char **src_buf, size_t *src_len,
115 int *responded)
116{
117 int len = packet_read(in, src_buf, src_len,
118 packet_buffer, sizeof(packet_buffer),
119 PACKET_READ_GENTLE_ON_EOF |
120 PACKET_READ_CHOMP_NEWLINE);
121 const char *arg;
122 if (len < 0)
123 die_initial_contact(*responded);
124 if (len > 4 && skip_prefix(packet_buffer, "ERR ", &arg))
125 die("remote error: %s", arg);
126
127 *responded = 1;
128
129 return len;
130}
131
132#define EXPECTING_FIRST_REF 0
133#define EXPECTING_REF 1
134#define EXPECTING_SHALLOW 2
135
136static void process_capabilities(int *len)
137{
138 int nul_location = strlen(packet_buffer);
139 if (nul_location == *len)
140 return;
141 server_capabilities = xstrdup(packet_buffer + nul_location + 1);
142 *len = nul_location;
143}
144
145static int process_dummy_ref(void)
146{
147 struct object_id oid;
148 const char *name;
149
150 if (parse_oid_hex(packet_buffer, &oid, &name))
151 return 0;
152 if (*name != ' ')
153 return 0;
154 name++;
155
156 return !oidcmp(&null_oid, &oid) && !strcmp(name, "capabilities^{}");
157}
158
159static void check_no_capabilities(int len)
160{
161 if (strlen(packet_buffer) != len)
162 warning("Ignoring capabilities after first line '%s'",
163 packet_buffer + strlen(packet_buffer));
164}
165
166static int process_ref(int len, struct ref ***list, unsigned int flags,
167 struct oid_array *extra_have)
168{
169 struct object_id old_oid;
170 const char *name;
171
172 if (parse_oid_hex(packet_buffer, &old_oid, &name))
173 return 0;
174 if (*name != ' ')
175 return 0;
176 name++;
177
178 if (extra_have && !strcmp(name, ".have")) {
179 oid_array_append(extra_have, &old_oid);
180 } else if (!strcmp(name, "capabilities^{}")) {
181 die("protocol error: unexpected capabilities^{}");
182 } else if (check_ref(name, flags)) {
183 struct ref *ref = alloc_ref(name);
184 oidcpy(&ref->old_oid, &old_oid);
185 **list = ref;
186 *list = &ref->next;
187 }
188 check_no_capabilities(len);
189 return 1;
190}
191
192static int process_shallow(int len, struct oid_array *shallow_points)
193{
194 const char *arg;
195 struct object_id old_oid;
196
197 if (!skip_prefix(packet_buffer, "shallow ", &arg))
198 return 0;
199
200 if (get_oid_hex(arg, &old_oid))
201 die("protocol error: expected shallow sha-1, got '%s'", arg);
202 if (!shallow_points)
203 die("repository on the other end cannot be shallow");
204 oid_array_append(shallow_points, &old_oid);
205 check_no_capabilities(len);
206 return 1;
207}
208
d1c133f5
LT
209/*
210 * Read all the refs from the other end
211 */
85edf4f5
JK
212struct ref **get_remote_heads(int in, char *src_buf, size_t src_len,
213 struct ref **list, unsigned int flags,
910650d2 214 struct oid_array *extra_have,
215 struct oid_array *shallow_points)
d1c133f5 216{
a45b5f05 217 struct ref **orig_list = list;
55e4f936
JN
218
219 /*
220 * A hang-up after seeing some response from the other end
221 * means that it is unexpected, as we know the other end is
222 * willing to talk to us. A hang-up before seeing any
223 * response does not necessarily mean an ACL problem, though.
224 */
0cd83283
JT
225 int responded = 0;
226 int len;
227 int state = EXPECTING_FIRST_REF;
46284dd1 228
d1c133f5 229 *list = NULL;
1a7141ff 230
0cd83283
JT
231 while ((len = read_remote_ref(in, &src_buf, &src_len, &responded))) {
232 switch (state) {
233 case EXPECTING_FIRST_REF:
234 process_capabilities(&len);
235 if (process_dummy_ref()) {
236 state = EXPECTING_SHALLOW;
237 break;
238 }
239 state = EXPECTING_REF;
240 /* fallthrough */
241 case EXPECTING_REF:
242 if (process_ref(len, &list, flags, extra_have))
243 break;
244 state = EXPECTING_SHALLOW;
245 /* fallthrough */
246 case EXPECTING_SHALLOW:
247 if (process_shallow(len, shallow_points))
248 break;
249 die("protocol error: unexpected '%s'", packet_buffer);
250 default:
251 die("unexpected state %d", state);
211b5f9e 252 }
d1c133f5 253 }
a45b5f05
JH
254
255 annotate_refs_with_symref_info(*orig_list);
256
d1c133f5
LT
257 return list;
258}
259
5d54cffc 260static const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp)
f47182c8
JH
261{
262 int len;
263
264 if (!feature_list)
265 return NULL;
266
267 len = strlen(feature);
268 while (*feature_list) {
269 const char *found = strstr(feature_list, feature);
270 if (!found)
271 return NULL;
94427108
JK
272 if (feature_list == found || isspace(found[-1])) {
273 const char *value = found + len;
274 /* feature with no value (e.g., "thin-pack") */
275 if (!*value || isspace(*value)) {
276 if (lenp)
277 *lenp = 0;
278 return value;
279 }
280 /* feature with a value (e.g., "agent=git/1.2.3") */
281 else if (*value == '=') {
282 value++;
283 if (lenp)
284 *lenp = strcspn(value, " \t\n");
285 return value;
286 }
287 /*
288 * otherwise we matched a substring of another feature;
289 * keep looking
290 */
291 }
f47182c8
JH
292 feature_list = found + 1;
293 }
294 return NULL;
211b5f9e
JS
295}
296
94427108
JK
297int parse_feature_request(const char *feature_list, const char *feature)
298{
299 return !!parse_feature_value(feature_list, feature, NULL);
300}
301
302const char *server_feature_value(const char *feature, int *len)
303{
304 return parse_feature_value(server_capabilities, feature, len);
305}
306
307int server_supports(const char *feature)
308{
309 return !!server_feature_value(feature, NULL);
310}
311
2386d658
LT
312enum protocol {
313 PROTO_LOCAL = 1,
c59ab2e5 314 PROTO_FILE,
2386d658 315 PROTO_SSH,
4b05548f 316 PROTO_GIT
2386d658
LT
317};
318
c59ab2e5
TB
319int url_is_local_not_ssh(const char *url)
320{
321 const char *colon = strchr(url, ':');
322 const char *slash = strchr(url, '/');
323 return !colon || (slash && slash < colon) ||
324 has_dos_drive_prefix(url);
325}
326
5610b7c0
TB
327static const char *prot_name(enum protocol protocol)
328{
329 switch (protocol) {
330 case PROTO_LOCAL:
c59ab2e5 331 case PROTO_FILE:
5610b7c0
TB
332 return "file";
333 case PROTO_SSH:
334 return "ssh";
335 case PROTO_GIT:
336 return "git";
337 default:
83e6bda3 338 return "unknown protocol";
5610b7c0
TB
339 }
340}
341
2386d658
LT
342static enum protocol get_protocol(const char *name)
343{
344 if (!strcmp(name, "ssh"))
345 return PROTO_SSH;
346 if (!strcmp(name, "git"))
347 return PROTO_GIT;
07c7782c 348 if (!strcmp(name, "git+ssh")) /* deprecated - do not use */
c05186cc 349 return PROTO_SSH;
07c7782c 350 if (!strcmp(name, "ssh+git")) /* deprecated - do not use */
c05186cc 351 return PROTO_SSH;
72a4f4b6 352 if (!strcmp(name, "file"))
c59ab2e5 353 return PROTO_FILE;
2386d658
LT
354 die("I don't handle protocol '%s'", name);
355}
356
86ceb337
TB
357static char *host_end(char **hoststart, int removebrackets)
358{
359 char *host = *hoststart;
360 char *end;
361 char *start = strstr(host, "@[");
362 if (start)
363 start++; /* Jump over '@' */
364 else
365 start = host;
366 if (start[0] == '[') {
367 end = strchr(start + 1, ']');
368 if (end) {
369 if (removebrackets) {
370 *end = 0;
371 memmove(start, start + 1, end - start);
372 end++;
373 }
374 } else
375 end = host;
376 } else
377 end = host;
378 return end;
379}
380
5ba88448
YH
381#define STR_(s) # s
382#define STR(s) STR_(s)
2386d658 383
72a534da
ML
384static void get_host_and_port(char **host, const char **port)
385{
386 char *colon, *end;
86ceb337 387 end = host_end(host, 1);
72a534da 388 colon = strchr(end, ':');
72a534da 389 if (colon) {
86ceb337
TB
390 long portnr = strtol(colon + 1, &end, 10);
391 if (end != colon + 1 && *end == '\0' && 0 <= portnr && portnr < 65536) {
392 *colon = 0;
393 *port = colon + 1;
6b6c5f7a
TB
394 } else if (!colon[1]) {
395 *colon = 0;
86ceb337 396 }
72a534da
ML
397 }
398}
399
e47a8583
EW
400static void enable_keepalive(int sockfd)
401{
402 int ka = 1;
403
404 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
405 fprintf(stderr, "unable to set SO_KEEPALIVE on socket: %s\n",
406 strerror(errno));
407}
408
49744d63 409#ifndef NO_IPV6
4c505f71 410
ba505322
AR
411static const char *ai_name(const struct addrinfo *ai)
412{
785a9857
BK
413 static char addr[NI_MAXHOST];
414 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
415 NI_NUMERICHOST) != 0)
5096d490 416 xsnprintf(addr, sizeof(addr), "(unknown)");
785a9857 417
ba505322
AR
418 return addr;
419}
420
5ad312be
JL
421/*
422 * Returns a connected socket() fd, or else die()s.
423 */
7841ce79 424static int git_tcp_connect_sock(char *host, int flags)
2386d658 425{
63a995b6
DZ
426 struct strbuf error_message = STRBUF_INIT;
427 int sockfd = -1;
554fe20d 428 const char *port = STR(DEFAULT_GIT_PORT);
5ba88448
YH
429 struct addrinfo hints, *ai0, *ai;
430 int gai;
ba505322 431 int cnt = 0;
5ba88448 432
72a534da
ML
433 get_host_and_port(&host, &port);
434 if (!*port)
435 port = "<none>";
5ba88448
YH
436
437 memset(&hints, 0, sizeof(hints));
c915f11e
EW
438 if (flags & CONNECT_IPV4)
439 hints.ai_family = AF_INET;
440 else if (flags & CONNECT_IPV6)
441 hints.ai_family = AF_INET6;
5ba88448
YH
442 hints.ai_socktype = SOCK_STREAM;
443 hints.ai_protocol = IPPROTO_TCP;
444
7841ce79
MT
445 if (flags & CONNECT_VERBOSE)
446 fprintf(stderr, "Looking up %s ... ", host);
447
5ba88448
YH
448 gai = getaddrinfo(host, port, &hints, &ai);
449 if (gai)
608d48b2 450 die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
5ba88448 451
7841ce79
MT
452 if (flags & CONNECT_VERBOSE)
453 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
454
e08afecd 455 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
5ad312be
JL
456 sockfd = socket(ai->ai_family,
457 ai->ai_socktype, ai->ai_protocol);
63a995b6
DZ
458 if ((sockfd < 0) ||
459 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
460 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
461 host, cnt, ai_name(ai), strerror(errno));
462 if (0 <= sockfd)
463 close(sockfd);
5ba88448
YH
464 sockfd = -1;
465 continue;
2386d658 466 }
ba505322
AR
467 if (flags & CONNECT_VERBOSE)
468 fprintf(stderr, "%s ", ai_name(ai));
5ba88448 469 break;
2386d658
LT
470 }
471
5ba88448 472 freeaddrinfo(ai0);
2386d658 473
2386d658 474 if (sockfd < 0)
63a995b6 475 die("unable to connect to %s:\n%s", host, error_message.buf);
5ba88448 476
e47a8583
EW
477 enable_keepalive(sockfd);
478
7841ce79
MT
479 if (flags & CONNECT_VERBOSE)
480 fprintf(stderr, "done.\n");
481
63a995b6
DZ
482 strbuf_release(&error_message);
483
5ad312be 484 return sockfd;
2386d658
LT
485}
486
49744d63 487#else /* NO_IPV6 */
4c505f71 488
5ad312be
JL
489/*
490 * Returns a connected socket() fd, or else die()s.
491 */
7841ce79 492static int git_tcp_connect_sock(char *host, int flags)
4c505f71 493{
7203a2d1
EFL
494 struct strbuf error_message = STRBUF_INIT;
495 int sockfd = -1;
72a534da
ML
496 const char *port = STR(DEFAULT_GIT_PORT);
497 char *ep;
4c505f71
PA
498 struct hostent *he;
499 struct sockaddr_in sa;
500 char **ap;
501 unsigned int nport;
ba505322 502 int cnt;
4c505f71 503
72a534da 504 get_host_and_port(&host, &port);
4c505f71 505
7841ce79
MT
506 if (flags & CONNECT_VERBOSE)
507 fprintf(stderr, "Looking up %s ... ", host);
508
4c505f71
PA
509 he = gethostbyname(host);
510 if (!he)
511 die("Unable to look up %s (%s)", host, hstrerror(h_errno));
512 nport = strtoul(port, &ep, 10);
513 if ( ep == port || *ep ) {
514 /* Not numeric */
515 struct servent *se = getservbyname(port,"tcp");
516 if ( !se )
d7530708 517 die("Unknown port %s", port);
4c505f71
PA
518 nport = se->s_port;
519 }
520
7841ce79
MT
521 if (flags & CONNECT_VERBOSE)
522 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
523
ba505322 524 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
4c505f71
PA
525 memset(&sa, 0, sizeof sa);
526 sa.sin_family = he->h_addrtype;
6573faff 527 sa.sin_port = htons(nport);
c6164218 528 memcpy(&sa.sin_addr, *ap, he->h_length);
4c505f71 529
7203a2d1
EFL
530 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
531 if ((sockfd < 0) ||
532 connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
533 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
ba505322
AR
534 host,
535 cnt,
536 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
7203a2d1
EFL
537 strerror(errno));
538 if (0 <= sockfd)
539 close(sockfd);
4c505f71
PA
540 sockfd = -1;
541 continue;
542 }
ba505322
AR
543 if (flags & CONNECT_VERBOSE)
544 fprintf(stderr, "%s ",
545 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
4c505f71
PA
546 break;
547 }
548
549 if (sockfd < 0)
7203a2d1 550 die("unable to connect to %s:\n%s", host, error_message.buf);
4c505f71 551
e47a8583
EW
552 enable_keepalive(sockfd);
553
7841ce79
MT
554 if (flags & CONNECT_VERBOSE)
555 fprintf(stderr, "done.\n");
556
5ad312be
JL
557 return sockfd;
558}
559
560#endif /* NO_IPV6 */
561
562
7841ce79 563static void git_tcp_connect(int fd[2], char *host, int flags)
5ad312be 564{
7841ce79 565 int sockfd = git_tcp_connect_sock(host, flags);
5ad312be 566
4c505f71 567 fd[0] = sockfd;
ec587fde 568 fd[1] = dup(sockfd);
4c505f71
PA
569}
570
4c505f71 571
96f1e58f 572static char *git_proxy_command;
f8014776 573
ef90d6d4
JS
574static int git_proxy_command_options(const char *var, const char *value,
575 void *cb)
f8014776 576{
e814bc4d 577 if (!strcmp(var, "core.gitproxy")) {
c3df8568
YH
578 const char *for_pos;
579 int matchlen = -1;
580 int hostlen;
15112c95
EFL
581 const char *rhost_name = cb;
582 int rhost_len = strlen(rhost_name);
c3df8568 583
e814bc4d 584 if (git_proxy_command)
f8014776 585 return 0;
c64b9ad0
JH
586 if (!value)
587 return config_error_nonbool(var);
e814bc4d
JH
588 /* [core]
589 * ;# matches www.kernel.org as well
590 * gitproxy = netcatter-1 for kernel.org
591 * gitproxy = netcatter-2 for sample.xz
592 * gitproxy = netcatter-default
593 */
c3df8568 594 for_pos = strstr(value, " for ");
e814bc4d
JH
595 if (!for_pos)
596 /* matches everybody */
597 matchlen = strlen(value);
598 else {
599 hostlen = strlen(for_pos + 5);
600 if (rhost_len < hostlen)
601 matchlen = -1;
602 else if (!strncmp(for_pos + 5,
603 rhost_name + rhost_len - hostlen,
604 hostlen) &&
605 ((rhost_len == hostlen) ||
606 rhost_name[rhost_len - hostlen -1] == '.'))
607 matchlen = for_pos - value;
608 else
609 matchlen = -1;
610 }
611 if (0 <= matchlen) {
612 /* core.gitproxy = none for kernel.org */
a6080a0a 613 if (matchlen == 4 &&
e814bc4d
JH
614 !memcmp(value, "none", 4))
615 matchlen = 0;
182af834 616 git_proxy_command = xmemdupz(value, matchlen);
f8014776 617 }
e814bc4d 618 return 0;
f8014776
PC
619 }
620
ef90d6d4 621 return git_default_config(var, value, cb);
f8014776
PC
622}
623
e814bc4d 624static int git_use_proxy(const char *host)
f8014776
PC
625{
626 git_proxy_command = getenv("GIT_PROXY_COMMAND");
15112c95 627 git_config(git_proxy_command_options, (void*)host);
e814bc4d 628 return (git_proxy_command && *git_proxy_command);
f8014776
PC
629}
630
5cbf8246 631static struct child_process *git_proxy_connect(int fd[2], char *host)
f8014776 632{
554fe20d 633 const char *port = STR(DEFAULT_GIT_PORT);
5cbf8246 634 struct child_process *proxy;
f8014776 635
72a534da 636 get_host_and_port(&host, &port);
f8014776 637
3be4cf09
JK
638 if (looks_like_command_line_option(host))
639 die("strange hostname '%s' blocked", host);
640 if (looks_like_command_line_option(port))
641 die("strange port '%s' blocked", port);
642
483bbd4e
RS
643 proxy = xmalloc(sizeof(*proxy));
644 child_process_init(proxy);
1823bea1
JK
645 argv_array_push(&proxy->args, git_proxy_command);
646 argv_array_push(&proxy->args, host);
647 argv_array_push(&proxy->args, port);
5cbf8246
JK
648 proxy->in = -1;
649 proxy->out = -1;
650 if (start_command(proxy))
1823bea1 651 die("cannot start proxy %s", git_proxy_command);
5cbf8246
JK
652 fd[0] = proxy->out; /* read from proxy stdout */
653 fd[1] = proxy->in; /* write to proxy stdin */
654 return proxy;
f8014776
PC
655}
656
86ceb337 657static char *get_port(char *host)
2e776665
LT
658{
659 char *end;
86ceb337
TB
660 char *p = strchr(host, ':');
661
2e776665 662 if (p) {
8f148253
RS
663 long port = strtol(p + 1, &end, 10);
664 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
86ceb337
TB
665 *p = '\0';
666 return p+1;
2e776665
LT
667 }
668 }
669
670 return NULL;
671}
672
f7192598 673/*
cabc3c12
JS
674 * Extract protocol and relevant parts from the specified connection URL.
675 * The caller must free() the returned strings.
f7192598 676 */
cabc3c12 677static enum protocol parse_connect_url(const char *url_orig, char **ret_host,
83b05875 678 char **ret_path)
f7192598 679{
9d2e9420 680 char *url;
8e76bf3f 681 char *host, *path;
356bece0 682 char *end;
c59ab2e5 683 int separator = '/';
faea9ccb 684 enum protocol protocol = PROTO_LOCAL;
f0b7367c 685
9d2e9420
JK
686 if (is_url(url_orig))
687 url = url_decode(url_orig);
688 else
689 url = xstrdup(url_orig);
690
faea9ccb 691 host = strstr(url, "://");
eeefa7c9 692 if (host) {
faea9ccb
AE
693 *host = '\0';
694 protocol = get_protocol(url);
695 host += 3;
356bece0 696 } else {
f7192598 697 host = url;
c59ab2e5
TB
698 if (!url_is_local_not_ssh(url)) {
699 protocol = PROTO_SSH;
700 separator = ':';
701 }
356bece0
YH
702 }
703
9aa5053d 704 /*
83b05875
TB
705 * Don't do destructive transforms as protocol code does
706 * '[]' unwrapping in get_host_and_port()
9aa5053d 707 */
86ceb337 708 end = host_end(&host, 0);
356bece0 709
c59ab2e5 710 if (protocol == PROTO_LOCAL)
72a4f4b6 711 path = end;
c59ab2e5
TB
712 else if (protocol == PROTO_FILE && has_dos_drive_prefix(end))
713 path = end; /* "file://$(pwd)" may be "file://C:/projects/repo" */
714 else
715 path = strchr(end, separator);
2386d658 716
faea9ccb
AE
717 if (!path || !*path)
718 die("No path specified. See 'man git-pull' for valid url syntax");
719
720 /*
721 * null-terminate hostname and point path to ~ for URL's like this:
722 * ssh://host.xz/~user/repo
723 */
c59ab2e5
TB
724
725 end = path; /* Need to \0 terminate host here */
726 if (separator == ':')
727 path++; /* path starts after ':' */
728 if (protocol == PROTO_GIT || protocol == PROTO_SSH) {
faea9ccb
AE
729 if (path[1] == '~')
730 path++;
faea9ccb
AE
731 }
732
c59ab2e5
TB
733 path = xstrdup(path);
734 *end = '\0';
735
cabc3c12 736 *ret_host = xstrdup(host);
c59ab2e5 737 *ret_path = path;
cabc3c12
JS
738 free(url);
739 return protocol;
740}
741
d3180279 742static struct child_process no_fork = CHILD_PROCESS_INIT;
cabc3c12 743
3c8ede3f
NTND
744static const char *get_ssh_command(void)
745{
746 const char *ssh;
747
748 if ((ssh = getenv("GIT_SSH_COMMAND")))
749 return ssh;
750
751 if (!git_config_get_string_const("core.sshcommand", &ssh))
752 return ssh;
753
754 return NULL;
755}
756
486c8e8c 757static int override_ssh_variant(int *port_option, int *needs_batch)
e2824e47 758{
486c8e8c
JH
759 char *variant;
760
761 variant = xstrdup_or_null(getenv("GIT_SSH_VARIANT"));
762 if (!variant &&
763 git_config_get_string("ssh.variant", &variant))
764 return 0;
765
766 if (!strcmp(variant, "plink") || !strcmp(variant, "putty")) {
767 *port_option = 'P';
768 *needs_batch = 0;
769 } else if (!strcmp(variant, "tortoiseplink")) {
770 *port_option = 'P';
771 *needs_batch = 1;
772 } else {
773 *port_option = 'p';
774 *needs_batch = 0;
775 }
776 free(variant);
777 return 1;
778}
779
780static void handle_ssh_variant(const char *ssh_command, int is_cmdline,
781 int *port_option, int *needs_batch)
782{
783 const char *variant;
e2824e47
JS
784 char *p = NULL;
785
486c8e8c
JH
786 if (override_ssh_variant(port_option, needs_batch))
787 return;
788
789 if (!is_cmdline) {
e2824e47
JS
790 p = xstrdup(ssh_command);
791 variant = basename(p);
792 } else {
793 const char **ssh_argv;
794
795 p = xstrdup(ssh_command);
22e5ae5c 796 if (split_cmdline(p, &ssh_argv) > 0) {
e2824e47
JS
797 variant = basename((char *)ssh_argv[0]);
798 /*
799 * At this point, variant points into the buffer
800 * referenced by p, hence we do not need ssh_argv
801 * any longer.
802 */
803 free(ssh_argv);
5d2993b6
JK
804 } else {
805 free(p);
486c8e8c 806 return;
5d2993b6 807 }
e2824e47
JS
808 }
809
810 if (!strcasecmp(variant, "plink") ||
486c8e8c 811 !strcasecmp(variant, "plink.exe"))
e2824e47
JS
812 *port_option = 'P';
813 else if (!strcasecmp(variant, "tortoiseplink") ||
814 !strcasecmp(variant, "tortoiseplink.exe")) {
815 *port_option = 'P';
816 *needs_batch = 1;
817 }
818 free(p);
e2824e47
JS
819}
820
cabc3c12
JS
821/*
822 * This returns a dummy child_process if the transport protocol does not
823 * need fork(2), or a struct child_process object if it does. Once done,
824 * finish the connection with finish_connect() with the value returned from
825 * this function (it is safe to call finish_connect() with NULL to support
826 * the former case).
827 *
828 * If it returns, the connect is successful; it just dies on errors (this
829 * will hopefully be changed in a libification effort, to return NULL when
830 * the connection failed).
831 */
832struct child_process *git_connect(int fd[2], const char *url,
833 const char *prog, int flags)
834{
a2036d7e 835 char *hostandport, *path;
cabc3c12
JS
836 struct child_process *conn = &no_fork;
837 enum protocol protocol;
cabc3c12
JS
838
839 /* Without this we cannot rely on waitpid() to tell
840 * what happened to our children.
2e776665 841 */
cabc3c12 842 signal(SIGCHLD, SIG_DFL);
2e776665 843
a2036d7e 844 protocol = parse_connect_url(url, &hostandport, &path);
3f55ccab 845 if ((flags & CONNECT_DIAG_URL) && (protocol != PROTO_SSH)) {
5610b7c0
TB
846 printf("Diag: url=%s\n", url ? url : "NULL");
847 printf("Diag: protocol=%s\n", prot_name(protocol));
a2036d7e 848 printf("Diag: hostandport=%s\n", hostandport ? hostandport : "NULL");
5610b7c0 849 printf("Diag: path=%s\n", path ? path : "NULL");
a2036d7e
TB
850 conn = NULL;
851 } else if (protocol == PROTO_GIT) {
94bc83c5
JK
852 /*
853 * Set up virtual host information based on where we will
854 * connect, unless the user has overridden us in
855 * the environment.
856 */
857 char *target_host = getenv("GIT_OVERRIDE_VIRTUAL_HOST");
858 if (target_host)
859 target_host = xstrdup(target_host);
860 else
861 target_host = xstrdup(hostandport);
862
a5adaced
JK
863 transport_check_allowed("git");
864
5ad312be
JL
865 /* These underlying connection commands die() if they
866 * cannot connect.
867 */
a2036d7e
TB
868 if (git_use_proxy(hostandport))
869 conn = git_proxy_connect(fd, hostandport);
da2a95b2 870 else
a2036d7e 871 git_tcp_connect(fd, hostandport, flags);
5ad312be
JL
872 /*
873 * Separate original protocol components prog and path
73bb33a9
SP
874 * from extended host header with a NUL byte.
875 *
876 * Note: Do not add any other headers here! Doing so
877 * will cause older git-daemon servers to crash.
5ad312be 878 */
81c634e9 879 packet_write_fmt(fd[1],
5ad312be
JL
880 "%s %s%chost=%s%c",
881 prog, path, 0,
882 target_host, 0);
883 free(target_host);
a2036d7e 884 } else {
f1399291
RS
885 struct strbuf cmd = STRBUF_INIT;
886
483bbd4e
RS
887 conn = xmalloc(sizeof(*conn));
888 child_process_init(conn);
a2036d7e 889
aeeb2d49
JK
890 if (looks_like_command_line_option(path))
891 die("strange pathname '%s' blocked", path);
892
a2036d7e
TB
893 strbuf_addstr(&cmd, prog);
894 strbuf_addch(&cmd, ' ');
895 sq_quote_buf(&cmd, path);
896
aab40438
JK
897 /* remove repo-local variables from the environment */
898 conn->env = local_repo_env;
a48b409f 899 conn->use_shell = 1;
a2036d7e 900 conn->in = conn->out = -1;
a2036d7e 901 if (protocol == PROTO_SSH) {
39942766 902 const char *ssh;
6a4f3a9e
JH
903 int needs_batch = 0;
904 int port_option = 'p';
a2036d7e
TB
905 char *ssh_host = hostandport;
906 const char *port = NULL;
a5adaced 907 transport_check_allowed("ssh");
a2036d7e 908 get_host_and_port(&ssh_host, &port);
a2036d7e 909
86ceb337
TB
910 if (!port)
911 port = get_port(ssh_host);
42da4840 912
3f55ccab
TB
913 if (flags & CONNECT_DIAG_URL) {
914 printf("Diag: url=%s\n", url ? url : "NULL");
915 printf("Diag: protocol=%s\n", prot_name(protocol));
916 printf("Diag: userandhost=%s\n", ssh_host ? ssh_host : "NULL");
917 printf("Diag: port=%s\n", port ? port : "NONE");
918 printf("Diag: path=%s\n", path ? path : "NULL");
a2036d7e 919
3f55ccab
TB
920 free(hostandport);
921 free(path);
04f20c04 922 free(conn);
f1399291 923 strbuf_release(&cmd);
3f55ccab 924 return NULL;
37ee646e 925 }
926
2491f77b 927 if (looks_like_command_line_option(ssh_host))
820d7650
JH
928 die("strange hostname '%s' blocked", ssh_host);
929
3c8ede3f 930 ssh = get_ssh_command();
e2824e47
JS
931 if (ssh)
932 handle_ssh_variant(ssh, 1, &port_option,
933 &needs_batch);
934 else {
a48b409f
JK
935 /*
936 * GIT_SSH is the no-shell version of
937 * GIT_SSH_COMMAND (and must remain so for
938 * historical compatibility).
939 */
940 conn->use_shell = 0;
941
37ee646e 942 ssh = getenv("GIT_SSH");
943 if (!ssh)
944 ssh = "ssh";
e2824e47
JS
945 else
946 handle_ssh_variant(ssh, 0,
947 &port_option,
948 &needs_batch);
37ee646e 949 }
950
951 argv_array_push(&conn->args, ssh);
c915f11e
EW
952 if (flags & CONNECT_IPV4)
953 argv_array_push(&conn->args, "-4");
954 else if (flags & CONNECT_IPV6)
955 argv_array_push(&conn->args, "-6");
6a4f3a9e 956 if (needs_batch)
37ee646e 957 argv_array_push(&conn->args, "-batch");
958 if (port) {
6a4f3a9e
JH
959 argv_array_pushf(&conn->args,
960 "-%c", port_option);
37ee646e 961 argv_array_push(&conn->args, port);
a2036d7e 962 }
37ee646e 963 argv_array_push(&conn->args, ssh_host);
c049b61d 964 } else {
a5adaced 965 transport_check_allowed("file");
4852f723 966 }
1823bea1 967 argv_array_push(&conn->args, cmd.buf);
f364cb88 968
a2036d7e
TB
969 if (start_command(conn))
970 die("unable to fork");
f364cb88 971
a2036d7e
TB
972 fd[0] = conn->out; /* read from child's stdout */
973 fd[1] = conn->in; /* write to child's stdin */
974 strbuf_release(&cmd);
975 }
976 free(hostandport);
cabc3c12 977 free(path);
98158e9c 978 return conn;
f7192598
LT
979}
980
7ffe853b
JK
981int git_connection_is_socket(struct child_process *conn)
982{
983 return conn == &no_fork;
984}
985
98158e9c 986int finish_connect(struct child_process *conn)
f7192598 987{
f364cb88 988 int code;
7ffe853b 989 if (!conn || git_connection_is_socket(conn))
f42a5c4e
FBH
990 return 0;
991
f364cb88 992 code = finish_command(conn);
98158e9c 993 free(conn);
f364cb88 994 return code;
f7192598 995}