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