Documentation/rev-list-options.txt: fix mark-up
[git/gitweb.git] / connect.c
blob553a80c734dc2a4420ee8c0db4491edead53b947
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"
9 #include "string-list.h"
11 static char *server_capabilities;
12 static const char *parse_feature_value(const char *, const char *, int *);
14 static int check_ref(const char *name, int len, unsigned int flags)
16 if (!flags)
17 return 1;
19 if (len < 5 || memcmp(name, "refs/", 5))
20 return 0;
22 /* Skip the "refs/" part */
23 name += 5;
24 len -= 5;
26 /* REF_NORMAL means that we don't want the magic fake tag refs */
27 if ((flags & REF_NORMAL) && check_refname_format(name, 0))
28 return 0;
30 /* REF_HEADS means that we want regular branch heads */
31 if ((flags & REF_HEADS) && !memcmp(name, "heads/", 6))
32 return 1;
34 /* REF_TAGS means that we want tags */
35 if ((flags & REF_TAGS) && !memcmp(name, "tags/", 5))
36 return 1;
38 /* All type bits clear means that we are ok with anything */
39 return !(flags & ~REF_NORMAL);
42 int check_ref_type(const struct ref *ref, int flags)
44 return check_ref(ref->name, strlen(ref->name), flags);
47 static void add_extra_have(struct extra_have_objects *extra, unsigned char *sha1)
49 ALLOC_GROW(extra->array, extra->nr + 1, extra->alloc);
50 hashcpy(&(extra->array[extra->nr][0]), sha1);
51 extra->nr++;
54 static void die_initial_contact(int got_at_least_one_head)
56 if (got_at_least_one_head)
57 die("The remote end hung up upon initial contact");
58 else
59 die("Could not read from remote repository.\n\n"
60 "Please make sure you have the correct access rights\n"
61 "and the repository exists.");
64 static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
66 char *sym, *target;
67 struct string_list_item *item;
69 if (!len)
70 return; /* just "symref" */
71 /* e.g. "symref=HEAD:refs/heads/master" */
72 sym = xmalloc(len + 1);
73 memcpy(sym, val, len);
74 sym[len] = '\0';
75 target = strchr(sym, ':');
76 if (!target)
77 /* just "symref=something" */
78 goto reject;
79 *(target++) = '\0';
80 if (check_refname_format(sym, REFNAME_ALLOW_ONELEVEL) ||
81 check_refname_format(target, REFNAME_ALLOW_ONELEVEL))
82 /* "symref=bogus:pair */
83 goto reject;
84 item = string_list_append(symref, sym);
85 item->util = target;
86 return;
87 reject:
88 free(sym);
89 return;
92 static void annotate_refs_with_symref_info(struct ref *ref)
94 struct string_list symref = STRING_LIST_INIT_DUP;
95 const char *feature_list = server_capabilities;
97 while (feature_list) {
98 int len;
99 const char *val;
101 val = parse_feature_value(feature_list, "symref", &len);
102 if (!val)
103 break;
104 parse_one_symref_info(&symref, val, len);
105 feature_list = val + 1;
107 sort_string_list(&symref);
109 for (; ref; ref = ref->next) {
110 struct string_list_item *item;
111 item = string_list_lookup(&symref, ref->name);
112 if (!item)
113 continue;
114 ref->symref = xstrdup((char *)item->util);
116 string_list_clear(&symref, 0);
120 * Read all the refs from the other end
122 struct ref **get_remote_heads(int in, char *src_buf, size_t src_len,
123 struct ref **list, unsigned int flags,
124 struct extra_have_objects *extra_have)
126 struct ref **orig_list = list;
127 int got_at_least_one_head = 0;
129 *list = NULL;
130 for (;;) {
131 struct ref *ref;
132 unsigned char old_sha1[20];
133 char *name;
134 int len, name_len;
135 char *buffer = packet_buffer;
137 len = packet_read(in, &src_buf, &src_len,
138 packet_buffer, sizeof(packet_buffer),
139 PACKET_READ_GENTLE_ON_EOF |
140 PACKET_READ_CHOMP_NEWLINE);
141 if (len < 0)
142 die_initial_contact(got_at_least_one_head);
144 if (!len)
145 break;
147 if (len > 4 && !prefixcmp(buffer, "ERR "))
148 die("remote error: %s", buffer + 4);
150 if (len < 42 || get_sha1_hex(buffer, old_sha1) || buffer[40] != ' ')
151 die("protocol error: expected sha/ref, got '%s'", buffer);
152 name = buffer + 41;
154 name_len = strlen(name);
155 if (len != name_len + 41) {
156 free(server_capabilities);
157 server_capabilities = xstrdup(name + name_len + 1);
160 if (extra_have &&
161 name_len == 5 && !memcmp(".have", name, 5)) {
162 add_extra_have(extra_have, old_sha1);
163 continue;
166 if (!check_ref(name, name_len, flags))
167 continue;
168 ref = alloc_ref(buffer + 41);
169 hashcpy(ref->old_sha1, old_sha1);
170 *list = ref;
171 list = &ref->next;
172 got_at_least_one_head = 1;
175 annotate_refs_with_symref_info(*orig_list);
177 return list;
180 static const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp)
182 int len;
184 if (!feature_list)
185 return NULL;
187 len = strlen(feature);
188 while (*feature_list) {
189 const char *found = strstr(feature_list, feature);
190 if (!found)
191 return NULL;
192 if (feature_list == found || isspace(found[-1])) {
193 const char *value = found + len;
194 /* feature with no value (e.g., "thin-pack") */
195 if (!*value || isspace(*value)) {
196 if (lenp)
197 *lenp = 0;
198 return value;
200 /* feature with a value (e.g., "agent=git/1.2.3") */
201 else if (*value == '=') {
202 value++;
203 if (lenp)
204 *lenp = strcspn(value, " \t\n");
205 return value;
208 * otherwise we matched a substring of another feature;
209 * keep looking
212 feature_list = found + 1;
214 return NULL;
217 int parse_feature_request(const char *feature_list, const char *feature)
219 return !!parse_feature_value(feature_list, feature, NULL);
222 const char *server_feature_value(const char *feature, int *len)
224 return parse_feature_value(server_capabilities, feature, len);
227 int server_supports(const char *feature)
229 return !!server_feature_value(feature, NULL);
232 enum protocol {
233 PROTO_LOCAL = 1,
234 PROTO_SSH,
235 PROTO_GIT
238 static enum protocol get_protocol(const char *name)
240 if (!strcmp(name, "ssh"))
241 return PROTO_SSH;
242 if (!strcmp(name, "git"))
243 return PROTO_GIT;
244 if (!strcmp(name, "git+ssh"))
245 return PROTO_SSH;
246 if (!strcmp(name, "ssh+git"))
247 return PROTO_SSH;
248 if (!strcmp(name, "file"))
249 return PROTO_LOCAL;
250 die("I don't handle protocol '%s'", name);
253 #define STR_(s) # s
254 #define STR(s) STR_(s)
256 static void get_host_and_port(char **host, const char **port)
258 char *colon, *end;
260 if (*host[0] == '[') {
261 end = strchr(*host + 1, ']');
262 if (end) {
263 *end = 0;
264 end++;
265 (*host)++;
266 } else
267 end = *host;
268 } else
269 end = *host;
270 colon = strchr(end, ':');
272 if (colon) {
273 *colon = 0;
274 *port = colon + 1;
278 static void enable_keepalive(int sockfd)
280 int ka = 1;
282 if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
283 fprintf(stderr, "unable to set SO_KEEPALIVE on socket: %s\n",
284 strerror(errno));
287 #ifndef NO_IPV6
289 static const char *ai_name(const struct addrinfo *ai)
291 static char addr[NI_MAXHOST];
292 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
293 NI_NUMERICHOST) != 0)
294 strcpy(addr, "(unknown)");
296 return addr;
300 * Returns a connected socket() fd, or else die()s.
302 static int git_tcp_connect_sock(char *host, int flags)
304 struct strbuf error_message = STRBUF_INIT;
305 int sockfd = -1;
306 const char *port = STR(DEFAULT_GIT_PORT);
307 struct addrinfo hints, *ai0, *ai;
308 int gai;
309 int cnt = 0;
311 get_host_and_port(&host, &port);
312 if (!*port)
313 port = "<none>";
315 memset(&hints, 0, sizeof(hints));
316 hints.ai_socktype = SOCK_STREAM;
317 hints.ai_protocol = IPPROTO_TCP;
319 if (flags & CONNECT_VERBOSE)
320 fprintf(stderr, "Looking up %s ... ", host);
322 gai = getaddrinfo(host, port, &hints, &ai);
323 if (gai)
324 die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
326 if (flags & CONNECT_VERBOSE)
327 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
329 for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
330 sockfd = socket(ai->ai_family,
331 ai->ai_socktype, ai->ai_protocol);
332 if ((sockfd < 0) ||
333 (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
334 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
335 host, cnt, ai_name(ai), strerror(errno));
336 if (0 <= sockfd)
337 close(sockfd);
338 sockfd = -1;
339 continue;
341 if (flags & CONNECT_VERBOSE)
342 fprintf(stderr, "%s ", ai_name(ai));
343 break;
346 freeaddrinfo(ai0);
348 if (sockfd < 0)
349 die("unable to connect to %s:\n%s", host, error_message.buf);
351 enable_keepalive(sockfd);
353 if (flags & CONNECT_VERBOSE)
354 fprintf(stderr, "done.\n");
356 strbuf_release(&error_message);
358 return sockfd;
361 #else /* NO_IPV6 */
364 * Returns a connected socket() fd, or else die()s.
366 static int git_tcp_connect_sock(char *host, int flags)
368 struct strbuf error_message = STRBUF_INIT;
369 int sockfd = -1;
370 const char *port = STR(DEFAULT_GIT_PORT);
371 char *ep;
372 struct hostent *he;
373 struct sockaddr_in sa;
374 char **ap;
375 unsigned int nport;
376 int cnt;
378 get_host_and_port(&host, &port);
380 if (flags & CONNECT_VERBOSE)
381 fprintf(stderr, "Looking up %s ... ", host);
383 he = gethostbyname(host);
384 if (!he)
385 die("Unable to look up %s (%s)", host, hstrerror(h_errno));
386 nport = strtoul(port, &ep, 10);
387 if ( ep == port || *ep ) {
388 /* Not numeric */
389 struct servent *se = getservbyname(port,"tcp");
390 if ( !se )
391 die("Unknown port %s", port);
392 nport = se->s_port;
395 if (flags & CONNECT_VERBOSE)
396 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
398 for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
399 memset(&sa, 0, sizeof sa);
400 sa.sin_family = he->h_addrtype;
401 sa.sin_port = htons(nport);
402 memcpy(&sa.sin_addr, *ap, he->h_length);
404 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
405 if ((sockfd < 0) ||
406 connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
407 strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
408 host,
409 cnt,
410 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
411 strerror(errno));
412 if (0 <= sockfd)
413 close(sockfd);
414 sockfd = -1;
415 continue;
417 if (flags & CONNECT_VERBOSE)
418 fprintf(stderr, "%s ",
419 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
420 break;
423 if (sockfd < 0)
424 die("unable to connect to %s:\n%s", host, error_message.buf);
426 enable_keepalive(sockfd);
428 if (flags & CONNECT_VERBOSE)
429 fprintf(stderr, "done.\n");
431 return sockfd;
434 #endif /* NO_IPV6 */
437 static void git_tcp_connect(int fd[2], char *host, int flags)
439 int sockfd = git_tcp_connect_sock(host, flags);
441 fd[0] = sockfd;
442 fd[1] = dup(sockfd);
446 static char *git_proxy_command;
448 static int git_proxy_command_options(const char *var, const char *value,
449 void *cb)
451 if (!strcmp(var, "core.gitproxy")) {
452 const char *for_pos;
453 int matchlen = -1;
454 int hostlen;
455 const char *rhost_name = cb;
456 int rhost_len = strlen(rhost_name);
458 if (git_proxy_command)
459 return 0;
460 if (!value)
461 return config_error_nonbool(var);
462 /* [core]
463 * ;# matches www.kernel.org as well
464 * gitproxy = netcatter-1 for kernel.org
465 * gitproxy = netcatter-2 for sample.xz
466 * gitproxy = netcatter-default
468 for_pos = strstr(value, " for ");
469 if (!for_pos)
470 /* matches everybody */
471 matchlen = strlen(value);
472 else {
473 hostlen = strlen(for_pos + 5);
474 if (rhost_len < hostlen)
475 matchlen = -1;
476 else if (!strncmp(for_pos + 5,
477 rhost_name + rhost_len - hostlen,
478 hostlen) &&
479 ((rhost_len == hostlen) ||
480 rhost_name[rhost_len - hostlen -1] == '.'))
481 matchlen = for_pos - value;
482 else
483 matchlen = -1;
485 if (0 <= matchlen) {
486 /* core.gitproxy = none for kernel.org */
487 if (matchlen == 4 &&
488 !memcmp(value, "none", 4))
489 matchlen = 0;
490 git_proxy_command = xmemdupz(value, matchlen);
492 return 0;
495 return git_default_config(var, value, cb);
498 static int git_use_proxy(const char *host)
500 git_proxy_command = getenv("GIT_PROXY_COMMAND");
501 git_config(git_proxy_command_options, (void*)host);
502 return (git_proxy_command && *git_proxy_command);
505 static struct child_process *git_proxy_connect(int fd[2], char *host)
507 const char *port = STR(DEFAULT_GIT_PORT);
508 const char **argv;
509 struct child_process *proxy;
511 get_host_and_port(&host, &port);
513 argv = xmalloc(sizeof(*argv) * 4);
514 argv[0] = git_proxy_command;
515 argv[1] = host;
516 argv[2] = port;
517 argv[3] = NULL;
518 proxy = xcalloc(1, sizeof(*proxy));
519 proxy->argv = argv;
520 proxy->in = -1;
521 proxy->out = -1;
522 if (start_command(proxy))
523 die("cannot start proxy %s", argv[0]);
524 fd[0] = proxy->out; /* read from proxy stdout */
525 fd[1] = proxy->in; /* write to proxy stdin */
526 return proxy;
529 #define MAX_CMD_LEN 1024
531 static char *get_port(char *host)
533 char *end;
534 char *p = strchr(host, ':');
536 if (p) {
537 long port = strtol(p + 1, &end, 10);
538 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
539 *p = '\0';
540 return p+1;
544 return NULL;
547 static struct child_process no_fork;
550 * This returns a dummy child_process if the transport protocol does not
551 * need fork(2), or a struct child_process object if it does. Once done,
552 * finish the connection with finish_connect() with the value returned from
553 * this function (it is safe to call finish_connect() with NULL to support
554 * the former case).
556 * If it returns, the connect is successful; it just dies on errors (this
557 * will hopefully be changed in a libification effort, to return NULL when
558 * the connection failed).
560 struct child_process *git_connect(int fd[2], const char *url_orig,
561 const char *prog, int flags)
563 char *url;
564 char *host, *path;
565 char *end;
566 int c;
567 struct child_process *conn = &no_fork;
568 enum protocol protocol = PROTO_LOCAL;
569 int free_path = 0;
570 char *port = NULL;
571 const char **arg;
572 struct strbuf cmd;
574 /* Without this we cannot rely on waitpid() to tell
575 * what happened to our children.
577 signal(SIGCHLD, SIG_DFL);
579 if (is_url(url_orig))
580 url = url_decode(url_orig);
581 else
582 url = xstrdup(url_orig);
584 host = strstr(url, "://");
585 if (host) {
586 *host = '\0';
587 protocol = get_protocol(url);
588 host += 3;
589 c = '/';
590 } else {
591 host = url;
592 c = ':';
596 * Don't do destructive transforms with git:// as that
597 * protocol code does '[]' unwrapping of its own.
599 if (host[0] == '[') {
600 end = strchr(host + 1, ']');
601 if (end) {
602 if (protocol != PROTO_GIT) {
603 *end = 0;
604 host++;
606 end++;
607 } else
608 end = host;
609 } else
610 end = host;
612 path = strchr(end, c);
613 if (path && !has_dos_drive_prefix(end)) {
614 if (c == ':') {
615 if (path < strchrnul(host, '/')) {
616 protocol = PROTO_SSH;
617 *path++ = '\0';
618 } else /* '/' in the host part, assume local path */
619 path = end;
621 } else
622 path = end;
624 if (!path || !*path)
625 die("No path specified. See 'man git-pull' for valid url syntax");
628 * null-terminate hostname and point path to ~ for URL's like this:
629 * ssh://host.xz/~user/repo
631 if (protocol != PROTO_LOCAL && host != url) {
632 char *ptr = path;
633 if (path[1] == '~')
634 path++;
635 else {
636 path = xstrdup(ptr);
637 free_path = 1;
640 *ptr = '\0';
644 * Add support for ssh port: ssh://host.xy:<port>/...
646 if (protocol == PROTO_SSH && host != url)
647 port = get_port(end);
649 if (protocol == PROTO_GIT) {
650 /* These underlying connection commands die() if they
651 * cannot connect.
653 char *target_host = xstrdup(host);
654 if (git_use_proxy(host))
655 conn = git_proxy_connect(fd, host);
656 else
657 git_tcp_connect(fd, host, flags);
659 * Separate original protocol components prog and path
660 * from extended host header with a NUL byte.
662 * Note: Do not add any other headers here! Doing so
663 * will cause older git-daemon servers to crash.
665 packet_write(fd[1],
666 "%s %s%chost=%s%c",
667 prog, path, 0,
668 target_host, 0);
669 free(target_host);
670 free(url);
671 if (free_path)
672 free(path);
673 return conn;
676 conn = xcalloc(1, sizeof(*conn));
678 strbuf_init(&cmd, MAX_CMD_LEN);
679 strbuf_addstr(&cmd, prog);
680 strbuf_addch(&cmd, ' ');
681 sq_quote_buf(&cmd, path);
682 if (cmd.len >= MAX_CMD_LEN)
683 die("command line too long");
685 conn->in = conn->out = -1;
686 conn->argv = arg = xcalloc(7, sizeof(*arg));
687 if (protocol == PROTO_SSH) {
688 const char *ssh = getenv("GIT_SSH");
689 int putty = ssh && strcasestr(ssh, "plink");
690 if (!ssh) ssh = "ssh";
692 *arg++ = ssh;
693 if (putty && !strcasestr(ssh, "tortoiseplink"))
694 *arg++ = "-batch";
695 if (port) {
696 /* P is for PuTTY, p is for OpenSSH */
697 *arg++ = putty ? "-P" : "-p";
698 *arg++ = port;
700 *arg++ = host;
702 else {
703 /* remove repo-local variables from the environment */
704 conn->env = local_repo_env;
705 conn->use_shell = 1;
707 *arg++ = cmd.buf;
708 *arg = NULL;
710 if (start_command(conn))
711 die("unable to fork");
713 fd[0] = conn->out; /* read from child's stdout */
714 fd[1] = conn->in; /* write to child's stdin */
715 strbuf_release(&cmd);
716 free(url);
717 if (free_path)
718 free(path);
719 return conn;
722 int git_connection_is_socket(struct child_process *conn)
724 return conn == &no_fork;
727 int finish_connect(struct child_process *conn)
729 int code;
730 if (!conn || git_connection_is_socket(conn))
731 return 0;
733 code = finish_command(conn);
734 free(conn->argv);
735 free(conn);
736 return code;