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