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