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