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