1 #include "git-compat-util.h"
5 #include "environment.h"
9 #include "run-command.h"
12 #include "string-list.h"
16 #define initgroups(x, y) (0) /* nothing */
19 static enum log_destination
{
20 LOG_DESTINATION_UNSET
= -1,
21 LOG_DESTINATION_NONE
= 0,
22 LOG_DESTINATION_STDERR
= 1,
23 LOG_DESTINATION_SYSLOG
= 2,
24 } log_destination
= LOG_DESTINATION_UNSET
;
27 static int informative_errors
;
29 static const char daemon_usage
[] =
30 "git daemon [--verbose] [--syslog] [--export-all]\n"
31 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
32 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
33 " [--user-path | --user-path=<path>]\n"
34 " [--interpolated-path=<path>]\n"
35 " [--reuseaddr] [--pid-file=<file>]\n"
36 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
37 " [--access-hook=<path>]\n"
38 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
39 " [--detach] [--user=<user> [--group=<group>]]\n"
40 " [--log-destination=(stderr|syslog|none)]\n"
43 /* List of acceptable pathname prefixes */
44 static const char **ok_paths
;
45 static int strict_paths
;
47 /* If this is set, git-daemon-export-ok is not required */
48 static int export_all_trees
;
50 /* Take all paths relative to this one if non-NULL */
51 static const char *base_path
;
52 static const char *interpolated_path
;
53 static int base_path_relaxed
;
55 /* If defined, ~user notation is allowed and the string is inserted
56 * after ~user/. E.g. a request to git://host/~alice/frotz would
57 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
59 static const char *user_path
;
61 /* Timeout, and initial timeout */
62 static unsigned int timeout
;
63 static unsigned int init_timeout
;
66 struct strbuf hostname
;
67 struct strbuf canon_hostname
;
68 struct strbuf ip_address
;
69 struct strbuf tcp_port
;
70 unsigned int hostname_lookup_done
:1;
71 unsigned int saw_extended_args
:1;
73 #define HOSTINFO_INIT { \
74 .hostname = STRBUF_INIT, \
75 .canon_hostname = STRBUF_INIT, \
76 .ip_address = STRBUF_INIT, \
77 .tcp_port = STRBUF_INIT, \
80 static void lookup_hostname(struct hostinfo
*hi
);
82 static const char *get_canon_hostname(struct hostinfo
*hi
)
85 return hi
->canon_hostname
.buf
;
88 static const char *get_ip_address(struct hostinfo
*hi
)
91 return hi
->ip_address
.buf
;
94 static void logreport(int priority
, const char *err
, va_list params
)
96 switch (log_destination
) {
97 case LOG_DESTINATION_SYSLOG
: {
99 vsnprintf(buf
, sizeof(buf
), err
, params
);
100 syslog(priority
, "%s", buf
);
103 case LOG_DESTINATION_STDERR
:
105 * Since stderr is set to buffered mode, the
106 * logging of different processes will not overlap
107 * unless they overflow the (rather big) buffers.
109 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
110 vfprintf(stderr
, err
, params
);
114 case LOG_DESTINATION_NONE
:
116 case LOG_DESTINATION_UNSET
:
117 BUG("log destination not initialized correctly");
121 __attribute__((format (printf
, 1, 2)))
122 static void logerror(const char *err
, ...)
125 va_start(params
, err
);
126 logreport(LOG_ERR
, err
, params
);
130 __attribute__((format (printf
, 1, 2)))
131 static void loginfo(const char *err
, ...)
136 va_start(params
, err
);
137 logreport(LOG_INFO
, err
, params
);
141 static void NORETURN
daemon_die(const char *err
, va_list params
)
143 logreport(LOG_ERR
, err
, params
);
147 struct expand_path_context
{
148 const char *directory
;
149 struct hostinfo
*hostinfo
;
152 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
154 struct expand_path_context
*context
= ctx
;
155 struct hostinfo
*hi
= context
->hostinfo
;
157 switch (placeholder
[0]) {
159 strbuf_addbuf(sb
, &hi
->hostname
);
162 if (placeholder
[1] == 'H') {
163 strbuf_addstr(sb
, get_canon_hostname(hi
));
168 if (placeholder
[1] == 'P') {
169 strbuf_addstr(sb
, get_ip_address(hi
));
174 strbuf_addbuf(sb
, &hi
->tcp_port
);
177 strbuf_addstr(sb
, context
->directory
);
183 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
185 static char rpath
[PATH_MAX
];
186 static char interp_path
[PATH_MAX
];
193 if (daemon_avoid_alias(dir
)) {
194 logerror("'%s': aliased", dir
);
200 logerror("'%s': User-path not allowed", dir
);
204 /* Got either "~alice" or "~alice/foo";
205 * rewrite them to "~alice/%s" or
208 int namlen
, restlen
= strlen(dir
);
209 const char *slash
= strchr(dir
, '/');
211 slash
= dir
+ restlen
;
212 namlen
= slash
- dir
;
214 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
215 rlen
= snprintf(rpath
, sizeof(rpath
), "%.*s/%s%.*s",
216 namlen
, dir
, user_path
, restlen
, slash
);
217 if (rlen
>= sizeof(rpath
)) {
218 logerror("user-path too large: %s", rpath
);
224 else if (interpolated_path
&& hi
->saw_extended_args
) {
225 struct strbuf expanded_path
= STRBUF_INIT
;
226 struct expand_path_context context
;
228 context
.directory
= directory
;
229 context
.hostinfo
= hi
;
232 /* Allow only absolute */
233 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
237 strbuf_expand(&expanded_path
, interpolated_path
,
238 expand_path
, &context
);
240 rlen
= strlcpy(interp_path
, expanded_path
.buf
,
241 sizeof(interp_path
));
242 strbuf_release(&expanded_path
);
243 if (rlen
>= sizeof(interp_path
)) {
244 logerror("interpolated path too large: %s",
249 loginfo("Interpolated dir '%s'", interp_path
);
253 else if (base_path
) {
255 /* Allow only absolute */
256 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
259 rlen
= snprintf(rpath
, sizeof(rpath
), "%s%s", base_path
, dir
);
260 if (rlen
>= sizeof(rpath
)) {
261 logerror("base-path too large: %s", rpath
);
267 path
= enter_repo(dir
, strict_paths
);
268 if (!path
&& base_path
&& base_path_relaxed
) {
270 * if we fail and base_path_relaxed is enabled, try without
271 * prefixing the base path
274 path
= enter_repo(dir
, strict_paths
);
278 logerror("'%s' does not appear to be a git repository", dir
);
282 if ( ok_paths
&& *ok_paths
) {
284 int pathlen
= strlen(path
);
286 /* The validation is done on the paths after enter_repo
287 * appends optional {.git,.git/.git} and friends, but
288 * it does not use getcwd(). So if your /pub is
289 * a symlink to /mnt/pub, you can include /pub and
290 * do not have to say /mnt/pub.
293 for ( pp
= ok_paths
; *pp
; pp
++ ) {
294 int len
= strlen(*pp
);
295 if (len
<= pathlen
&&
296 !memcmp(*pp
, path
, len
) &&
297 (path
[len
] == '\0' ||
298 (!strict_paths
&& path
[len
] == '/')))
303 /* be backwards compatible */
308 logerror("'%s': not in directory list", path
);
309 return NULL
; /* Fallthrough. Deny by default */
312 typedef int (*daemon_service_fn
)(const struct strvec
*env
);
313 struct daemon_service
{
315 const char *config_name
;
316 daemon_service_fn fn
;
321 static int daemon_error(const char *dir
, const char *msg
)
323 if (!informative_errors
)
324 msg
= "access denied or repository not exported";
325 packet_write_fmt(1, "ERR %s: %s", msg
, dir
);
329 static const char *access_hook
;
331 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
332 const char *path
, struct hostinfo
*hi
)
334 struct child_process child
= CHILD_PROCESS_INIT
;
335 struct strbuf buf
= STRBUF_INIT
;
339 strvec_push(&child
.args
, access_hook
);
340 strvec_push(&child
.args
, service
->name
);
341 strvec_push(&child
.args
, path
);
342 strvec_push(&child
.args
, hi
->hostname
.buf
);
343 strvec_push(&child
.args
, get_canon_hostname(hi
));
344 strvec_push(&child
.args
, get_ip_address(hi
));
345 strvec_push(&child
.args
, hi
->tcp_port
.buf
);
351 if (start_command(&child
)) {
352 logerror("daemon access hook '%s' failed to start",
356 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
357 logerror("failed to read from pipe to daemon access hook '%s'",
362 if (close(child
.out
) < 0) {
363 logerror("failed to close pipe to daemon access hook '%s'",
367 if (finish_command(&child
))
371 strbuf_release(&buf
);
378 strbuf_addstr(&buf
, "service rejected");
379 eol
= strchr(buf
.buf
, '\n');
383 daemon_error(dir
, buf
.buf
);
384 strbuf_release(&buf
);
388 static int run_service(const char *dir
, struct daemon_service
*service
,
389 struct hostinfo
*hi
, const struct strvec
*env
)
392 int enabled
= service
->enabled
;
393 struct strbuf var
= STRBUF_INIT
;
395 loginfo("Request %s for '%s'", service
->name
, dir
);
397 if (!enabled
&& !service
->overridable
) {
398 logerror("'%s': service not enabled.", service
->name
);
400 return daemon_error(dir
, "service not enabled");
403 if (!(path
= path_ok(dir
, hi
)))
404 return daemon_error(dir
, "no such repository");
407 * Security on the cheap.
409 * We want a readable HEAD, usable "objects" directory, and
410 * a "git-daemon-export-ok" flag that says that the other side
411 * is ok with us doing this.
413 * path_ok() uses enter_repo() and checks for included directories.
414 * We only need to make sure the repository is exported.
417 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
418 logerror("'%s': repository not exported.", path
);
420 return daemon_error(dir
, "repository not exported");
423 if (service
->overridable
) {
424 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
425 git_config_get_bool(var
.buf
, &enabled
);
426 strbuf_release(&var
);
429 logerror("'%s': service not enabled for '%s'",
430 service
->name
, path
);
432 return daemon_error(dir
, "service not enabled");
436 * Optionally, a hook can choose to deny access to the
437 * repository depending on the phase of the moon.
439 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
443 * We'll ignore SIGTERM from now on, we have a
446 signal(SIGTERM
, SIG_IGN
);
448 return service
->fn(env
);
451 static void copy_to_log(int fd
)
453 struct strbuf line
= STRBUF_INIT
;
456 fp
= fdopen(fd
, "r");
458 logerror("fdopen of error channel failed");
463 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
464 logerror("%s", line
.buf
);
465 strbuf_setlen(&line
, 0);
468 strbuf_release(&line
);
472 static int run_service_command(struct child_process
*cld
)
474 strvec_push(&cld
->args
, ".");
477 if (start_command(cld
))
483 copy_to_log(cld
->err
);
485 return finish_command(cld
);
488 static int upload_pack(const struct strvec
*env
)
490 struct child_process cld
= CHILD_PROCESS_INIT
;
491 strvec_pushl(&cld
.args
, "upload-pack", "--strict", NULL
);
492 strvec_pushf(&cld
.args
, "--timeout=%u", timeout
);
494 strvec_pushv(&cld
.env
, env
->v
);
496 return run_service_command(&cld
);
499 static int upload_archive(const struct strvec
*env
)
501 struct child_process cld
= CHILD_PROCESS_INIT
;
502 strvec_push(&cld
.args
, "upload-archive");
504 strvec_pushv(&cld
.env
, env
->v
);
506 return run_service_command(&cld
);
509 static int receive_pack(const struct strvec
*env
)
511 struct child_process cld
= CHILD_PROCESS_INIT
;
512 strvec_push(&cld
.args
, "receive-pack");
514 strvec_pushv(&cld
.env
, env
->v
);
516 return run_service_command(&cld
);
519 static struct daemon_service daemon_service
[] = {
520 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
521 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
522 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
525 static void enable_service(const char *name
, int ena
)
528 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
529 if (!strcmp(daemon_service
[i
].name
, name
)) {
530 daemon_service
[i
].enabled
= ena
;
534 die("No such service %s", name
);
537 static void make_service_overridable(const char *name
, int ena
)
540 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
541 if (!strcmp(daemon_service
[i
].name
, name
)) {
542 daemon_service
[i
].overridable
= ena
;
546 die("No such service %s", name
);
549 static void parse_host_and_port(char *hostport
, char **host
,
552 if (*hostport
== '[') {
555 end
= strchr(hostport
, ']');
557 die("Invalid request ('[' without ']')");
559 *host
= hostport
+ 1;
562 else if (end
[1] == ':')
565 die("Garbage after end of host part");
568 *port
= strrchr(hostport
, ':');
577 * Sanitize a string from the client so that it's OK to be inserted into a
578 * filesystem path. Specifically, we disallow directory separators, runs
579 * of "..", and trailing and leading dots, which means that the client
580 * cannot escape our base path via ".." traversal.
582 static void sanitize_client(struct strbuf
*out
, const char *in
)
587 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
589 strbuf_addch(out
, *in
);
592 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
593 strbuf_setlen(out
, out
->len
- 1);
597 * Like sanitize_client, but we also perform any canonicalization
598 * to make life easier on the admin.
600 static void canonicalize_client(struct strbuf
*out
, const char *in
)
602 sanitize_client(out
, in
);
607 * Read the host as supplied by the client connection.
609 * Returns a pointer to the character after the NUL byte terminating the host
610 * argument, or 'extra_args' if there is no host argument.
612 static char *parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
616 char *end
= extra_args
+ buflen
;
618 if (extra_args
< end
&& *extra_args
) {
619 hi
->saw_extended_args
= 1;
620 if (strncasecmp("host=", extra_args
, 5) == 0) {
621 val
= extra_args
+ 5;
622 vallen
= strlen(val
) + 1;
623 loginfo("Extended attribute \"host\": %s", val
);
625 /* Split <host>:<port> at colon. */
628 parse_host_and_port(val
, &host
, &port
);
630 sanitize_client(&hi
->tcp_port
, port
);
631 canonicalize_client(&hi
->hostname
, host
);
632 hi
->hostname_lookup_done
= 0;
635 /* On to the next one */
636 extra_args
= val
+ vallen
;
638 if (extra_args
< end
&& *extra_args
)
639 die("Invalid request");
645 static void parse_extra_args(struct hostinfo
*hi
, struct strvec
*env
,
646 char *extra_args
, int buflen
)
648 const char *end
= extra_args
+ buflen
;
649 struct strbuf git_protocol
= STRBUF_INIT
;
651 /* First look for the host argument */
652 extra_args
= parse_host_arg(hi
, extra_args
, buflen
);
654 /* Look for additional arguments places after a second NUL byte */
655 for (; extra_args
< end
; extra_args
+= strlen(extra_args
) + 1) {
656 const char *arg
= extra_args
;
659 * Parse the extra arguments, adding most to 'git_protocol'
660 * which will be used to set the 'GIT_PROTOCOL' envvar in the
661 * service that will be run.
663 * If there ends up being a particular arg in the future that
664 * git-daemon needs to parse specifically (like the 'host' arg)
665 * then it can be parsed here and not added to 'git_protocol'.
668 if (git_protocol
.len
> 0)
669 strbuf_addch(&git_protocol
, ':');
670 strbuf_addstr(&git_protocol
, arg
);
674 if (git_protocol
.len
> 0) {
675 loginfo("Extended attribute \"protocol\": %s", git_protocol
.buf
);
676 strvec_pushf(env
, GIT_PROTOCOL_ENVIRONMENT
"=%s",
679 strbuf_release(&git_protocol
);
683 * Locate canonical hostname and its IP address.
685 static void lookup_hostname(struct hostinfo
*hi
)
687 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
689 struct addrinfo hints
;
692 static char addrbuf
[HOST_NAME_MAX
+ 1];
694 memset(&hints
, 0, sizeof(hints
));
695 hints
.ai_flags
= AI_CANONNAME
;
697 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
699 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
701 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
702 addrbuf
, sizeof(addrbuf
));
703 strbuf_addstr(&hi
->ip_address
, addrbuf
);
705 if (ai
->ai_canonname
)
706 sanitize_client(&hi
->canon_hostname
,
709 strbuf_addbuf(&hi
->canon_hostname
,
715 struct hostent
*hent
;
716 struct sockaddr_in sa
;
718 static char addrbuf
[HOST_NAME_MAX
+ 1];
720 hent
= gethostbyname(hi
->hostname
.buf
);
722 ap
= hent
->h_addr_list
;
723 memset(&sa
, 0, sizeof sa
);
724 sa
.sin_family
= hent
->h_addrtype
;
725 sa
.sin_port
= htons(0);
726 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
728 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
729 addrbuf
, sizeof(addrbuf
));
731 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
732 strbuf_addstr(&hi
->ip_address
, addrbuf
);
735 hi
->hostname_lookup_done
= 1;
739 static void hostinfo_clear(struct hostinfo
*hi
)
741 strbuf_release(&hi
->hostname
);
742 strbuf_release(&hi
->canon_hostname
);
743 strbuf_release(&hi
->ip_address
);
744 strbuf_release(&hi
->tcp_port
);
747 static void set_keep_alive(int sockfd
)
751 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0) {
752 if (errno
!= ENOTSOCK
)
753 logerror("unable to set SO_KEEPALIVE on socket: %s",
758 static int execute(void)
760 char *line
= packet_buffer
;
762 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
763 struct hostinfo hi
= HOSTINFO_INIT
;
764 struct strvec env
= STRVEC_INIT
;
767 loginfo("Connection from %s:%s", addr
, port
);
770 alarm(init_timeout
? init_timeout
: timeout
);
771 pktlen
= packet_read(0, packet_buffer
, sizeof(packet_buffer
), 0);
775 if (len
&& line
[len
-1] == '\n')
778 /* parse additional args hidden behind a NUL byte */
780 parse_extra_args(&hi
, &env
, line
+ len
+ 1, pktlen
- len
- 1);
782 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
783 struct daemon_service
*s
= &(daemon_service
[i
]);
786 if (skip_prefix(line
, "git-", &arg
) &&
787 skip_prefix(arg
, s
->name
, &arg
) &&
790 * Note: The directory here is probably context sensitive,
791 * and might depend on the actual service being performed.
793 int rc
= run_service(arg
, s
, &hi
, &env
);
802 logerror("Protocol error: '%s'", line
);
806 static int addrcmp(const struct sockaddr_storage
*s1
,
807 const struct sockaddr_storage
*s2
)
809 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
810 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
812 if (sa1
->sa_family
!= sa2
->sa_family
)
813 return sa1
->sa_family
- sa2
->sa_family
;
814 if (sa1
->sa_family
== AF_INET
)
815 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
816 &((struct sockaddr_in
*)s2
)->sin_addr
,
817 sizeof(struct in_addr
));
819 if (sa1
->sa_family
== AF_INET6
)
820 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
821 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
822 sizeof(struct in6_addr
));
827 static int max_connections
= 32;
829 static unsigned int live_children
;
831 static struct child
{
833 struct child_process cld
;
834 struct sockaddr_storage address
;
837 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
839 struct child
*newborn
, **cradle
;
841 CALLOC_ARRAY(newborn
, 1);
843 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
844 memcpy(&newborn
->address
, addr
, addrlen
);
845 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
846 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
848 newborn
->next
= *cradle
;
853 * This gets called if the number of connections grows
854 * past "max_connections".
856 * We kill the newest connection from a duplicate IP.
858 static void kill_some_child(void)
860 const struct child
*blanket
, *next
;
862 if (!(blanket
= firstborn
))
865 for (; (next
= blanket
->next
); blanket
= next
)
866 if (!addrcmp(&blanket
->address
, &next
->address
)) {
867 kill(blanket
->cld
.pid
, SIGTERM
);
872 static void check_dead_children(void)
877 struct child
**cradle
, *blanket
;
878 for (cradle
= &firstborn
; (blanket
= *cradle
);)
879 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
880 const char *dead
= "";
882 dead
= " (with error)";
883 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
885 /* remove the child */
886 *cradle
= blanket
->next
;
888 child_process_clear(&blanket
->cld
);
891 cradle
= &blanket
->next
;
894 static struct strvec cld_argv
= STRVEC_INIT
;
895 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
897 struct child_process cld
= CHILD_PROCESS_INIT
;
899 if (max_connections
&& live_children
>= max_connections
) {
901 sleep(1); /* give it some time to die */
902 check_dead_children();
903 if (live_children
>= max_connections
) {
905 logerror("Too many children, dropping connection");
910 if (addr
->sa_family
== AF_INET
) {
912 struct sockaddr_in
*sin_addr
= (void *) addr
;
913 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
914 strvec_pushf(&cld
.env
, "REMOTE_ADDR=%s", buf
);
915 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
916 ntohs(sin_addr
->sin_port
));
918 } else if (addr
->sa_family
== AF_INET6
) {
920 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
921 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
922 strvec_pushf(&cld
.env
, "REMOTE_ADDR=[%s]", buf
);
923 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
924 ntohs(sin6_addr
->sin6_port
));
928 strvec_pushv(&cld
.args
, cld_argv
.v
);
930 cld
.out
= dup(incoming
);
932 if (start_command(&cld
))
933 logerror("unable to fork");
935 add_child(&cld
, addr
, addrlen
);
938 static void child_handler(int signo UNUSED
)
941 * Otherwise empty handler because systemcalls will get interrupted
942 * upon signal receipt
943 * SysV needs the handler to be rearmed
945 signal(SIGCHLD
, child_handler
);
948 static int set_reuse_addr(int sockfd
)
954 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
964 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
967 static char ip
[INET_ADDRSTRLEN
];
969 static char ip
[INET6_ADDRSTRLEN
];
975 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
979 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
982 xsnprintf(ip
, sizeof(ip
), "<unknown>");
989 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
992 char pbuf
[NI_MAXSERV
];
993 struct addrinfo hints
, *ai0
, *ai
;
997 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
998 memset(&hints
, 0, sizeof(hints
));
999 hints
.ai_family
= AF_UNSPEC
;
1000 hints
.ai_socktype
= SOCK_STREAM
;
1001 hints
.ai_protocol
= IPPROTO_TCP
;
1002 hints
.ai_flags
= AI_PASSIVE
;
1004 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
1006 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
1010 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
1013 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
1016 if (sockfd
>= FD_SETSIZE
) {
1017 logerror("Socket descriptor too large");
1023 if (ai
->ai_family
== AF_INET6
) {
1025 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
1027 /* Note: error is not fatal */
1031 if (set_reuse_addr(sockfd
)) {
1032 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1037 set_keep_alive(sockfd
);
1039 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1040 logerror("Could not bind to %s: %s",
1041 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1044 continue; /* not fatal */
1046 if (listen(sockfd
, 5) < 0) {
1047 logerror("Could not listen to %s: %s",
1048 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1051 continue; /* not fatal */
1054 flags
= fcntl(sockfd
, F_GETFD
, 0);
1056 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1058 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1059 socklist
->list
[socklist
->nr
++] = sockfd
;
1070 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1072 struct sockaddr_in sin
;
1076 memset(&sin
, 0, sizeof sin
);
1077 sin
.sin_family
= AF_INET
;
1078 sin
.sin_port
= htons(listen_port
);
1081 /* Well, host better be an IP address here. */
1082 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1085 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1088 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1092 if (set_reuse_addr(sockfd
)) {
1093 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1098 set_keep_alive(sockfd
);
1100 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1101 logerror("Could not bind to %s: %s",
1102 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1108 if (listen(sockfd
, 5) < 0) {
1109 logerror("Could not listen to %s: %s",
1110 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1116 flags
= fcntl(sockfd
, F_GETFD
, 0);
1118 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1120 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1121 socklist
->list
[socklist
->nr
++] = sockfd
;
1127 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1129 if (!listen_addr
->nr
)
1130 setup_named_sock(NULL
, listen_port
, socklist
);
1133 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1134 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1135 listen_port
, socklist
);
1138 logerror("unable to allocate any listen sockets for host %s on port %u",
1139 listen_addr
->items
[i
].string
, listen_port
);
1144 static int service_loop(struct socketlist
*socklist
)
1149 CALLOC_ARRAY(pfd
, socklist
->nr
);
1151 for (i
= 0; i
< socklist
->nr
; i
++) {
1152 pfd
[i
].fd
= socklist
->list
[i
];
1153 pfd
[i
].events
= POLLIN
;
1156 signal(SIGCHLD
, child_handler
);
1161 check_dead_children();
1163 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1164 if (errno
!= EINTR
) {
1165 logerror("Poll failed, resuming: %s",
1172 for (i
= 0; i
< socklist
->nr
; i
++) {
1173 if (pfd
[i
].revents
& POLLIN
) {
1176 struct sockaddr_in sai
;
1178 struct sockaddr_in6 sai6
;
1181 socklen_t sslen
= sizeof(ss
);
1182 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1190 die_errno("accept returned");
1193 handle(incoming
, &ss
.sa
, sslen
);
1199 #ifdef NO_POSIX_GOODIES
1203 static void drop_privileges(struct credentials
*cred
)
1208 static struct credentials
*prepare_credentials(const char *user_name
,
1209 const char *group_name
)
1211 die("--user not supported on this platform");
1216 struct credentials
{
1217 struct passwd
*pass
;
1221 static void drop_privileges(struct credentials
*cred
)
1223 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1224 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1225 die("cannot drop privileges");
1228 static struct credentials
*prepare_credentials(const char *user_name
,
1229 const char *group_name
)
1231 static struct credentials c
;
1233 c
.pass
= getpwnam(user_name
);
1235 die("user not found - %s", user_name
);
1238 c
.gid
= c
.pass
->pw_gid
;
1240 struct group
*group
= getgrnam(group_name
);
1242 die("group not found - %s", group_name
);
1244 c
.gid
= group
->gr_gid
;
1251 static int serve(struct string_list
*listen_addr
, int listen_port
,
1252 struct credentials
*cred
)
1254 struct socketlist socklist
= { NULL
, 0, 0 };
1256 socksetup(listen_addr
, listen_port
, &socklist
);
1257 if (socklist
.nr
== 0)
1258 die("unable to allocate any listen sockets on port %u",
1261 drop_privileges(cred
);
1263 loginfo("Ready to rumble");
1265 return service_loop(&socklist
);
1268 int cmd_main(int argc
, const char **argv
)
1270 int listen_port
= 0;
1271 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1272 int serve_mode
= 0, inetd_mode
= 0;
1273 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1275 struct credentials
*cred
= NULL
;
1278 for (i
= 1; i
< argc
; i
++) {
1279 const char *arg
= argv
[i
];
1282 if (skip_prefix(arg
, "--listen=", &v
)) {
1283 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1286 if (skip_prefix(arg
, "--port=", &v
)) {
1289 n
= strtoul(v
, &end
, 0);
1295 if (!strcmp(arg
, "--serve")) {
1299 if (!strcmp(arg
, "--inetd")) {
1303 if (!strcmp(arg
, "--verbose")) {
1307 if (!strcmp(arg
, "--syslog")) {
1308 log_destination
= LOG_DESTINATION_SYSLOG
;
1311 if (skip_prefix(arg
, "--log-destination=", &v
)) {
1312 if (!strcmp(v
, "syslog")) {
1313 log_destination
= LOG_DESTINATION_SYSLOG
;
1315 } else if (!strcmp(v
, "stderr")) {
1316 log_destination
= LOG_DESTINATION_STDERR
;
1318 } else if (!strcmp(v
, "none")) {
1319 log_destination
= LOG_DESTINATION_NONE
;
1322 die("unknown log destination '%s'", v
);
1324 if (!strcmp(arg
, "--export-all")) {
1325 export_all_trees
= 1;
1328 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1332 if (skip_prefix(arg
, "--timeout=", &v
)) {
1336 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1337 init_timeout
= atoi(v
);
1340 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1341 max_connections
= atoi(v
);
1342 if (max_connections
< 0)
1343 max_connections
= 0; /* unlimited */
1346 if (!strcmp(arg
, "--strict-paths")) {
1350 if (skip_prefix(arg
, "--base-path=", &v
)) {
1354 if (!strcmp(arg
, "--base-path-relaxed")) {
1355 base_path_relaxed
= 1;
1358 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1359 interpolated_path
= v
;
1362 if (!strcmp(arg
, "--reuseaddr")) {
1366 if (!strcmp(arg
, "--user-path")) {
1370 if (skip_prefix(arg
, "--user-path=", &v
)) {
1374 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1378 if (!strcmp(arg
, "--detach")) {
1382 if (skip_prefix(arg
, "--user=", &v
)) {
1386 if (skip_prefix(arg
, "--group=", &v
)) {
1390 if (skip_prefix(arg
, "--enable=", &v
)) {
1391 enable_service(v
, 1);
1394 if (skip_prefix(arg
, "--disable=", &v
)) {
1395 enable_service(v
, 0);
1398 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1399 make_service_overridable(v
, 1);
1402 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1403 make_service_overridable(v
, 0);
1406 if (!strcmp(arg
, "--informative-errors")) {
1407 informative_errors
= 1;
1410 if (!strcmp(arg
, "--no-informative-errors")) {
1411 informative_errors
= 0;
1414 if (!strcmp(arg
, "--")) {
1415 ok_paths
= &argv
[i
+1];
1417 } else if (arg
[0] != '-') {
1418 ok_paths
= &argv
[i
];
1422 usage(daemon_usage
);
1425 if (log_destination
== LOG_DESTINATION_UNSET
) {
1426 if (inetd_mode
|| detach
)
1427 log_destination
= LOG_DESTINATION_SYSLOG
;
1429 log_destination
= LOG_DESTINATION_STDERR
;
1432 if (log_destination
== LOG_DESTINATION_SYSLOG
) {
1433 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1434 set_die_routine(daemon_die
);
1436 /* avoid splitting a message in the middle */
1437 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1439 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1440 die("--detach, --user and --group are incompatible with --inetd");
1442 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1443 die("--listen= and --port= are incompatible with --inetd");
1444 else if (listen_port
== 0)
1445 listen_port
= DEFAULT_GIT_PORT
;
1447 if (group_name
&& !user_name
)
1448 die("--group supplied without --user");
1451 cred
= prepare_credentials(user_name
, group_name
);
1453 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1454 die("option --strict-paths requires '<directory>' arguments");
1456 if (base_path
&& !is_directory(base_path
))
1457 die("base-path '%s' does not exist or is not a directory",
1460 if (log_destination
!= LOG_DESTINATION_STDERR
) {
1461 if (!freopen("/dev/null", "w", stderr
))
1462 die_errno("failed to redirect stderr to /dev/null");
1465 if (inetd_mode
|| serve_mode
)
1470 die("--detach not supported on this platform");
1474 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1476 /* prepare argv for serving-processes */
1477 strvec_push(&cld_argv
, argv
[0]); /* git-daemon */
1478 strvec_push(&cld_argv
, "--serve");
1479 for (i
= 1; i
< argc
; ++i
)
1480 strvec_push(&cld_argv
, argv
[i
]);
1482 return serve(&listen_addr
, listen_port
, cred
);