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