Merge branch 'jc/mention-tracking-for-pull-default'
[git.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 HOST_NAME_MAX
9 #define HOST_NAME_MAX 256
10 #endif
11
12 #ifndef NI_MAXSERV
13 #define NI_MAXSERV 32
14 #endif
15
16 #ifdef NO_INITGROUPS
17 #define initgroups(x, y) (0) /* nothing */
18 #endif
19
20 static int log_syslog;
21 static int verbose;
22 static int reuseaddr;
23 static int informative_errors;
24
25 static const char daemon_usage[] =
26 "git daemon [--verbose] [--syslog] [--export-all]\n"
27 "           [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
28 "           [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
29 "           [--user-path | --user-path=<path>]\n"
30 "           [--interpolated-path=<path>]\n"
31 "           [--reuseaddr] [--pid-file=<file>]\n"
32 "           [--(enable|disable|allow-override|forbid-override)=<service>]\n"
33 "           [--access-hook=<path>]\n"
34 "           [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
35 "                      [--detach] [--user=<user> [--group=<group>]]\n"
36 "           [<directory>...]";
37
38 /* List of acceptable pathname prefixes */
39 static char **ok_paths;
40 static int strict_paths;
41
42 /* If this is set, git-daemon-export-ok is not required */
43 static int export_all_trees;
44
45 /* Take all paths relative to this one if non-NULL */
46 static char *base_path;
47 static char *interpolated_path;
48 static int base_path_relaxed;
49
50 /* Flag indicating client sent extra args. */
51 static int saw_extended_args;
52
53 /* If defined, ~user notation is allowed and the string is inserted
54  * after ~user/.  E.g. a request to git://host/~alice/frotz would
55  * go to /home/alice/pub_git/frotz with --user-path=pub_git.
56  */
57 static const char *user_path;
58
59 /* Timeout, and initial timeout */
60 static unsigned int timeout;
61 static unsigned int init_timeout;
62
63 static char *hostname;
64 static char *canon_hostname;
65 static char *ip_address;
66 static char *tcp_port;
67
68 static void logreport(int priority, const char *err, va_list params)
69 {
70         if (log_syslog) {
71                 char buf[1024];
72                 vsnprintf(buf, sizeof(buf), err, params);
73                 syslog(priority, "%s", buf);
74         } else {
75                 /*
76                  * Since stderr is set to buffered mode, the
77                  * logging of different processes will not overlap
78                  * unless they overflow the (rather big) buffers.
79                  */
80                 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
81                 vfprintf(stderr, err, params);
82                 fputc('\n', stderr);
83                 fflush(stderr);
84         }
85 }
86
87 __attribute__((format (printf, 1, 2)))
88 static void logerror(const char *err, ...)
89 {
90         va_list params;
91         va_start(params, err);
92         logreport(LOG_ERR, err, params);
93         va_end(params);
94 }
95
96 __attribute__((format (printf, 1, 2)))
97 static void loginfo(const char *err, ...)
98 {
99         va_list params;
100         if (!verbose)
101                 return;
102         va_start(params, err);
103         logreport(LOG_INFO, err, params);
104         va_end(params);
105 }
106
107 static void NORETURN daemon_die(const char *err, va_list params)
108 {
109         logreport(LOG_ERR, err, params);
110         exit(1);
111 }
112
113 static const char *path_ok(char *directory)
114 {
115         static char rpath[PATH_MAX];
116         static char interp_path[PATH_MAX];
117         const char *path;
118         char *dir;
119
120         dir = directory;
121
122         if (daemon_avoid_alias(dir)) {
123                 logerror("'%s': aliased", dir);
124                 return NULL;
125         }
126
127         if (*dir == '~') {
128                 if (!user_path) {
129                         logerror("'%s': User-path not allowed", dir);
130                         return NULL;
131                 }
132                 if (*user_path) {
133                         /* Got either "~alice" or "~alice/foo";
134                          * rewrite them to "~alice/%s" or
135                          * "~alice/%s/foo".
136                          */
137                         int namlen, restlen = strlen(dir);
138                         char *slash = strchr(dir, '/');
139                         if (!slash)
140                                 slash = dir + restlen;
141                         namlen = slash - dir;
142                         restlen -= namlen;
143                         loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
144                         snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
145                                  namlen, dir, user_path, restlen, slash);
146                         dir = rpath;
147                 }
148         }
149         else if (interpolated_path && saw_extended_args) {
150                 struct strbuf expanded_path = STRBUF_INIT;
151                 struct strbuf_expand_dict_entry dict[6];
152
153                 dict[0].placeholder = "H"; dict[0].value = hostname;
154                 dict[1].placeholder = "CH"; dict[1].value = canon_hostname;
155                 dict[2].placeholder = "IP"; dict[2].value = ip_address;
156                 dict[3].placeholder = "P"; dict[3].value = tcp_port;
157                 dict[4].placeholder = "D"; dict[4].value = directory;
158                 dict[5].placeholder = NULL; dict[5].value = NULL;
159                 if (*dir != '/') {
160                         /* Allow only absolute */
161                         logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
162                         return NULL;
163                 }
164
165                 strbuf_expand(&expanded_path, interpolated_path,
166                                 strbuf_expand_dict_cb, &dict);
167                 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
168                 strbuf_release(&expanded_path);
169                 loginfo("Interpolated dir '%s'", interp_path);
170
171                 dir = interp_path;
172         }
173         else if (base_path) {
174                 if (*dir != '/') {
175                         /* Allow only absolute */
176                         logerror("'%s': Non-absolute path denied (base-path active)", dir);
177                         return NULL;
178                 }
179                 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
180                 dir = rpath;
181         }
182
183         path = enter_repo(dir, strict_paths);
184         if (!path && base_path && base_path_relaxed) {
185                 /*
186                  * if we fail and base_path_relaxed is enabled, try without
187                  * prefixing the base path
188                  */
189                 dir = directory;
190                 path = enter_repo(dir, strict_paths);
191         }
192
193         if (!path) {
194                 logerror("'%s' does not appear to be a git repository", dir);
195                 return NULL;
196         }
197
198         if ( ok_paths && *ok_paths ) {
199                 char **pp;
200                 int pathlen = strlen(path);
201
202                 /* The validation is done on the paths after enter_repo
203                  * appends optional {.git,.git/.git} and friends, but
204                  * it does not use getcwd().  So if your /pub is
205                  * a symlink to /mnt/pub, you can whitelist /pub and
206                  * do not have to say /mnt/pub.
207                  * Do not say /pub/.
208                  */
209                 for ( pp = ok_paths ; *pp ; pp++ ) {
210                         int len = strlen(*pp);
211                         if (len <= pathlen &&
212                             !memcmp(*pp, path, len) &&
213                             (path[len] == '\0' ||
214                              (!strict_paths && path[len] == '/')))
215                                 return path;
216                 }
217         }
218         else {
219                 /* be backwards compatible */
220                 if (!strict_paths)
221                         return path;
222         }
223
224         logerror("'%s': not in whitelist", path);
225         return NULL;            /* Fallthrough. Deny by default */
226 }
227
228 typedef int (*daemon_service_fn)(void);
229 struct daemon_service {
230         const char *name;
231         const char *config_name;
232         daemon_service_fn fn;
233         int enabled;
234         int overridable;
235 };
236
237 static struct daemon_service *service_looking_at;
238 static int service_enabled;
239
240 static int git_daemon_config(const char *var, const char *value, void *cb)
241 {
242         if (!prefixcmp(var, "daemon.") &&
243             !strcmp(var + 7, service_looking_at->config_name)) {
244                 service_enabled = git_config_bool(var, value);
245                 return 0;
246         }
247
248         /* we are not interested in parsing any other configuration here */
249         return 0;
250 }
251
252 static int daemon_error(const char *dir, const char *msg)
253 {
254         if (!informative_errors)
255                 msg = "access denied or repository not exported";
256         packet_write(1, "ERR %s: %s", msg, dir);
257         return -1;
258 }
259
260 static char *access_hook;
261
262 static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
263 {
264         struct child_process child;
265         struct strbuf buf = STRBUF_INIT;
266         const char *argv[8];
267         const char **arg = argv;
268         char *eol;
269         int seen_errors = 0;
270
271 #define STRARG(x) ((x) ? (x) : "")
272         *arg++ = access_hook;
273         *arg++ = service->name;
274         *arg++ = path;
275         *arg++ = STRARG(hostname);
276         *arg++ = STRARG(canon_hostname);
277         *arg++ = STRARG(ip_address);
278         *arg++ = STRARG(tcp_port);
279         *arg = NULL;
280 #undef STRARG
281
282         memset(&child, 0, sizeof(child));
283         child.use_shell = 1;
284         child.argv = argv;
285         child.no_stdin = 1;
286         child.no_stderr = 1;
287         child.out = -1;
288         if (start_command(&child)) {
289                 logerror("daemon access hook '%s' failed to start",
290                          access_hook);
291                 goto error_return;
292         }
293         if (strbuf_read(&buf, child.out, 0) < 0) {
294                 logerror("failed to read from pipe to daemon access hook '%s'",
295                          access_hook);
296                 strbuf_reset(&buf);
297                 seen_errors = 1;
298         }
299         if (close(child.out) < 0) {
300                 logerror("failed to close pipe to daemon access hook '%s'",
301                          access_hook);
302                 seen_errors = 1;
303         }
304         if (finish_command(&child))
305                 seen_errors = 1;
306
307         if (!seen_errors) {
308                 strbuf_release(&buf);
309                 return 0;
310         }
311
312 error_return:
313         strbuf_ltrim(&buf);
314         if (!buf.len)
315                 strbuf_addstr(&buf, "service rejected");
316         eol = strchr(buf.buf, '\n');
317         if (eol)
318                 *eol = '\0';
319         errno = EACCES;
320         daemon_error(dir, buf.buf);
321         strbuf_release(&buf);
322         return -1;
323 }
324
325 static int run_service(char *dir, struct daemon_service *service)
326 {
327         const char *path;
328         int enabled = service->enabled;
329
330         loginfo("Request %s for '%s'", service->name, dir);
331
332         if (!enabled && !service->overridable) {
333                 logerror("'%s': service not enabled.", service->name);
334                 errno = EACCES;
335                 return daemon_error(dir, "service not enabled");
336         }
337
338         if (!(path = path_ok(dir)))
339                 return daemon_error(dir, "no such repository");
340
341         /*
342          * Security on the cheap.
343          *
344          * We want a readable HEAD, usable "objects" directory, and
345          * a "git-daemon-export-ok" flag that says that the other side
346          * is ok with us doing this.
347          *
348          * path_ok() uses enter_repo() and does whitelist checking.
349          * We only need to make sure the repository is exported.
350          */
351
352         if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
353                 logerror("'%s': repository not exported.", path);
354                 errno = EACCES;
355                 return daemon_error(dir, "repository not exported");
356         }
357
358         if (service->overridable) {
359                 service_looking_at = service;
360                 service_enabled = -1;
361                 git_config(git_daemon_config, NULL);
362                 if (0 <= service_enabled)
363                         enabled = service_enabled;
364         }
365         if (!enabled) {
366                 logerror("'%s': service not enabled for '%s'",
367                          service->name, path);
368                 errno = EACCES;
369                 return daemon_error(dir, "service not enabled");
370         }
371
372         /*
373          * Optionally, a hook can choose to deny access to the
374          * repository depending on the phase of the moon.
375          */
376         if (access_hook && run_access_hook(service, dir, path))
377                 return -1;
378
379         /*
380          * We'll ignore SIGTERM from now on, we have a
381          * good client.
382          */
383         signal(SIGTERM, SIG_IGN);
384
385         return service->fn();
386 }
387
388 static void copy_to_log(int fd)
389 {
390         struct strbuf line = STRBUF_INIT;
391         FILE *fp;
392
393         fp = fdopen(fd, "r");
394         if (fp == NULL) {
395                 logerror("fdopen of error channel failed");
396                 close(fd);
397                 return;
398         }
399
400         while (strbuf_getline(&line, fp, '\n') != EOF) {
401                 logerror("%s", line.buf);
402                 strbuf_setlen(&line, 0);
403         }
404
405         strbuf_release(&line);
406         fclose(fp);
407 }
408
409 static int run_service_command(const char **argv)
410 {
411         struct child_process cld;
412
413         memset(&cld, 0, sizeof(cld));
414         cld.argv = argv;
415         cld.git_cmd = 1;
416         cld.err = -1;
417         if (start_command(&cld))
418                 return -1;
419
420         close(0);
421         close(1);
422
423         copy_to_log(cld.err);
424
425         return finish_command(&cld);
426 }
427
428 static int upload_pack(void)
429 {
430         /* Timeout as string */
431         char timeout_buf[64];
432         const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
433
434         argv[2] = timeout_buf;
435
436         snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
437         return run_service_command(argv);
438 }
439
440 static int upload_archive(void)
441 {
442         static const char *argv[] = { "upload-archive", ".", NULL };
443         return run_service_command(argv);
444 }
445
446 static int receive_pack(void)
447 {
448         static const char *argv[] = { "receive-pack", ".", NULL };
449         return run_service_command(argv);
450 }
451
452 static struct daemon_service daemon_service[] = {
453         { "upload-archive", "uploadarch", upload_archive, 0, 1 },
454         { "upload-pack", "uploadpack", upload_pack, 1, 1 },
455         { "receive-pack", "receivepack", receive_pack, 0, 1 },
456 };
457
458 static void enable_service(const char *name, int ena)
459 {
460         int i;
461         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
462                 if (!strcmp(daemon_service[i].name, name)) {
463                         daemon_service[i].enabled = ena;
464                         return;
465                 }
466         }
467         die("No such service %s", name);
468 }
469
470 static void make_service_overridable(const char *name, int ena)
471 {
472         int i;
473         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
474                 if (!strcmp(daemon_service[i].name, name)) {
475                         daemon_service[i].overridable = ena;
476                         return;
477                 }
478         }
479         die("No such service %s", name);
480 }
481
482 static char *xstrdup_tolower(const char *str)
483 {
484         char *p, *dup = xstrdup(str);
485         for (p = dup; *p; p++)
486                 *p = tolower(*p);
487         return dup;
488 }
489
490 static void parse_host_and_port(char *hostport, char **host,
491         char **port)
492 {
493         if (*hostport == '[') {
494                 char *end;
495
496                 end = strchr(hostport, ']');
497                 if (!end)
498                         die("Invalid request ('[' without ']')");
499                 *end = '\0';
500                 *host = hostport + 1;
501                 if (!end[1])
502                         *port = NULL;
503                 else if (end[1] == ':')
504                         *port = end + 2;
505                 else
506                         die("Garbage after end of host part");
507         } else {
508                 *host = hostport;
509                 *port = strrchr(hostport, ':');
510                 if (*port) {
511                         **port = '\0';
512                         ++*port;
513                 }
514         }
515 }
516
517 /*
518  * Read the host as supplied by the client connection.
519  */
520 static void parse_host_arg(char *extra_args, int buflen)
521 {
522         char *val;
523         int vallen;
524         char *end = extra_args + buflen;
525
526         if (extra_args < end && *extra_args) {
527                 saw_extended_args = 1;
528                 if (strncasecmp("host=", extra_args, 5) == 0) {
529                         val = extra_args + 5;
530                         vallen = strlen(val) + 1;
531                         if (*val) {
532                                 /* Split <host>:<port> at colon. */
533                                 char *host;
534                                 char *port;
535                                 parse_host_and_port(val, &host, &port);
536                                 if (port) {
537                                         free(tcp_port);
538                                         tcp_port = xstrdup(port);
539                                 }
540                                 free(hostname);
541                                 hostname = xstrdup_tolower(host);
542                         }
543
544                         /* On to the next one */
545                         extra_args = val + vallen;
546                 }
547                 if (extra_args < end && *extra_args)
548                         die("Invalid request");
549         }
550
551         /*
552          * Locate canonical hostname and its IP address.
553          */
554         if (hostname) {
555 #ifndef NO_IPV6
556                 struct addrinfo hints;
557                 struct addrinfo *ai;
558                 int gai;
559                 static char addrbuf[HOST_NAME_MAX + 1];
560
561                 memset(&hints, 0, sizeof(hints));
562                 hints.ai_flags = AI_CANONNAME;
563
564                 gai = getaddrinfo(hostname, NULL, &hints, &ai);
565                 if (!gai) {
566                         struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
567
568                         inet_ntop(AF_INET, &sin_addr->sin_addr,
569                                   addrbuf, sizeof(addrbuf));
570                         free(ip_address);
571                         ip_address = xstrdup(addrbuf);
572
573                         free(canon_hostname);
574                         canon_hostname = xstrdup(ai->ai_canonname ?
575                                                  ai->ai_canonname : ip_address);
576
577                         freeaddrinfo(ai);
578                 }
579 #else
580                 struct hostent *hent;
581                 struct sockaddr_in sa;
582                 char **ap;
583                 static char addrbuf[HOST_NAME_MAX + 1];
584
585                 hent = gethostbyname(hostname);
586
587                 ap = hent->h_addr_list;
588                 memset(&sa, 0, sizeof sa);
589                 sa.sin_family = hent->h_addrtype;
590                 sa.sin_port = htons(0);
591                 memcpy(&sa.sin_addr, *ap, hent->h_length);
592
593                 inet_ntop(hent->h_addrtype, &sa.sin_addr,
594                           addrbuf, sizeof(addrbuf));
595
596                 free(canon_hostname);
597                 canon_hostname = xstrdup(hent->h_name);
598                 free(ip_address);
599                 ip_address = xstrdup(addrbuf);
600 #endif
601         }
602 }
603
604
605 static int execute(void)
606 {
607         static char line[1000];
608         int pktlen, len, i;
609         char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
610
611         if (addr)
612                 loginfo("Connection from %s:%s", addr, port);
613
614         alarm(init_timeout ? init_timeout : timeout);
615         pktlen = packet_read_line(0, line, sizeof(line));
616         alarm(0);
617
618         len = strlen(line);
619         if (pktlen != len)
620                 loginfo("Extended attributes (%d bytes) exist <%.*s>",
621                         (int) pktlen - len,
622                         (int) pktlen - len, line + len + 1);
623         if (len && line[len-1] == '\n') {
624                 line[--len] = 0;
625                 pktlen--;
626         }
627
628         free(hostname);
629         free(canon_hostname);
630         free(ip_address);
631         free(tcp_port);
632         hostname = canon_hostname = ip_address = tcp_port = NULL;
633
634         if (len != pktlen)
635                 parse_host_arg(line + len + 1, pktlen - len - 1);
636
637         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
638                 struct daemon_service *s = &(daemon_service[i]);
639                 int namelen = strlen(s->name);
640                 if (!prefixcmp(line, "git-") &&
641                     !strncmp(s->name, line + 4, namelen) &&
642                     line[namelen + 4] == ' ') {
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(line + namelen + 5, 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 && 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 /* if any standard file descriptor is missing open it to /dev/null */
1055 static void sanitize_stdfds(void)
1056 {
1057         int fd = open("/dev/null", O_RDWR, 0);
1058         while (fd != -1 && fd < 2)
1059                 fd = dup(fd);
1060         if (fd == -1)
1061                 die_errno("open /dev/null or dup failed");
1062         if (fd > 2)
1063                 close(fd);
1064 }
1065
1066 #ifdef NO_POSIX_GOODIES
1067
1068 struct credentials;
1069
1070 static void drop_privileges(struct credentials *cred)
1071 {
1072         /* nothing */
1073 }
1074
1075 static void daemonize(void)
1076 {
1077         die("--detach not supported on this platform");
1078 }
1079
1080 static struct credentials *prepare_credentials(const char *user_name,
1081     const char *group_name)
1082 {
1083         die("--user not supported on this platform");
1084 }
1085
1086 #else
1087
1088 struct credentials {
1089         struct passwd *pass;
1090         gid_t gid;
1091 };
1092
1093 static void drop_privileges(struct credentials *cred)
1094 {
1095         if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1096             setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1097                 die("cannot drop privileges");
1098 }
1099
1100 static struct credentials *prepare_credentials(const char *user_name,
1101     const char *group_name)
1102 {
1103         static struct credentials c;
1104
1105         c.pass = getpwnam(user_name);
1106         if (!c.pass)
1107                 die("user not found - %s", user_name);
1108
1109         if (!group_name)
1110                 c.gid = c.pass->pw_gid;
1111         else {
1112                 struct group *group = getgrnam(group_name);
1113                 if (!group)
1114                         die("group not found - %s", group_name);
1115
1116                 c.gid = group->gr_gid;
1117         }
1118
1119         return &c;
1120 }
1121
1122 static void daemonize(void)
1123 {
1124         switch (fork()) {
1125                 case 0:
1126                         break;
1127                 case -1:
1128                         die_errno("fork failed");
1129                 default:
1130                         exit(0);
1131         }
1132         if (setsid() == -1)
1133                 die_errno("setsid failed");
1134         close(0);
1135         close(1);
1136         close(2);
1137         sanitize_stdfds();
1138 }
1139 #endif
1140
1141 static void store_pid(const char *path)
1142 {
1143         FILE *f = fopen(path, "w");
1144         if (!f)
1145                 die_errno("cannot open pid file '%s'", path);
1146         if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1147                 die_errno("failed to write pid file '%s'", path);
1148 }
1149
1150 static int serve(struct string_list *listen_addr, int listen_port,
1151     struct credentials *cred)
1152 {
1153         struct socketlist socklist = { NULL, 0, 0 };
1154
1155         socksetup(listen_addr, listen_port, &socklist);
1156         if (socklist.nr == 0)
1157                 die("unable to allocate any listen sockets on port %u",
1158                     listen_port);
1159
1160         drop_privileges(cred);
1161
1162         loginfo("Ready to rumble");
1163
1164         return service_loop(&socklist);
1165 }
1166
1167 int main(int argc, char **argv)
1168 {
1169         int listen_port = 0;
1170         struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1171         int serve_mode = 0, inetd_mode = 0;
1172         const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1173         int detach = 0;
1174         struct credentials *cred = NULL;
1175         int i;
1176
1177         git_setup_gettext();
1178
1179         git_extract_argv0_path(argv[0]);
1180
1181         for (i = 1; i < argc; i++) {
1182                 char *arg = argv[i];
1183
1184                 if (!prefixcmp(arg, "--listen=")) {
1185                         string_list_append(&listen_addr, xstrdup_tolower(arg + 9));
1186                         continue;
1187                 }
1188                 if (!prefixcmp(arg, "--port=")) {
1189                         char *end;
1190                         unsigned long n;
1191                         n = strtoul(arg+7, &end, 0);
1192                         if (arg[7] && !*end) {
1193                                 listen_port = n;
1194                                 continue;
1195                         }
1196                 }
1197                 if (!strcmp(arg, "--serve")) {
1198                         serve_mode = 1;
1199                         continue;
1200                 }
1201                 if (!strcmp(arg, "--inetd")) {
1202                         inetd_mode = 1;
1203                         log_syslog = 1;
1204                         continue;
1205                 }
1206                 if (!strcmp(arg, "--verbose")) {
1207                         verbose = 1;
1208                         continue;
1209                 }
1210                 if (!strcmp(arg, "--syslog")) {
1211                         log_syslog = 1;
1212                         continue;
1213                 }
1214                 if (!strcmp(arg, "--export-all")) {
1215                         export_all_trees = 1;
1216                         continue;
1217                 }
1218                 if (!prefixcmp(arg, "--access-hook=")) {
1219                         access_hook = arg + 14;
1220                         continue;
1221                 }
1222                 if (!prefixcmp(arg, "--timeout=")) {
1223                         timeout = atoi(arg+10);
1224                         continue;
1225                 }
1226                 if (!prefixcmp(arg, "--init-timeout=")) {
1227                         init_timeout = atoi(arg+15);
1228                         continue;
1229                 }
1230                 if (!prefixcmp(arg, "--max-connections=")) {
1231                         max_connections = atoi(arg+18);
1232                         if (max_connections < 0)
1233                                 max_connections = 0;            /* unlimited */
1234                         continue;
1235                 }
1236                 if (!strcmp(arg, "--strict-paths")) {
1237                         strict_paths = 1;
1238                         continue;
1239                 }
1240                 if (!prefixcmp(arg, "--base-path=")) {
1241                         base_path = arg+12;
1242                         continue;
1243                 }
1244                 if (!strcmp(arg, "--base-path-relaxed")) {
1245                         base_path_relaxed = 1;
1246                         continue;
1247                 }
1248                 if (!prefixcmp(arg, "--interpolated-path=")) {
1249                         interpolated_path = arg+20;
1250                         continue;
1251                 }
1252                 if (!strcmp(arg, "--reuseaddr")) {
1253                         reuseaddr = 1;
1254                         continue;
1255                 }
1256                 if (!strcmp(arg, "--user-path")) {
1257                         user_path = "";
1258                         continue;
1259                 }
1260                 if (!prefixcmp(arg, "--user-path=")) {
1261                         user_path = arg + 12;
1262                         continue;
1263                 }
1264                 if (!prefixcmp(arg, "--pid-file=")) {
1265                         pid_file = arg + 11;
1266                         continue;
1267                 }
1268                 if (!strcmp(arg, "--detach")) {
1269                         detach = 1;
1270                         log_syslog = 1;
1271                         continue;
1272                 }
1273                 if (!prefixcmp(arg, "--user=")) {
1274                         user_name = arg + 7;
1275                         continue;
1276                 }
1277                 if (!prefixcmp(arg, "--group=")) {
1278                         group_name = arg + 8;
1279                         continue;
1280                 }
1281                 if (!prefixcmp(arg, "--enable=")) {
1282                         enable_service(arg + 9, 1);
1283                         continue;
1284                 }
1285                 if (!prefixcmp(arg, "--disable=")) {
1286                         enable_service(arg + 10, 0);
1287                         continue;
1288                 }
1289                 if (!prefixcmp(arg, "--allow-override=")) {
1290                         make_service_overridable(arg + 17, 1);
1291                         continue;
1292                 }
1293                 if (!prefixcmp(arg, "--forbid-override=")) {
1294                         make_service_overridable(arg + 18, 0);
1295                         continue;
1296                 }
1297                 if (!prefixcmp(arg, "--informative-errors")) {
1298                         informative_errors = 1;
1299                         continue;
1300                 }
1301                 if (!prefixcmp(arg, "--no-informative-errors")) {
1302                         informative_errors = 0;
1303                         continue;
1304                 }
1305                 if (!strcmp(arg, "--")) {
1306                         ok_paths = &argv[i+1];
1307                         break;
1308                 } else if (arg[0] != '-') {
1309                         ok_paths = &argv[i];
1310                         break;
1311                 }
1312
1313                 usage(daemon_usage);
1314         }
1315
1316         if (log_syslog) {
1317                 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1318                 set_die_routine(daemon_die);
1319         } else
1320                 /* avoid splitting a message in the middle */
1321                 setvbuf(stderr, NULL, _IOFBF, 4096);
1322
1323         if (inetd_mode && (detach || group_name || user_name))
1324                 die("--detach, --user and --group are incompatible with --inetd");
1325
1326         if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1327                 die("--listen= and --port= are incompatible with --inetd");
1328         else if (listen_port == 0)
1329                 listen_port = DEFAULT_GIT_PORT;
1330
1331         if (group_name && !user_name)
1332                 die("--group supplied without --user");
1333
1334         if (user_name)
1335                 cred = prepare_credentials(user_name, group_name);
1336
1337         if (strict_paths && (!ok_paths || !*ok_paths))
1338                 die("option --strict-paths requires a whitelist");
1339
1340         if (base_path && !is_directory(base_path))
1341                 die("base-path '%s' does not exist or is not a directory",
1342                     base_path);
1343
1344         if (inetd_mode) {
1345                 if (!freopen("/dev/null", "w", stderr))
1346                         die_errno("failed to redirect stderr to /dev/null");
1347         }
1348
1349         if (inetd_mode || serve_mode)
1350                 return execute();
1351
1352         if (detach)
1353                 daemonize();
1354         else
1355                 sanitize_stdfds();
1356
1357         if (pid_file)
1358                 store_pid(pid_file);
1359
1360         /* prepare argv for serving-processes */
1361         cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1362         cld_argv[0] = argv[0];  /* git-daemon */
1363         cld_argv[1] = "--serve";
1364         for (i = 1; i < argc; ++i)
1365                 cld_argv[i+1] = argv[i];
1366         cld_argv[argc+1] = NULL;
1367
1368         return serve(&listen_addr, listen_port, cred);
1369 }