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