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