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