Merge branch 'ew/keepalive' into maint
[alt-git.git] / connect.c
blobd0f59ef0deebff3967c0b054f2f998dfb3ab5b00
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_refname_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++;
53 * Read all the refs from the other end
55 struct ref **get_remote_heads(int in, struct ref **list,
56 int nr_match, char **match,
57 unsigned int flags,
58 struct extra_have_objects *extra_have)
60 *list = NULL;
61 for (;;) {
62 struct ref *ref;
63 unsigned char old_sha1[20];
64 static char buffer[1000];
65 char *name;
66 int len, name_len;
68 len = packet_read_line(in, buffer, sizeof(buffer));
69 if (!len)
70 break;
71 if (buffer[len-1] == '\n')
72 buffer[--len] = 0;
74 if (len > 4 && !prefixcmp(buffer, "ERR "))
75 die("remote error: %s", buffer + 4);
77 if (len < 42 || get_sha1_hex(buffer, old_sha1) || buffer[40] != ' ')
78 die("protocol error: expected sha/ref, got '%s'", buffer);
79 name = buffer + 41;
81 name_len = strlen(name);
82 if (len != name_len + 41) {
83 free(server_capabilities);
84 server_capabilities = xstrdup(name + name_len + 1);
87 if (extra_have &&
88 name_len == 5 && !memcmp(".have", name, 5)) {
89 add_extra_have(extra_have, old_sha1);
90 continue;
93 if (!check_ref(name, name_len, flags))
94 continue;
95 if (nr_match && !path_match(name, nr_match, match))
96 continue;
97 ref = alloc_ref(buffer + 41);
98 hashcpy(ref->old_sha1, old_sha1);
99 *list = ref;
100 list = &ref->next;
102 return list;
105 int server_supports(const char *feature)
107 return server_capabilities &&
108 strstr(server_capabilities, feature) != NULL;
111 int path_match(const char *path, int nr, char **match)
113 int i;
114 int pathlen = strlen(path);
116 for (i = 0; i < nr; i++) {
117 char *s = match[i];
118 int len = strlen(s);
120 if (!len || len > pathlen)
121 continue;
122 if (memcmp(path + pathlen - len, s, len))
123 continue;
124 if (pathlen > len && path[pathlen - len - 1] != '/')
125 continue;
126 *s = 0;
127 return (i + 1);
129 return 0;
132 enum protocol {
133 PROTO_LOCAL = 1,
134 PROTO_SSH,
135 PROTO_GIT
138 static enum protocol get_protocol(const char *name)
140 if (!strcmp(name, "ssh"))
141 return PROTO_SSH;
142 if (!strcmp(name, "git"))
143 return PROTO_GIT;
144 if (!strcmp(name, "git+ssh"))
145 return PROTO_SSH;
146 if (!strcmp(name, "ssh+git"))
147 return PROTO_SSH;
148 if (!strcmp(name, "file"))
149 return PROTO_LOCAL;
150 die("I don't handle protocol '%s'", name);
153 #define STR_(s) # s
154 #define STR(s) STR_(s)
156 static void get_host_and_port(char **host, const char **port)
158 char *colon, *end;
160 if (*host[0] == '[') {
161 end = strchr(*host + 1, ']');
162 if (end) {
163 *end = 0;
164 end++;
165 (*host)++;
166 } else
167 end = *host;
168 } else
169 end = *host;
170 colon = strchr(end, ':');
172 if (colon) {
173 *colon = 0;
174 *port = colon + 1;
178 static void enable_keepalive(int sockfd)
180 int ka = 1;
182 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
183 fprintf(stderr, "unable to set SO_KEEPALIVE on socket: %s\n",
184 strerror(errno));
187 #ifndef NO_IPV6
189 static const char *ai_name(const struct addrinfo *ai)
191 static char addr[NI_MAXHOST];
192 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
193 NI_NUMERICHOST) != 0)
194 strcpy(addr, "(unknown)");
196 return addr;
200 * Returns a connected socket() fd, or else die()s.
202 static int git_tcp_connect_sock(char *host, int flags)
204 struct strbuf error_message = STRBUF_INIT;
205 int sockfd = -1;
206 const char *port = STR(DEFAULT_GIT_PORT);
207 struct addrinfo hints, *ai0, *ai;
208 int gai;
209 int cnt = 0;
211 get_host_and_port(&host, &port);
212 if (!*port)
213 port = "<none>";
215 memset(&hints, 0, sizeof(hints));
216 hints.ai_socktype = SOCK_STREAM;
217 hints.ai_protocol = IPPROTO_TCP;
219 if (flags & CONNECT_VERBOSE)
220 fprintf(stderr, "Looking up %s ... ", host);
222 gai = getaddrinfo(host, port, &hints, &ai);
223 if (gai)
224 die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
226 if (flags & CONNECT_VERBOSE)
227 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
229 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
230 sockfd = socket(ai->ai_family,
231 ai->ai_socktype, ai->ai_protocol);
232 if ((sockfd < 0) ||
233 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
234 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
235 host, cnt, ai_name(ai), strerror(errno));
236 if (0 <= sockfd)
237 close(sockfd);
238 sockfd = -1;
239 continue;
241 if (flags & CONNECT_VERBOSE)
242 fprintf(stderr, "%s ", ai_name(ai));
243 break;
246 freeaddrinfo(ai0);
248 if (sockfd < 0)
249 die("unable to connect to %s:\n%s", host, error_message.buf);
251 enable_keepalive(sockfd);
253 if (flags & CONNECT_VERBOSE)
254 fprintf(stderr, "done.\n");
256 strbuf_release(&error_message);
258 return sockfd;
261 #else /* NO_IPV6 */
264 * Returns a connected socket() fd, or else die()s.
266 static int git_tcp_connect_sock(char *host, int flags)
268 struct strbuf error_message = STRBUF_INIT;
269 int sockfd = -1;
270 const char *port = STR(DEFAULT_GIT_PORT);
271 char *ep;
272 struct hostent *he;
273 struct sockaddr_in sa;
274 char **ap;
275 unsigned int nport;
276 int cnt;
278 get_host_and_port(&host, &port);
280 if (flags & CONNECT_VERBOSE)
281 fprintf(stderr, "Looking up %s ... ", host);
283 he = gethostbyname(host);
284 if (!he)
285 die("Unable to look up %s (%s)", host, hstrerror(h_errno));
286 nport = strtoul(port, &ep, 10);
287 if ( ep == port || *ep ) {
288 /* Not numeric */
289 struct servent *se = getservbyname(port,"tcp");
290 if ( !se )
291 die("Unknown port %s", port);
292 nport = se->s_port;
295 if (flags & CONNECT_VERBOSE)
296 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
298 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
299 memset(&sa, 0, sizeof sa);
300 sa.sin_family = he->h_addrtype;
301 sa.sin_port = htons(nport);
302 memcpy(&sa.sin_addr, *ap, he->h_length);
304 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
305 if ((sockfd < 0) ||
306 connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
307 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
308 host,
309 cnt,
310 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
311 strerror(errno));
312 if (0 <= sockfd)
313 close(sockfd);
314 sockfd = -1;
315 continue;
317 if (flags & CONNECT_VERBOSE)
318 fprintf(stderr, "%s ",
319 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
320 break;
323 if (sockfd < 0)
324 die("unable to connect to %s:\n%s", host, error_message.buf);
326 enable_keepalive(sockfd);
328 if (flags & CONNECT_VERBOSE)
329 fprintf(stderr, "done.\n");
331 return sockfd;
334 #endif /* NO_IPV6 */
337 static void git_tcp_connect(int fd[2], char *host, int flags)
339 int sockfd = git_tcp_connect_sock(host, flags);
341 fd[0] = sockfd;
342 fd[1] = dup(sockfd);
346 static char *git_proxy_command;
348 static int git_proxy_command_options(const char *var, const char *value,
349 void *cb)
351 if (!strcmp(var, "core.gitproxy")) {
352 const char *for_pos;
353 int matchlen = -1;
354 int hostlen;
355 const char *rhost_name = cb;
356 int rhost_len = strlen(rhost_name);
358 if (git_proxy_command)
359 return 0;
360 if (!value)
361 return config_error_nonbool(var);
362 /* [core]
363 * ;# matches www.kernel.org as well
364 * gitproxy = netcatter-1 for kernel.org
365 * gitproxy = netcatter-2 for sample.xz
366 * gitproxy = netcatter-default
368 for_pos = strstr(value, " for ");
369 if (!for_pos)
370 /* matches everybody */
371 matchlen = strlen(value);
372 else {
373 hostlen = strlen(for_pos + 5);
374 if (rhost_len < hostlen)
375 matchlen = -1;
376 else if (!strncmp(for_pos + 5,
377 rhost_name + rhost_len - hostlen,
378 hostlen) &&
379 ((rhost_len == hostlen) ||
380 rhost_name[rhost_len - hostlen -1] == '.'))
381 matchlen = for_pos - value;
382 else
383 matchlen = -1;
385 if (0 <= matchlen) {
386 /* core.gitproxy = none for kernel.org */
387 if (matchlen == 4 &&
388 !memcmp(value, "none", 4))
389 matchlen = 0;
390 git_proxy_command = xmemdupz(value, matchlen);
392 return 0;
395 return git_default_config(var, value, cb);
398 static int git_use_proxy(const char *host)
400 git_proxy_command = getenv("GIT_PROXY_COMMAND");
401 git_config(git_proxy_command_options, (void*)host);
402 return (git_proxy_command && *git_proxy_command);
405 static struct child_process *git_proxy_connect(int fd[2], char *host)
407 const char *port = STR(DEFAULT_GIT_PORT);
408 const char **argv;
409 struct child_process *proxy;
411 get_host_and_port(&host, &port);
413 argv = xmalloc(sizeof(*argv) * 4);
414 argv[0] = git_proxy_command;
415 argv[1] = host;
416 argv[2] = port;
417 argv[3] = NULL;
418 proxy = xcalloc(1, sizeof(*proxy));
419 proxy->argv = argv;
420 proxy->in = -1;
421 proxy->out = -1;
422 if (start_command(proxy))
423 die("cannot start proxy %s", argv[0]);
424 fd[0] = proxy->out; /* read from proxy stdout */
425 fd[1] = proxy->in; /* write to proxy stdin */
426 return proxy;
429 #define MAX_CMD_LEN 1024
431 static char *get_port(char *host)
433 char *end;
434 char *p = strchr(host, ':');
436 if (p) {
437 long port = strtol(p + 1, &end, 10);
438 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
439 *p = '\0';
440 return p+1;
444 return NULL;
447 static struct child_process no_fork;
450 * This returns a dummy child_process if the transport protocol does not
451 * need fork(2), or a struct child_process object if it does. Once done,
452 * finish the connection with finish_connect() with the value returned from
453 * this function (it is safe to call finish_connect() with NULL to support
454 * the former case).
456 * If it returns, the connect is successful; it just dies on errors (this
457 * will hopefully be changed in a libification effort, to return NULL when
458 * the connection failed).
460 struct child_process *git_connect(int fd[2], const char *url_orig,
461 const char *prog, int flags)
463 char *url;
464 char *host, *path;
465 char *end;
466 int c;
467 struct child_process *conn = &no_fork;
468 enum protocol protocol = PROTO_LOCAL;
469 int free_path = 0;
470 char *port = NULL;
471 const char **arg;
472 struct strbuf cmd;
474 /* Without this we cannot rely on waitpid() to tell
475 * what happened to our children.
477 signal(SIGCHLD, SIG_DFL);
479 if (is_url(url_orig))
480 url = url_decode(url_orig);
481 else
482 url = xstrdup(url_orig);
484 host = strstr(url, "://");
485 if (host) {
486 *host = '\0';
487 protocol = get_protocol(url);
488 host += 3;
489 c = '/';
490 } else {
491 host = url;
492 c = ':';
496 * Don't do destructive transforms with git:// as that
497 * protocol code does '[]' unwrapping of its own.
499 if (host[0] == '[') {
500 end = strchr(host + 1, ']');
501 if (end) {
502 if (protocol != PROTO_GIT) {
503 *end = 0;
504 host++;
506 end++;
507 } else
508 end = host;
509 } else
510 end = host;
512 path = strchr(end, c);
513 if (path && !has_dos_drive_prefix(end)) {
514 if (c == ':') {
515 protocol = PROTO_SSH;
516 *path++ = '\0';
518 } else
519 path = end;
521 if (!path || !*path)
522 die("No path specified. See 'man git-pull' for valid url syntax");
525 * null-terminate hostname and point path to ~ for URL's like this:
526 * ssh://host.xz/~user/repo
528 if (protocol != PROTO_LOCAL && host != url) {
529 char *ptr = path;
530 if (path[1] == '~')
531 path++;
532 else {
533 path = xstrdup(ptr);
534 free_path = 1;
537 *ptr = '\0';
541 * Add support for ssh port: ssh://host.xy:<port>/...
543 if (protocol == PROTO_SSH && host != url)
544 port = get_port(host);
546 if (protocol == PROTO_GIT) {
547 /* These underlying connection commands die() if they
548 * cannot connect.
550 char *target_host = xstrdup(host);
551 if (git_use_proxy(host))
552 conn = git_proxy_connect(fd, host);
553 else
554 git_tcp_connect(fd, host, flags);
556 * Separate original protocol components prog and path
557 * from extended host header with a NUL byte.
559 * Note: Do not add any other headers here! Doing so
560 * will cause older git-daemon servers to crash.
562 packet_write(fd[1],
563 "%s %s%chost=%s%c",
564 prog, path, 0,
565 target_host, 0);
566 free(target_host);
567 free(url);
568 if (free_path)
569 free(path);
570 return conn;
573 conn = xcalloc(1, sizeof(*conn));
575 strbuf_init(&cmd, MAX_CMD_LEN);
576 strbuf_addstr(&cmd, prog);
577 strbuf_addch(&cmd, ' ');
578 sq_quote_buf(&cmd, path);
579 if (cmd.len >= MAX_CMD_LEN)
580 die("command line too long");
582 conn->in = conn->out = -1;
583 conn->argv = arg = xcalloc(7, sizeof(*arg));
584 if (protocol == PROTO_SSH) {
585 const char *ssh = getenv("GIT_SSH");
586 int putty = ssh && strcasestr(ssh, "plink");
587 if (!ssh) ssh = "ssh";
589 *arg++ = ssh;
590 if (putty && !strcasestr(ssh, "tortoiseplink"))
591 *arg++ = "-batch";
592 if (port) {
593 /* P is for PuTTY, p is for OpenSSH */
594 *arg++ = putty ? "-P" : "-p";
595 *arg++ = port;
597 *arg++ = host;
599 else {
600 /* remove repo-local variables from the environment */
601 conn->env = local_repo_env;
602 conn->use_shell = 1;
604 *arg++ = cmd.buf;
605 *arg = NULL;
607 if (start_command(conn))
608 die("unable to fork");
610 fd[0] = conn->out; /* read from child's stdout */
611 fd[1] = conn->in; /* write to child's stdin */
612 strbuf_release(&cmd);
613 free(url);
614 if (free_path)
615 free(path);
616 return conn;
619 int git_connection_is_socket(struct child_process *conn)
621 return conn == &no_fork;
624 int finish_connect(struct child_process *conn)
626 int code;
627 if (!conn || git_connection_is_socket(conn))
628 return 0;
630 code = finish_command(conn);
631 free(conn->argv);
632 free(conn);
633 return code;
636 char *git_getpass(const char *prompt)
638 const char *askpass;
639 struct child_process pass;
640 const char *args[3];
641 static struct strbuf buffer = STRBUF_INIT;
643 askpass = getenv("GIT_ASKPASS");
644 if (!askpass)
645 askpass = askpass_program;
646 if (!askpass)
647 askpass = getenv("SSH_ASKPASS");
648 if (!askpass || !(*askpass)) {
649 char *result = getpass(prompt);
650 if (!result)
651 die_errno("Could not read password");
652 return result;
655 args[0] = askpass;
656 args[1] = prompt;
657 args[2] = NULL;
659 memset(&pass, 0, sizeof(pass));
660 pass.argv = args;
661 pass.out = -1;
663 if (start_command(&pass))
664 exit(1);
666 strbuf_reset(&buffer);
667 if (strbuf_read(&buffer, pass.out, 20) < 0)
668 die("failed to read password from %s\n", askpass);
670 close(pass.out);
672 if (finish_command(&pass))
673 exit(1);
675 strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));
677 return buffer.buf;