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