4 #include "run-command.h"
6 #include "string-list.h"
9 #define initgroups(x, y) (0) /* nothing */
12 static enum log_destination
{
13 LOG_DESTINATION_UNSET
= -1,
14 LOG_DESTINATION_NONE
= 0,
15 LOG_DESTINATION_STDERR
= 1,
16 LOG_DESTINATION_SYSLOG
= 2,
17 } log_destination
= LOG_DESTINATION_UNSET
;
20 static int informative_errors
;
22 static const char daemon_usage
[] =
23 "git daemon [--verbose] [--syslog] [--export-all]\n"
24 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
25 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
26 " [--user-path | --user-path=<path>]\n"
27 " [--interpolated-path=<path>]\n"
28 " [--reuseaddr] [--pid-file=<file>]\n"
29 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
30 " [--access-hook=<path>]\n"
31 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
32 " [--detach] [--user=<user> [--group=<group>]]\n"
33 " [--log-destination=(stderr|syslog|none)]\n"
36 /* List of acceptable pathname prefixes */
37 static const char **ok_paths
;
38 static int strict_paths
;
40 /* If this is set, git-daemon-export-ok is not required */
41 static int export_all_trees
;
43 /* Take all paths relative to this one if non-NULL */
44 static const char *base_path
;
45 static const char *interpolated_path
;
46 static int base_path_relaxed
;
48 /* If defined, ~user notation is allowed and the string is inserted
49 * after ~user/. E.g. a request to git://host/~alice/frotz would
50 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
52 static const char *user_path
;
54 /* Timeout, and initial timeout */
55 static unsigned int timeout
;
56 static unsigned int init_timeout
;
59 struct strbuf hostname
;
60 struct strbuf canon_hostname
;
61 struct strbuf ip_address
;
62 struct strbuf tcp_port
;
63 unsigned int hostname_lookup_done
:1;
64 unsigned int saw_extended_args
:1;
66 #define HOSTINFO_INIT { \
67 .hostname = STRBUF_INIT, \
68 .canon_hostname = STRBUF_INIT, \
69 .ip_address = STRBUF_INIT, \
70 .tcp_port = STRBUF_INIT, \
73 static void lookup_hostname(struct hostinfo
*hi
);
75 static const char *get_canon_hostname(struct hostinfo
*hi
)
78 return hi
->canon_hostname
.buf
;
81 static const char *get_ip_address(struct hostinfo
*hi
)
84 return hi
->ip_address
.buf
;
87 static void logreport(int priority
, const char *err
, va_list params
)
89 switch (log_destination
) {
90 case LOG_DESTINATION_SYSLOG
: {
92 vsnprintf(buf
, sizeof(buf
), err
, params
);
93 syslog(priority
, "%s", buf
);
96 case LOG_DESTINATION_STDERR
:
98 * Since stderr is set to buffered mode, the
99 * logging of different processes will not overlap
100 * unless they overflow the (rather big) buffers.
102 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
103 vfprintf(stderr
, err
, params
);
107 case LOG_DESTINATION_NONE
:
109 case LOG_DESTINATION_UNSET
:
110 BUG("log destination not initialized correctly");
114 __attribute__((format (printf
, 1, 2)))
115 static void logerror(const char *err
, ...)
118 va_start(params
, err
);
119 logreport(LOG_ERR
, err
, params
);
123 __attribute__((format (printf
, 1, 2)))
124 static void loginfo(const char *err
, ...)
129 va_start(params
, err
);
130 logreport(LOG_INFO
, err
, params
);
134 static void NORETURN
daemon_die(const char *err
, va_list params
)
136 logreport(LOG_ERR
, err
, params
);
140 struct expand_path_context
{
141 const char *directory
;
142 struct hostinfo
*hostinfo
;
145 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
147 struct expand_path_context
*context
= ctx
;
148 struct hostinfo
*hi
= context
->hostinfo
;
150 switch (placeholder
[0]) {
152 strbuf_addbuf(sb
, &hi
->hostname
);
155 if (placeholder
[1] == 'H') {
156 strbuf_addstr(sb
, get_canon_hostname(hi
));
161 if (placeholder
[1] == 'P') {
162 strbuf_addstr(sb
, get_ip_address(hi
));
167 strbuf_addbuf(sb
, &hi
->tcp_port
);
170 strbuf_addstr(sb
, context
->directory
);
176 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
178 static char rpath
[PATH_MAX
];
179 static char interp_path
[PATH_MAX
];
186 if (daemon_avoid_alias(dir
)) {
187 logerror("'%s': aliased", dir
);
193 logerror("'%s': User-path not allowed", dir
);
197 /* Got either "~alice" or "~alice/foo";
198 * rewrite them to "~alice/%s" or
201 int namlen
, restlen
= strlen(dir
);
202 const char *slash
= strchr(dir
, '/');
204 slash
= dir
+ restlen
;
205 namlen
= slash
- dir
;
207 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
208 rlen
= snprintf(rpath
, sizeof(rpath
), "%.*s/%s%.*s",
209 namlen
, dir
, user_path
, restlen
, slash
);
210 if (rlen
>= sizeof(rpath
)) {
211 logerror("user-path too large: %s", rpath
);
217 else if (interpolated_path
&& hi
->saw_extended_args
) {
218 struct strbuf expanded_path
= STRBUF_INIT
;
219 struct expand_path_context context
;
221 context
.directory
= directory
;
222 context
.hostinfo
= hi
;
225 /* Allow only absolute */
226 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
230 strbuf_expand(&expanded_path
, interpolated_path
,
231 expand_path
, &context
);
233 rlen
= strlcpy(interp_path
, expanded_path
.buf
,
234 sizeof(interp_path
));
235 if (rlen
>= sizeof(interp_path
)) {
236 logerror("interpolated path too large: %s",
241 strbuf_release(&expanded_path
);
242 loginfo("Interpolated dir '%s'", interp_path
);
246 else if (base_path
) {
248 /* Allow only absolute */
249 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
252 rlen
= snprintf(rpath
, sizeof(rpath
), "%s%s", base_path
, dir
);
253 if (rlen
>= sizeof(rpath
)) {
254 logerror("base-path too large: %s", rpath
);
260 path
= enter_repo(dir
, strict_paths
);
261 if (!path
&& base_path
&& base_path_relaxed
) {
263 * if we fail and base_path_relaxed is enabled, try without
264 * prefixing the base path
267 path
= enter_repo(dir
, strict_paths
);
271 logerror("'%s' does not appear to be a git repository", dir
);
275 if ( ok_paths
&& *ok_paths
) {
277 int pathlen
= strlen(path
);
279 /* The validation is done on the paths after enter_repo
280 * appends optional {.git,.git/.git} and friends, but
281 * it does not use getcwd(). So if your /pub is
282 * a symlink to /mnt/pub, you can whitelist /pub and
283 * do not have to say /mnt/pub.
286 for ( pp
= ok_paths
; *pp
; pp
++ ) {
287 int len
= strlen(*pp
);
288 if (len
<= pathlen
&&
289 !memcmp(*pp
, path
, len
) &&
290 (path
[len
] == '\0' ||
291 (!strict_paths
&& path
[len
] == '/')))
296 /* be backwards compatible */
301 logerror("'%s': not in whitelist", path
);
302 return NULL
; /* Fallthrough. Deny by default */
305 typedef int (*daemon_service_fn
)(const struct strvec
*env
);
306 struct daemon_service
{
308 const char *config_name
;
309 daemon_service_fn fn
;
314 static int daemon_error(const char *dir
, const char *msg
)
316 if (!informative_errors
)
317 msg
= "access denied or repository not exported";
318 packet_write_fmt(1, "ERR %s: %s", msg
, dir
);
322 static const char *access_hook
;
324 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
325 const char *path
, struct hostinfo
*hi
)
327 struct child_process child
= CHILD_PROCESS_INIT
;
328 struct strbuf buf
= STRBUF_INIT
;
330 const char **arg
= argv
;
334 *arg
++ = access_hook
;
335 *arg
++ = service
->name
;
337 *arg
++ = hi
->hostname
.buf
;
338 *arg
++ = get_canon_hostname(hi
);
339 *arg
++ = get_ip_address(hi
);
340 *arg
++ = hi
->tcp_port
.buf
;
348 if (start_command(&child
)) {
349 logerror("daemon access hook '%s' failed to start",
353 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
354 logerror("failed to read from pipe to daemon access hook '%s'",
359 if (close(child
.out
) < 0) {
360 logerror("failed to close pipe to daemon access hook '%s'",
364 if (finish_command(&child
))
368 strbuf_release(&buf
);
375 strbuf_addstr(&buf
, "service rejected");
376 eol
= strchr(buf
.buf
, '\n');
380 daemon_error(dir
, buf
.buf
);
381 strbuf_release(&buf
);
385 static int run_service(const char *dir
, struct daemon_service
*service
,
386 struct hostinfo
*hi
, const struct strvec
*env
)
389 int enabled
= service
->enabled
;
390 struct strbuf var
= STRBUF_INIT
;
392 loginfo("Request %s for '%s'", service
->name
, dir
);
394 if (!enabled
&& !service
->overridable
) {
395 logerror("'%s': service not enabled.", service
->name
);
397 return daemon_error(dir
, "service not enabled");
400 if (!(path
= path_ok(dir
, hi
)))
401 return daemon_error(dir
, "no such repository");
404 * Security on the cheap.
406 * We want a readable HEAD, usable "objects" directory, and
407 * a "git-daemon-export-ok" flag that says that the other side
408 * is ok with us doing this.
410 * path_ok() uses enter_repo() and does whitelist checking.
411 * We only need to make sure the repository is exported.
414 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
415 logerror("'%s': repository not exported.", path
);
417 return daemon_error(dir
, "repository not exported");
420 if (service
->overridable
) {
421 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
422 git_config_get_bool(var
.buf
, &enabled
);
423 strbuf_release(&var
);
426 logerror("'%s': service not enabled for '%s'",
427 service
->name
, path
);
429 return daemon_error(dir
, "service not enabled");
433 * Optionally, a hook can choose to deny access to the
434 * repository depending on the phase of the moon.
436 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
440 * We'll ignore SIGTERM from now on, we have a
443 signal(SIGTERM
, SIG_IGN
);
445 return service
->fn(env
);
448 static void copy_to_log(int fd
)
450 struct strbuf line
= STRBUF_INIT
;
453 fp
= fdopen(fd
, "r");
455 logerror("fdopen of error channel failed");
460 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
461 logerror("%s", line
.buf
);
462 strbuf_setlen(&line
, 0);
465 strbuf_release(&line
);
469 static int run_service_command(struct child_process
*cld
)
471 strvec_push(&cld
->args
, ".");
474 if (start_command(cld
))
480 copy_to_log(cld
->err
);
482 return finish_command(cld
);
485 static int upload_pack(const struct strvec
*env
)
487 struct child_process cld
= CHILD_PROCESS_INIT
;
488 strvec_pushl(&cld
.args
, "upload-pack", "--strict", NULL
);
489 strvec_pushf(&cld
.args
, "--timeout=%u", timeout
);
491 strvec_pushv(&cld
.env_array
, env
->v
);
493 return run_service_command(&cld
);
496 static int upload_archive(const struct strvec
*env
)
498 struct child_process cld
= CHILD_PROCESS_INIT
;
499 strvec_push(&cld
.args
, "upload-archive");
501 strvec_pushv(&cld
.env_array
, env
->v
);
503 return run_service_command(&cld
);
506 static int receive_pack(const struct strvec
*env
)
508 struct child_process cld
= CHILD_PROCESS_INIT
;
509 strvec_push(&cld
.args
, "receive-pack");
511 strvec_pushv(&cld
.env_array
, env
->v
);
513 return run_service_command(&cld
);
516 static struct daemon_service daemon_service
[] = {
517 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
518 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
519 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
522 static void enable_service(const char *name
, int ena
)
525 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
526 if (!strcmp(daemon_service
[i
].name
, name
)) {
527 daemon_service
[i
].enabled
= ena
;
531 die("No such service %s", name
);
534 static void make_service_overridable(const char *name
, int ena
)
537 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
538 if (!strcmp(daemon_service
[i
].name
, name
)) {
539 daemon_service
[i
].overridable
= ena
;
543 die("No such service %s", name
);
546 static void parse_host_and_port(char *hostport
, char **host
,
549 if (*hostport
== '[') {
552 end
= strchr(hostport
, ']');
554 die("Invalid request ('[' without ']')");
556 *host
= hostport
+ 1;
559 else if (end
[1] == ':')
562 die("Garbage after end of host part");
565 *port
= strrchr(hostport
, ':');
574 * Sanitize a string from the client so that it's OK to be inserted into a
575 * filesystem path. Specifically, we disallow directory separators, runs
576 * of "..", and trailing and leading dots, which means that the client
577 * cannot escape our base path via ".." traversal.
579 static void sanitize_client(struct strbuf
*out
, const char *in
)
584 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
586 strbuf_addch(out
, *in
);
589 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
590 strbuf_setlen(out
, out
->len
- 1);
594 * Like sanitize_client, but we also perform any canonicalization
595 * to make life easier on the admin.
597 static void canonicalize_client(struct strbuf
*out
, const char *in
)
599 sanitize_client(out
, in
);
604 * Read the host as supplied by the client connection.
606 * Returns a pointer to the character after the NUL byte terminating the host
607 * argument, or 'extra_args' if there is no host argument.
609 static char *parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
613 char *end
= extra_args
+ buflen
;
615 if (extra_args
< end
&& *extra_args
) {
616 hi
->saw_extended_args
= 1;
617 if (strncasecmp("host=", extra_args
, 5) == 0) {
618 val
= extra_args
+ 5;
619 vallen
= strlen(val
) + 1;
620 loginfo("Extended attribute \"host\": %s", val
);
622 /* Split <host>:<port> at colon. */
625 parse_host_and_port(val
, &host
, &port
);
627 sanitize_client(&hi
->tcp_port
, port
);
628 canonicalize_client(&hi
->hostname
, host
);
629 hi
->hostname_lookup_done
= 0;
632 /* On to the next one */
633 extra_args
= val
+ vallen
;
635 if (extra_args
< end
&& *extra_args
)
636 die("Invalid request");
642 static void parse_extra_args(struct hostinfo
*hi
, struct strvec
*env
,
643 char *extra_args
, int buflen
)
645 const char *end
= extra_args
+ buflen
;
646 struct strbuf git_protocol
= STRBUF_INIT
;
648 /* First look for the host argument */
649 extra_args
= parse_host_arg(hi
, extra_args
, buflen
);
651 /* Look for additional arguments places after a second NUL byte */
652 for (; extra_args
< end
; extra_args
+= strlen(extra_args
) + 1) {
653 const char *arg
= extra_args
;
656 * Parse the extra arguments, adding most to 'git_protocol'
657 * which will be used to set the 'GIT_PROTOCOL' envvar in the
658 * service that will be run.
660 * If there ends up being a particular arg in the future that
661 * git-daemon needs to parse specifically (like the 'host' arg)
662 * then it can be parsed here and not added to 'git_protocol'.
665 if (git_protocol
.len
> 0)
666 strbuf_addch(&git_protocol
, ':');
667 strbuf_addstr(&git_protocol
, arg
);
671 if (git_protocol
.len
> 0) {
672 loginfo("Extended attribute \"protocol\": %s", git_protocol
.buf
);
673 strvec_pushf(env
, GIT_PROTOCOL_ENVIRONMENT
"=%s",
676 strbuf_release(&git_protocol
);
680 * Locate canonical hostname and its IP address.
682 static void lookup_hostname(struct hostinfo
*hi
)
684 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
686 struct addrinfo hints
;
689 static char addrbuf
[HOST_NAME_MAX
+ 1];
691 memset(&hints
, 0, sizeof(hints
));
692 hints
.ai_flags
= AI_CANONNAME
;
694 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
696 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
698 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
699 addrbuf
, sizeof(addrbuf
));
700 strbuf_addstr(&hi
->ip_address
, addrbuf
);
702 if (ai
->ai_canonname
)
703 sanitize_client(&hi
->canon_hostname
,
706 strbuf_addbuf(&hi
->canon_hostname
,
712 struct hostent
*hent
;
713 struct sockaddr_in sa
;
715 static char addrbuf
[HOST_NAME_MAX
+ 1];
717 hent
= gethostbyname(hi
->hostname
.buf
);
719 ap
= hent
->h_addr_list
;
720 memset(&sa
, 0, sizeof sa
);
721 sa
.sin_family
= hent
->h_addrtype
;
722 sa
.sin_port
= htons(0);
723 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
725 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
726 addrbuf
, sizeof(addrbuf
));
728 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
729 strbuf_addstr(&hi
->ip_address
, addrbuf
);
732 hi
->hostname_lookup_done
= 1;
736 static void hostinfo_clear(struct hostinfo
*hi
)
738 strbuf_release(&hi
->hostname
);
739 strbuf_release(&hi
->canon_hostname
);
740 strbuf_release(&hi
->ip_address
);
741 strbuf_release(&hi
->tcp_port
);
744 static void set_keep_alive(int sockfd
)
748 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0) {
749 if (errno
!= ENOTSOCK
)
750 logerror("unable to set SO_KEEPALIVE on socket: %s",
755 static int execute(void)
757 char *line
= packet_buffer
;
759 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
760 struct hostinfo hi
= HOSTINFO_INIT
;
761 struct strvec env
= STRVEC_INIT
;
764 loginfo("Connection from %s:%s", addr
, port
);
767 alarm(init_timeout
? init_timeout
: timeout
);
768 pktlen
= packet_read(0, packet_buffer
, sizeof(packet_buffer
), 0);
772 if (len
&& line
[len
-1] == '\n')
775 /* parse additional args hidden behind a NUL byte */
777 parse_extra_args(&hi
, &env
, line
+ len
+ 1, pktlen
- len
- 1);
779 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
780 struct daemon_service
*s
= &(daemon_service
[i
]);
783 if (skip_prefix(line
, "git-", &arg
) &&
784 skip_prefix(arg
, s
->name
, &arg
) &&
787 * Note: The directory here is probably context sensitive,
788 * and might depend on the actual service being performed.
790 int rc
= run_service(arg
, s
, &hi
, &env
);
799 logerror("Protocol error: '%s'", line
);
803 static int addrcmp(const struct sockaddr_storage
*s1
,
804 const struct sockaddr_storage
*s2
)
806 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
807 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
809 if (sa1
->sa_family
!= sa2
->sa_family
)
810 return sa1
->sa_family
- sa2
->sa_family
;
811 if (sa1
->sa_family
== AF_INET
)
812 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
813 &((struct sockaddr_in
*)s2
)->sin_addr
,
814 sizeof(struct in_addr
));
816 if (sa1
->sa_family
== AF_INET6
)
817 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
818 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
819 sizeof(struct in6_addr
));
824 static int max_connections
= 32;
826 static unsigned int live_children
;
828 static struct child
{
830 struct child_process cld
;
831 struct sockaddr_storage address
;
834 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
836 struct child
*newborn
, **cradle
;
838 CALLOC_ARRAY(newborn
, 1);
840 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
841 memcpy(&newborn
->address
, addr
, addrlen
);
842 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
843 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
845 newborn
->next
= *cradle
;
850 * This gets called if the number of connections grows
851 * past "max_connections".
853 * We kill the newest connection from a duplicate IP.
855 static void kill_some_child(void)
857 const struct child
*blanket
, *next
;
859 if (!(blanket
= firstborn
))
862 for (; (next
= blanket
->next
); blanket
= next
)
863 if (!addrcmp(&blanket
->address
, &next
->address
)) {
864 kill(blanket
->cld
.pid
, SIGTERM
);
869 static void check_dead_children(void)
874 struct child
**cradle
, *blanket
;
875 for (cradle
= &firstborn
; (blanket
= *cradle
);)
876 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
877 const char *dead
= "";
879 dead
= " (with error)";
880 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
882 /* remove the child */
883 *cradle
= blanket
->next
;
885 child_process_clear(&blanket
->cld
);
888 cradle
= &blanket
->next
;
891 static struct strvec cld_argv
= STRVEC_INIT
;
892 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
894 struct child_process cld
= CHILD_PROCESS_INIT
;
896 if (max_connections
&& live_children
>= max_connections
) {
898 sleep(1); /* give it some time to die */
899 check_dead_children();
900 if (live_children
>= max_connections
) {
902 logerror("Too many children, dropping connection");
907 if (addr
->sa_family
== AF_INET
) {
909 struct sockaddr_in
*sin_addr
= (void *) addr
;
910 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
911 strvec_pushf(&cld
.env_array
, "REMOTE_ADDR=%s", buf
);
912 strvec_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
913 ntohs(sin_addr
->sin_port
));
915 } else if (addr
->sa_family
== AF_INET6
) {
917 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
918 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
919 strvec_pushf(&cld
.env_array
, "REMOTE_ADDR=[%s]", buf
);
920 strvec_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
921 ntohs(sin6_addr
->sin6_port
));
925 cld
.argv
= cld_argv
.v
;
927 cld
.out
= dup(incoming
);
929 if (start_command(&cld
))
930 logerror("unable to fork");
932 add_child(&cld
, addr
, addrlen
);
935 static void child_handler(int signo
)
938 * Otherwise empty handler because systemcalls will get interrupted
939 * upon signal receipt
940 * SysV needs the handler to be rearmed
942 signal(SIGCHLD
, child_handler
);
945 static int set_reuse_addr(int sockfd
)
951 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
961 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
964 static char ip
[INET_ADDRSTRLEN
];
966 static char ip
[INET6_ADDRSTRLEN
];
972 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
976 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
979 xsnprintf(ip
, sizeof(ip
), "<unknown>");
986 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
989 char pbuf
[NI_MAXSERV
];
990 struct addrinfo hints
, *ai0
, *ai
;
994 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
995 memset(&hints
, 0, sizeof(hints
));
996 hints
.ai_family
= AF_UNSPEC
;
997 hints
.ai_socktype
= SOCK_STREAM
;
998 hints
.ai_protocol
= IPPROTO_TCP
;
999 hints
.ai_flags
= AI_PASSIVE
;
1001 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
1003 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
1007 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
1010 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
1013 if (sockfd
>= FD_SETSIZE
) {
1014 logerror("Socket descriptor too large");
1020 if (ai
->ai_family
== AF_INET6
) {
1022 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
1024 /* Note: error is not fatal */
1028 if (set_reuse_addr(sockfd
)) {
1029 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1034 set_keep_alive(sockfd
);
1036 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1037 logerror("Could not bind to %s: %s",
1038 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1041 continue; /* not fatal */
1043 if (listen(sockfd
, 5) < 0) {
1044 logerror("Could not listen to %s: %s",
1045 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1048 continue; /* not fatal */
1051 flags
= fcntl(sockfd
, F_GETFD
, 0);
1053 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1055 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1056 socklist
->list
[socklist
->nr
++] = sockfd
;
1067 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1069 struct sockaddr_in sin
;
1073 memset(&sin
, 0, sizeof sin
);
1074 sin
.sin_family
= AF_INET
;
1075 sin
.sin_port
= htons(listen_port
);
1078 /* Well, host better be an IP address here. */
1079 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1082 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1085 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1089 if (set_reuse_addr(sockfd
)) {
1090 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1095 set_keep_alive(sockfd
);
1097 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1098 logerror("Could not bind to %s: %s",
1099 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1105 if (listen(sockfd
, 5) < 0) {
1106 logerror("Could not listen to %s: %s",
1107 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1113 flags
= fcntl(sockfd
, F_GETFD
, 0);
1115 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1117 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1118 socklist
->list
[socklist
->nr
++] = sockfd
;
1124 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1126 if (!listen_addr
->nr
)
1127 setup_named_sock(NULL
, listen_port
, socklist
);
1130 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1131 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1132 listen_port
, socklist
);
1135 logerror("unable to allocate any listen sockets for host %s on port %u",
1136 listen_addr
->items
[i
].string
, listen_port
);
1141 static int service_loop(struct socketlist
*socklist
)
1146 CALLOC_ARRAY(pfd
, socklist
->nr
);
1148 for (i
= 0; i
< socklist
->nr
; i
++) {
1149 pfd
[i
].fd
= socklist
->list
[i
];
1150 pfd
[i
].events
= POLLIN
;
1153 signal(SIGCHLD
, child_handler
);
1158 check_dead_children();
1160 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1161 if (errno
!= EINTR
) {
1162 logerror("Poll failed, resuming: %s",
1169 for (i
= 0; i
< socklist
->nr
; i
++) {
1170 if (pfd
[i
].revents
& POLLIN
) {
1173 struct sockaddr_in sai
;
1175 struct sockaddr_in6 sai6
;
1178 socklen_t sslen
= sizeof(ss
);
1179 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1187 die_errno("accept returned");
1190 handle(incoming
, &ss
.sa
, sslen
);
1196 #ifdef NO_POSIX_GOODIES
1200 static void drop_privileges(struct credentials
*cred
)
1205 static struct credentials
*prepare_credentials(const char *user_name
,
1206 const char *group_name
)
1208 die("--user not supported on this platform");
1213 struct credentials
{
1214 struct passwd
*pass
;
1218 static void drop_privileges(struct credentials
*cred
)
1220 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1221 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1222 die("cannot drop privileges");
1225 static struct credentials
*prepare_credentials(const char *user_name
,
1226 const char *group_name
)
1228 static struct credentials c
;
1230 c
.pass
= getpwnam(user_name
);
1232 die("user not found - %s", user_name
);
1235 c
.gid
= c
.pass
->pw_gid
;
1237 struct group
*group
= getgrnam(group_name
);
1239 die("group not found - %s", group_name
);
1241 c
.gid
= group
->gr_gid
;
1248 static int serve(struct string_list
*listen_addr
, int listen_port
,
1249 struct credentials
*cred
)
1251 struct socketlist socklist
= { NULL
, 0, 0 };
1253 socksetup(listen_addr
, listen_port
, &socklist
);
1254 if (socklist
.nr
== 0)
1255 die("unable to allocate any listen sockets on port %u",
1258 drop_privileges(cred
);
1260 loginfo("Ready to rumble");
1262 return service_loop(&socklist
);
1265 int cmd_main(int argc
, const char **argv
)
1267 int listen_port
= 0;
1268 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1269 int serve_mode
= 0, inetd_mode
= 0;
1270 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1272 struct credentials
*cred
= NULL
;
1275 for (i
= 1; i
< argc
; i
++) {
1276 const char *arg
= argv
[i
];
1279 if (skip_prefix(arg
, "--listen=", &v
)) {
1280 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1283 if (skip_prefix(arg
, "--port=", &v
)) {
1286 n
= strtoul(v
, &end
, 0);
1292 if (!strcmp(arg
, "--serve")) {
1296 if (!strcmp(arg
, "--inetd")) {
1300 if (!strcmp(arg
, "--verbose")) {
1304 if (!strcmp(arg
, "--syslog")) {
1305 log_destination
= LOG_DESTINATION_SYSLOG
;
1308 if (skip_prefix(arg
, "--log-destination=", &v
)) {
1309 if (!strcmp(v
, "syslog")) {
1310 log_destination
= LOG_DESTINATION_SYSLOG
;
1312 } else if (!strcmp(v
, "stderr")) {
1313 log_destination
= LOG_DESTINATION_STDERR
;
1315 } else if (!strcmp(v
, "none")) {
1316 log_destination
= LOG_DESTINATION_NONE
;
1319 die("unknown log destination '%s'", v
);
1321 if (!strcmp(arg
, "--export-all")) {
1322 export_all_trees
= 1;
1325 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1329 if (skip_prefix(arg
, "--timeout=", &v
)) {
1333 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1334 init_timeout
= atoi(v
);
1337 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1338 max_connections
= atoi(v
);
1339 if (max_connections
< 0)
1340 max_connections
= 0; /* unlimited */
1343 if (!strcmp(arg
, "--strict-paths")) {
1347 if (skip_prefix(arg
, "--base-path=", &v
)) {
1351 if (!strcmp(arg
, "--base-path-relaxed")) {
1352 base_path_relaxed
= 1;
1355 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1356 interpolated_path
= v
;
1359 if (!strcmp(arg
, "--reuseaddr")) {
1363 if (!strcmp(arg
, "--user-path")) {
1367 if (skip_prefix(arg
, "--user-path=", &v
)) {
1371 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1375 if (!strcmp(arg
, "--detach")) {
1379 if (skip_prefix(arg
, "--user=", &v
)) {
1383 if (skip_prefix(arg
, "--group=", &v
)) {
1387 if (skip_prefix(arg
, "--enable=", &v
)) {
1388 enable_service(v
, 1);
1391 if (skip_prefix(arg
, "--disable=", &v
)) {
1392 enable_service(v
, 0);
1395 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1396 make_service_overridable(v
, 1);
1399 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1400 make_service_overridable(v
, 0);
1403 if (!strcmp(arg
, "--informative-errors")) {
1404 informative_errors
= 1;
1407 if (!strcmp(arg
, "--no-informative-errors")) {
1408 informative_errors
= 0;
1411 if (!strcmp(arg
, "--")) {
1412 ok_paths
= &argv
[i
+1];
1414 } else if (arg
[0] != '-') {
1415 ok_paths
= &argv
[i
];
1419 usage(daemon_usage
);
1422 if (log_destination
== LOG_DESTINATION_UNSET
) {
1423 if (inetd_mode
|| detach
)
1424 log_destination
= LOG_DESTINATION_SYSLOG
;
1426 log_destination
= LOG_DESTINATION_STDERR
;
1429 if (log_destination
== LOG_DESTINATION_SYSLOG
) {
1430 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1431 set_die_routine(daemon_die
);
1433 /* avoid splitting a message in the middle */
1434 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1436 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1437 die("--detach, --user and --group are incompatible with --inetd");
1439 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1440 die("--listen= and --port= are incompatible with --inetd");
1441 else if (listen_port
== 0)
1442 listen_port
= DEFAULT_GIT_PORT
;
1444 if (group_name
&& !user_name
)
1445 die("--group supplied without --user");
1448 cred
= prepare_credentials(user_name
, group_name
);
1450 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1451 die("option --strict-paths requires a whitelist");
1453 if (base_path
&& !is_directory(base_path
))
1454 die("base-path '%s' does not exist or is not a directory",
1457 if (log_destination
!= LOG_DESTINATION_STDERR
) {
1458 if (!freopen("/dev/null", "w", stderr
))
1459 die_errno("failed to redirect stderr to /dev/null");
1462 if (inetd_mode
|| serve_mode
)
1467 die("--detach not supported on this platform");
1471 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1473 /* prepare argv for serving-processes */
1474 strvec_push(&cld_argv
, argv
[0]); /* git-daemon */
1475 strvec_push(&cld_argv
, "--serve");
1476 for (i
= 1; i
< argc
; ++i
)
1477 strvec_push(&cld_argv
, argv
[i
]);
1479 return serve(&listen_addr
, listen_port
, cred
);