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