5 #include "environment.h"
7 #include "run-command.h"
10 #include "string-list.h"
14 #define initgroups(x, y) (0) /* nothing */
17 static enum log_destination
{
18 LOG_DESTINATION_UNSET
= -1,
19 LOG_DESTINATION_NONE
= 0,
20 LOG_DESTINATION_STDERR
= 1,
21 LOG_DESTINATION_SYSLOG
= 2,
22 } log_destination
= LOG_DESTINATION_UNSET
;
25 static int informative_errors
;
27 static const char daemon_usage
[] =
28 "git daemon [--verbose] [--syslog] [--export-all]\n"
29 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
30 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
31 " [--user-path | --user-path=<path>]\n"
32 " [--interpolated-path=<path>]\n"
33 " [--reuseaddr] [--pid-file=<file>]\n"
34 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
35 " [--access-hook=<path>]\n"
36 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
37 " [--detach] [--user=<user> [--group=<group>]]\n"
38 " [--log-destination=(stderr|syslog|none)]\n"
41 /* List of acceptable pathname prefixes */
42 static const char **ok_paths
;
43 static int strict_paths
;
45 /* If this is set, git-daemon-export-ok is not required */
46 static int export_all_trees
;
48 /* Take all paths relative to this one if non-NULL */
49 static const char *base_path
;
50 static const char *interpolated_path
;
51 static int base_path_relaxed
;
53 /* If defined, ~user notation is allowed and the string is inserted
54 * after ~user/. E.g. a request to git://host/~alice/frotz would
55 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
57 static const char *user_path
;
59 /* Timeout, and initial timeout */
60 static unsigned int timeout
;
61 static unsigned int init_timeout
;
64 struct strbuf hostname
;
65 struct strbuf canon_hostname
;
66 struct strbuf ip_address
;
67 struct strbuf tcp_port
;
68 unsigned int hostname_lookup_done
:1;
69 unsigned int saw_extended_args
:1;
71 #define HOSTINFO_INIT { \
72 .hostname = STRBUF_INIT, \
73 .canon_hostname = STRBUF_INIT, \
74 .ip_address = STRBUF_INIT, \
75 .tcp_port = STRBUF_INIT, \
78 static void lookup_hostname(struct hostinfo
*hi
);
80 static const char *get_canon_hostname(struct hostinfo
*hi
)
83 return hi
->canon_hostname
.buf
;
86 static const char *get_ip_address(struct hostinfo
*hi
)
89 return hi
->ip_address
.buf
;
92 static void logreport(int priority
, const char *err
, va_list params
)
94 switch (log_destination
) {
95 case LOG_DESTINATION_SYSLOG
: {
97 vsnprintf(buf
, sizeof(buf
), err
, params
);
98 syslog(priority
, "%s", buf
);
101 case LOG_DESTINATION_STDERR
:
103 * Since stderr is set to buffered mode, the
104 * logging of different processes will not overlap
105 * unless they overflow the (rather big) buffers.
107 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
108 vfprintf(stderr
, err
, params
);
112 case LOG_DESTINATION_NONE
:
114 case LOG_DESTINATION_UNSET
:
115 BUG("log destination not initialized correctly");
119 __attribute__((format (printf
, 1, 2)))
120 static void logerror(const char *err
, ...)
123 va_start(params
, err
);
124 logreport(LOG_ERR
, err
, params
);
128 __attribute__((format (printf
, 1, 2)))
129 static void loginfo(const char *err
, ...)
134 va_start(params
, err
);
135 logreport(LOG_INFO
, err
, params
);
139 static void NORETURN
daemon_die(const char *err
, va_list params
)
141 logreport(LOG_ERR
, err
, params
);
145 struct expand_path_context
{
146 const char *directory
;
147 struct hostinfo
*hostinfo
;
150 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
152 struct expand_path_context
*context
= ctx
;
153 struct hostinfo
*hi
= context
->hostinfo
;
155 switch (placeholder
[0]) {
157 strbuf_addbuf(sb
, &hi
->hostname
);
160 if (placeholder
[1] == 'H') {
161 strbuf_addstr(sb
, get_canon_hostname(hi
));
166 if (placeholder
[1] == 'P') {
167 strbuf_addstr(sb
, get_ip_address(hi
));
172 strbuf_addbuf(sb
, &hi
->tcp_port
);
175 strbuf_addstr(sb
, context
->directory
);
181 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
183 static char rpath
[PATH_MAX
];
184 static char interp_path
[PATH_MAX
];
191 if (daemon_avoid_alias(dir
)) {
192 logerror("'%s': aliased", dir
);
198 logerror("'%s': User-path not allowed", dir
);
202 /* Got either "~alice" or "~alice/foo";
203 * rewrite them to "~alice/%s" or
206 int namlen
, restlen
= strlen(dir
);
207 const char *slash
= strchr(dir
, '/');
209 slash
= dir
+ restlen
;
210 namlen
= slash
- dir
;
212 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
213 rlen
= snprintf(rpath
, sizeof(rpath
), "%.*s/%s%.*s",
214 namlen
, dir
, user_path
, restlen
, slash
);
215 if (rlen
>= sizeof(rpath
)) {
216 logerror("user-path too large: %s", rpath
);
222 else if (interpolated_path
&& hi
->saw_extended_args
) {
223 struct strbuf expanded_path
= STRBUF_INIT
;
224 struct expand_path_context context
;
226 context
.directory
= directory
;
227 context
.hostinfo
= hi
;
230 /* Allow only absolute */
231 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
235 strbuf_expand(&expanded_path
, interpolated_path
,
236 expand_path
, &context
);
238 rlen
= strlcpy(interp_path
, expanded_path
.buf
,
239 sizeof(interp_path
));
240 strbuf_release(&expanded_path
);
241 if (rlen
>= sizeof(interp_path
)) {
242 logerror("interpolated path too large: %s",
247 loginfo("Interpolated dir '%s'", interp_path
);
251 else if (base_path
) {
253 /* Allow only absolute */
254 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
257 rlen
= snprintf(rpath
, sizeof(rpath
), "%s%s", base_path
, dir
);
258 if (rlen
>= sizeof(rpath
)) {
259 logerror("base-path too large: %s", rpath
);
265 path
= enter_repo(dir
, strict_paths
);
266 if (!path
&& base_path
&& base_path_relaxed
) {
268 * if we fail and base_path_relaxed is enabled, try without
269 * prefixing the base path
272 path
= enter_repo(dir
, strict_paths
);
276 logerror("'%s' does not appear to be a git repository", dir
);
280 if ( ok_paths
&& *ok_paths
) {
282 int pathlen
= strlen(path
);
284 /* The validation is done on the paths after enter_repo
285 * appends optional {.git,.git/.git} and friends, but
286 * it does not use getcwd(). So if your /pub is
287 * a symlink to /mnt/pub, you can include /pub and
288 * do not have to say /mnt/pub.
291 for ( pp
= ok_paths
; *pp
; pp
++ ) {
292 int len
= strlen(*pp
);
293 if (len
<= pathlen
&&
294 !memcmp(*pp
, path
, len
) &&
295 (path
[len
] == '\0' ||
296 (!strict_paths
&& path
[len
] == '/')))
301 /* be backwards compatible */
306 logerror("'%s': not in directory list", path
);
307 return NULL
; /* Fallthrough. Deny by default */
310 typedef int (*daemon_service_fn
)(const struct strvec
*env
);
311 struct daemon_service
{
313 const char *config_name
;
314 daemon_service_fn fn
;
319 static int daemon_error(const char *dir
, const char *msg
)
321 if (!informative_errors
)
322 msg
= "access denied or repository not exported";
323 packet_write_fmt(1, "ERR %s: %s", msg
, dir
);
327 static const char *access_hook
;
329 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
330 const char *path
, struct hostinfo
*hi
)
332 struct child_process child
= CHILD_PROCESS_INIT
;
333 struct strbuf buf
= STRBUF_INIT
;
337 strvec_push(&child
.args
, access_hook
);
338 strvec_push(&child
.args
, service
->name
);
339 strvec_push(&child
.args
, path
);
340 strvec_push(&child
.args
, hi
->hostname
.buf
);
341 strvec_push(&child
.args
, get_canon_hostname(hi
));
342 strvec_push(&child
.args
, get_ip_address(hi
));
343 strvec_push(&child
.args
, hi
->tcp_port
.buf
);
349 if (start_command(&child
)) {
350 logerror("daemon access hook '%s' failed to start",
354 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
355 logerror("failed to read from pipe to daemon access hook '%s'",
360 if (close(child
.out
) < 0) {
361 logerror("failed to close pipe to daemon access hook '%s'",
365 if (finish_command(&child
))
369 strbuf_release(&buf
);
376 strbuf_addstr(&buf
, "service rejected");
377 eol
= strchr(buf
.buf
, '\n');
381 daemon_error(dir
, buf
.buf
);
382 strbuf_release(&buf
);
386 static int run_service(const char *dir
, struct daemon_service
*service
,
387 struct hostinfo
*hi
, const struct strvec
*env
)
390 int enabled
= service
->enabled
;
391 struct strbuf var
= STRBUF_INIT
;
393 loginfo("Request %s for '%s'", service
->name
, dir
);
395 if (!enabled
&& !service
->overridable
) {
396 logerror("'%s': service not enabled.", service
->name
);
398 return daemon_error(dir
, "service not enabled");
401 if (!(path
= path_ok(dir
, hi
)))
402 return daemon_error(dir
, "no such repository");
405 * Security on the cheap.
407 * We want a readable HEAD, usable "objects" directory, and
408 * a "git-daemon-export-ok" flag that says that the other side
409 * is ok with us doing this.
411 * path_ok() uses enter_repo() and checks for included directories.
412 * We only need to make sure the repository is exported.
415 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
416 logerror("'%s': repository not exported.", path
);
418 return daemon_error(dir
, "repository not exported");
421 if (service
->overridable
) {
422 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
423 git_config_get_bool(var
.buf
, &enabled
);
424 strbuf_release(&var
);
427 logerror("'%s': service not enabled for '%s'",
428 service
->name
, path
);
430 return daemon_error(dir
, "service not enabled");
434 * Optionally, a hook can choose to deny access to the
435 * repository depending on the phase of the moon.
437 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
441 * We'll ignore SIGTERM from now on, we have a
444 signal(SIGTERM
, SIG_IGN
);
446 return service
->fn(env
);
449 static void copy_to_log(int fd
)
451 struct strbuf line
= STRBUF_INIT
;
454 fp
= fdopen(fd
, "r");
456 logerror("fdopen of error channel failed");
461 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
462 logerror("%s", line
.buf
);
463 strbuf_setlen(&line
, 0);
466 strbuf_release(&line
);
470 static int run_service_command(struct child_process
*cld
)
472 strvec_push(&cld
->args
, ".");
475 if (start_command(cld
))
481 copy_to_log(cld
->err
);
483 return finish_command(cld
);
486 static int upload_pack(const struct strvec
*env
)
488 struct child_process cld
= CHILD_PROCESS_INIT
;
489 strvec_pushl(&cld
.args
, "upload-pack", "--strict", NULL
);
490 strvec_pushf(&cld
.args
, "--timeout=%u", timeout
);
492 strvec_pushv(&cld
.env
, env
->v
);
494 return run_service_command(&cld
);
497 static int upload_archive(const struct strvec
*env
)
499 struct child_process cld
= CHILD_PROCESS_INIT
;
500 strvec_push(&cld
.args
, "upload-archive");
502 strvec_pushv(&cld
.env
, env
->v
);
504 return run_service_command(&cld
);
507 static int receive_pack(const struct strvec
*env
)
509 struct child_process cld
= CHILD_PROCESS_INIT
;
510 strvec_push(&cld
.args
, "receive-pack");
512 strvec_pushv(&cld
.env
, env
->v
);
514 return run_service_command(&cld
);
517 static struct daemon_service daemon_service
[] = {
518 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
519 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
520 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
523 static void enable_service(const char *name
, int ena
)
526 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
527 if (!strcmp(daemon_service
[i
].name
, name
)) {
528 daemon_service
[i
].enabled
= ena
;
532 die("No such service %s", name
);
535 static void make_service_overridable(const char *name
, int ena
)
538 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
539 if (!strcmp(daemon_service
[i
].name
, name
)) {
540 daemon_service
[i
].overridable
= ena
;
544 die("No such service %s", name
);
547 static void parse_host_and_port(char *hostport
, char **host
,
550 if (*hostport
== '[') {
553 end
= strchr(hostport
, ']');
555 die("Invalid request ('[' without ']')");
557 *host
= hostport
+ 1;
560 else if (end
[1] == ':')
563 die("Garbage after end of host part");
566 *port
= strrchr(hostport
, ':');
575 * Sanitize a string from the client so that it's OK to be inserted into a
576 * filesystem path. Specifically, we disallow directory separators, runs
577 * of "..", and trailing and leading dots, which means that the client
578 * cannot escape our base path via ".." traversal.
580 static void sanitize_client(struct strbuf
*out
, const char *in
)
585 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
587 strbuf_addch(out
, *in
);
590 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
591 strbuf_setlen(out
, out
->len
- 1);
595 * Like sanitize_client, but we also perform any canonicalization
596 * to make life easier on the admin.
598 static void canonicalize_client(struct strbuf
*out
, const char *in
)
600 sanitize_client(out
, in
);
605 * Read the host as supplied by the client connection.
607 * Returns a pointer to the character after the NUL byte terminating the host
608 * argument, or 'extra_args' if there is no host argument.
610 static char *parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
614 char *end
= extra_args
+ buflen
;
616 if (extra_args
< end
&& *extra_args
) {
617 hi
->saw_extended_args
= 1;
618 if (strncasecmp("host=", extra_args
, 5) == 0) {
619 val
= extra_args
+ 5;
620 vallen
= strlen(val
) + 1;
621 loginfo("Extended attribute \"host\": %s", val
);
623 /* Split <host>:<port> at colon. */
626 parse_host_and_port(val
, &host
, &port
);
628 sanitize_client(&hi
->tcp_port
, port
);
629 canonicalize_client(&hi
->hostname
, host
);
630 hi
->hostname_lookup_done
= 0;
633 /* On to the next one */
634 extra_args
= val
+ vallen
;
636 if (extra_args
< end
&& *extra_args
)
637 die("Invalid request");
643 static void parse_extra_args(struct hostinfo
*hi
, struct strvec
*env
,
644 char *extra_args
, int buflen
)
646 const char *end
= extra_args
+ buflen
;
647 struct strbuf git_protocol
= STRBUF_INIT
;
649 /* First look for the host argument */
650 extra_args
= parse_host_arg(hi
, extra_args
, buflen
);
652 /* Look for additional arguments places after a second NUL byte */
653 for (; extra_args
< end
; extra_args
+= strlen(extra_args
) + 1) {
654 const char *arg
= extra_args
;
657 * Parse the extra arguments, adding most to 'git_protocol'
658 * which will be used to set the 'GIT_PROTOCOL' envvar in the
659 * service that will be run.
661 * If there ends up being a particular arg in the future that
662 * git-daemon needs to parse specifically (like the 'host' arg)
663 * then it can be parsed here and not added to 'git_protocol'.
666 if (git_protocol
.len
> 0)
667 strbuf_addch(&git_protocol
, ':');
668 strbuf_addstr(&git_protocol
, arg
);
672 if (git_protocol
.len
> 0) {
673 loginfo("Extended attribute \"protocol\": %s", git_protocol
.buf
);
674 strvec_pushf(env
, GIT_PROTOCOL_ENVIRONMENT
"=%s",
677 strbuf_release(&git_protocol
);
681 * Locate canonical hostname and its IP address.
683 static void lookup_hostname(struct hostinfo
*hi
)
685 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
687 struct addrinfo hints
;
690 static char addrbuf
[HOST_NAME_MAX
+ 1];
692 memset(&hints
, 0, sizeof(hints
));
693 hints
.ai_flags
= AI_CANONNAME
;
695 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
697 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
699 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
700 addrbuf
, sizeof(addrbuf
));
701 strbuf_addstr(&hi
->ip_address
, addrbuf
);
703 if (ai
->ai_canonname
)
704 sanitize_client(&hi
->canon_hostname
,
707 strbuf_addbuf(&hi
->canon_hostname
,
713 struct hostent
*hent
;
714 struct sockaddr_in sa
;
716 static char addrbuf
[HOST_NAME_MAX
+ 1];
718 hent
= gethostbyname(hi
->hostname
.buf
);
720 ap
= hent
->h_addr_list
;
721 memset(&sa
, 0, sizeof sa
);
722 sa
.sin_family
= hent
->h_addrtype
;
723 sa
.sin_port
= htons(0);
724 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
726 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
727 addrbuf
, sizeof(addrbuf
));
729 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
730 strbuf_addstr(&hi
->ip_address
, addrbuf
);
733 hi
->hostname_lookup_done
= 1;
737 static void hostinfo_clear(struct hostinfo
*hi
)
739 strbuf_release(&hi
->hostname
);
740 strbuf_release(&hi
->canon_hostname
);
741 strbuf_release(&hi
->ip_address
);
742 strbuf_release(&hi
->tcp_port
);
745 static void set_keep_alive(int sockfd
)
749 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0) {
750 if (errno
!= ENOTSOCK
)
751 logerror("unable to set SO_KEEPALIVE on socket: %s",
756 static int execute(void)
758 char *line
= packet_buffer
;
760 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
761 struct hostinfo hi
= HOSTINFO_INIT
;
762 struct strvec env
= STRVEC_INIT
;
765 loginfo("Connection from %s:%s", addr
, port
);
768 alarm(init_timeout
? init_timeout
: timeout
);
769 pktlen
= packet_read(0, packet_buffer
, sizeof(packet_buffer
), 0);
773 if (len
&& line
[len
-1] == '\n')
776 /* parse additional args hidden behind a NUL byte */
778 parse_extra_args(&hi
, &env
, line
+ len
+ 1, pktlen
- len
- 1);
780 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
781 struct daemon_service
*s
= &(daemon_service
[i
]);
784 if (skip_prefix(line
, "git-", &arg
) &&
785 skip_prefix(arg
, s
->name
, &arg
) &&
788 * Note: The directory here is probably context sensitive,
789 * and might depend on the actual service being performed.
791 int rc
= run_service(arg
, s
, &hi
, &env
);
800 logerror("Protocol error: '%s'", line
);
804 static int addrcmp(const struct sockaddr_storage
*s1
,
805 const struct sockaddr_storage
*s2
)
807 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
808 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
810 if (sa1
->sa_family
!= sa2
->sa_family
)
811 return sa1
->sa_family
- sa2
->sa_family
;
812 if (sa1
->sa_family
== AF_INET
)
813 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
814 &((struct sockaddr_in
*)s2
)->sin_addr
,
815 sizeof(struct in_addr
));
817 if (sa1
->sa_family
== AF_INET6
)
818 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
819 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
820 sizeof(struct in6_addr
));
825 static int max_connections
= 32;
827 static unsigned int live_children
;
829 static struct child
{
831 struct child_process cld
;
832 struct sockaddr_storage address
;
835 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
837 struct child
*newborn
, **cradle
;
839 CALLOC_ARRAY(newborn
, 1);
841 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
842 memcpy(&newborn
->address
, addr
, addrlen
);
843 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
844 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
846 newborn
->next
= *cradle
;
851 * This gets called if the number of connections grows
852 * past "max_connections".
854 * We kill the newest connection from a duplicate IP.
856 static void kill_some_child(void)
858 const struct child
*blanket
, *next
;
860 if (!(blanket
= firstborn
))
863 for (; (next
= blanket
->next
); blanket
= next
)
864 if (!addrcmp(&blanket
->address
, &next
->address
)) {
865 kill(blanket
->cld
.pid
, SIGTERM
);
870 static void check_dead_children(void)
875 struct child
**cradle
, *blanket
;
876 for (cradle
= &firstborn
; (blanket
= *cradle
);)
877 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
878 const char *dead
= "";
880 dead
= " (with error)";
881 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
883 /* remove the child */
884 *cradle
= blanket
->next
;
886 child_process_clear(&blanket
->cld
);
889 cradle
= &blanket
->next
;
892 static struct strvec cld_argv
= STRVEC_INIT
;
893 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
895 struct child_process cld
= CHILD_PROCESS_INIT
;
897 if (max_connections
&& live_children
>= max_connections
) {
899 sleep(1); /* give it some time to die */
900 check_dead_children();
901 if (live_children
>= max_connections
) {
903 logerror("Too many children, dropping connection");
908 if (addr
->sa_family
== AF_INET
) {
910 struct sockaddr_in
*sin_addr
= (void *) addr
;
911 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
912 strvec_pushf(&cld
.env
, "REMOTE_ADDR=%s", buf
);
913 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
914 ntohs(sin_addr
->sin_port
));
916 } else if (addr
->sa_family
== AF_INET6
) {
918 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
919 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
920 strvec_pushf(&cld
.env
, "REMOTE_ADDR=[%s]", buf
);
921 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
922 ntohs(sin6_addr
->sin6_port
));
926 strvec_pushv(&cld
.args
, cld_argv
.v
);
928 cld
.out
= dup(incoming
);
930 if (start_command(&cld
))
931 logerror("unable to fork");
933 add_child(&cld
, addr
, addrlen
);
936 static void child_handler(int signo UNUSED
)
939 * Otherwise empty handler because systemcalls will get interrupted
940 * upon signal receipt
941 * SysV needs the handler to be rearmed
943 signal(SIGCHLD
, child_handler
);
946 static int set_reuse_addr(int sockfd
)
952 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
962 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
965 static char ip
[INET_ADDRSTRLEN
];
967 static char ip
[INET6_ADDRSTRLEN
];
973 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
977 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
980 xsnprintf(ip
, sizeof(ip
), "<unknown>");
987 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
990 char pbuf
[NI_MAXSERV
];
991 struct addrinfo hints
, *ai0
, *ai
;
995 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
996 memset(&hints
, 0, sizeof(hints
));
997 hints
.ai_family
= AF_UNSPEC
;
998 hints
.ai_socktype
= SOCK_STREAM
;
999 hints
.ai_protocol
= IPPROTO_TCP
;
1000 hints
.ai_flags
= AI_PASSIVE
;
1002 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
1004 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
1008 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
1011 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
1014 if (sockfd
>= FD_SETSIZE
) {
1015 logerror("Socket descriptor too large");
1021 if (ai
->ai_family
== AF_INET6
) {
1023 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
1025 /* Note: error is not fatal */
1029 if (set_reuse_addr(sockfd
)) {
1030 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1035 set_keep_alive(sockfd
);
1037 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1038 logerror("Could not bind to %s: %s",
1039 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1042 continue; /* not fatal */
1044 if (listen(sockfd
, 5) < 0) {
1045 logerror("Could not listen to %s: %s",
1046 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1049 continue; /* not fatal */
1052 flags
= fcntl(sockfd
, F_GETFD
, 0);
1054 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1056 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1057 socklist
->list
[socklist
->nr
++] = sockfd
;
1068 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1070 struct sockaddr_in sin
;
1074 memset(&sin
, 0, sizeof sin
);
1075 sin
.sin_family
= AF_INET
;
1076 sin
.sin_port
= htons(listen_port
);
1079 /* Well, host better be an IP address here. */
1080 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1083 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1086 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1090 if (set_reuse_addr(sockfd
)) {
1091 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1096 set_keep_alive(sockfd
);
1098 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1099 logerror("Could not bind to %s: %s",
1100 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1106 if (listen(sockfd
, 5) < 0) {
1107 logerror("Could not listen to %s: %s",
1108 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1114 flags
= fcntl(sockfd
, F_GETFD
, 0);
1116 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1118 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1119 socklist
->list
[socklist
->nr
++] = sockfd
;
1125 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1127 if (!listen_addr
->nr
)
1128 setup_named_sock(NULL
, listen_port
, socklist
);
1131 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1132 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1133 listen_port
, socklist
);
1136 logerror("unable to allocate any listen sockets for host %s on port %u",
1137 listen_addr
->items
[i
].string
, listen_port
);
1142 static int service_loop(struct socketlist
*socklist
)
1147 CALLOC_ARRAY(pfd
, socklist
->nr
);
1149 for (i
= 0; i
< socklist
->nr
; i
++) {
1150 pfd
[i
].fd
= socklist
->list
[i
];
1151 pfd
[i
].events
= POLLIN
;
1154 signal(SIGCHLD
, child_handler
);
1159 check_dead_children();
1161 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1162 if (errno
!= EINTR
) {
1163 logerror("Poll failed, resuming: %s",
1170 for (i
= 0; i
< socklist
->nr
; i
++) {
1171 if (pfd
[i
].revents
& POLLIN
) {
1174 struct sockaddr_in sai
;
1176 struct sockaddr_in6 sai6
;
1179 socklen_t sslen
= sizeof(ss
);
1180 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1188 die_errno("accept returned");
1191 handle(incoming
, &ss
.sa
, sslen
);
1197 #ifdef NO_POSIX_GOODIES
1201 static void drop_privileges(struct credentials
*cred
)
1206 static struct credentials
*prepare_credentials(const char *user_name
,
1207 const char *group_name
)
1209 die("--user not supported on this platform");
1214 struct credentials
{
1215 struct passwd
*pass
;
1219 static void drop_privileges(struct credentials
*cred
)
1221 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1222 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1223 die("cannot drop privileges");
1226 static struct credentials
*prepare_credentials(const char *user_name
,
1227 const char *group_name
)
1229 static struct credentials c
;
1231 c
.pass
= getpwnam(user_name
);
1233 die("user not found - %s", user_name
);
1236 c
.gid
= c
.pass
->pw_gid
;
1238 struct group
*group
= getgrnam(group_name
);
1240 die("group not found - %s", group_name
);
1242 c
.gid
= group
->gr_gid
;
1249 static int serve(struct string_list
*listen_addr
, int listen_port
,
1250 struct credentials
*cred
)
1252 struct socketlist socklist
= { NULL
, 0, 0 };
1254 socksetup(listen_addr
, listen_port
, &socklist
);
1255 if (socklist
.nr
== 0)
1256 die("unable to allocate any listen sockets on port %u",
1259 drop_privileges(cred
);
1261 loginfo("Ready to rumble");
1263 return service_loop(&socklist
);
1266 int cmd_main(int argc
, const char **argv
)
1268 int listen_port
= 0;
1269 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1270 int serve_mode
= 0, inetd_mode
= 0;
1271 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1273 struct credentials
*cred
= NULL
;
1276 for (i
= 1; i
< argc
; i
++) {
1277 const char *arg
= argv
[i
];
1280 if (skip_prefix(arg
, "--listen=", &v
)) {
1281 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1284 if (skip_prefix(arg
, "--port=", &v
)) {
1287 n
= strtoul(v
, &end
, 0);
1293 if (!strcmp(arg
, "--serve")) {
1297 if (!strcmp(arg
, "--inetd")) {
1301 if (!strcmp(arg
, "--verbose")) {
1305 if (!strcmp(arg
, "--syslog")) {
1306 log_destination
= LOG_DESTINATION_SYSLOG
;
1309 if (skip_prefix(arg
, "--log-destination=", &v
)) {
1310 if (!strcmp(v
, "syslog")) {
1311 log_destination
= LOG_DESTINATION_SYSLOG
;
1313 } else if (!strcmp(v
, "stderr")) {
1314 log_destination
= LOG_DESTINATION_STDERR
;
1316 } else if (!strcmp(v
, "none")) {
1317 log_destination
= LOG_DESTINATION_NONE
;
1320 die("unknown log destination '%s'", v
);
1322 if (!strcmp(arg
, "--export-all")) {
1323 export_all_trees
= 1;
1326 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1330 if (skip_prefix(arg
, "--timeout=", &v
)) {
1334 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1335 init_timeout
= atoi(v
);
1338 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1339 max_connections
= atoi(v
);
1340 if (max_connections
< 0)
1341 max_connections
= 0; /* unlimited */
1344 if (!strcmp(arg
, "--strict-paths")) {
1348 if (skip_prefix(arg
, "--base-path=", &v
)) {
1352 if (!strcmp(arg
, "--base-path-relaxed")) {
1353 base_path_relaxed
= 1;
1356 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1357 interpolated_path
= v
;
1360 if (!strcmp(arg
, "--reuseaddr")) {
1364 if (!strcmp(arg
, "--user-path")) {
1368 if (skip_prefix(arg
, "--user-path=", &v
)) {
1372 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1376 if (!strcmp(arg
, "--detach")) {
1380 if (skip_prefix(arg
, "--user=", &v
)) {
1384 if (skip_prefix(arg
, "--group=", &v
)) {
1388 if (skip_prefix(arg
, "--enable=", &v
)) {
1389 enable_service(v
, 1);
1392 if (skip_prefix(arg
, "--disable=", &v
)) {
1393 enable_service(v
, 0);
1396 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1397 make_service_overridable(v
, 1);
1400 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1401 make_service_overridable(v
, 0);
1404 if (!strcmp(arg
, "--informative-errors")) {
1405 informative_errors
= 1;
1408 if (!strcmp(arg
, "--no-informative-errors")) {
1409 informative_errors
= 0;
1412 if (!strcmp(arg
, "--")) {
1413 ok_paths
= &argv
[i
+1];
1415 } else if (arg
[0] != '-') {
1416 ok_paths
= &argv
[i
];
1420 usage(daemon_usage
);
1423 if (log_destination
== LOG_DESTINATION_UNSET
) {
1424 if (inetd_mode
|| detach
)
1425 log_destination
= LOG_DESTINATION_SYSLOG
;
1427 log_destination
= LOG_DESTINATION_STDERR
;
1430 if (log_destination
== LOG_DESTINATION_SYSLOG
) {
1431 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1432 set_die_routine(daemon_die
);
1434 /* avoid splitting a message in the middle */
1435 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1437 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1438 die("--detach, --user and --group are incompatible with --inetd");
1440 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1441 die("--listen= and --port= are incompatible with --inetd");
1442 else if (listen_port
== 0)
1443 listen_port
= DEFAULT_GIT_PORT
;
1445 if (group_name
&& !user_name
)
1446 die("--group supplied without --user");
1449 cred
= prepare_credentials(user_name
, group_name
);
1451 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1452 die("option --strict-paths requires '<directory>' arguments");
1454 if (base_path
&& !is_directory(base_path
))
1455 die("base-path '%s' does not exist or is not a directory",
1458 if (log_destination
!= LOG_DESTINATION_STDERR
) {
1459 if (!freopen("/dev/null", "w", stderr
))
1460 die_errno("failed to redirect stderr to /dev/null");
1463 if (inetd_mode
|| serve_mode
)
1468 die("--detach not supported on this platform");
1472 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1474 /* prepare argv for serving-processes */
1475 strvec_push(&cld_argv
, argv
[0]); /* git-daemon */
1476 strvec_push(&cld_argv
, "--serve");
1477 for (i
= 1; i
< argc
; ++i
)
1478 strvec_push(&cld_argv
, argv
[i
]);
1480 return serve(&listen_addr
, listen_port
, cred
);