Merge branch 'nd/daemon-log-sock-errors'
[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
24 static const char daemon_usage[] =
25 "git daemon [--verbose] [--syslog] [--export-all]\n"
26 "           [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
27 "           [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
28 "           [--user-path | --user-path=<path>]\n"
29 "           [--interpolated-path=<path>]\n"
30 "           [--reuseaddr] [--pid-file=<file>]\n"
31 "           [--(enable|disable|allow-override|forbid-override)=<service>]\n"
32 "           [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
33 "                      [--detach] [--user=<user> [--group=<group>]]\n"
34 "           [<directory>...]";
35
36 /* List of acceptable pathname prefixes */
37 static char **ok_paths;
38 static int strict_paths;
39
40 /* If this is set, git-daemon-export-ok is not required */
41 static int export_all_trees;
42
43 /* Take all paths relative to this one if non-NULL */
44 static char *base_path;
45 static char *interpolated_path;
46 static int base_path_relaxed;
47
48 /* Flag indicating client sent extra args. */
49 static int saw_extended_args;
50
51 /* If defined, ~user notation is allowed and the string is inserted
52  * after ~user/.  E.g. a request to git://host/~alice/frotz would
53  * go to /home/alice/pub_git/frotz with --user-path=pub_git.
54  */
55 static const char *user_path;
56
57 /* Timeout, and initial timeout */
58 static unsigned int timeout;
59 static unsigned int init_timeout;
60
61 static char *hostname;
62 static char *canon_hostname;
63 static char *ip_address;
64 static char *tcp_port;
65
66 static void logreport(int priority, const char *err, va_list params)
67 {
68         if (log_syslog) {
69                 char buf[1024];
70                 vsnprintf(buf, sizeof(buf), err, params);
71                 syslog(priority, "%s", buf);
72         } else {
73                 /*
74                  * Since stderr is set to buffered mode, the
75                  * logging of different processes will not overlap
76                  * unless they overflow the (rather big) buffers.
77                  */
78                 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
79                 vfprintf(stderr, err, params);
80                 fputc('\n', stderr);
81                 fflush(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(void)
524 {
525         static char line[1000];
526         int pktlen, len, i;
527         char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
528
529         if (addr)
530                 loginfo("Connection from %s:%s", addr, port);
531
532         alarm(init_timeout ? init_timeout : timeout);
533         pktlen = packet_read_line(0, line, sizeof(line));
534         alarm(0);
535
536         len = strlen(line);
537         if (pktlen != len)
538                 loginfo("Extended attributes (%d bytes) exist <%.*s>",
539                         (int) pktlen - len,
540                         (int) pktlen - len, line + len + 1);
541         if (len && line[len-1] == '\n') {
542                 line[--len] = 0;
543                 pktlen--;
544         }
545
546         free(hostname);
547         free(canon_hostname);
548         free(ip_address);
549         free(tcp_port);
550         hostname = canon_hostname = ip_address = tcp_port = NULL;
551
552         if (len != pktlen)
553                 parse_host_arg(line + len + 1, pktlen - len - 1);
554
555         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
556                 struct daemon_service *s = &(daemon_service[i]);
557                 int namelen = strlen(s->name);
558                 if (!prefixcmp(line, "git-") &&
559                     !strncmp(s->name, line + 4, namelen) &&
560                     line[namelen + 4] == ' ') {
561                         /*
562                          * Note: The directory here is probably context sensitive,
563                          * and might depend on the actual service being performed.
564                          */
565                         return run_service(line + namelen + 5, s);
566                 }
567         }
568
569         logerror("Protocol error: '%s'", line);
570         return -1;
571 }
572
573 static int addrcmp(const struct sockaddr_storage *s1,
574     const struct sockaddr_storage *s2)
575 {
576         const struct sockaddr *sa1 = (const struct sockaddr*) s1;
577         const struct sockaddr *sa2 = (const struct sockaddr*) s2;
578
579         if (sa1->sa_family != sa2->sa_family)
580                 return sa1->sa_family - sa2->sa_family;
581         if (sa1->sa_family == AF_INET)
582                 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
583                     &((struct sockaddr_in *)s2)->sin_addr,
584                     sizeof(struct in_addr));
585 #ifndef NO_IPV6
586         if (sa1->sa_family == AF_INET6)
587                 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
588                     &((struct sockaddr_in6 *)s2)->sin6_addr,
589                     sizeof(struct in6_addr));
590 #endif
591         return 0;
592 }
593
594 static int max_connections = 32;
595
596 static unsigned int live_children;
597
598 static struct child {
599         struct child *next;
600         struct child_process cld;
601         struct sockaddr_storage address;
602 } *firstborn;
603
604 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
605 {
606         struct child *newborn, **cradle;
607
608         newborn = xcalloc(1, sizeof(*newborn));
609         live_children++;
610         memcpy(&newborn->cld, cld, sizeof(*cld));
611         memcpy(&newborn->address, addr, addrlen);
612         for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
613                 if (!addrcmp(&(*cradle)->address, &newborn->address))
614                         break;
615         newborn->next = *cradle;
616         *cradle = newborn;
617 }
618
619 /*
620  * This gets called if the number of connections grows
621  * past "max_connections".
622  *
623  * We kill the newest connection from a duplicate IP.
624  */
625 static void kill_some_child(void)
626 {
627         const struct child *blanket, *next;
628
629         if (!(blanket = firstborn))
630                 return;
631
632         for (; (next = blanket->next); blanket = next)
633                 if (!addrcmp(&blanket->address, &next->address)) {
634                         kill(blanket->cld.pid, SIGTERM);
635                         break;
636                 }
637 }
638
639 static void check_dead_children(void)
640 {
641         int status;
642         pid_t pid;
643
644         struct child **cradle, *blanket;
645         for (cradle = &firstborn; (blanket = *cradle);)
646                 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
647                         const char *dead = "";
648                         if (status)
649                                 dead = " (with error)";
650                         loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
651
652                         /* remove the child */
653                         *cradle = blanket->next;
654                         live_children--;
655                         free(blanket);
656                 } else
657                         cradle = &blanket->next;
658 }
659
660 static char **cld_argv;
661 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
662 {
663         struct child_process cld = { NULL };
664         char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
665         char *env[] = { addrbuf, portbuf, NULL };
666
667         if (max_connections && live_children >= max_connections) {
668                 kill_some_child();
669                 sleep(1);  /* give it some time to die */
670                 check_dead_children();
671                 if (live_children >= max_connections) {
672                         close(incoming);
673                         logerror("Too many children, dropping connection");
674                         return;
675                 }
676         }
677
678         if (addr->sa_family == AF_INET) {
679                 struct sockaddr_in *sin_addr = (void *) addr;
680                 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
681                     sizeof(addrbuf) - 12);
682                 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
683                     ntohs(sin_addr->sin_port));
684 #ifndef NO_IPV6
685         } else if (addr && addr->sa_family == AF_INET6) {
686                 struct sockaddr_in6 *sin6_addr = (void *) addr;
687
688                 char *buf = addrbuf + 12;
689                 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
690                 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
691                     sizeof(addrbuf) - 13);
692                 strcat(buf, "]");
693
694                 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
695                     ntohs(sin6_addr->sin6_port));
696 #endif
697         }
698
699         cld.env = (const char **)env;
700         cld.argv = (const char **)cld_argv;
701         cld.in = incoming;
702         cld.out = dup(incoming);
703
704         if (start_command(&cld))
705                 logerror("unable to fork");
706         else
707                 add_child(&cld, addr, addrlen);
708         close(incoming);
709 }
710
711 static void child_handler(int signo)
712 {
713         /*
714          * Otherwise empty handler because systemcalls will get interrupted
715          * upon signal receipt
716          * SysV needs the handler to be rearmed
717          */
718         signal(SIGCHLD, child_handler);
719 }
720
721 static int set_reuse_addr(int sockfd)
722 {
723         int on = 1;
724
725         if (!reuseaddr)
726                 return 0;
727         return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
728                           &on, sizeof(on));
729 }
730
731 struct socketlist {
732         int *list;
733         size_t nr;
734         size_t alloc;
735 };
736
737 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
738 {
739 #ifdef NO_IPV6
740         static char ip[INET_ADDRSTRLEN];
741 #else
742         static char ip[INET6_ADDRSTRLEN];
743 #endif
744
745         switch (family) {
746 #ifndef NO_IPV6
747         case AF_INET6:
748                 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
749                 break;
750 #endif
751         case AF_INET:
752                 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
753                 break;
754         default:
755                 strcpy(ip, "<unknown>");
756         }
757         return ip;
758 }
759
760 #ifndef NO_IPV6
761
762 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
763 {
764         int socknum = 0;
765         int maxfd = -1;
766         char pbuf[NI_MAXSERV];
767         struct addrinfo hints, *ai0, *ai;
768         int gai;
769         long flags;
770
771         sprintf(pbuf, "%d", listen_port);
772         memset(&hints, 0, sizeof(hints));
773         hints.ai_family = AF_UNSPEC;
774         hints.ai_socktype = SOCK_STREAM;
775         hints.ai_protocol = IPPROTO_TCP;
776         hints.ai_flags = AI_PASSIVE;
777
778         gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
779         if (gai) {
780                 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
781                 return 0;
782         }
783
784         for (ai = ai0; ai; ai = ai->ai_next) {
785                 int sockfd;
786
787                 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
788                 if (sockfd < 0)
789                         continue;
790                 if (sockfd >= FD_SETSIZE) {
791                         logerror("Socket descriptor too large");
792                         close(sockfd);
793                         continue;
794                 }
795
796 #ifdef IPV6_V6ONLY
797                 if (ai->ai_family == AF_INET6) {
798                         int on = 1;
799                         setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
800                                    &on, sizeof(on));
801                         /* Note: error is not fatal */
802                 }
803 #endif
804
805                 if (set_reuse_addr(sockfd)) {
806                         logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
807                         close(sockfd);
808                         continue;
809                 }
810
811                 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
812                         logerror("Could not bind to %s: %s",
813                                  ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
814                                  strerror(errno));
815                         close(sockfd);
816                         continue;       /* not fatal */
817                 }
818                 if (listen(sockfd, 5) < 0) {
819                         logerror("Could not listen to %s: %s",
820                                  ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
821                                  strerror(errno));
822                         close(sockfd);
823                         continue;       /* not fatal */
824                 }
825
826                 flags = fcntl(sockfd, F_GETFD, 0);
827                 if (flags >= 0)
828                         fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
829
830                 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
831                 socklist->list[socklist->nr++] = sockfd;
832                 socknum++;
833
834                 if (maxfd < sockfd)
835                         maxfd = sockfd;
836         }
837
838         freeaddrinfo(ai0);
839
840         return socknum;
841 }
842
843 #else /* NO_IPV6 */
844
845 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
846 {
847         struct sockaddr_in sin;
848         int sockfd;
849         long flags;
850
851         memset(&sin, 0, sizeof sin);
852         sin.sin_family = AF_INET;
853         sin.sin_port = htons(listen_port);
854
855         if (listen_addr) {
856                 /* Well, host better be an IP address here. */
857                 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
858                         return 0;
859         } else {
860                 sin.sin_addr.s_addr = htonl(INADDR_ANY);
861         }
862
863         sockfd = socket(AF_INET, SOCK_STREAM, 0);
864         if (sockfd < 0)
865                 return 0;
866
867         if (set_reuse_addr(sockfd)) {
868                 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
869                 close(sockfd);
870                 return 0;
871         }
872
873         if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
874                 logerror("Could not listen to %s: %s",
875                          ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
876                          strerror(errno));
877                 close(sockfd);
878                 return 0;
879         }
880
881         if (listen(sockfd, 5) < 0) {
882                 logerror("Could not listen to %s: %s",
883                          ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
884                          strerror(errno));
885                 close(sockfd);
886                 return 0;
887         }
888
889         flags = fcntl(sockfd, F_GETFD, 0);
890         if (flags >= 0)
891                 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
892
893         ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
894         socklist->list[socklist->nr++] = sockfd;
895         return 1;
896 }
897
898 #endif
899
900 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
901 {
902         if (!listen_addr->nr)
903                 setup_named_sock(NULL, listen_port, socklist);
904         else {
905                 int i, socknum;
906                 for (i = 0; i < listen_addr->nr; i++) {
907                         socknum = setup_named_sock(listen_addr->items[i].string,
908                                                    listen_port, socklist);
909
910                         if (socknum == 0)
911                                 logerror("unable to allocate any listen sockets for host %s on port %u",
912                                          listen_addr->items[i].string, listen_port);
913                 }
914         }
915 }
916
917 static int service_loop(struct socketlist *socklist)
918 {
919         struct pollfd *pfd;
920         int i;
921
922         pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
923
924         for (i = 0; i < socklist->nr; i++) {
925                 pfd[i].fd = socklist->list[i];
926                 pfd[i].events = POLLIN;
927         }
928
929         signal(SIGCHLD, child_handler);
930
931         for (;;) {
932                 int i;
933
934                 check_dead_children();
935
936                 if (poll(pfd, socklist->nr, -1) < 0) {
937                         if (errno != EINTR) {
938                                 logerror("Poll failed, resuming: %s",
939                                       strerror(errno));
940                                 sleep(1);
941                         }
942                         continue;
943                 }
944
945                 for (i = 0; i < socklist->nr; i++) {
946                         if (pfd[i].revents & POLLIN) {
947                                 union {
948                                         struct sockaddr sa;
949                                         struct sockaddr_in sai;
950 #ifndef NO_IPV6
951                                         struct sockaddr_in6 sai6;
952 #endif
953                                 } ss;
954                                 socklen_t sslen = sizeof(ss);
955                                 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
956                                 if (incoming < 0) {
957                                         switch (errno) {
958                                         case EAGAIN:
959                                         case EINTR:
960                                         case ECONNABORTED:
961                                                 continue;
962                                         default:
963                                                 die_errno("accept returned");
964                                         }
965                                 }
966                                 handle(incoming, &ss.sa, sslen);
967                         }
968                 }
969         }
970 }
971
972 /* if any standard file descriptor is missing open it to /dev/null */
973 static void sanitize_stdfds(void)
974 {
975         int fd = open("/dev/null", O_RDWR, 0);
976         while (fd != -1 && fd < 2)
977                 fd = dup(fd);
978         if (fd == -1)
979                 die_errno("open /dev/null or dup failed");
980         if (fd > 2)
981                 close(fd);
982 }
983
984 #ifdef NO_POSIX_GOODIES
985
986 struct credentials;
987
988 static void drop_privileges(struct credentials *cred)
989 {
990         /* nothing */
991 }
992
993 static void daemonize(void)
994 {
995         die("--detach not supported on this platform");
996 }
997
998 static struct credentials *prepare_credentials(const char *user_name,
999     const char *group_name)
1000 {
1001         die("--user not supported on this platform");
1002 }
1003
1004 #else
1005
1006 struct credentials {
1007         struct passwd *pass;
1008         gid_t gid;
1009 };
1010
1011 static void drop_privileges(struct credentials *cred)
1012 {
1013         if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1014             setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1015                 die("cannot drop privileges");
1016 }
1017
1018 static struct credentials *prepare_credentials(const char *user_name,
1019     const char *group_name)
1020 {
1021         static struct credentials c;
1022
1023         c.pass = getpwnam(user_name);
1024         if (!c.pass)
1025                 die("user not found - %s", user_name);
1026
1027         if (!group_name)
1028                 c.gid = c.pass->pw_gid;
1029         else {
1030                 struct group *group = getgrnam(group_name);
1031                 if (!group)
1032                         die("group not found - %s", group_name);
1033
1034                 c.gid = group->gr_gid;
1035         }
1036
1037         return &c;
1038 }
1039
1040 static void daemonize(void)
1041 {
1042         switch (fork()) {
1043                 case 0:
1044                         break;
1045                 case -1:
1046                         die_errno("fork failed");
1047                 default:
1048                         exit(0);
1049         }
1050         if (setsid() == -1)
1051                 die_errno("setsid failed");
1052         close(0);
1053         close(1);
1054         close(2);
1055         sanitize_stdfds();
1056 }
1057 #endif
1058
1059 static void store_pid(const char *path)
1060 {
1061         FILE *f = fopen(path, "w");
1062         if (!f)
1063                 die_errno("cannot open pid file '%s'", path);
1064         if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1065                 die_errno("failed to write pid file '%s'", path);
1066 }
1067
1068 static int serve(struct string_list *listen_addr, int listen_port,
1069     struct credentials *cred)
1070 {
1071         struct socketlist socklist = { NULL, 0, 0 };
1072
1073         socksetup(listen_addr, listen_port, &socklist);
1074         if (socklist.nr == 0)
1075                 die("unable to allocate any listen sockets on port %u",
1076                     listen_port);
1077
1078         drop_privileges(cred);
1079
1080         return service_loop(&socklist);
1081 }
1082
1083 int main(int argc, char **argv)
1084 {
1085         int listen_port = 0;
1086         struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1087         int serve_mode = 0, inetd_mode = 0;
1088         const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1089         int detach = 0;
1090         struct credentials *cred = NULL;
1091         int i;
1092
1093         git_extract_argv0_path(argv[0]);
1094
1095         for (i = 1; i < argc; i++) {
1096                 char *arg = argv[i];
1097
1098                 if (!prefixcmp(arg, "--listen=")) {
1099                         string_list_append(&listen_addr, xstrdup_tolower(arg + 9));
1100                         continue;
1101                 }
1102                 if (!prefixcmp(arg, "--port=")) {
1103                         char *end;
1104                         unsigned long n;
1105                         n = strtoul(arg+7, &end, 0);
1106                         if (arg[7] && !*end) {
1107                                 listen_port = n;
1108                                 continue;
1109                         }
1110                 }
1111                 if (!strcmp(arg, "--serve")) {
1112                         serve_mode = 1;
1113                         continue;
1114                 }
1115                 if (!strcmp(arg, "--inetd")) {
1116                         inetd_mode = 1;
1117                         log_syslog = 1;
1118                         continue;
1119                 }
1120                 if (!strcmp(arg, "--verbose")) {
1121                         verbose = 1;
1122                         continue;
1123                 }
1124                 if (!strcmp(arg, "--syslog")) {
1125                         log_syslog = 1;
1126                         continue;
1127                 }
1128                 if (!strcmp(arg, "--export-all")) {
1129                         export_all_trees = 1;
1130                         continue;
1131                 }
1132                 if (!prefixcmp(arg, "--timeout=")) {
1133                         timeout = atoi(arg+10);
1134                         continue;
1135                 }
1136                 if (!prefixcmp(arg, "--init-timeout=")) {
1137                         init_timeout = atoi(arg+15);
1138                         continue;
1139                 }
1140                 if (!prefixcmp(arg, "--max-connections=")) {
1141                         max_connections = atoi(arg+18);
1142                         if (max_connections < 0)
1143                                 max_connections = 0;            /* unlimited */
1144                         continue;
1145                 }
1146                 if (!strcmp(arg, "--strict-paths")) {
1147                         strict_paths = 1;
1148                         continue;
1149                 }
1150                 if (!prefixcmp(arg, "--base-path=")) {
1151                         base_path = arg+12;
1152                         continue;
1153                 }
1154                 if (!strcmp(arg, "--base-path-relaxed")) {
1155                         base_path_relaxed = 1;
1156                         continue;
1157                 }
1158                 if (!prefixcmp(arg, "--interpolated-path=")) {
1159                         interpolated_path = arg+20;
1160                         continue;
1161                 }
1162                 if (!strcmp(arg, "--reuseaddr")) {
1163                         reuseaddr = 1;
1164                         continue;
1165                 }
1166                 if (!strcmp(arg, "--user-path")) {
1167                         user_path = "";
1168                         continue;
1169                 }
1170                 if (!prefixcmp(arg, "--user-path=")) {
1171                         user_path = arg + 12;
1172                         continue;
1173                 }
1174                 if (!prefixcmp(arg, "--pid-file=")) {
1175                         pid_file = arg + 11;
1176                         continue;
1177                 }
1178                 if (!strcmp(arg, "--detach")) {
1179                         detach = 1;
1180                         log_syslog = 1;
1181                         continue;
1182                 }
1183                 if (!prefixcmp(arg, "--user=")) {
1184                         user_name = arg + 7;
1185                         continue;
1186                 }
1187                 if (!prefixcmp(arg, "--group=")) {
1188                         group_name = arg + 8;
1189                         continue;
1190                 }
1191                 if (!prefixcmp(arg, "--enable=")) {
1192                         enable_service(arg + 9, 1);
1193                         continue;
1194                 }
1195                 if (!prefixcmp(arg, "--disable=")) {
1196                         enable_service(arg + 10, 0);
1197                         continue;
1198                 }
1199                 if (!prefixcmp(arg, "--allow-override=")) {
1200                         make_service_overridable(arg + 17, 1);
1201                         continue;
1202                 }
1203                 if (!prefixcmp(arg, "--forbid-override=")) {
1204                         make_service_overridable(arg + 18, 0);
1205                         continue;
1206                 }
1207                 if (!strcmp(arg, "--")) {
1208                         ok_paths = &argv[i+1];
1209                         break;
1210                 } else if (arg[0] != '-') {
1211                         ok_paths = &argv[i];
1212                         break;
1213                 }
1214
1215                 usage(daemon_usage);
1216         }
1217
1218         if (log_syslog) {
1219                 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1220                 set_die_routine(daemon_die);
1221         } else
1222                 /* avoid splitting a message in the middle */
1223                 setvbuf(stderr, NULL, _IOFBF, 4096);
1224
1225         if (inetd_mode && (detach || group_name || user_name))
1226                 die("--detach, --user and --group are incompatible with --inetd");
1227
1228         if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1229                 die("--listen= and --port= are incompatible with --inetd");
1230         else if (listen_port == 0)
1231                 listen_port = DEFAULT_GIT_PORT;
1232
1233         if (group_name && !user_name)
1234                 die("--group supplied without --user");
1235
1236         if (user_name)
1237                 cred = prepare_credentials(user_name, group_name);
1238
1239         if (strict_paths && (!ok_paths || !*ok_paths))
1240                 die("option --strict-paths requires a whitelist");
1241
1242         if (base_path && !is_directory(base_path))
1243                 die("base-path '%s' does not exist or is not a directory",
1244                     base_path);
1245
1246         if (inetd_mode) {
1247                 if (!freopen("/dev/null", "w", stderr))
1248                         die_errno("failed to redirect stderr to /dev/null");
1249         }
1250
1251         if (inetd_mode || serve_mode)
1252                 return execute();
1253
1254         if (detach) {
1255                 daemonize();
1256                 loginfo("Ready to rumble");
1257         }
1258         else
1259                 sanitize_stdfds();
1260
1261         if (pid_file)
1262                 store_pid(pid_file);
1263
1264         /* prepare argv for serving-processes */
1265         cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1266         cld_argv[0] = argv[0];  /* git-daemon */
1267         cld_argv[1] = "--serve";
1268         for (i = 1; i < argc; ++i)
1269                 cld_argv[i+1] = argv[i];
1270         cld_argv[argc+1] = NULL;
1271
1272         return serve(&listen_addr, listen_port, cred);
1273 }