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