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