Implement first draft of DNS-SD support in git-daemon
[git] / daemon.c
1 #include "cache.h"
2 #include "pkt-line.h"
3 #include "exec_cmd.h"
4 #include "run-command.h"
5 #include "strbuf.h"
6 #include "string-list.h"
7
8 #ifndef NO_DNSSD
9 #include <dns_sd.h>
10 static DNSServiceRef sdRef;
11 #endif
12
13 static void dnssd_register(struct string_list *listen_addr, int listen_port);
14 static void dnssd_unregister(void);
15
16 #ifndef HOST_NAME_MAX
17 #define HOST_NAME_MAX 256
18 #endif
19
20 #ifdef NO_INITGROUPS
21 #define initgroups(x, y) (0) /* nothing */
22 #endif
23
24 static int log_syslog;
25 static int verbose;
26 static int reuseaddr;
27 static int informative_errors;
28
29 static const char daemon_usage[] =
30 "git daemon [--verbose] [--syslog] [--export-all]\n"
31 "           [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
32 "           [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
33 "           [--user-path | --user-path=<path>]\n"
34 "           [--interpolated-path=<path>]\n"
35 "           [--reuseaddr] [--pid-file=<file>]\n"
36 "           [--(enable|disable|allow-override|forbid-override)=<service>]\n"
37 "           [--access-hook=<path>]\n"
38 "           [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
39 "                      [--detach] [--user=<user> [--group=<group>]]\n"
40 "           [<directory>...]";
41
42 /* List of acceptable pathname prefixes */
43 static char **ok_paths;
44 static int strict_paths;
45
46 /* If this is set, git-daemon-export-ok is not required */
47 static int export_all_trees;
48
49 /* Take all paths relative to this one if non-NULL */
50 static const char *base_path;
51 static const char *interpolated_path;
52 static int base_path_relaxed;
53
54 /* Flag indicating client sent extra args. */
55 static int saw_extended_args;
56
57 /* If defined, ~user notation is allowed and the string is inserted
58  * after ~user/.  E.g. a request to git://host/~alice/frotz would
59  * go to /home/alice/pub_git/frotz with --user-path=pub_git.
60  */
61 static const char *user_path;
62
63 /* Timeout, and initial timeout */
64 static unsigned int timeout;
65 static unsigned int init_timeout;
66
67 static char *hostname;
68 static char *canon_hostname;
69 static char *ip_address;
70 static char *tcp_port;
71
72 static void logreport(int priority, const char *err, va_list params)
73 {
74         if (log_syslog) {
75                 char buf[1024];
76                 vsnprintf(buf, sizeof(buf), err, params);
77                 syslog(priority, "%s", buf);
78         } else {
79                 /*
80                  * Since stderr is set to buffered mode, the
81                  * logging of different processes will not overlap
82                  * unless they overflow the (rather big) buffers.
83                  */
84                 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
85                 vfprintf(stderr, err, params);
86                 fputc('\n', stderr);
87                 fflush(stderr);
88         }
89 }
90
91 __attribute__((format (printf, 1, 2)))
92 static void logerror(const char *err, ...)
93 {
94         va_list params;
95         va_start(params, err);
96         logreport(LOG_ERR, err, params);
97         va_end(params);
98 }
99
100 __attribute__((format (printf, 1, 2)))
101 static void loginfo(const char *err, ...)
102 {
103         va_list params;
104         if (!verbose)
105                 return;
106         va_start(params, err);
107         logreport(LOG_INFO, err, params);
108         va_end(params);
109 }
110
111 static void NORETURN daemon_die(const char *err, va_list params)
112 {
113         logreport(LOG_ERR, err, params);
114         dnssd_unregister();
115         exit(1);
116 }
117
118 static const char *path_ok(const char *directory)
119 {
120         static char rpath[PATH_MAX];
121         static char interp_path[PATH_MAX];
122         const char *path;
123         const char *dir;
124
125         dir = directory;
126
127         if (daemon_avoid_alias(dir)) {
128                 logerror("'%s': aliased", dir);
129                 return NULL;
130         }
131
132         if (*dir == '~') {
133                 if (!user_path) {
134                         logerror("'%s': User-path not allowed", dir);
135                         return NULL;
136                 }
137                 if (*user_path) {
138                         /* Got either "~alice" or "~alice/foo";
139                          * rewrite them to "~alice/%s" or
140                          * "~alice/%s/foo".
141                          */
142                         int namlen, restlen = strlen(dir);
143                         const char *slash = strchr(dir, '/');
144                         if (!slash)
145                                 slash = dir + restlen;
146                         namlen = slash - dir;
147                         restlen -= namlen;
148                         loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
149                         snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
150                                  namlen, dir, user_path, restlen, slash);
151                         dir = rpath;
152                 }
153         }
154         else if (interpolated_path && saw_extended_args) {
155                 struct strbuf expanded_path = STRBUF_INIT;
156                 struct strbuf_expand_dict_entry dict[6];
157
158                 dict[0].placeholder = "H"; dict[0].value = hostname;
159                 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
160                 dict[2].placeholder = "IP"; dict[2].value = ip_address;
161                 dict[3].placeholder = "P"; dict[3].value = tcp_port;
162                 dict[4].placeholder = "D"; dict[4].value = directory;
163                 dict[5].placeholder = NULL; dict[5].value = NULL;
164                 if (*dir != '/') {
165                         /* Allow only absolute */
166                         logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
167                         return NULL;
168                 }
169
170                 strbuf_expand(&expanded_path, interpolated_path,
171                                 strbuf_expand_dict_cb, &dict);
172                 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
173                 strbuf_release(&expanded_path);
174                 loginfo("Interpolated dir '%s'", interp_path);
175
176                 dir = interp_path;
177         }
178         else if (base_path) {
179                 if (*dir != '/') {
180                         /* Allow only absolute */
181                         logerror("'%s': Non-absolute path denied (base-path active)", dir);
182                         return NULL;
183                 }
184                 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
185                 dir = rpath;
186         }
187
188         path = enter_repo(dir, strict_paths);
189         if (!path && base_path && base_path_relaxed) {
190                 /*
191                  * if we fail and base_path_relaxed is enabled, try without
192                  * prefixing the base path
193                  */
194                 dir = directory;
195                 path = enter_repo(dir, strict_paths);
196         }
197
198         if (!path) {
199                 logerror("'%s' does not appear to be a git repository", dir);
200                 return NULL;
201         }
202
203         if ( ok_paths && *ok_paths ) {
204                 char **pp;
205                 int pathlen = strlen(path);
206
207                 /* The validation is done on the paths after enter_repo
208                  * appends optional {.git,.git/.git} and friends, but
209                  * it does not use getcwd().  So if your /pub is
210                  * a symlink to /mnt/pub, you can whitelist /pub and
211                  * do not have to say /mnt/pub.
212                  * Do not say /pub/.
213                  */
214                 for ( pp = ok_paths ; *pp ; pp++ ) {
215                         int len = strlen(*pp);
216                         if (len <= pathlen &&
217                             !memcmp(*pp, path, len) &&
218                             (path[len] == '\0' ||
219                              (!strict_paths && path[len] == '/')))
220                                 return path;
221                 }
222         }
223         else {
224                 /* be backwards compatible */
225                 if (!strict_paths)
226                         return path;
227         }
228
229         logerror("'%s': not in whitelist", path);
230         return NULL;            /* Fallthrough. Deny by default */
231 }
232
233 typedef int (*daemon_service_fn)(void);
234 struct daemon_service {
235         const char *name;
236         const char *config_name;
237         daemon_service_fn fn;
238         int enabled;
239         int overridable;
240 };
241
242 static struct daemon_service *service_looking_at;
243 static int service_enabled;
244
245 static int git_daemon_config(const char *var, const char *value, void *cb)
246 {
247         const char *service;
248
249         if (skip_prefix(var, "daemon.", &service) &&
250             !strcmp(service, service_looking_at->config_name)) {
251                 service_enabled = git_config_bool(var, value);
252                 return 0;
253         }
254
255         /* we are not interested in parsing any other configuration here */
256         return 0;
257 }
258
259 static int daemon_error(const char *dir, const char *msg)
260 {
261         if (!informative_errors)
262                 msg = "access denied or repository not exported";
263         packet_write(1, "ERR %s: %s", msg, dir);
264         return -1;
265 }
266
267 static const char *access_hook;
268
269 static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
270 {
271         struct child_process child;
272         struct strbuf buf = STRBUF_INIT;
273         const char *argv[8];
274         const char **arg = argv;
275         char *eol;
276         int seen_errors = 0;
277
278 #define STRARG(x) ((x) ? (x) : "")
279         *arg++ = access_hook;
280         *arg++ = service->name;
281         *arg++ = path;
282         *arg++ = STRARG(hostname);
283         *arg++ = STRARG(canon_hostname);
284         *arg++ = STRARG(ip_address);
285         *arg++ = STRARG(tcp_port);
286         *arg = NULL;
287 #undef STRARG
288
289         memset(&child, 0, sizeof(child));
290         child.use_shell = 1;
291         child.argv = argv;
292         child.no_stdin = 1;
293         child.no_stderr = 1;
294         child.out = -1;
295         if (start_command(&child)) {
296                 logerror("daemon access hook '%s' failed to start",
297                          access_hook);
298                 goto error_return;
299         }
300         if (strbuf_read(&buf, child.out, 0) < 0) {
301                 logerror("failed to read from pipe to daemon access hook '%s'",
302                          access_hook);
303                 strbuf_reset(&buf);
304                 seen_errors = 1;
305         }
306         if (close(child.out) < 0) {
307                 logerror("failed to close pipe to daemon access hook '%s'",
308                          access_hook);
309                 seen_errors = 1;
310         }
311         if (finish_command(&child))
312                 seen_errors = 1;
313
314         if (!seen_errors) {
315                 strbuf_release(&buf);
316                 return 0;
317         }
318
319 error_return:
320         strbuf_ltrim(&buf);
321         if (!buf.len)
322                 strbuf_addstr(&buf, "service rejected");
323         eol = strchr(buf.buf, '\n');
324         if (eol)
325                 *eol = '\0';
326         errno = EACCES;
327         daemon_error(dir, buf.buf);
328         strbuf_release(&buf);
329         return -1;
330 }
331
332 static int run_service(const char *dir, struct daemon_service *service)
333 {
334         const char *path;
335         int enabled = service->enabled;
336
337         loginfo("Request %s for '%s'", service->name, dir);
338
339         if (!enabled && !service->overridable) {
340                 logerror("'%s': service not enabled.", service->name);
341                 errno = EACCES;
342                 return daemon_error(dir, "service not enabled");
343         }
344
345         if (!(path = path_ok(dir)))
346                 return daemon_error(dir, "no such repository");
347
348         /*
349          * Security on the cheap.
350          *
351          * We want a readable HEAD, usable "objects" directory, and
352          * a "git-daemon-export-ok" flag that says that the other side
353          * is ok with us doing this.
354          *
355          * path_ok() uses enter_repo() and does whitelist checking.
356          * We only need to make sure the repository is exported.
357          */
358
359         if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
360                 logerror("'%s': repository not exported.", path);
361                 errno = EACCES;
362                 return daemon_error(dir, "repository not exported");
363         }
364
365         if (service->overridable) {
366                 service_looking_at = service;
367                 service_enabled = -1;
368                 git_config(git_daemon_config, NULL);
369                 if (0 <= service_enabled)
370                         enabled = service_enabled;
371         }
372         if (!enabled) {
373                 logerror("'%s': service not enabled for '%s'",
374                          service->name, path);
375                 errno = EACCES;
376                 return daemon_error(dir, "service not enabled");
377         }
378
379         /*
380          * Optionally, a hook can choose to deny access to the
381          * repository depending on the phase of the moon.
382          */
383         if (access_hook && run_access_hook(service, dir, path))
384                 return -1;
385
386         /*
387          * We'll ignore SIGTERM from now on, we have a
388          * good client.
389          */
390         signal(SIGTERM, SIG_IGN);
391
392         return service->fn();
393 }
394
395 static void copy_to_log(int fd)
396 {
397         struct strbuf line = STRBUF_INIT;
398         FILE *fp;
399
400         fp = fdopen(fd, "r");
401         if (fp == NULL) {
402                 logerror("fdopen of error channel failed");
403                 close(fd);
404                 return;
405         }
406
407         while (strbuf_getline(&line, fp, '\n') != EOF) {
408                 logerror("%s", line.buf);
409                 strbuf_setlen(&line, 0);
410         }
411
412         strbuf_release(&line);
413         fclose(fp);
414 }
415
416 static int run_service_command(const char **argv)
417 {
418         struct child_process cld;
419
420         memset(&cld, 0, sizeof(cld));
421         cld.argv = argv;
422         cld.git_cmd = 1;
423         cld.err = -1;
424         if (start_command(&cld))
425                 return -1;
426
427         close(0);
428         close(1);
429
430         copy_to_log(cld.err);
431
432         return finish_command(&cld);
433 }
434
435 static int upload_pack(void)
436 {
437         /* Timeout as string */
438         char timeout_buf[64];
439         const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
440
441         argv[2] = timeout_buf;
442
443         snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
444         return run_service_command(argv);
445 }
446
447 static int upload_archive(void)
448 {
449         static const char *argv[] = { "upload-archive", ".", NULL };
450         return run_service_command(argv);
451 }
452
453 static int receive_pack(void)
454 {
455         static const char *argv[] = { "receive-pack", ".", NULL };
456         return run_service_command(argv);
457 }
458
459 static struct daemon_service daemon_service[] = {
460         { "upload-archive", "uploadarch", upload_archive, 0, 1 },
461         { "upload-pack", "uploadpack", upload_pack, 1, 1 },
462         { "receive-pack", "receivepack", receive_pack, 0, 1 },
463 };
464
465 static void enable_service(const char *name, int ena)
466 {
467         int i;
468         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
469                 if (!strcmp(daemon_service[i].name, name)) {
470                         daemon_service[i].enabled = ena;
471                         return;
472                 }
473         }
474         die("No such service %s", name);
475 }
476
477 static void make_service_overridable(const char *name, int ena)
478 {
479         int i;
480         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
481                 if (!strcmp(daemon_service[i].name, name)) {
482                         daemon_service[i].overridable = ena;
483                         return;
484                 }
485         }
486         die("No such service %s", name);
487 }
488
489 static void parse_host_and_port(char *hostport, char **host,
490         char **port)
491 {
492         if (*hostport == '[') {
493                 char *end;
494
495                 end = strchr(hostport, ']');
496                 if (!end)
497                         die("Invalid request ('[' without ']')");
498                 *end = '\0';
499                 *host = hostport + 1;
500                 if (!end[1])
501                         *port = NULL;
502                 else if (end[1] == ':')
503                         *port = end + 2;
504                 else
505                         die("Garbage after end of host part");
506         } else {
507                 *host = hostport;
508                 *port = strrchr(hostport, ':');
509                 if (*port) {
510                         **port = '\0';
511                         ++*port;
512                 }
513         }
514 }
515
516 /*
517  * Read the host as supplied by the client connection.
518  */
519 static void parse_host_arg(char *extra_args, int buflen)
520 {
521         char *val;
522         int vallen;
523         char *end = extra_args + buflen;
524
525         if (extra_args < end && *extra_args) {
526                 saw_extended_args = 1;
527                 if (strncasecmp("host=", extra_args, 5) == 0) {
528                         val = extra_args + 5;
529                         vallen = strlen(val) + 1;
530                         if (*val) {
531                                 /* Split <host>:<port> at colon. */
532                                 char *host;
533                                 char *port;
534                                 parse_host_and_port(val, &host, &port);
535                                 if (port) {
536                                         free(tcp_port);
537                                         tcp_port = xstrdup(port);
538                                 }
539                                 free(hostname);
540                                 hostname = xstrdup_tolower(host);
541                         }
542
543                         /* On to the next one */
544                         extra_args = val + vallen;
545                 }
546                 if (extra_args < end && *extra_args)
547                         die("Invalid request");
548         }
549
550         /*
551          * Locate canonical hostname and its IP address.
552          */
553         if (hostname) {
554 #ifndef NO_IPV6
555                 struct addrinfo hints;
556                 struct addrinfo *ai;
557                 int gai;
558                 static char addrbuf[HOST_NAME_MAX + 1];
559
560                 memset(&hints, 0, sizeof(hints));
561                 hints.ai_flags = AI_CANONNAME;
562
563                 gai = getaddrinfo(hostname, NULL, &hints, &ai);
564                 if (!gai) {
565                         struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
566
567                         inet_ntop(AF_INET, &sin_addr->sin_addr,
568                                   addrbuf, sizeof(addrbuf));
569                         free(ip_address);
570                         ip_address = xstrdup(addrbuf);
571
572                         free(canon_hostname);
573                         canon_hostname = xstrdup(ai->ai_canonname ?
574                                                  ai->ai_canonname : ip_address);
575
576                         freeaddrinfo(ai);
577                 }
578 #else
579                 struct hostent *hent;
580                 struct sockaddr_in sa;
581                 char **ap;
582                 static char addrbuf[HOST_NAME_MAX + 1];
583
584                 hent = gethostbyname(hostname);
585
586                 ap = hent->h_addr_list;
587                 memset(&sa, 0, sizeof sa);
588                 sa.sin_family = hent->h_addrtype;
589                 sa.sin_port = htons(0);
590                 memcpy(&sa.sin_addr, *ap, hent->h_length);
591
592                 inet_ntop(hent->h_addrtype, &sa.sin_addr,
593                           addrbuf, sizeof(addrbuf));
594
595                 free(canon_hostname);
596                 canon_hostname = xstrdup(hent->h_name);
597                 free(ip_address);
598                 ip_address = xstrdup(addrbuf);
599 #endif
600         }
601 }
602
603
604 static int execute(void)
605 {
606         char *line = packet_buffer;
607         int pktlen, len, i;
608         char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
609
610         if (addr)
611                 loginfo("Connection from %s:%s", addr, port);
612
613         alarm(init_timeout ? init_timeout : timeout);
614         pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
615         alarm(0);
616
617         len = strlen(line);
618         if (pktlen != len)
619                 loginfo("Extended attributes (%d bytes) exist <%.*s>",
620                         (int) pktlen - len,
621                         (int) pktlen - len, line + len + 1);
622         if (len && line[len-1] == '\n') {
623                 line[--len] = 0;
624                 pktlen--;
625         }
626
627         free(hostname);
628         free(canon_hostname);
629         free(ip_address);
630         free(tcp_port);
631         hostname = canon_hostname = ip_address = tcp_port = NULL;
632
633         if (len != pktlen)
634                 parse_host_arg(line + len + 1, pktlen - len - 1);
635
636         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
637                 struct daemon_service *s = &(daemon_service[i]);
638                 const char *arg;
639
640                 if (skip_prefix(line, "git-", &arg) &&
641                     skip_prefix(arg, s->name, &arg) &&
642                     *arg++ == ' ') {
643                         /*
644                          * Note: The directory here is probably context sensitive,
645                          * and might depend on the actual service being performed.
646                          */
647                         return run_service(arg, s);
648                 }
649         }
650
651         logerror("Protocol error: '%s'", line);
652         return -1;
653 }
654
655 static int addrcmp(const struct sockaddr_storage *s1,
656     const struct sockaddr_storage *s2)
657 {
658         const struct sockaddr *sa1 = (const struct sockaddr*) s1;
659         const struct sockaddr *sa2 = (const struct sockaddr*) s2;
660
661         if (sa1->sa_family != sa2->sa_family)
662                 return sa1->sa_family - sa2->sa_family;
663         if (sa1->sa_family == AF_INET)
664                 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
665                     &((struct sockaddr_in *)s2)->sin_addr,
666                     sizeof(struct in_addr));
667 #ifndef NO_IPV6
668         if (sa1->sa_family == AF_INET6)
669                 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
670                     &((struct sockaddr_in6 *)s2)->sin6_addr,
671                     sizeof(struct in6_addr));
672 #endif
673         return 0;
674 }
675
676 static int max_connections = 32;
677
678 static unsigned int live_children;
679
680 static struct child {
681         struct child *next;
682         struct child_process cld;
683         struct sockaddr_storage address;
684 } *firstborn;
685
686 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
687 {
688         struct child *newborn, **cradle;
689
690         newborn = xcalloc(1, sizeof(*newborn));
691         live_children++;
692         memcpy(&newborn->cld, cld, sizeof(*cld));
693         memcpy(&newborn->address, addr, addrlen);
694         for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
695                 if (!addrcmp(&(*cradle)->address, &newborn->address))
696                         break;
697         newborn->next = *cradle;
698         *cradle = newborn;
699 }
700
701 /*
702  * This gets called if the number of connections grows
703  * past "max_connections".
704  *
705  * We kill the newest connection from a duplicate IP.
706  */
707 static void kill_some_child(void)
708 {
709         const struct child *blanket, *next;
710
711         if (!(blanket = firstborn))
712                 return;
713
714         for (; (next = blanket->next); blanket = next)
715                 if (!addrcmp(&blanket->address, &next->address)) {
716                         kill(blanket->cld.pid, SIGTERM);
717                         break;
718                 }
719 }
720
721 static void check_dead_children(void)
722 {
723         int status;
724         pid_t pid;
725
726         struct child **cradle, *blanket;
727         for (cradle = &firstborn; (blanket = *cradle);)
728                 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
729                         const char *dead = "";
730                         if (status)
731                                 dead = " (with error)";
732                         loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
733
734                         /* remove the child */
735                         *cradle = blanket->next;
736                         live_children--;
737                         free(blanket);
738                 } else
739                         cradle = &blanket->next;
740 }
741
742 static char **cld_argv;
743 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
744 {
745         struct child_process cld = { NULL };
746         char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
747         char *env[] = { addrbuf, portbuf, NULL };
748
749         if (max_connections && live_children >= max_connections) {
750                 kill_some_child();
751                 sleep(1);  /* give it some time to die */
752                 check_dead_children();
753                 if (live_children >= max_connections) {
754                         close(incoming);
755                         logerror("Too many children, dropping connection");
756                         return;
757                 }
758         }
759
760         if (addr->sa_family == AF_INET) {
761                 struct sockaddr_in *sin_addr = (void *) addr;
762                 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
763                     sizeof(addrbuf) - 12);
764                 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
765                     ntohs(sin_addr->sin_port));
766 #ifndef NO_IPV6
767         } else if (addr->sa_family == AF_INET6) {
768                 struct sockaddr_in6 *sin6_addr = (void *) addr;
769
770                 char *buf = addrbuf + 12;
771                 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
772                 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
773                     sizeof(addrbuf) - 13);
774                 strcat(buf, "]");
775
776                 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
777                     ntohs(sin6_addr->sin6_port));
778 #endif
779         }
780
781         cld.env = (const char **)env;
782         cld.argv = (const char **)cld_argv;
783         cld.in = incoming;
784         cld.out = dup(incoming);
785
786         if (start_command(&cld))
787                 logerror("unable to fork");
788         else
789                 add_child(&cld, addr, addrlen);
790         close(incoming);
791 }
792
793 static void child_handler(int signo)
794 {
795         /*
796          * Otherwise empty handler because systemcalls will get interrupted
797          * upon signal receipt
798          * SysV needs the handler to be rearmed
799          */
800         signal(SIGCHLD, child_handler);
801 }
802
803 static int set_reuse_addr(int sockfd)
804 {
805         int on = 1;
806
807         if (!reuseaddr)
808                 return 0;
809         return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
810                           &on, sizeof(on));
811 }
812
813 struct socketlist {
814         int *list;
815         size_t nr;
816         size_t alloc;
817 };
818
819 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
820 {
821 #ifdef NO_IPV6
822         static char ip[INET_ADDRSTRLEN];
823 #else
824         static char ip[INET6_ADDRSTRLEN];
825 #endif
826
827         switch (family) {
828 #ifndef NO_IPV6
829         case AF_INET6:
830                 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
831                 break;
832 #endif
833         case AF_INET:
834                 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
835                 break;
836         default:
837                 strcpy(ip, "<unknown>");
838         }
839         return ip;
840 }
841
842 #ifndef NO_IPV6
843
844 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
845 {
846         int socknum = 0;
847         int maxfd = -1;
848         char pbuf[NI_MAXSERV];
849         struct addrinfo hints, *ai0, *ai;
850         int gai;
851         long flags;
852
853         sprintf(pbuf, "%d", listen_port);
854         memset(&hints, 0, sizeof(hints));
855         hints.ai_family = AF_UNSPEC;
856         hints.ai_socktype = SOCK_STREAM;
857         hints.ai_protocol = IPPROTO_TCP;
858         hints.ai_flags = AI_PASSIVE;
859
860         gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
861         if (gai) {
862                 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
863                 return 0;
864         }
865
866         for (ai = ai0; ai; ai = ai->ai_next) {
867                 int sockfd;
868
869                 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
870                 if (sockfd < 0)
871                         continue;
872                 if (sockfd >= FD_SETSIZE) {
873                         logerror("Socket descriptor too large");
874                         close(sockfd);
875                         continue;
876                 }
877
878 #ifdef IPV6_V6ONLY
879                 if (ai->ai_family == AF_INET6) {
880                         int on = 1;
881                         setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
882                                    &on, sizeof(on));
883                         /* Note: error is not fatal */
884                 }
885 #endif
886
887                 if (set_reuse_addr(sockfd)) {
888                         logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
889                         close(sockfd);
890                         continue;
891                 }
892
893                 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
894                         logerror("Could not bind to %s: %s",
895                                  ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
896                                  strerror(errno));
897                         close(sockfd);
898                         continue;       /* not fatal */
899                 }
900                 if (listen(sockfd, 5) < 0) {
901                         logerror("Could not listen to %s: %s",
902                                  ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
903                                  strerror(errno));
904                         close(sockfd);
905                         continue;       /* not fatal */
906                 }
907
908                 flags = fcntl(sockfd, F_GETFD, 0);
909                 if (flags >= 0)
910                         fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
911
912                 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
913                 socklist->list[socklist->nr++] = sockfd;
914                 socknum++;
915
916                 if (maxfd < sockfd)
917                         maxfd = sockfd;
918         }
919
920         freeaddrinfo(ai0);
921
922         return socknum;
923 }
924
925 #else /* NO_IPV6 */
926
927 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
928 {
929         struct sockaddr_in sin;
930         int sockfd;
931         long flags;
932
933         memset(&sin, 0, sizeof sin);
934         sin.sin_family = AF_INET;
935         sin.sin_port = htons(listen_port);
936
937         if (listen_addr) {
938                 /* Well, host better be an IP address here. */
939                 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
940                         return 0;
941         } else {
942                 sin.sin_addr.s_addr = htonl(INADDR_ANY);
943         }
944
945         sockfd = socket(AF_INET, SOCK_STREAM, 0);
946         if (sockfd < 0)
947                 return 0;
948
949         if (set_reuse_addr(sockfd)) {
950                 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
951                 close(sockfd);
952                 return 0;
953         }
954
955         if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
956                 logerror("Could not listen to %s: %s",
957                          ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
958                          strerror(errno));
959                 close(sockfd);
960                 return 0;
961         }
962
963         if (listen(sockfd, 5) < 0) {
964                 logerror("Could not listen to %s: %s",
965                          ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
966                          strerror(errno));
967                 close(sockfd);
968                 return 0;
969         }
970
971         flags = fcntl(sockfd, F_GETFD, 0);
972         if (flags >= 0)
973                 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
974
975         ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
976         socklist->list[socklist->nr++] = sockfd;
977         return 1;
978 }
979
980 #endif
981
982 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
983 {
984         if (!listen_addr->nr)
985                 setup_named_sock(NULL, listen_port, socklist);
986         else {
987                 int i, socknum;
988                 for (i = 0; i < listen_addr->nr; i++) {
989                         socknum = setup_named_sock(listen_addr->items[i].string,
990                                                    listen_port, socklist);
991
992                         if (socknum == 0)
993                                 logerror("unable to allocate any listen sockets for host %s on port %u",
994                                          listen_addr->items[i].string, listen_port);
995                 }
996         }
997 }
998
999 static int service_loop(struct socketlist *socklist)
1000 {
1001         struct pollfd *pfd;
1002         int i;
1003
1004         pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1005
1006         for (i = 0; i < socklist->nr; i++) {
1007                 pfd[i].fd = socklist->list[i];
1008                 pfd[i].events = POLLIN;
1009         }
1010
1011         signal(SIGCHLD, child_handler);
1012
1013         for (;;) {
1014                 int i;
1015
1016                 check_dead_children();
1017
1018                 if (poll(pfd, socklist->nr, -1) < 0) {
1019                         if (errno != EINTR) {
1020                                 logerror("Poll failed, resuming: %s",
1021                                       strerror(errno));
1022                                 sleep(1);
1023                         }
1024                         continue;
1025                 }
1026
1027                 for (i = 0; i < socklist->nr; i++) {
1028                         if (pfd[i].revents & POLLIN) {
1029                                 union {
1030                                         struct sockaddr sa;
1031                                         struct sockaddr_in sai;
1032 #ifndef NO_IPV6
1033                                         struct sockaddr_in6 sai6;
1034 #endif
1035                                 } ss;
1036                                 socklen_t sslen = sizeof(ss);
1037                                 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1038                                 if (incoming < 0) {
1039                                         switch (errno) {
1040                                         case EAGAIN:
1041                                         case EINTR:
1042                                         case ECONNABORTED:
1043                                                 continue;
1044                                         default:
1045                                                 die_errno("accept returned");
1046                                         }
1047                                 }
1048                                 handle(incoming, &ss.sa, sslen);
1049                         }
1050                 }
1051         }
1052 }
1053
1054 #ifdef NO_POSIX_GOODIES
1055
1056 struct credentials;
1057
1058 static void drop_privileges(struct credentials *cred)
1059 {
1060         /* nothing */
1061 }
1062
1063 static struct credentials *prepare_credentials(const char *user_name,
1064     const char *group_name)
1065 {
1066         die("--user not supported on this platform");
1067 }
1068
1069 #else
1070
1071 struct credentials {
1072         struct passwd *pass;
1073         gid_t gid;
1074 };
1075
1076 static void drop_privileges(struct credentials *cred)
1077 {
1078         if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1079             setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1080                 die("cannot drop privileges");
1081 }
1082
1083 static struct credentials *prepare_credentials(const char *user_name,
1084     const char *group_name)
1085 {
1086         static struct credentials c;
1087
1088         c.pass = getpwnam(user_name);
1089         if (!c.pass)
1090                 die("user not found - %s", user_name);
1091
1092         if (!group_name)
1093                 c.gid = c.pass->pw_gid;
1094         else {
1095                 struct group *group = getgrnam(group_name);
1096                 if (!group)
1097                         die("group not found - %s", group_name);
1098
1099                 c.gid = group->gr_gid;
1100         }
1101
1102         return &c;
1103 }
1104 #endif
1105
1106 #ifndef NO_DNSSD
1107 static void register_dnssd_addr(const char *listen_addr, int listen_port)
1108 {
1109         /* We can use if_nametoindex() to turn an interface name
1110            into an index, but how do we turn a listen_addr into
1111            an interface name? */
1112         unsigned if_idx = 0;
1113         DNSServiceErrorType err = DNSServiceRegister(&sdRef,
1114                         0, /* Default flags */
1115                         if_idx,
1116                         "git daemon", /* TODO customize */
1117                         "_git._tcp",
1118                         NULL, /* domain */
1119                         NULL, /* host */
1120                         listen_port,
1121                         0, NULL, /* TODO customize TXT */
1122                         NULL, NULL);
1123         if (err != kDNSServiceErr_NoError)
1124                 logerror("failed to register service on DNS-SD (%d)\n", err);
1125         else
1126                 loginfo("registered git service for port %d on DNS-SD\n",
1127                         listen_port);
1128 }
1129
1130 static void dnssd_register(struct string_list *listen_addr, int listen_port)
1131 {
1132         if (!listen_addr->nr)
1133                 register_dnssd_addr("", listen_port);
1134         else {
1135                 int i;
1136                 for (i = 0; i < listen_addr->nr; ++i) {
1137                         register_dnssd_addr(listen_addr->items[i].string,
1138                                             listen_port);
1139                 }
1140         }
1141 }
1142
1143 static void dnssd_unregister(void)
1144 {
1145         DNSServiceRefDeallocate(sdRef);
1146         sdRef = NULL;
1147 }
1148 #else
1149 static void dnssd_register(struct string_list *listen_addr, int listen_port)
1150 {};
1151 static void dnssd_unregister(void)
1152 {};
1153 #endif
1154
1155 static void store_pid(const char *path)
1156 {
1157         FILE *f = fopen(path, "w");
1158         if (!f)
1159                 die_errno("cannot open pid file '%s'", path);
1160         if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1161                 die_errno("failed to write pid file '%s'", path);
1162 }
1163
1164 static int serve(struct string_list *listen_addr, int listen_port,
1165     struct credentials *cred)
1166 {
1167         struct socketlist socklist = { NULL, 0, 0 };
1168
1169         socksetup(listen_addr, listen_port, &socklist);
1170         if (socklist.nr == 0)
1171                 die("unable to allocate any listen sockets on port %u",
1172                     listen_port);
1173
1174         drop_privileges(cred);
1175
1176         dnssd_register(listen_addr, listen_port);
1177
1178         loginfo("Ready to rumble");
1179
1180         return service_loop(&socklist);
1181 }
1182
1183 int main(int argc, char **argv)
1184 {
1185         int listen_port = 0;
1186         struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1187         int serve_mode = 0, inetd_mode = 0;
1188         const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1189         int detach = 0;
1190         struct credentials *cred = NULL;
1191         int i;
1192
1193         git_setup_gettext();
1194
1195         git_extract_argv0_path(argv[0]);
1196
1197         for (i = 1; i < argc; i++) {
1198                 char *arg = argv[i];
1199                 const char *v;
1200
1201                 if (skip_prefix(arg, "--listen=", &v)) {
1202                         string_list_append(&listen_addr, xstrdup_tolower(v));
1203                         continue;
1204                 }
1205                 if (skip_prefix(arg, "--port=", &v)) {
1206                         char *end;
1207                         unsigned long n;
1208                         n = strtoul(v, &end, 0);
1209                         if (*v && !*end) {
1210                                 listen_port = n;
1211                                 continue;
1212                         }
1213                 }
1214                 if (!strcmp(arg, "--serve")) {
1215                         serve_mode = 1;
1216                         continue;
1217                 }
1218                 if (!strcmp(arg, "--inetd")) {
1219                         inetd_mode = 1;
1220                         log_syslog = 1;
1221                         continue;
1222                 }
1223                 if (!strcmp(arg, "--verbose")) {
1224                         verbose = 1;
1225                         continue;
1226                 }
1227                 if (!strcmp(arg, "--syslog")) {
1228                         log_syslog = 1;
1229                         continue;
1230                 }
1231                 if (!strcmp(arg, "--export-all")) {
1232                         export_all_trees = 1;
1233                         continue;
1234                 }
1235                 if (skip_prefix(arg, "--access-hook=", &v)) {
1236                         access_hook = v;
1237                         continue;
1238                 }
1239                 if (skip_prefix(arg, "--timeout=", &v)) {
1240                         timeout = atoi(v);
1241                         continue;
1242                 }
1243                 if (skip_prefix(arg, "--init-timeout=", &v)) {
1244                         init_timeout = atoi(v);
1245                         continue;
1246                 }
1247                 if (skip_prefix(arg, "--max-connections=", &v)) {
1248                         max_connections = atoi(v);
1249                         if (max_connections < 0)
1250                                 max_connections = 0;            /* unlimited */
1251                         continue;
1252                 }
1253                 if (!strcmp(arg, "--strict-paths")) {
1254                         strict_paths = 1;
1255                         continue;
1256                 }
1257                 if (skip_prefix(arg, "--base-path=", &v)) {
1258                         base_path = v;
1259                         continue;
1260                 }
1261                 if (!strcmp(arg, "--base-path-relaxed")) {
1262                         base_path_relaxed = 1;
1263                         continue;
1264                 }
1265                 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1266                         interpolated_path = v;
1267                         continue;
1268                 }
1269                 if (!strcmp(arg, "--reuseaddr")) {
1270                         reuseaddr = 1;
1271                         continue;
1272                 }
1273                 if (!strcmp(arg, "--user-path")) {
1274                         user_path = "";
1275                         continue;
1276                 }
1277                 if (skip_prefix(arg, "--user-path=", &v)) {
1278                         user_path = v;
1279                         continue;
1280                 }
1281                 if (skip_prefix(arg, "--pid-file=", &v)) {
1282                         pid_file = v;
1283                         continue;
1284                 }
1285                 if (!strcmp(arg, "--detach")) {
1286                         detach = 1;
1287                         log_syslog = 1;
1288                         continue;
1289                 }
1290                 if (skip_prefix(arg, "--user=", &v)) {
1291                         user_name = v;
1292                         continue;
1293                 }
1294                 if (skip_prefix(arg, "--group=", &v)) {
1295                         group_name = v;
1296                         continue;
1297                 }
1298                 if (skip_prefix(arg, "--enable=", &v)) {
1299                         enable_service(v, 1);
1300                         continue;
1301                 }
1302                 if (skip_prefix(arg, "--disable=", &v)) {
1303                         enable_service(v, 0);
1304                         continue;
1305                 }
1306                 if (skip_prefix(arg, "--allow-override=", &v)) {
1307                         make_service_overridable(v, 1);
1308                         continue;
1309                 }
1310                 if (skip_prefix(arg, "--forbid-override=", &v)) {
1311                         make_service_overridable(v, 0);
1312                         continue;
1313                 }
1314                 if (!strcmp(arg, "--informative-errors")) {
1315                         informative_errors = 1;
1316                         continue;
1317                 }
1318                 if (!strcmp(arg, "--no-informative-errors")) {
1319                         informative_errors = 0;
1320                         continue;
1321                 }
1322                 if (!strcmp(arg, "--")) {
1323                         ok_paths = &argv[i+1];
1324                         break;
1325                 } else if (arg[0] != '-') {
1326                         ok_paths = &argv[i];
1327                         break;
1328                 }
1329
1330                 usage(daemon_usage);
1331         }
1332
1333         if (log_syslog) {
1334                 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1335                 set_die_routine(daemon_die);
1336         } else
1337                 /* avoid splitting a message in the middle */
1338                 setvbuf(stderr, NULL, _IOFBF, 4096);
1339
1340         if (inetd_mode && (detach || group_name || user_name))
1341                 die("--detach, --user and --group are incompatible with --inetd");
1342
1343         if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1344                 die("--listen= and --port= are incompatible with --inetd");
1345         else if (listen_port == 0)
1346                 listen_port = DEFAULT_GIT_PORT;
1347
1348         if (group_name && !user_name)
1349                 die("--group supplied without --user");
1350
1351         if (user_name)
1352                 cred = prepare_credentials(user_name, group_name);
1353
1354         if (strict_paths && (!ok_paths || !*ok_paths))
1355                 die("option --strict-paths requires a whitelist");
1356
1357         if (base_path && !is_directory(base_path))
1358                 die("base-path '%s' does not exist or is not a directory",
1359                     base_path);
1360
1361         if (inetd_mode) {
1362                 if (!freopen("/dev/null", "w", stderr))
1363                         die_errno("failed to redirect stderr to /dev/null");
1364         }
1365
1366         if (inetd_mode || serve_mode)
1367                 return execute();
1368
1369         if (detach) {
1370                 if (daemonize())
1371                         die("--detach not supported on this platform");
1372         } else
1373                 sanitize_stdfds();
1374
1375         if (pid_file)
1376                 store_pid(pid_file);
1377
1378         /* prepare argv for serving-processes */
1379         cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1380         cld_argv[0] = argv[0];  /* git-daemon */
1381         cld_argv[1] = "--serve";
1382         for (i = 1; i < argc; ++i)
1383                 cld_argv[i+1] = argv[i];
1384         cld_argv[argc+1] = NULL;
1385
1386         return serve(&listen_addr, listen_port, cred);
1387 }