remove the impression of unexpectedness when access is denied
[git/mingw/j6t.git] / connect.c
blobfe6e9214b29cc0d53accabcd3d88be53ed0b0129
1 #include "git-compat-util.h"
2 #include "cache.h"
3 #include "pkt-line.h"
4 #include "quote.h"
5 #include "refs.h"
6 #include "run-command.h"
7 #include "remote.h"
8 #include "url.h"
10 static char *server_capabilities;
12 static int check_ref(const char *name, int len, unsigned int flags)
14 if (!flags)
15 return 1;
17 if (len < 5 || memcmp(name, "refs/", 5))
18 return 0;
20 /* Skip the "refs/" part */
21 name += 5;
22 len -= 5;
24 /* REF_NORMAL means that we don't want the magic fake tag refs */
25 if ((flags & REF_NORMAL) && check_ref_format(name) < 0)
26 return 0;
28 /* REF_HEADS means that we want regular branch heads */
29 if ((flags & REF_HEADS) && !memcmp(name, "heads/", 6))
30 return 1;
32 /* REF_TAGS means that we want tags */
33 if ((flags & REF_TAGS) && !memcmp(name, "tags/", 5))
34 return 1;
36 /* All type bits clear means that we are ok with anything */
37 return !(flags & ~REF_NORMAL);
40 int check_ref_type(const struct ref *ref, int flags)
42 return check_ref(ref->name, strlen(ref->name), flags);
45 static void add_extra_have(struct extra_have_objects *extra, unsigned char *sha1)
47 ALLOC_GROW(extra->array, extra->nr + 1, extra->alloc);
48 hashcpy(&(extra->array[extra->nr][0]), sha1);
49 extra->nr++;
52 static void die_initial_contact(int got_at_least_one_head)
54 if (got_at_least_one_head)
55 die("The remote end hung up upon initial contact");
56 else
57 die("Could not read from remote repository.\n\n"
58 "Please make sure you have the correct access rights\n"
59 "and the repository exists.");
63 * Read all the refs from the other end
65 struct ref **get_remote_heads(int in, struct ref **list,
66 int nr_match, char **match,
67 unsigned int flags,
68 struct extra_have_objects *extra_have)
70 int got_at_least_one_head = 0;
72 *list = NULL;
73 for (;;) {
74 struct ref *ref;
75 unsigned char old_sha1[20];
76 static char buffer[1000];
77 char *name;
78 int len, name_len;
80 len = packet_read(in, buffer, sizeof(buffer));
81 if (len < 0)
82 die_initial_contact(got_at_least_one_head);
84 if (!len)
85 break;
86 if (buffer[len-1] == '\n')
87 buffer[--len] = 0;
89 if (len > 4 && !prefixcmp(buffer, "ERR "))
90 die("remote error: %s", buffer + 4);
92 if (len < 42 || get_sha1_hex(buffer, old_sha1) || buffer[40] != ' ')
93 die("protocol error: expected sha/ref, got '%s'", buffer);
94 name = buffer + 41;
96 name_len = strlen(name);
97 if (len != name_len + 41) {
98 free(server_capabilities);
99 server_capabilities = xstrdup(name + name_len + 1);
102 if (extra_have &&
103 name_len == 5 && !memcmp(".have", name, 5)) {
104 add_extra_have(extra_have, old_sha1);
105 continue;
108 if (!check_ref(name, name_len, flags))
109 continue;
110 if (nr_match && !path_match(name, nr_match, match))
111 continue;
112 ref = alloc_ref(buffer + 41);
113 hashcpy(ref->old_sha1, old_sha1);
114 *list = ref;
115 list = &ref->next;
116 got_at_least_one_head = 1;
118 return list;
121 int server_supports(const char *feature)
123 return server_capabilities &&
124 strstr(server_capabilities, feature) != NULL;
127 int path_match(const char *path, int nr, char **match)
129 int i;
130 int pathlen = strlen(path);
132 for (i = 0; i < nr; i++) {
133 char *s = match[i];
134 int len = strlen(s);
136 if (!len || len > pathlen)
137 continue;
138 if (memcmp(path + pathlen - len, s, len))
139 continue;
140 if (pathlen > len && path[pathlen - len - 1] != '/')
141 continue;
142 *s = 0;
143 return (i + 1);
145 return 0;
148 enum protocol {
149 PROTO_LOCAL = 1,
150 PROTO_SSH,
151 PROTO_GIT
154 static enum protocol get_protocol(const char *name)
156 if (!strcmp(name, "ssh"))
157 return PROTO_SSH;
158 if (!strcmp(name, "git"))
159 return PROTO_GIT;
160 if (!strcmp(name, "git+ssh"))
161 return PROTO_SSH;
162 if (!strcmp(name, "ssh+git"))
163 return PROTO_SSH;
164 if (!strcmp(name, "file"))
165 return PROTO_LOCAL;
166 die("I don't handle protocol '%s'", name);
169 #define STR_(s) # s
170 #define STR(s) STR_(s)
172 static void get_host_and_port(char **host, const char **port)
174 char *colon, *end;
176 if (*host[0] == '[') {
177 end = strchr(*host + 1, ']');
178 if (end) {
179 *end = 0;
180 end++;
181 (*host)++;
182 } else
183 end = *host;
184 } else
185 end = *host;
186 colon = strchr(end, ':');
188 if (colon) {
189 *colon = 0;
190 *port = colon + 1;
194 #ifndef NO_IPV6
196 static const char *ai_name(const struct addrinfo *ai)
198 static char addr[NI_MAXHOST];
199 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
200 NI_NUMERICHOST) != 0)
201 strcpy(addr, "(unknown)");
203 return addr;
207 * Returns a connected socket() fd, or else die()s.
209 static int git_tcp_connect_sock(char *host, int flags)
211 struct strbuf error_message = STRBUF_INIT;
212 int sockfd = -1;
213 const char *port = STR(DEFAULT_GIT_PORT);
214 struct addrinfo hints, *ai0, *ai;
215 int gai;
216 int cnt = 0;
218 get_host_and_port(&host, &port);
219 if (!*port)
220 port = "<none>";
222 memset(&hints, 0, sizeof(hints));
223 hints.ai_socktype = SOCK_STREAM;
224 hints.ai_protocol = IPPROTO_TCP;
226 if (flags & CONNECT_VERBOSE)
227 fprintf(stderr, "Looking up %s ... ", host);
229 gai = getaddrinfo(host, port, &hints, &ai);
230 if (gai)
231 die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
233 if (flags & CONNECT_VERBOSE)
234 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
236 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
237 sockfd = socket(ai->ai_family,
238 ai->ai_socktype, ai->ai_protocol);
239 if ((sockfd < 0) ||
240 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
241 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
242 host, cnt, ai_name(ai), strerror(errno));
243 if (0 <= sockfd)
244 close(sockfd);
245 sockfd = -1;
246 continue;
248 if (flags & CONNECT_VERBOSE)
249 fprintf(stderr, "%s ", ai_name(ai));
250 break;
253 freeaddrinfo(ai0);
255 if (sockfd < 0)
256 die("unable to connect to %s:\n%s", host, error_message.buf);
258 if (flags & CONNECT_VERBOSE)
259 fprintf(stderr, "done.\n");
261 strbuf_release(&error_message);
263 return sockfd;
266 #else /* NO_IPV6 */
269 * Returns a connected socket() fd, or else die()s.
271 static int git_tcp_connect_sock(char *host, int flags)
273 int sockfd = -1, saved_errno = 0;
274 const char *port = STR(DEFAULT_GIT_PORT);
275 char *ep;
276 struct hostent *he;
277 struct sockaddr_in sa;
278 char **ap;
279 unsigned int nport;
280 int cnt;
282 get_host_and_port(&host, &port);
284 if (flags & CONNECT_VERBOSE)
285 fprintf(stderr, "Looking up %s ... ", host);
287 he = gethostbyname(host);
288 if (!he)
289 die("Unable to look up %s (%s)", host, hstrerror(h_errno));
290 nport = strtoul(port, &ep, 10);
291 if ( ep == port || *ep ) {
292 /* Not numeric */
293 struct servent *se = getservbyname(port,"tcp");
294 if ( !se )
295 die("Unknown port %s", port);
296 nport = se->s_port;
299 if (flags & CONNECT_VERBOSE)
300 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
302 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
303 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
304 if (sockfd < 0) {
305 saved_errno = errno;
306 continue;
309 memset(&sa, 0, sizeof sa);
310 sa.sin_family = he->h_addrtype;
311 sa.sin_port = htons(nport);
312 memcpy(&sa.sin_addr, *ap, he->h_length);
314 if (connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
315 saved_errno = errno;
316 fprintf(stderr, "%s[%d: %s]: errno=%s\n",
317 host,
318 cnt,
319 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
320 strerror(saved_errno));
321 close(sockfd);
322 sockfd = -1;
323 continue;
325 if (flags & CONNECT_VERBOSE)
326 fprintf(stderr, "%s ",
327 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
328 break;
331 if (sockfd < 0)
332 die("unable to connect a socket (%s)", strerror(saved_errno));
334 if (flags & CONNECT_VERBOSE)
335 fprintf(stderr, "done.\n");
337 return sockfd;
340 #endif /* NO_IPV6 */
343 static void git_tcp_connect(int fd[2], char *host, int flags)
345 int sockfd = git_tcp_connect_sock(host, flags);
347 fd[0] = sockfd;
348 fd[1] = dup(sockfd);
352 static char *git_proxy_command;
354 static int git_proxy_command_options(const char *var, const char *value,
355 void *cb)
357 if (!strcmp(var, "core.gitproxy")) {
358 const char *for_pos;
359 int matchlen = -1;
360 int hostlen;
361 const char *rhost_name = cb;
362 int rhost_len = strlen(rhost_name);
364 if (git_proxy_command)
365 return 0;
366 if (!value)
367 return config_error_nonbool(var);
368 /* [core]
369 * ;# matches www.kernel.org as well
370 * gitproxy = netcatter-1 for kernel.org
371 * gitproxy = netcatter-2 for sample.xz
372 * gitproxy = netcatter-default
374 for_pos = strstr(value, " for ");
375 if (!for_pos)
376 /* matches everybody */
377 matchlen = strlen(value);
378 else {
379 hostlen = strlen(for_pos + 5);
380 if (rhost_len < hostlen)
381 matchlen = -1;
382 else if (!strncmp(for_pos + 5,
383 rhost_name + rhost_len - hostlen,
384 hostlen) &&
385 ((rhost_len == hostlen) ||
386 rhost_name[rhost_len - hostlen -1] == '.'))
387 matchlen = for_pos - value;
388 else
389 matchlen = -1;
391 if (0 <= matchlen) {
392 /* core.gitproxy = none for kernel.org */
393 if (matchlen == 4 &&
394 !memcmp(value, "none", 4))
395 matchlen = 0;
396 git_proxy_command = xmemdupz(value, matchlen);
398 return 0;
401 return git_default_config(var, value, cb);
404 static int git_use_proxy(const char *host)
406 git_proxy_command = getenv("GIT_PROXY_COMMAND");
407 git_config(git_proxy_command_options, (void*)host);
408 return (git_proxy_command && *git_proxy_command);
411 static struct child_process *git_proxy_connect(int fd[2], char *host)
413 const char *port = STR(DEFAULT_GIT_PORT);
414 const char **argv;
415 struct child_process *proxy;
417 get_host_and_port(&host, &port);
419 argv = xmalloc(sizeof(*argv) * 4);
420 argv[0] = git_proxy_command;
421 argv[1] = host;
422 argv[2] = port;
423 argv[3] = NULL;
424 proxy = xcalloc(1, sizeof(*proxy));
425 proxy->argv = argv;
426 proxy->in = -1;
427 proxy->out = -1;
428 if (start_command(proxy))
429 die("cannot start proxy %s", argv[0]);
430 fd[0] = proxy->out; /* read from proxy stdout */
431 fd[1] = proxy->in; /* write to proxy stdin */
432 return proxy;
435 #define MAX_CMD_LEN 1024
437 static char *get_port(char *host)
439 char *end;
440 char *p = strchr(host, ':');
442 if (p) {
443 long port = strtol(p + 1, &end, 10);
444 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
445 *p = '\0';
446 return p+1;
450 return NULL;
453 static struct child_process no_fork;
456 * This returns a dummy child_process if the transport protocol does not
457 * need fork(2), or a struct child_process object if it does. Once done,
458 * finish the connection with finish_connect() with the value returned from
459 * this function (it is safe to call finish_connect() with NULL to support
460 * the former case).
462 * If it returns, the connect is successful; it just dies on errors (this
463 * will hopefully be changed in a libification effort, to return NULL when
464 * the connection failed).
466 struct child_process *git_connect(int fd[2], const char *url_orig,
467 const char *prog, int flags)
469 char *url;
470 char *host, *path;
471 char *end;
472 int c;
473 struct child_process *conn = &no_fork;
474 enum protocol protocol = PROTO_LOCAL;
475 int free_path = 0;
476 char *port = NULL;
477 const char **arg;
478 struct strbuf cmd;
480 /* Without this we cannot rely on waitpid() to tell
481 * what happened to our children.
483 signal(SIGCHLD, SIG_DFL);
485 if (is_url(url_orig))
486 url = url_decode(url_orig);
487 else
488 url = xstrdup(url_orig);
490 host = strstr(url, "://");
491 if (host) {
492 *host = '\0';
493 protocol = get_protocol(url);
494 host += 3;
495 c = '/';
496 } else {
497 host = url;
498 c = ':';
502 * Don't do destructive transforms with git:// as that
503 * protocol code does '[]' unwrapping of its own.
505 if (host[0] == '[') {
506 end = strchr(host + 1, ']');
507 if (end) {
508 if (protocol != PROTO_GIT) {
509 *end = 0;
510 host++;
512 end++;
513 } else
514 end = host;
515 } else
516 end = host;
518 path = strchr(end, c);
519 if (path && !has_dos_drive_prefix(end)) {
520 if (c == ':') {
521 protocol = PROTO_SSH;
522 *path++ = '\0';
524 } else
525 path = end;
527 if (!path || !*path)
528 die("No path specified. See 'man git-pull' for valid url syntax");
531 * null-terminate hostname and point path to ~ for URL's like this:
532 * ssh://host.xz/~user/repo
534 if (protocol != PROTO_LOCAL && host != url) {
535 char *ptr = path;
536 if (path[1] == '~')
537 path++;
538 else {
539 path = xstrdup(ptr);
540 free_path = 1;
543 *ptr = '\0';
547 * Add support for ssh port: ssh://host.xy:<port>/...
549 if (protocol == PROTO_SSH && host != url)
550 port = get_port(host);
552 if (protocol == PROTO_GIT) {
553 /* These underlying connection commands die() if they
554 * cannot connect.
556 char *target_host = xstrdup(host);
557 if (git_use_proxy(host))
558 conn = git_proxy_connect(fd, host);
559 else
560 git_tcp_connect(fd, host, flags);
562 * Separate original protocol components prog and path
563 * from extended host header with a NUL byte.
565 * Note: Do not add any other headers here! Doing so
566 * will cause older git-daemon servers to crash.
568 packet_write(fd[1],
569 "%s %s%chost=%s%c",
570 prog, path, 0,
571 target_host, 0);
572 free(target_host);
573 free(url);
574 if (free_path)
575 free(path);
576 return conn;
579 conn = xcalloc(1, sizeof(*conn));
581 strbuf_init(&cmd, MAX_CMD_LEN);
582 strbuf_addstr(&cmd, prog);
583 strbuf_addch(&cmd, ' ');
584 sq_quote_buf(&cmd, path);
585 if (cmd.len >= MAX_CMD_LEN)
586 die("command line too long");
588 conn->in = conn->out = -1;
589 conn->argv = arg = xcalloc(7, sizeof(*arg));
590 if (protocol == PROTO_SSH) {
591 const char *ssh = getenv("GIT_SSH");
592 int putty = ssh && strcasestr(ssh, "plink");
593 if (!ssh) ssh = "ssh";
595 *arg++ = ssh;
596 if (putty && !strcasestr(ssh, "tortoiseplink"))
597 *arg++ = "-batch";
598 if (port) {
599 /* P is for PuTTY, p is for OpenSSH */
600 *arg++ = putty ? "-P" : "-p";
601 *arg++ = port;
603 *arg++ = host;
605 else {
606 /* remove repo-local variables from the environment */
607 conn->env = local_repo_env;
608 conn->use_shell = 1;
610 *arg++ = cmd.buf;
611 *arg = NULL;
613 if (start_command(conn))
614 die("unable to fork");
616 fd[0] = conn->out; /* read from child's stdout */
617 fd[1] = conn->in; /* write to child's stdin */
618 strbuf_release(&cmd);
619 free(url);
620 if (free_path)
621 free(path);
622 return conn;
625 int git_connection_is_socket(struct child_process *conn)
627 return conn == &no_fork;
630 int finish_connect(struct child_process *conn)
632 int code;
633 if (!conn || git_connection_is_socket(conn))
634 return 0;
636 code = finish_command(conn);
637 free(conn->argv);
638 free(conn);
639 return code;
642 char *git_getpass(const char *prompt)
644 const char *askpass;
645 struct child_process pass;
646 const char *args[3];
647 static struct strbuf buffer = STRBUF_INIT;
649 askpass = getenv("GIT_ASKPASS");
650 if (!askpass)
651 askpass = askpass_program;
652 if (!askpass)
653 askpass = getenv("SSH_ASKPASS");
654 if (!askpass || !(*askpass)) {
655 char *result = getpass(prompt);
656 if (!result)
657 die_errno("Could not read password");
658 return result;
661 args[0] = askpass;
662 args[1] = prompt;
663 args[2] = NULL;
665 memset(&pass, 0, sizeof(pass));
666 pass.argv = args;
667 pass.out = -1;
669 if (start_command(&pass))
670 exit(1);
672 strbuf_reset(&buffer);
673 if (strbuf_read(&buffer, pass.out, 20) < 0)
674 die("failed to read password from %s\n", askpass);
676 close(pass.out);
678 if (finish_command(&pass))
679 exit(1);
681 strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));
683 return buffer.buf;