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