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