parse_feature_request: make it easier to see feature values
[git] / connect.c
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
10 static char *server_capabilities;
11
12 static int check_ref(const char *name, int len, unsigned int flags)
13 {
14         if (!flags)
15                 return 1;
16
17         if (len < 5 || memcmp(name, "refs/", 5))
18                 return 0;
19
20         /* Skip the "refs/" part */
21         name += 5;
22         len -= 5;
23
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;
27
28         /* REF_HEADS means that we want regular branch heads */
29         if ((flags & REF_HEADS) && !memcmp(name, "heads/", 6))
30                 return 1;
31
32         /* REF_TAGS means that we want tags */
33         if ((flags & REF_TAGS) && !memcmp(name, "tags/", 5))
34                 return 1;
35
36         /* All type bits clear means that we are ok with anything */
37         return !(flags & ~REF_NORMAL);
38 }
39
40 int check_ref_type(const struct ref *ref, int flags)
41 {
42         return check_ref(ref->name, strlen(ref->name), flags);
43 }
44
45 static void add_extra_have(struct extra_have_objects *extra, unsigned char *sha1)
46 {
47         ALLOC_GROW(extra->array, extra->nr + 1, extra->alloc);
48         hashcpy(&(extra->array[extra->nr][0]), sha1);
49         extra->nr++;
50 }
51
52 /*
53  * Read all the refs from the other end
54  */
55 struct ref **get_remote_heads(int in, struct ref **list,
56                               unsigned int flags,
57                               struct extra_have_objects *extra_have)
58 {
59         *list = NULL;
60         for (;;) {
61                 struct ref *ref;
62                 unsigned char old_sha1[20];
63                 static char buffer[1000];
64                 char *name;
65                 int len, name_len;
66
67                 len = packet_read_line(in, buffer, sizeof(buffer));
68                 if (!len)
69                         break;
70                 if (buffer[len-1] == '\n')
71                         buffer[--len] = 0;
72
73                 if (len > 4 && !prefixcmp(buffer, "ERR "))
74                         die("remote error: %s", buffer + 4);
75
76                 if (len < 42 || get_sha1_hex(buffer, old_sha1) || buffer[40] != ' ')
77                         die("protocol error: expected sha/ref, got '%s'", buffer);
78                 name = buffer + 41;
79
80                 name_len = strlen(name);
81                 if (len != name_len + 41) {
82                         free(server_capabilities);
83                         server_capabilities = xstrdup(name + name_len + 1);
84                 }
85
86                 if (extra_have &&
87                     name_len == 5 && !memcmp(".have", name, 5)) {
88                         add_extra_have(extra_have, old_sha1);
89                         continue;
90                 }
91
92                 if (!check_ref(name, name_len, flags))
93                         continue;
94                 ref = alloc_ref(buffer + 41);
95                 hashcpy(ref->old_sha1, old_sha1);
96                 *list = ref;
97                 list = &ref->next;
98         }
99         return list;
100 }
101
102 const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp)
103 {
104         int len;
105
106         if (!feature_list)
107                 return NULL;
108
109         len = strlen(feature);
110         while (*feature_list) {
111                 const char *found = strstr(feature_list, feature);
112                 if (!found)
113                         return NULL;
114                 if (feature_list == found || isspace(found[-1])) {
115                         const char *value = found + len;
116                         /* feature with no value (e.g., "thin-pack") */
117                         if (!*value || isspace(*value)) {
118                                 if (lenp)
119                                         *lenp = 0;
120                                 return value;
121                         }
122                         /* feature with a value (e.g., "agent=git/1.2.3") */
123                         else if (*value == '=') {
124                                 value++;
125                                 if (lenp)
126                                         *lenp = strcspn(value, " \t\n");
127                                 return value;
128                         }
129                         /*
130                          * otherwise we matched a substring of another feature;
131                          * keep looking
132                          */
133                 }
134                 feature_list = found + 1;
135         }
136         return NULL;
137 }
138
139 int parse_feature_request(const char *feature_list, const char *feature)
140 {
141         return !!parse_feature_value(feature_list, feature, NULL);
142 }
143
144 const char *server_feature_value(const char *feature, int *len)
145 {
146         return parse_feature_value(server_capabilities, feature, len);
147 }
148
149 int server_supports(const char *feature)
150 {
151         return !!server_feature_value(feature, NULL);
152 }
153
154 enum protocol {
155         PROTO_LOCAL = 1,
156         PROTO_SSH,
157         PROTO_GIT
158 };
159
160 static enum protocol get_protocol(const char *name)
161 {
162         if (!strcmp(name, "ssh"))
163                 return PROTO_SSH;
164         if (!strcmp(name, "git"))
165                 return PROTO_GIT;
166         if (!strcmp(name, "git+ssh"))
167                 return PROTO_SSH;
168         if (!strcmp(name, "ssh+git"))
169                 return PROTO_SSH;
170         if (!strcmp(name, "file"))
171                 return PROTO_LOCAL;
172         die("I don't handle protocol '%s'", name);
173 }
174
175 #define STR_(s) # s
176 #define STR(s)  STR_(s)
177
178 static void get_host_and_port(char **host, const char **port)
179 {
180         char *colon, *end;
181
182         if (*host[0] == '[') {
183                 end = strchr(*host + 1, ']');
184                 if (end) {
185                         *end = 0;
186                         end++;
187                         (*host)++;
188                 } else
189                         end = *host;
190         } else
191                 end = *host;
192         colon = strchr(end, ':');
193
194         if (colon) {
195                 *colon = 0;
196                 *port = colon + 1;
197         }
198 }
199
200 static void enable_keepalive(int sockfd)
201 {
202         int ka = 1;
203
204         if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
205                 fprintf(stderr, "unable to set SO_KEEPALIVE on socket: %s\n",
206                         strerror(errno));
207 }
208
209 #ifndef NO_IPV6
210
211 static const char *ai_name(const struct addrinfo *ai)
212 {
213         static char addr[NI_MAXHOST];
214         if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
215                         NI_NUMERICHOST) != 0)
216                 strcpy(addr, "(unknown)");
217
218         return addr;
219 }
220
221 /*
222  * Returns a connected socket() fd, or else die()s.
223  */
224 static int git_tcp_connect_sock(char *host, int flags)
225 {
226         struct strbuf error_message = STRBUF_INIT;
227         int sockfd = -1;
228         const char *port = STR(DEFAULT_GIT_PORT);
229         struct addrinfo hints, *ai0, *ai;
230         int gai;
231         int cnt = 0;
232
233         get_host_and_port(&host, &port);
234         if (!*port)
235                 port = "<none>";
236
237         memset(&hints, 0, sizeof(hints));
238         hints.ai_socktype = SOCK_STREAM;
239         hints.ai_protocol = IPPROTO_TCP;
240
241         if (flags & CONNECT_VERBOSE)
242                 fprintf(stderr, "Looking up %s ... ", host);
243
244         gai = getaddrinfo(host, port, &hints, &ai);
245         if (gai)
246                 die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
247
248         if (flags & CONNECT_VERBOSE)
249                 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
250
251         for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
252                 sockfd = socket(ai->ai_family,
253                                 ai->ai_socktype, ai->ai_protocol);
254                 if ((sockfd < 0) ||
255                     (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
256                         strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
257                                     host, cnt, ai_name(ai), strerror(errno));
258                         if (0 <= sockfd)
259                                 close(sockfd);
260                         sockfd = -1;
261                         continue;
262                 }
263                 if (flags & CONNECT_VERBOSE)
264                         fprintf(stderr, "%s ", ai_name(ai));
265                 break;
266         }
267
268         freeaddrinfo(ai0);
269
270         if (sockfd < 0)
271                 die("unable to connect to %s:\n%s", host, error_message.buf);
272
273         enable_keepalive(sockfd);
274
275         if (flags & CONNECT_VERBOSE)
276                 fprintf(stderr, "done.\n");
277
278         strbuf_release(&error_message);
279
280         return sockfd;
281 }
282
283 #else /* NO_IPV6 */
284
285 /*
286  * Returns a connected socket() fd, or else die()s.
287  */
288 static int git_tcp_connect_sock(char *host, int flags)
289 {
290         struct strbuf error_message = STRBUF_INIT;
291         int sockfd = -1;
292         const char *port = STR(DEFAULT_GIT_PORT);
293         char *ep;
294         struct hostent *he;
295         struct sockaddr_in sa;
296         char **ap;
297         unsigned int nport;
298         int cnt;
299
300         get_host_and_port(&host, &port);
301
302         if (flags & CONNECT_VERBOSE)
303                 fprintf(stderr, "Looking up %s ... ", host);
304
305         he = gethostbyname(host);
306         if (!he)
307                 die("Unable to look up %s (%s)", host, hstrerror(h_errno));
308         nport = strtoul(port, &ep, 10);
309         if ( ep == port || *ep ) {
310                 /* Not numeric */
311                 struct servent *se = getservbyname(port,"tcp");
312                 if ( !se )
313                         die("Unknown port %s", port);
314                 nport = se->s_port;
315         }
316
317         if (flags & CONNECT_VERBOSE)
318                 fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
319
320         for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
321                 memset(&sa, 0, sizeof sa);
322                 sa.sin_family = he->h_addrtype;
323                 sa.sin_port = htons(nport);
324                 memcpy(&sa.sin_addr, *ap, he->h_length);
325
326                 sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
327                 if ((sockfd < 0) ||
328                     connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
329                         strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
330                                 host,
331                                 cnt,
332                                 inet_ntoa(*(struct in_addr *)&sa.sin_addr),
333                                 strerror(errno));
334                         if (0 <= sockfd)
335                                 close(sockfd);
336                         sockfd = -1;
337                         continue;
338                 }
339                 if (flags & CONNECT_VERBOSE)
340                         fprintf(stderr, "%s ",
341                                 inet_ntoa(*(struct in_addr *)&sa.sin_addr));
342                 break;
343         }
344
345         if (sockfd < 0)
346                 die("unable to connect to %s:\n%s", host, error_message.buf);
347
348         enable_keepalive(sockfd);
349
350         if (flags & CONNECT_VERBOSE)
351                 fprintf(stderr, "done.\n");
352
353         return sockfd;
354 }
355
356 #endif /* NO_IPV6 */
357
358
359 static void git_tcp_connect(int fd[2], char *host, int flags)
360 {
361         int sockfd = git_tcp_connect_sock(host, flags);
362
363         fd[0] = sockfd;
364         fd[1] = dup(sockfd);
365 }
366
367
368 static char *git_proxy_command;
369
370 static int git_proxy_command_options(const char *var, const char *value,
371                 void *cb)
372 {
373         if (!strcmp(var, "core.gitproxy")) {
374                 const char *for_pos;
375                 int matchlen = -1;
376                 int hostlen;
377                 const char *rhost_name = cb;
378                 int rhost_len = strlen(rhost_name);
379
380                 if (git_proxy_command)
381                         return 0;
382                 if (!value)
383                         return config_error_nonbool(var);
384                 /* [core]
385                  * ;# matches www.kernel.org as well
386                  * gitproxy = netcatter-1 for kernel.org
387                  * gitproxy = netcatter-2 for sample.xz
388                  * gitproxy = netcatter-default
389                  */
390                 for_pos = strstr(value, " for ");
391                 if (!for_pos)
392                         /* matches everybody */
393                         matchlen = strlen(value);
394                 else {
395                         hostlen = strlen(for_pos + 5);
396                         if (rhost_len < hostlen)
397                                 matchlen = -1;
398                         else if (!strncmp(for_pos + 5,
399                                           rhost_name + rhost_len - hostlen,
400                                           hostlen) &&
401                                  ((rhost_len == hostlen) ||
402                                   rhost_name[rhost_len - hostlen -1] == '.'))
403                                 matchlen = for_pos - value;
404                         else
405                                 matchlen = -1;
406                 }
407                 if (0 <= matchlen) {
408                         /* core.gitproxy = none for kernel.org */
409                         if (matchlen == 4 &&
410                             !memcmp(value, "none", 4))
411                                 matchlen = 0;
412                         git_proxy_command = xmemdupz(value, matchlen);
413                 }
414                 return 0;
415         }
416
417         return git_default_config(var, value, cb);
418 }
419
420 static int git_use_proxy(const char *host)
421 {
422         git_proxy_command = getenv("GIT_PROXY_COMMAND");
423         git_config(git_proxy_command_options, (void*)host);
424         return (git_proxy_command && *git_proxy_command);
425 }
426
427 static struct child_process *git_proxy_connect(int fd[2], char *host)
428 {
429         const char *port = STR(DEFAULT_GIT_PORT);
430         const char **argv;
431         struct child_process *proxy;
432
433         get_host_and_port(&host, &port);
434
435         argv = xmalloc(sizeof(*argv) * 4);
436         argv[0] = git_proxy_command;
437         argv[1] = host;
438         argv[2] = port;
439         argv[3] = NULL;
440         proxy = xcalloc(1, sizeof(*proxy));
441         proxy->argv = argv;
442         proxy->in = -1;
443         proxy->out = -1;
444         if (start_command(proxy))
445                 die("cannot start proxy %s", argv[0]);
446         fd[0] = proxy->out; /* read from proxy stdout */
447         fd[1] = proxy->in;  /* write to proxy stdin */
448         return proxy;
449 }
450
451 #define MAX_CMD_LEN 1024
452
453 static char *get_port(char *host)
454 {
455         char *end;
456         char *p = strchr(host, ':');
457
458         if (p) {
459                 long port = strtol(p + 1, &end, 10);
460                 if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
461                         *p = '\0';
462                         return p+1;
463                 }
464         }
465
466         return NULL;
467 }
468
469 static struct child_process no_fork;
470
471 /*
472  * This returns a dummy child_process if the transport protocol does not
473  * need fork(2), or a struct child_process object if it does.  Once done,
474  * finish the connection with finish_connect() with the value returned from
475  * this function (it is safe to call finish_connect() with NULL to support
476  * the former case).
477  *
478  * If it returns, the connect is successful; it just dies on errors (this
479  * will hopefully be changed in a libification effort, to return NULL when
480  * the connection failed).
481  */
482 struct child_process *git_connect(int fd[2], const char *url_orig,
483                                   const char *prog, int flags)
484 {
485         char *url;
486         char *host, *path;
487         char *end;
488         int c;
489         struct child_process *conn = &no_fork;
490         enum protocol protocol = PROTO_LOCAL;
491         int free_path = 0;
492         char *port = NULL;
493         const char **arg;
494         struct strbuf cmd;
495
496         /* Without this we cannot rely on waitpid() to tell
497          * what happened to our children.
498          */
499         signal(SIGCHLD, SIG_DFL);
500
501         if (is_url(url_orig))
502                 url = url_decode(url_orig);
503         else
504                 url = xstrdup(url_orig);
505
506         host = strstr(url, "://");
507         if (host) {
508                 *host = '\0';
509                 protocol = get_protocol(url);
510                 host += 3;
511                 c = '/';
512         } else {
513                 host = url;
514                 c = ':';
515         }
516
517         /*
518          * Don't do destructive transforms with git:// as that
519          * protocol code does '[]' unwrapping of its own.
520          */
521         if (host[0] == '[') {
522                 end = strchr(host + 1, ']');
523                 if (end) {
524                         if (protocol != PROTO_GIT) {
525                                 *end = 0;
526                                 host++;
527                         }
528                         end++;
529                 } else
530                         end = host;
531         } else
532                 end = host;
533
534         path = strchr(end, c);
535         if (path && !has_dos_drive_prefix(end)) {
536                 if (c == ':') {
537                         protocol = PROTO_SSH;
538                         *path++ = '\0';
539                 }
540         } else
541                 path = end;
542
543         if (!path || !*path)
544                 die("No path specified. See 'man git-pull' for valid url syntax");
545
546         /*
547          * null-terminate hostname and point path to ~ for URL's like this:
548          *    ssh://host.xz/~user/repo
549          */
550         if (protocol != PROTO_LOCAL && host != url) {
551                 char *ptr = path;
552                 if (path[1] == '~')
553                         path++;
554                 else {
555                         path = xstrdup(ptr);
556                         free_path = 1;
557                 }
558
559                 *ptr = '\0';
560         }
561
562         /*
563          * Add support for ssh port: ssh://host.xy:<port>/...
564          */
565         if (protocol == PROTO_SSH && host != url)
566                 port = get_port(host);
567
568         if (protocol == PROTO_GIT) {
569                 /* These underlying connection commands die() if they
570                  * cannot connect.
571                  */
572                 char *target_host = xstrdup(host);
573                 if (git_use_proxy(host))
574                         conn = git_proxy_connect(fd, host);
575                 else
576                         git_tcp_connect(fd, host, flags);
577                 /*
578                  * Separate original protocol components prog and path
579                  * from extended host header with a NUL byte.
580                  *
581                  * Note: Do not add any other headers here!  Doing so
582                  * will cause older git-daemon servers to crash.
583                  */
584                 packet_write(fd[1],
585                              "%s %s%chost=%s%c",
586                              prog, path, 0,
587                              target_host, 0);
588                 free(target_host);
589                 free(url);
590                 if (free_path)
591                         free(path);
592                 return conn;
593         }
594
595         conn = xcalloc(1, sizeof(*conn));
596
597         strbuf_init(&cmd, MAX_CMD_LEN);
598         strbuf_addstr(&cmd, prog);
599         strbuf_addch(&cmd, ' ');
600         sq_quote_buf(&cmd, path);
601         if (cmd.len >= MAX_CMD_LEN)
602                 die("command line too long");
603
604         conn->in = conn->out = -1;
605         conn->argv = arg = xcalloc(7, sizeof(*arg));
606         if (protocol == PROTO_SSH) {
607                 const char *ssh = getenv("GIT_SSH");
608                 int putty = ssh && strcasestr(ssh, "plink");
609                 if (!ssh) ssh = "ssh";
610
611                 *arg++ = ssh;
612                 if (putty && !strcasestr(ssh, "tortoiseplink"))
613                         *arg++ = "-batch";
614                 if (port) {
615                         /* P is for PuTTY, p is for OpenSSH */
616                         *arg++ = putty ? "-P" : "-p";
617                         *arg++ = port;
618                 }
619                 *arg++ = host;
620         }
621         else {
622                 /* remove repo-local variables from the environment */
623                 conn->env = local_repo_env;
624                 conn->use_shell = 1;
625         }
626         *arg++ = cmd.buf;
627         *arg = NULL;
628
629         if (start_command(conn))
630                 die("unable to fork");
631
632         fd[0] = conn->out; /* read from child's stdout */
633         fd[1] = conn->in;  /* write to child's stdin */
634         strbuf_release(&cmd);
635         free(url);
636         if (free_path)
637                 free(path);
638         return conn;
639 }
640
641 int git_connection_is_socket(struct child_process *conn)
642 {
643         return conn == &no_fork;
644 }
645
646 int finish_connect(struct child_process *conn)
647 {
648         int code;
649         if (!conn || git_connection_is_socket(conn))
650                 return 0;
651
652         code = finish_command(conn);
653         free(conn->argv);
654         free(conn);
655         return code;
656 }