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