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