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