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