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