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