daemon: use callback to build interpolated path
[git.git] / daemon.c
blobdf9768fecc490b681449bdaff17bacb78d257f8c
1 #include "cache.h"
2 #include "pkt-line.h"
3 #include "exec_cmd.h"
4 #include "run-command.h"
5 #include "strbuf.h"
6 #include "string-list.h"
8 #ifndef HOST_NAME_MAX
9 #define HOST_NAME_MAX 256
10 #endif
12 #ifdef NO_INITGROUPS
13 #define initgroups(x, y) (0) /* nothing */
14 #endif
16 static int log_syslog;
17 static int verbose;
18 static int reuseaddr;
19 static int informative_errors;
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] [--pid-file=<file>]\n"
28 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
29 " [--access-hook=<path>]\n"
30 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
31 " [--detach] [--user=<user> [--group=<group>]]\n"
32 " [<directory>...]";
34 /* List of acceptable pathname prefixes */
35 static char **ok_paths;
36 static int strict_paths;
38 /* If this is set, git-daemon-export-ok is not required */
39 static int export_all_trees;
41 /* Take all paths relative to this one if non-NULL */
42 static const char *base_path;
43 static const char *interpolated_path;
44 static int base_path_relaxed;
46 /* Flag indicating client sent extra args. */
47 static int saw_extended_args;
49 /* If defined, ~user notation is allowed and the string is inserted
50 * after ~user/. E.g. a request to git://host/~alice/frotz would
51 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
53 static const char *user_path;
55 /* Timeout, and initial timeout */
56 static unsigned int timeout;
57 static unsigned int init_timeout;
59 static char *hostname;
60 static char *canon_hostname;
61 static char *ip_address;
62 static char *tcp_port;
64 static int hostname_lookup_done;
66 static void lookup_hostname(void);
68 static const char *get_canon_hostname(void)
70 lookup_hostname();
71 return canon_hostname;
74 static const char *get_ip_address(void)
76 lookup_hostname();
77 return ip_address;
80 static void logreport(int priority, const char *err, va_list params)
82 if (log_syslog) {
83 char buf[1024];
84 vsnprintf(buf, sizeof(buf), err, params);
85 syslog(priority, "%s", buf);
86 } else {
88 * Since stderr is set to buffered mode, the
89 * logging of different processes will not overlap
90 * unless they overflow the (rather big) buffers.
92 fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
93 vfprintf(stderr, err, params);
94 fputc('\n', stderr);
95 fflush(stderr);
99 __attribute__((format (printf, 1, 2)))
100 static void logerror(const char *err, ...)
102 va_list params;
103 va_start(params, err);
104 logreport(LOG_ERR, err, params);
105 va_end(params);
108 __attribute__((format (printf, 1, 2)))
109 static void loginfo(const char *err, ...)
111 va_list params;
112 if (!verbose)
113 return;
114 va_start(params, err);
115 logreport(LOG_INFO, err, params);
116 va_end(params);
119 static void NORETURN daemon_die(const char *err, va_list params)
121 logreport(LOG_ERR, err, params);
122 exit(1);
125 static void strbuf_addstr_or_null(struct strbuf *sb, const char *s)
127 if (s)
128 strbuf_addstr(sb, s);
131 struct expand_path_context {
132 const char *directory;
135 static size_t expand_path(struct strbuf *sb, const char *placeholder, void *ctx)
137 struct expand_path_context *context = ctx;
139 switch (placeholder[0]) {
140 case 'H':
141 strbuf_addstr_or_null(sb, hostname);
142 return 1;
143 case 'C':
144 if (placeholder[1] == 'H') {
145 strbuf_addstr_or_null(sb, get_canon_hostname());
146 return 2;
148 break;
149 case 'I':
150 if (placeholder[1] == 'P') {
151 strbuf_addstr_or_null(sb, get_ip_address());
152 return 2;
154 break;
155 case 'P':
156 strbuf_addstr_or_null(sb, tcp_port);
157 return 1;
158 case 'D':
159 strbuf_addstr(sb, context->directory);
160 return 1;
162 return 0;
165 static const char *path_ok(const char *directory)
167 static char rpath[PATH_MAX];
168 static char interp_path[PATH_MAX];
169 const char *path;
170 const char *dir;
172 dir = directory;
174 if (daemon_avoid_alias(dir)) {
175 logerror("'%s': aliased", dir);
176 return NULL;
179 if (*dir == '~') {
180 if (!user_path) {
181 logerror("'%s': User-path not allowed", dir);
182 return NULL;
184 if (*user_path) {
185 /* Got either "~alice" or "~alice/foo";
186 * rewrite them to "~alice/%s" or
187 * "~alice/%s/foo".
189 int namlen, restlen = strlen(dir);
190 const char *slash = strchr(dir, '/');
191 if (!slash)
192 slash = dir + restlen;
193 namlen = slash - dir;
194 restlen -= namlen;
195 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
196 snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
197 namlen, dir, user_path, restlen, slash);
198 dir = rpath;
201 else if (interpolated_path && saw_extended_args) {
202 struct strbuf expanded_path = STRBUF_INIT;
203 struct expand_path_context context;
205 context.directory = directory;
207 if (*dir != '/') {
208 /* Allow only absolute */
209 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
210 return NULL;
213 strbuf_expand(&expanded_path, interpolated_path,
214 expand_path, &context);
215 strlcpy(interp_path, expanded_path.buf, PATH_MAX);
216 strbuf_release(&expanded_path);
217 loginfo("Interpolated dir '%s'", interp_path);
219 dir = interp_path;
221 else if (base_path) {
222 if (*dir != '/') {
223 /* Allow only absolute */
224 logerror("'%s': Non-absolute path denied (base-path active)", dir);
225 return NULL;
227 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
228 dir = rpath;
231 path = enter_repo(dir, strict_paths);
232 if (!path && base_path && base_path_relaxed) {
234 * if we fail and base_path_relaxed is enabled, try without
235 * prefixing the base path
237 dir = directory;
238 path = enter_repo(dir, strict_paths);
241 if (!path) {
242 logerror("'%s' does not appear to be a git repository", dir);
243 return NULL;
246 if ( ok_paths && *ok_paths ) {
247 char **pp;
248 int pathlen = strlen(path);
250 /* The validation is done on the paths after enter_repo
251 * appends optional {.git,.git/.git} and friends, but
252 * it does not use getcwd(). So if your /pub is
253 * a symlink to /mnt/pub, you can whitelist /pub and
254 * do not have to say /mnt/pub.
255 * Do not say /pub/.
257 for ( pp = ok_paths ; *pp ; pp++ ) {
258 int len = strlen(*pp);
259 if (len <= pathlen &&
260 !memcmp(*pp, path, len) &&
261 (path[len] == '\0' ||
262 (!strict_paths && path[len] == '/')))
263 return path;
266 else {
267 /* be backwards compatible */
268 if (!strict_paths)
269 return path;
272 logerror("'%s': not in whitelist", path);
273 return NULL; /* Fallthrough. Deny by default */
276 typedef int (*daemon_service_fn)(void);
277 struct daemon_service {
278 const char *name;
279 const char *config_name;
280 daemon_service_fn fn;
281 int enabled;
282 int overridable;
285 static struct daemon_service *service_looking_at;
286 static int service_enabled;
288 static int git_daemon_config(const char *var, const char *value, void *cb)
290 const char *service;
292 if (skip_prefix(var, "daemon.", &service) &&
293 !strcmp(service, service_looking_at->config_name)) {
294 service_enabled = git_config_bool(var, value);
295 return 0;
298 /* we are not interested in parsing any other configuration here */
299 return 0;
302 static int daemon_error(const char *dir, const char *msg)
304 if (!informative_errors)
305 msg = "access denied or repository not exported";
306 packet_write(1, "ERR %s: %s", msg, dir);
307 return -1;
310 static const char *access_hook;
312 static int run_access_hook(struct daemon_service *service, const char *dir, const char *path)
314 struct child_process child;
315 struct strbuf buf = STRBUF_INIT;
316 const char *argv[8];
317 const char **arg = argv;
318 char *eol;
319 int seen_errors = 0;
321 #define STRARG(x) ((x) ? (x) : "")
322 *arg++ = access_hook;
323 *arg++ = service->name;
324 *arg++ = path;
325 *arg++ = STRARG(hostname);
326 *arg++ = STRARG(get_canon_hostname());
327 *arg++ = STRARG(get_ip_address());
328 *arg++ = STRARG(tcp_port);
329 *arg = NULL;
330 #undef STRARG
332 memset(&child, 0, sizeof(child));
333 child.use_shell = 1;
334 child.argv = argv;
335 child.no_stdin = 1;
336 child.no_stderr = 1;
337 child.out = -1;
338 if (start_command(&child)) {
339 logerror("daemon access hook '%s' failed to start",
340 access_hook);
341 goto error_return;
343 if (strbuf_read(&buf, child.out, 0) < 0) {
344 logerror("failed to read from pipe to daemon access hook '%s'",
345 access_hook);
346 strbuf_reset(&buf);
347 seen_errors = 1;
349 if (close(child.out) < 0) {
350 logerror("failed to close pipe to daemon access hook '%s'",
351 access_hook);
352 seen_errors = 1;
354 if (finish_command(&child))
355 seen_errors = 1;
357 if (!seen_errors) {
358 strbuf_release(&buf);
359 return 0;
362 error_return:
363 strbuf_ltrim(&buf);
364 if (!buf.len)
365 strbuf_addstr(&buf, "service rejected");
366 eol = strchr(buf.buf, '\n');
367 if (eol)
368 *eol = '\0';
369 errno = EACCES;
370 daemon_error(dir, buf.buf);
371 strbuf_release(&buf);
372 return -1;
375 static int run_service(const char *dir, struct daemon_service *service)
377 const char *path;
378 int enabled = service->enabled;
380 loginfo("Request %s for '%s'", service->name, dir);
382 if (!enabled && !service->overridable) {
383 logerror("'%s': service not enabled.", service->name);
384 errno = EACCES;
385 return daemon_error(dir, "service not enabled");
388 if (!(path = path_ok(dir)))
389 return daemon_error(dir, "no such repository");
392 * Security on the cheap.
394 * We want a readable HEAD, usable "objects" directory, and
395 * a "git-daemon-export-ok" flag that says that the other side
396 * is ok with us doing this.
398 * path_ok() uses enter_repo() and does whitelist checking.
399 * We only need to make sure the repository is exported.
402 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
403 logerror("'%s': repository not exported.", path);
404 errno = EACCES;
405 return daemon_error(dir, "repository not exported");
408 if (service->overridable) {
409 service_looking_at = service;
410 service_enabled = -1;
411 git_config(git_daemon_config, NULL);
412 if (0 <= service_enabled)
413 enabled = service_enabled;
415 if (!enabled) {
416 logerror("'%s': service not enabled for '%s'",
417 service->name, path);
418 errno = EACCES;
419 return daemon_error(dir, "service not enabled");
423 * Optionally, a hook can choose to deny access to the
424 * repository depending on the phase of the moon.
426 if (access_hook && run_access_hook(service, dir, path))
427 return -1;
430 * We'll ignore SIGTERM from now on, we have a
431 * good client.
433 signal(SIGTERM, SIG_IGN);
435 return service->fn();
438 static void copy_to_log(int fd)
440 struct strbuf line = STRBUF_INIT;
441 FILE *fp;
443 fp = fdopen(fd, "r");
444 if (fp == NULL) {
445 logerror("fdopen of error channel failed");
446 close(fd);
447 return;
450 while (strbuf_getline(&line, fp, '\n') != EOF) {
451 logerror("%s", line.buf);
452 strbuf_setlen(&line, 0);
455 strbuf_release(&line);
456 fclose(fp);
459 static int run_service_command(const char **argv)
461 struct child_process cld;
463 memset(&cld, 0, sizeof(cld));
464 cld.argv = argv;
465 cld.git_cmd = 1;
466 cld.err = -1;
467 if (start_command(&cld))
468 return -1;
470 close(0);
471 close(1);
473 copy_to_log(cld.err);
475 return finish_command(&cld);
478 static int upload_pack(void)
480 /* Timeout as string */
481 char timeout_buf[64];
482 const char *argv[] = { "upload-pack", "--strict", NULL, ".", NULL };
484 argv[2] = timeout_buf;
486 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
487 return run_service_command(argv);
490 static int upload_archive(void)
492 static const char *argv[] = { "upload-archive", ".", NULL };
493 return run_service_command(argv);
496 static int receive_pack(void)
498 static const char *argv[] = { "receive-pack", ".", NULL };
499 return run_service_command(argv);
502 static struct daemon_service daemon_service[] = {
503 { "upload-archive", "uploadarch", upload_archive, 0, 1 },
504 { "upload-pack", "uploadpack", upload_pack, 1, 1 },
505 { "receive-pack", "receivepack", receive_pack, 0, 1 },
508 static void enable_service(const char *name, int ena)
510 int i;
511 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
512 if (!strcmp(daemon_service[i].name, name)) {
513 daemon_service[i].enabled = ena;
514 return;
517 die("No such service %s", name);
520 static void make_service_overridable(const char *name, int ena)
522 int i;
523 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
524 if (!strcmp(daemon_service[i].name, name)) {
525 daemon_service[i].overridable = ena;
526 return;
529 die("No such service %s", name);
532 static void parse_host_and_port(char *hostport, char **host,
533 char **port)
535 if (*hostport == '[') {
536 char *end;
538 end = strchr(hostport, ']');
539 if (!end)
540 die("Invalid request ('[' without ']')");
541 *end = '\0';
542 *host = hostport + 1;
543 if (!end[1])
544 *port = NULL;
545 else if (end[1] == ':')
546 *port = end + 2;
547 else
548 die("Garbage after end of host part");
549 } else {
550 *host = hostport;
551 *port = strrchr(hostport, ':');
552 if (*port) {
553 **port = '\0';
554 ++*port;
560 * Read the host as supplied by the client connection.
562 static void parse_host_arg(char *extra_args, int buflen)
564 char *val;
565 int vallen;
566 char *end = extra_args + buflen;
568 if (extra_args < end && *extra_args) {
569 saw_extended_args = 1;
570 if (strncasecmp("host=", extra_args, 5) == 0) {
571 val = extra_args + 5;
572 vallen = strlen(val) + 1;
573 if (*val) {
574 /* Split <host>:<port> at colon. */
575 char *host;
576 char *port;
577 parse_host_and_port(val, &host, &port);
578 if (port) {
579 free(tcp_port);
580 tcp_port = xstrdup(port);
582 free(hostname);
583 hostname = xstrdup_tolower(host);
584 hostname_lookup_done = 0;
587 /* On to the next one */
588 extra_args = val + vallen;
590 if (extra_args < end && *extra_args)
591 die("Invalid request");
596 * Locate canonical hostname and its IP address.
598 static void lookup_hostname(void)
600 if (!hostname_lookup_done && hostname) {
601 #ifndef NO_IPV6
602 struct addrinfo hints;
603 struct addrinfo *ai;
604 int gai;
605 static char addrbuf[HOST_NAME_MAX + 1];
607 memset(&hints, 0, sizeof(hints));
608 hints.ai_flags = AI_CANONNAME;
610 gai = getaddrinfo(hostname, NULL, &hints, &ai);
611 if (!gai) {
612 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
614 inet_ntop(AF_INET, &sin_addr->sin_addr,
615 addrbuf, sizeof(addrbuf));
616 free(ip_address);
617 ip_address = xstrdup(addrbuf);
619 free(canon_hostname);
620 canon_hostname = xstrdup(ai->ai_canonname ?
621 ai->ai_canonname : ip_address);
623 freeaddrinfo(ai);
625 #else
626 struct hostent *hent;
627 struct sockaddr_in sa;
628 char **ap;
629 static char addrbuf[HOST_NAME_MAX + 1];
631 hent = gethostbyname(hostname);
632 if (hent) {
633 ap = hent->h_addr_list;
634 memset(&sa, 0, sizeof sa);
635 sa.sin_family = hent->h_addrtype;
636 sa.sin_port = htons(0);
637 memcpy(&sa.sin_addr, *ap, hent->h_length);
639 inet_ntop(hent->h_addrtype, &sa.sin_addr,
640 addrbuf, sizeof(addrbuf));
642 free(canon_hostname);
643 canon_hostname = xstrdup(hent->h_name);
644 free(ip_address);
645 ip_address = xstrdup(addrbuf);
647 #endif
648 hostname_lookup_done = 1;
653 static int execute(void)
655 char *line = packet_buffer;
656 int pktlen, len, i;
657 char *addr = getenv("REMOTE_ADDR"), *port = getenv("REMOTE_PORT");
659 if (addr)
660 loginfo("Connection from %s:%s", addr, port);
662 alarm(init_timeout ? init_timeout : timeout);
663 pktlen = packet_read(0, NULL, NULL, packet_buffer, sizeof(packet_buffer), 0);
664 alarm(0);
666 len = strlen(line);
667 if (pktlen != len)
668 loginfo("Extended attributes (%d bytes) exist <%.*s>",
669 (int) pktlen - len,
670 (int) pktlen - len, line + len + 1);
671 if (len && line[len-1] == '\n') {
672 line[--len] = 0;
673 pktlen--;
676 free(hostname);
677 free(canon_hostname);
678 free(ip_address);
679 free(tcp_port);
680 hostname = canon_hostname = ip_address = tcp_port = NULL;
682 if (len != pktlen)
683 parse_host_arg(line + len + 1, pktlen - len - 1);
685 for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
686 struct daemon_service *s = &(daemon_service[i]);
687 const char *arg;
689 if (skip_prefix(line, "git-", &arg) &&
690 skip_prefix(arg, s->name, &arg) &&
691 *arg++ == ' ') {
693 * Note: The directory here is probably context sensitive,
694 * and might depend on the actual service being performed.
696 return run_service(arg, s);
700 logerror("Protocol error: '%s'", line);
701 return -1;
704 static int addrcmp(const struct sockaddr_storage *s1,
705 const struct sockaddr_storage *s2)
707 const struct sockaddr *sa1 = (const struct sockaddr*) s1;
708 const struct sockaddr *sa2 = (const struct sockaddr*) s2;
710 if (sa1->sa_family != sa2->sa_family)
711 return sa1->sa_family - sa2->sa_family;
712 if (sa1->sa_family == AF_INET)
713 return memcmp(&((struct sockaddr_in *)s1)->sin_addr,
714 &((struct sockaddr_in *)s2)->sin_addr,
715 sizeof(struct in_addr));
716 #ifndef NO_IPV6
717 if (sa1->sa_family == AF_INET6)
718 return memcmp(&((struct sockaddr_in6 *)s1)->sin6_addr,
719 &((struct sockaddr_in6 *)s2)->sin6_addr,
720 sizeof(struct in6_addr));
721 #endif
722 return 0;
725 static int max_connections = 32;
727 static unsigned int live_children;
729 static struct child {
730 struct child *next;
731 struct child_process cld;
732 struct sockaddr_storage address;
733 } *firstborn;
735 static void add_child(struct child_process *cld, struct sockaddr *addr, socklen_t addrlen)
737 struct child *newborn, **cradle;
739 newborn = xcalloc(1, sizeof(*newborn));
740 live_children++;
741 memcpy(&newborn->cld, cld, sizeof(*cld));
742 memcpy(&newborn->address, addr, addrlen);
743 for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
744 if (!addrcmp(&(*cradle)->address, &newborn->address))
745 break;
746 newborn->next = *cradle;
747 *cradle = newborn;
751 * This gets called if the number of connections grows
752 * past "max_connections".
754 * We kill the newest connection from a duplicate IP.
756 static void kill_some_child(void)
758 const struct child *blanket, *next;
760 if (!(blanket = firstborn))
761 return;
763 for (; (next = blanket->next); blanket = next)
764 if (!addrcmp(&blanket->address, &next->address)) {
765 kill(blanket->cld.pid, SIGTERM);
766 break;
770 static void check_dead_children(void)
772 int status;
773 pid_t pid;
775 struct child **cradle, *blanket;
776 for (cradle = &firstborn; (blanket = *cradle);)
777 if ((pid = waitpid(blanket->cld.pid, &status, WNOHANG)) > 1) {
778 const char *dead = "";
779 if (status)
780 dead = " (with error)";
781 loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
783 /* remove the child */
784 *cradle = blanket->next;
785 live_children--;
786 free(blanket);
787 } else
788 cradle = &blanket->next;
791 static char **cld_argv;
792 static void handle(int incoming, struct sockaddr *addr, socklen_t addrlen)
794 struct child_process cld = { NULL };
795 char addrbuf[300] = "REMOTE_ADDR=", portbuf[300];
796 char *env[] = { addrbuf, portbuf, NULL };
798 if (max_connections && live_children >= max_connections) {
799 kill_some_child();
800 sleep(1); /* give it some time to die */
801 check_dead_children();
802 if (live_children >= max_connections) {
803 close(incoming);
804 logerror("Too many children, dropping connection");
805 return;
809 if (addr->sa_family == AF_INET) {
810 struct sockaddr_in *sin_addr = (void *) addr;
811 inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf + 12,
812 sizeof(addrbuf) - 12);
813 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
814 ntohs(sin_addr->sin_port));
815 #ifndef NO_IPV6
816 } else if (addr->sa_family == AF_INET6) {
817 struct sockaddr_in6 *sin6_addr = (void *) addr;
819 char *buf = addrbuf + 12;
820 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
821 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf,
822 sizeof(addrbuf) - 13);
823 strcat(buf, "]");
825 snprintf(portbuf, sizeof(portbuf), "REMOTE_PORT=%d",
826 ntohs(sin6_addr->sin6_port));
827 #endif
830 cld.env = (const char **)env;
831 cld.argv = (const char **)cld_argv;
832 cld.in = incoming;
833 cld.out = dup(incoming);
835 if (start_command(&cld))
836 logerror("unable to fork");
837 else
838 add_child(&cld, addr, addrlen);
841 static void child_handler(int signo)
844 * Otherwise empty handler because systemcalls will get interrupted
845 * upon signal receipt
846 * SysV needs the handler to be rearmed
848 signal(SIGCHLD, child_handler);
851 static int set_reuse_addr(int sockfd)
853 int on = 1;
855 if (!reuseaddr)
856 return 0;
857 return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
858 &on, sizeof(on));
861 struct socketlist {
862 int *list;
863 size_t nr;
864 size_t alloc;
867 static const char *ip2str(int family, struct sockaddr *sin, socklen_t len)
869 #ifdef NO_IPV6
870 static char ip[INET_ADDRSTRLEN];
871 #else
872 static char ip[INET6_ADDRSTRLEN];
873 #endif
875 switch (family) {
876 #ifndef NO_IPV6
877 case AF_INET6:
878 inet_ntop(family, &((struct sockaddr_in6*)sin)->sin6_addr, ip, len);
879 break;
880 #endif
881 case AF_INET:
882 inet_ntop(family, &((struct sockaddr_in*)sin)->sin_addr, ip, len);
883 break;
884 default:
885 strcpy(ip, "<unknown>");
887 return ip;
890 #ifndef NO_IPV6
892 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
894 int socknum = 0;
895 char pbuf[NI_MAXSERV];
896 struct addrinfo hints, *ai0, *ai;
897 int gai;
898 long flags;
900 sprintf(pbuf, "%d", listen_port);
901 memset(&hints, 0, sizeof(hints));
902 hints.ai_family = AF_UNSPEC;
903 hints.ai_socktype = SOCK_STREAM;
904 hints.ai_protocol = IPPROTO_TCP;
905 hints.ai_flags = AI_PASSIVE;
907 gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
908 if (gai) {
909 logerror("getaddrinfo() for %s failed: %s", listen_addr, gai_strerror(gai));
910 return 0;
913 for (ai = ai0; ai; ai = ai->ai_next) {
914 int sockfd;
916 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
917 if (sockfd < 0)
918 continue;
919 if (sockfd >= FD_SETSIZE) {
920 logerror("Socket descriptor too large");
921 close(sockfd);
922 continue;
925 #ifdef IPV6_V6ONLY
926 if (ai->ai_family == AF_INET6) {
927 int on = 1;
928 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
929 &on, sizeof(on));
930 /* Note: error is not fatal */
932 #endif
934 if (set_reuse_addr(sockfd)) {
935 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
936 close(sockfd);
937 continue;
940 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
941 logerror("Could not bind to %s: %s",
942 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
943 strerror(errno));
944 close(sockfd);
945 continue; /* not fatal */
947 if (listen(sockfd, 5) < 0) {
948 logerror("Could not listen to %s: %s",
949 ip2str(ai->ai_family, ai->ai_addr, ai->ai_addrlen),
950 strerror(errno));
951 close(sockfd);
952 continue; /* not fatal */
955 flags = fcntl(sockfd, F_GETFD, 0);
956 if (flags >= 0)
957 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
959 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
960 socklist->list[socklist->nr++] = sockfd;
961 socknum++;
964 freeaddrinfo(ai0);
966 return socknum;
969 #else /* NO_IPV6 */
971 static int setup_named_sock(char *listen_addr, int listen_port, struct socketlist *socklist)
973 struct sockaddr_in sin;
974 int sockfd;
975 long flags;
977 memset(&sin, 0, sizeof sin);
978 sin.sin_family = AF_INET;
979 sin.sin_port = htons(listen_port);
981 if (listen_addr) {
982 /* Well, host better be an IP address here. */
983 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
984 return 0;
985 } else {
986 sin.sin_addr.s_addr = htonl(INADDR_ANY);
989 sockfd = socket(AF_INET, SOCK_STREAM, 0);
990 if (sockfd < 0)
991 return 0;
993 if (set_reuse_addr(sockfd)) {
994 logerror("Could not set SO_REUSEADDR: %s", strerror(errno));
995 close(sockfd);
996 return 0;
999 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
1000 logerror("Could not bind to %s: %s",
1001 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1002 strerror(errno));
1003 close(sockfd);
1004 return 0;
1007 if (listen(sockfd, 5) < 0) {
1008 logerror("Could not listen to %s: %s",
1009 ip2str(AF_INET, (struct sockaddr *)&sin, sizeof(sin)),
1010 strerror(errno));
1011 close(sockfd);
1012 return 0;
1015 flags = fcntl(sockfd, F_GETFD, 0);
1016 if (flags >= 0)
1017 fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
1019 ALLOC_GROW(socklist->list, socklist->nr + 1, socklist->alloc);
1020 socklist->list[socklist->nr++] = sockfd;
1021 return 1;
1024 #endif
1026 static void socksetup(struct string_list *listen_addr, int listen_port, struct socketlist *socklist)
1028 if (!listen_addr->nr)
1029 setup_named_sock(NULL, listen_port, socklist);
1030 else {
1031 int i, socknum;
1032 for (i = 0; i < listen_addr->nr; i++) {
1033 socknum = setup_named_sock(listen_addr->items[i].string,
1034 listen_port, socklist);
1036 if (socknum == 0)
1037 logerror("unable to allocate any listen sockets for host %s on port %u",
1038 listen_addr->items[i].string, listen_port);
1043 static int service_loop(struct socketlist *socklist)
1045 struct pollfd *pfd;
1046 int i;
1048 pfd = xcalloc(socklist->nr, sizeof(struct pollfd));
1050 for (i = 0; i < socklist->nr; i++) {
1051 pfd[i].fd = socklist->list[i];
1052 pfd[i].events = POLLIN;
1055 signal(SIGCHLD, child_handler);
1057 for (;;) {
1058 int i;
1060 check_dead_children();
1062 if (poll(pfd, socklist->nr, -1) < 0) {
1063 if (errno != EINTR) {
1064 logerror("Poll failed, resuming: %s",
1065 strerror(errno));
1066 sleep(1);
1068 continue;
1071 for (i = 0; i < socklist->nr; i++) {
1072 if (pfd[i].revents & POLLIN) {
1073 union {
1074 struct sockaddr sa;
1075 struct sockaddr_in sai;
1076 #ifndef NO_IPV6
1077 struct sockaddr_in6 sai6;
1078 #endif
1079 } ss;
1080 socklen_t sslen = sizeof(ss);
1081 int incoming = accept(pfd[i].fd, &ss.sa, &sslen);
1082 if (incoming < 0) {
1083 switch (errno) {
1084 case EAGAIN:
1085 case EINTR:
1086 case ECONNABORTED:
1087 continue;
1088 default:
1089 die_errno("accept returned");
1092 handle(incoming, &ss.sa, sslen);
1098 #ifdef NO_POSIX_GOODIES
1100 struct credentials;
1102 static void drop_privileges(struct credentials *cred)
1104 /* nothing */
1107 static struct credentials *prepare_credentials(const char *user_name,
1108 const char *group_name)
1110 die("--user not supported on this platform");
1113 #else
1115 struct credentials {
1116 struct passwd *pass;
1117 gid_t gid;
1120 static void drop_privileges(struct credentials *cred)
1122 if (cred && (initgroups(cred->pass->pw_name, cred->gid) ||
1123 setgid (cred->gid) || setuid(cred->pass->pw_uid)))
1124 die("cannot drop privileges");
1127 static struct credentials *prepare_credentials(const char *user_name,
1128 const char *group_name)
1130 static struct credentials c;
1132 c.pass = getpwnam(user_name);
1133 if (!c.pass)
1134 die("user not found - %s", user_name);
1136 if (!group_name)
1137 c.gid = c.pass->pw_gid;
1138 else {
1139 struct group *group = getgrnam(group_name);
1140 if (!group)
1141 die("group not found - %s", group_name);
1143 c.gid = group->gr_gid;
1146 return &c;
1148 #endif
1150 static void store_pid(const char *path)
1152 FILE *f = fopen(path, "w");
1153 if (!f)
1154 die_errno("cannot open pid file '%s'", path);
1155 if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
1156 die_errno("failed to write pid file '%s'", path);
1159 static int serve(struct string_list *listen_addr, int listen_port,
1160 struct credentials *cred)
1162 struct socketlist socklist = { NULL, 0, 0 };
1164 socksetup(listen_addr, listen_port, &socklist);
1165 if (socklist.nr == 0)
1166 die("unable to allocate any listen sockets on port %u",
1167 listen_port);
1169 drop_privileges(cred);
1171 loginfo("Ready to rumble");
1173 return service_loop(&socklist);
1176 int main(int argc, char **argv)
1178 int listen_port = 0;
1179 struct string_list listen_addr = STRING_LIST_INIT_NODUP;
1180 int serve_mode = 0, inetd_mode = 0;
1181 const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
1182 int detach = 0;
1183 struct credentials *cred = NULL;
1184 int i;
1186 git_setup_gettext();
1188 git_extract_argv0_path(argv[0]);
1190 for (i = 1; i < argc; i++) {
1191 char *arg = argv[i];
1192 const char *v;
1194 if (skip_prefix(arg, "--listen=", &v)) {
1195 string_list_append(&listen_addr, xstrdup_tolower(v));
1196 continue;
1198 if (skip_prefix(arg, "--port=", &v)) {
1199 char *end;
1200 unsigned long n;
1201 n = strtoul(v, &end, 0);
1202 if (*v && !*end) {
1203 listen_port = n;
1204 continue;
1207 if (!strcmp(arg, "--serve")) {
1208 serve_mode = 1;
1209 continue;
1211 if (!strcmp(arg, "--inetd")) {
1212 inetd_mode = 1;
1213 log_syslog = 1;
1214 continue;
1216 if (!strcmp(arg, "--verbose")) {
1217 verbose = 1;
1218 continue;
1220 if (!strcmp(arg, "--syslog")) {
1221 log_syslog = 1;
1222 continue;
1224 if (!strcmp(arg, "--export-all")) {
1225 export_all_trees = 1;
1226 continue;
1228 if (skip_prefix(arg, "--access-hook=", &v)) {
1229 access_hook = v;
1230 continue;
1232 if (skip_prefix(arg, "--timeout=", &v)) {
1233 timeout = atoi(v);
1234 continue;
1236 if (skip_prefix(arg, "--init-timeout=", &v)) {
1237 init_timeout = atoi(v);
1238 continue;
1240 if (skip_prefix(arg, "--max-connections=", &v)) {
1241 max_connections = atoi(v);
1242 if (max_connections < 0)
1243 max_connections = 0; /* unlimited */
1244 continue;
1246 if (!strcmp(arg, "--strict-paths")) {
1247 strict_paths = 1;
1248 continue;
1250 if (skip_prefix(arg, "--base-path=", &v)) {
1251 base_path = v;
1252 continue;
1254 if (!strcmp(arg, "--base-path-relaxed")) {
1255 base_path_relaxed = 1;
1256 continue;
1258 if (skip_prefix(arg, "--interpolated-path=", &v)) {
1259 interpolated_path = v;
1260 continue;
1262 if (!strcmp(arg, "--reuseaddr")) {
1263 reuseaddr = 1;
1264 continue;
1266 if (!strcmp(arg, "--user-path")) {
1267 user_path = "";
1268 continue;
1270 if (skip_prefix(arg, "--user-path=", &v)) {
1271 user_path = v;
1272 continue;
1274 if (skip_prefix(arg, "--pid-file=", &v)) {
1275 pid_file = v;
1276 continue;
1278 if (!strcmp(arg, "--detach")) {
1279 detach = 1;
1280 log_syslog = 1;
1281 continue;
1283 if (skip_prefix(arg, "--user=", &v)) {
1284 user_name = v;
1285 continue;
1287 if (skip_prefix(arg, "--group=", &v)) {
1288 group_name = v;
1289 continue;
1291 if (skip_prefix(arg, "--enable=", &v)) {
1292 enable_service(v, 1);
1293 continue;
1295 if (skip_prefix(arg, "--disable=", &v)) {
1296 enable_service(v, 0);
1297 continue;
1299 if (skip_prefix(arg, "--allow-override=", &v)) {
1300 make_service_overridable(v, 1);
1301 continue;
1303 if (skip_prefix(arg, "--forbid-override=", &v)) {
1304 make_service_overridable(v, 0);
1305 continue;
1307 if (!strcmp(arg, "--informative-errors")) {
1308 informative_errors = 1;
1309 continue;
1311 if (!strcmp(arg, "--no-informative-errors")) {
1312 informative_errors = 0;
1313 continue;
1315 if (!strcmp(arg, "--")) {
1316 ok_paths = &argv[i+1];
1317 break;
1318 } else if (arg[0] != '-') {
1319 ok_paths = &argv[i];
1320 break;
1323 usage(daemon_usage);
1326 if (log_syslog) {
1327 openlog("git-daemon", LOG_PID, LOG_DAEMON);
1328 set_die_routine(daemon_die);
1329 } else
1330 /* avoid splitting a message in the middle */
1331 setvbuf(stderr, NULL, _IOFBF, 4096);
1333 if (inetd_mode && (detach || group_name || user_name))
1334 die("--detach, --user and --group are incompatible with --inetd");
1336 if (inetd_mode && (listen_port || (listen_addr.nr > 0)))
1337 die("--listen= and --port= are incompatible with --inetd");
1338 else if (listen_port == 0)
1339 listen_port = DEFAULT_GIT_PORT;
1341 if (group_name && !user_name)
1342 die("--group supplied without --user");
1344 if (user_name)
1345 cred = prepare_credentials(user_name, group_name);
1347 if (strict_paths && (!ok_paths || !*ok_paths))
1348 die("option --strict-paths requires a whitelist");
1350 if (base_path && !is_directory(base_path))
1351 die("base-path '%s' does not exist or is not a directory",
1352 base_path);
1354 if (inetd_mode) {
1355 if (!freopen("/dev/null", "w", stderr))
1356 die_errno("failed to redirect stderr to /dev/null");
1359 if (inetd_mode || serve_mode)
1360 return execute();
1362 if (detach) {
1363 if (daemonize())
1364 die("--detach not supported on this platform");
1365 } else
1366 sanitize_stdfds();
1368 if (pid_file)
1369 store_pid(pid_file);
1371 /* prepare argv for serving-processes */
1372 cld_argv = xmalloc(sizeof (char *) * (argc + 2));
1373 cld_argv[0] = argv[0]; /* git-daemon */
1374 cld_argv[1] = "--serve";
1375 for (i = 1; i < argc; ++i)
1376 cld_argv[i+1] = argv[i];
1377 cld_argv[argc+1] = NULL;
1379 return serve(&listen_addr, listen_port, cred);