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