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
;
332 strvec_push(&child
.args
, access_hook
);
333 strvec_push(&child
.args
, service
->name
);
334 strvec_push(&child
.args
, path
);
335 strvec_push(&child
.args
, hi
->hostname
.buf
);
336 strvec_push(&child
.args
, get_canon_hostname(hi
));
337 strvec_push(&child
.args
, get_ip_address(hi
));
338 strvec_push(&child
.args
, hi
->tcp_port
.buf
);
344 if (start_command(&child
)) {
345 logerror("daemon access hook '%s' failed to start",
349 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
350 logerror("failed to read from pipe to daemon access hook '%s'",
355 if (close(child
.out
) < 0) {
356 logerror("failed to close pipe to daemon access hook '%s'",
360 if (finish_command(&child
))
364 strbuf_release(&buf
);
371 strbuf_addstr(&buf
, "service rejected");
372 eol
= strchr(buf
.buf
, '\n');
376 daemon_error(dir
, buf
.buf
);
377 strbuf_release(&buf
);
381 static int run_service(const char *dir
, struct daemon_service
*service
,
382 struct hostinfo
*hi
, const struct strvec
*env
)
385 int enabled
= service
->enabled
;
386 struct strbuf var
= STRBUF_INIT
;
388 loginfo("Request %s for '%s'", service
->name
, dir
);
390 if (!enabled
&& !service
->overridable
) {
391 logerror("'%s': service not enabled.", service
->name
);
393 return daemon_error(dir
, "service not enabled");
396 if (!(path
= path_ok(dir
, hi
)))
397 return daemon_error(dir
, "no such repository");
400 * Security on the cheap.
402 * We want a readable HEAD, usable "objects" directory, and
403 * a "git-daemon-export-ok" flag that says that the other side
404 * is ok with us doing this.
406 * path_ok() uses enter_repo() and does whitelist checking.
407 * We only need to make sure the repository is exported.
410 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
411 logerror("'%s': repository not exported.", path
);
413 return daemon_error(dir
, "repository not exported");
416 if (service
->overridable
) {
417 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
418 git_config_get_bool(var
.buf
, &enabled
);
419 strbuf_release(&var
);
422 logerror("'%s': service not enabled for '%s'",
423 service
->name
, path
);
425 return daemon_error(dir
, "service not enabled");
429 * Optionally, a hook can choose to deny access to the
430 * repository depending on the phase of the moon.
432 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
436 * We'll ignore SIGTERM from now on, we have a
439 signal(SIGTERM
, SIG_IGN
);
441 return service
->fn(env
);
444 static void copy_to_log(int fd
)
446 struct strbuf line
= STRBUF_INIT
;
449 fp
= fdopen(fd
, "r");
451 logerror("fdopen of error channel failed");
456 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
457 logerror("%s", line
.buf
);
458 strbuf_setlen(&line
, 0);
461 strbuf_release(&line
);
465 static int run_service_command(struct child_process
*cld
)
467 strvec_push(&cld
->args
, ".");
470 if (start_command(cld
))
476 copy_to_log(cld
->err
);
478 return finish_command(cld
);
481 static int upload_pack(const struct strvec
*env
)
483 struct child_process cld
= CHILD_PROCESS_INIT
;
484 strvec_pushl(&cld
.args
, "upload-pack", "--strict", NULL
);
485 strvec_pushf(&cld
.args
, "--timeout=%u", timeout
);
487 strvec_pushv(&cld
.env_array
, env
->v
);
489 return run_service_command(&cld
);
492 static int upload_archive(const struct strvec
*env
)
494 struct child_process cld
= CHILD_PROCESS_INIT
;
495 strvec_push(&cld
.args
, "upload-archive");
497 strvec_pushv(&cld
.env_array
, env
->v
);
499 return run_service_command(&cld
);
502 static int receive_pack(const struct strvec
*env
)
504 struct child_process cld
= CHILD_PROCESS_INIT
;
505 strvec_push(&cld
.args
, "receive-pack");
507 strvec_pushv(&cld
.env_array
, env
->v
);
509 return run_service_command(&cld
);
512 static struct daemon_service daemon_service
[] = {
513 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
514 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
515 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
518 static void enable_service(const char *name
, int ena
)
521 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
522 if (!strcmp(daemon_service
[i
].name
, name
)) {
523 daemon_service
[i
].enabled
= ena
;
527 die("No such service %s", name
);
530 static void make_service_overridable(const char *name
, int ena
)
533 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
534 if (!strcmp(daemon_service
[i
].name
, name
)) {
535 daemon_service
[i
].overridable
= ena
;
539 die("No such service %s", name
);
542 static void parse_host_and_port(char *hostport
, char **host
,
545 if (*hostport
== '[') {
548 end
= strchr(hostport
, ']');
550 die("Invalid request ('[' without ']')");
552 *host
= hostport
+ 1;
555 else if (end
[1] == ':')
558 die("Garbage after end of host part");
561 *port
= strrchr(hostport
, ':');
570 * Sanitize a string from the client so that it's OK to be inserted into a
571 * filesystem path. Specifically, we disallow directory separators, runs
572 * of "..", and trailing and leading dots, which means that the client
573 * cannot escape our base path via ".." traversal.
575 static void sanitize_client(struct strbuf
*out
, const char *in
)
580 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
582 strbuf_addch(out
, *in
);
585 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
586 strbuf_setlen(out
, out
->len
- 1);
590 * Like sanitize_client, but we also perform any canonicalization
591 * to make life easier on the admin.
593 static void canonicalize_client(struct strbuf
*out
, const char *in
)
595 sanitize_client(out
, in
);
600 * Read the host as supplied by the client connection.
602 * Returns a pointer to the character after the NUL byte terminating the host
603 * argument, or 'extra_args' if there is no host argument.
605 static char *parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
609 char *end
= extra_args
+ buflen
;
611 if (extra_args
< end
&& *extra_args
) {
612 hi
->saw_extended_args
= 1;
613 if (strncasecmp("host=", extra_args
, 5) == 0) {
614 val
= extra_args
+ 5;
615 vallen
= strlen(val
) + 1;
616 loginfo("Extended attribute \"host\": %s", val
);
618 /* Split <host>:<port> at colon. */
621 parse_host_and_port(val
, &host
, &port
);
623 sanitize_client(&hi
->tcp_port
, port
);
624 canonicalize_client(&hi
->hostname
, host
);
625 hi
->hostname_lookup_done
= 0;
628 /* On to the next one */
629 extra_args
= val
+ vallen
;
631 if (extra_args
< end
&& *extra_args
)
632 die("Invalid request");
638 static void parse_extra_args(struct hostinfo
*hi
, struct strvec
*env
,
639 char *extra_args
, int buflen
)
641 const char *end
= extra_args
+ buflen
;
642 struct strbuf git_protocol
= STRBUF_INIT
;
644 /* First look for the host argument */
645 extra_args
= parse_host_arg(hi
, extra_args
, buflen
);
647 /* Look for additional arguments places after a second NUL byte */
648 for (; extra_args
< end
; extra_args
+= strlen(extra_args
) + 1) {
649 const char *arg
= extra_args
;
652 * Parse the extra arguments, adding most to 'git_protocol'
653 * which will be used to set the 'GIT_PROTOCOL' envvar in the
654 * service that will be run.
656 * If there ends up being a particular arg in the future that
657 * git-daemon needs to parse specifically (like the 'host' arg)
658 * then it can be parsed here and not added to 'git_protocol'.
661 if (git_protocol
.len
> 0)
662 strbuf_addch(&git_protocol
, ':');
663 strbuf_addstr(&git_protocol
, arg
);
667 if (git_protocol
.len
> 0) {
668 loginfo("Extended attribute \"protocol\": %s", git_protocol
.buf
);
669 strvec_pushf(env
, GIT_PROTOCOL_ENVIRONMENT
"=%s",
672 strbuf_release(&git_protocol
);
676 * Locate canonical hostname and its IP address.
678 static void lookup_hostname(struct hostinfo
*hi
)
680 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
682 struct addrinfo hints
;
685 static char addrbuf
[HOST_NAME_MAX
+ 1];
687 memset(&hints
, 0, sizeof(hints
));
688 hints
.ai_flags
= AI_CANONNAME
;
690 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
692 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
694 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
695 addrbuf
, sizeof(addrbuf
));
696 strbuf_addstr(&hi
->ip_address
, addrbuf
);
698 if (ai
->ai_canonname
)
699 sanitize_client(&hi
->canon_hostname
,
702 strbuf_addbuf(&hi
->canon_hostname
,
708 struct hostent
*hent
;
709 struct sockaddr_in sa
;
711 static char addrbuf
[HOST_NAME_MAX
+ 1];
713 hent
= gethostbyname(hi
->hostname
.buf
);
715 ap
= hent
->h_addr_list
;
716 memset(&sa
, 0, sizeof sa
);
717 sa
.sin_family
= hent
->h_addrtype
;
718 sa
.sin_port
= htons(0);
719 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
721 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
722 addrbuf
, sizeof(addrbuf
));
724 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
725 strbuf_addstr(&hi
->ip_address
, addrbuf
);
728 hi
->hostname_lookup_done
= 1;
732 static void hostinfo_clear(struct hostinfo
*hi
)
734 strbuf_release(&hi
->hostname
);
735 strbuf_release(&hi
->canon_hostname
);
736 strbuf_release(&hi
->ip_address
);
737 strbuf_release(&hi
->tcp_port
);
740 static void set_keep_alive(int sockfd
)
744 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0) {
745 if (errno
!= ENOTSOCK
)
746 logerror("unable to set SO_KEEPALIVE on socket: %s",
751 static int execute(void)
753 char *line
= packet_buffer
;
755 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
756 struct hostinfo hi
= HOSTINFO_INIT
;
757 struct strvec env
= STRVEC_INIT
;
760 loginfo("Connection from %s:%s", addr
, port
);
763 alarm(init_timeout
? init_timeout
: timeout
);
764 pktlen
= packet_read(0, packet_buffer
, sizeof(packet_buffer
), 0);
768 if (len
&& line
[len
-1] == '\n')
771 /* parse additional args hidden behind a NUL byte */
773 parse_extra_args(&hi
, &env
, line
+ len
+ 1, pktlen
- len
- 1);
775 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
776 struct daemon_service
*s
= &(daemon_service
[i
]);
779 if (skip_prefix(line
, "git-", &arg
) &&
780 skip_prefix(arg
, s
->name
, &arg
) &&
783 * Note: The directory here is probably context sensitive,
784 * and might depend on the actual service being performed.
786 int rc
= run_service(arg
, s
, &hi
, &env
);
795 logerror("Protocol error: '%s'", line
);
799 static int addrcmp(const struct sockaddr_storage
*s1
,
800 const struct sockaddr_storage
*s2
)
802 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
803 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
805 if (sa1
->sa_family
!= sa2
->sa_family
)
806 return sa1
->sa_family
- sa2
->sa_family
;
807 if (sa1
->sa_family
== AF_INET
)
808 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
809 &((struct sockaddr_in
*)s2
)->sin_addr
,
810 sizeof(struct in_addr
));
812 if (sa1
->sa_family
== AF_INET6
)
813 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
814 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
815 sizeof(struct in6_addr
));
820 static int max_connections
= 32;
822 static unsigned int live_children
;
824 static struct child
{
826 struct child_process cld
;
827 struct sockaddr_storage address
;
830 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
832 struct child
*newborn
, **cradle
;
834 CALLOC_ARRAY(newborn
, 1);
836 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
837 memcpy(&newborn
->address
, addr
, addrlen
);
838 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
839 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
841 newborn
->next
= *cradle
;
846 * This gets called if the number of connections grows
847 * past "max_connections".
849 * We kill the newest connection from a duplicate IP.
851 static void kill_some_child(void)
853 const struct child
*blanket
, *next
;
855 if (!(blanket
= firstborn
))
858 for (; (next
= blanket
->next
); blanket
= next
)
859 if (!addrcmp(&blanket
->address
, &next
->address
)) {
860 kill(blanket
->cld
.pid
, SIGTERM
);
865 static void check_dead_children(void)
870 struct child
**cradle
, *blanket
;
871 for (cradle
= &firstborn
; (blanket
= *cradle
);)
872 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
873 const char *dead
= "";
875 dead
= " (with error)";
876 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
878 /* remove the child */
879 *cradle
= blanket
->next
;
881 child_process_clear(&blanket
->cld
);
884 cradle
= &blanket
->next
;
887 static struct strvec cld_argv
= STRVEC_INIT
;
888 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
890 struct child_process cld
= CHILD_PROCESS_INIT
;
892 if (max_connections
&& live_children
>= max_connections
) {
894 sleep(1); /* give it some time to die */
895 check_dead_children();
896 if (live_children
>= max_connections
) {
898 logerror("Too many children, dropping connection");
903 if (addr
->sa_family
== AF_INET
) {
905 struct sockaddr_in
*sin_addr
= (void *) addr
;
906 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
907 strvec_pushf(&cld
.env_array
, "REMOTE_ADDR=%s", buf
);
908 strvec_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
909 ntohs(sin_addr
->sin_port
));
911 } else if (addr
->sa_family
== AF_INET6
) {
913 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
914 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
915 strvec_pushf(&cld
.env_array
, "REMOTE_ADDR=[%s]", buf
);
916 strvec_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
917 ntohs(sin6_addr
->sin6_port
));
921 strvec_pushv(&cld
.args
, cld_argv
.v
);
923 cld
.out
= dup(incoming
);
925 if (start_command(&cld
))
926 logerror("unable to fork");
928 add_child(&cld
, addr
, addrlen
);
931 static void child_handler(int signo
)
934 * Otherwise empty handler because systemcalls will get interrupted
935 * upon signal receipt
936 * SysV needs the handler to be rearmed
938 signal(SIGCHLD
, child_handler
);
941 static int set_reuse_addr(int sockfd
)
947 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
957 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
960 static char ip
[INET_ADDRSTRLEN
];
962 static char ip
[INET6_ADDRSTRLEN
];
968 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
972 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
975 xsnprintf(ip
, sizeof(ip
), "<unknown>");
982 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
985 char pbuf
[NI_MAXSERV
];
986 struct addrinfo hints
, *ai0
, *ai
;
990 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
991 memset(&hints
, 0, sizeof(hints
));
992 hints
.ai_family
= AF_UNSPEC
;
993 hints
.ai_socktype
= SOCK_STREAM
;
994 hints
.ai_protocol
= IPPROTO_TCP
;
995 hints
.ai_flags
= AI_PASSIVE
;
997 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
999 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
1003 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
1006 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
1009 if (sockfd
>= FD_SETSIZE
) {
1010 logerror("Socket descriptor too large");
1016 if (ai
->ai_family
== AF_INET6
) {
1018 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
1020 /* Note: error is not fatal */
1024 if (set_reuse_addr(sockfd
)) {
1025 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1030 set_keep_alive(sockfd
);
1032 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1033 logerror("Could not bind to %s: %s",
1034 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1037 continue; /* not fatal */
1039 if (listen(sockfd
, 5) < 0) {
1040 logerror("Could not listen to %s: %s",
1041 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1044 continue; /* not fatal */
1047 flags
= fcntl(sockfd
, F_GETFD
, 0);
1049 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1051 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1052 socklist
->list
[socklist
->nr
++] = sockfd
;
1063 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1065 struct sockaddr_in sin
;
1069 memset(&sin
, 0, sizeof sin
);
1070 sin
.sin_family
= AF_INET
;
1071 sin
.sin_port
= htons(listen_port
);
1074 /* Well, host better be an IP address here. */
1075 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1078 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1081 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1085 if (set_reuse_addr(sockfd
)) {
1086 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1091 set_keep_alive(sockfd
);
1093 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1094 logerror("Could not bind to %s: %s",
1095 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1101 if (listen(sockfd
, 5) < 0) {
1102 logerror("Could not listen to %s: %s",
1103 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1109 flags
= fcntl(sockfd
, F_GETFD
, 0);
1111 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1113 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1114 socklist
->list
[socklist
->nr
++] = sockfd
;
1120 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1122 if (!listen_addr
->nr
)
1123 setup_named_sock(NULL
, listen_port
, socklist
);
1126 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1127 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1128 listen_port
, socklist
);
1131 logerror("unable to allocate any listen sockets for host %s on port %u",
1132 listen_addr
->items
[i
].string
, listen_port
);
1137 static int service_loop(struct socketlist
*socklist
)
1142 CALLOC_ARRAY(pfd
, socklist
->nr
);
1144 for (i
= 0; i
< socklist
->nr
; i
++) {
1145 pfd
[i
].fd
= socklist
->list
[i
];
1146 pfd
[i
].events
= POLLIN
;
1149 signal(SIGCHLD
, child_handler
);
1154 check_dead_children();
1156 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1157 if (errno
!= EINTR
) {
1158 logerror("Poll failed, resuming: %s",
1165 for (i
= 0; i
< socklist
->nr
; i
++) {
1166 if (pfd
[i
].revents
& POLLIN
) {
1169 struct sockaddr_in sai
;
1171 struct sockaddr_in6 sai6
;
1174 socklen_t sslen
= sizeof(ss
);
1175 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1183 die_errno("accept returned");
1186 handle(incoming
, &ss
.sa
, sslen
);
1192 #ifdef NO_POSIX_GOODIES
1196 static void drop_privileges(struct credentials
*cred
)
1201 static struct credentials
*prepare_credentials(const char *user_name
,
1202 const char *group_name
)
1204 die("--user not supported on this platform");
1209 struct credentials
{
1210 struct passwd
*pass
;
1214 static void drop_privileges(struct credentials
*cred
)
1216 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1217 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1218 die("cannot drop privileges");
1221 static struct credentials
*prepare_credentials(const char *user_name
,
1222 const char *group_name
)
1224 static struct credentials c
;
1226 c
.pass
= getpwnam(user_name
);
1228 die("user not found - %s", user_name
);
1231 c
.gid
= c
.pass
->pw_gid
;
1233 struct group
*group
= getgrnam(group_name
);
1235 die("group not found - %s", group_name
);
1237 c
.gid
= group
->gr_gid
;
1244 static int serve(struct string_list
*listen_addr
, int listen_port
,
1245 struct credentials
*cred
)
1247 struct socketlist socklist
= { NULL
, 0, 0 };
1249 socksetup(listen_addr
, listen_port
, &socklist
);
1250 if (socklist
.nr
== 0)
1251 die("unable to allocate any listen sockets on port %u",
1254 drop_privileges(cred
);
1256 loginfo("Ready to rumble");
1258 return service_loop(&socklist
);
1261 int cmd_main(int argc
, const char **argv
)
1263 int listen_port
= 0;
1264 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1265 int serve_mode
= 0, inetd_mode
= 0;
1266 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1268 struct credentials
*cred
= NULL
;
1271 for (i
= 1; i
< argc
; i
++) {
1272 const char *arg
= argv
[i
];
1275 if (skip_prefix(arg
, "--listen=", &v
)) {
1276 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1279 if (skip_prefix(arg
, "--port=", &v
)) {
1282 n
= strtoul(v
, &end
, 0);
1288 if (!strcmp(arg
, "--serve")) {
1292 if (!strcmp(arg
, "--inetd")) {
1296 if (!strcmp(arg
, "--verbose")) {
1300 if (!strcmp(arg
, "--syslog")) {
1301 log_destination
= LOG_DESTINATION_SYSLOG
;
1304 if (skip_prefix(arg
, "--log-destination=", &v
)) {
1305 if (!strcmp(v
, "syslog")) {
1306 log_destination
= LOG_DESTINATION_SYSLOG
;
1308 } else if (!strcmp(v
, "stderr")) {
1309 log_destination
= LOG_DESTINATION_STDERR
;
1311 } else if (!strcmp(v
, "none")) {
1312 log_destination
= LOG_DESTINATION_NONE
;
1315 die("unknown log destination '%s'", v
);
1317 if (!strcmp(arg
, "--export-all")) {
1318 export_all_trees
= 1;
1321 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1325 if (skip_prefix(arg
, "--timeout=", &v
)) {
1329 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1330 init_timeout
= atoi(v
);
1333 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1334 max_connections
= atoi(v
);
1335 if (max_connections
< 0)
1336 max_connections
= 0; /* unlimited */
1339 if (!strcmp(arg
, "--strict-paths")) {
1343 if (skip_prefix(arg
, "--base-path=", &v
)) {
1347 if (!strcmp(arg
, "--base-path-relaxed")) {
1348 base_path_relaxed
= 1;
1351 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1352 interpolated_path
= v
;
1355 if (!strcmp(arg
, "--reuseaddr")) {
1359 if (!strcmp(arg
, "--user-path")) {
1363 if (skip_prefix(arg
, "--user-path=", &v
)) {
1367 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1371 if (!strcmp(arg
, "--detach")) {
1375 if (skip_prefix(arg
, "--user=", &v
)) {
1379 if (skip_prefix(arg
, "--group=", &v
)) {
1383 if (skip_prefix(arg
, "--enable=", &v
)) {
1384 enable_service(v
, 1);
1387 if (skip_prefix(arg
, "--disable=", &v
)) {
1388 enable_service(v
, 0);
1391 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1392 make_service_overridable(v
, 1);
1395 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1396 make_service_overridable(v
, 0);
1399 if (!strcmp(arg
, "--informative-errors")) {
1400 informative_errors
= 1;
1403 if (!strcmp(arg
, "--no-informative-errors")) {
1404 informative_errors
= 0;
1407 if (!strcmp(arg
, "--")) {
1408 ok_paths
= &argv
[i
+1];
1410 } else if (arg
[0] != '-') {
1411 ok_paths
= &argv
[i
];
1415 usage(daemon_usage
);
1418 if (log_destination
== LOG_DESTINATION_UNSET
) {
1419 if (inetd_mode
|| detach
)
1420 log_destination
= LOG_DESTINATION_SYSLOG
;
1422 log_destination
= LOG_DESTINATION_STDERR
;
1425 if (log_destination
== LOG_DESTINATION_SYSLOG
) {
1426 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1427 set_die_routine(daemon_die
);
1429 /* avoid splitting a message in the middle */
1430 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1432 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1433 die("--detach, --user and --group are incompatible with --inetd");
1435 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1436 die("--listen= and --port= are incompatible with --inetd");
1437 else if (listen_port
== 0)
1438 listen_port
= DEFAULT_GIT_PORT
;
1440 if (group_name
&& !user_name
)
1441 die("--group supplied without --user");
1444 cred
= prepare_credentials(user_name
, group_name
);
1446 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1447 die("option --strict-paths requires a whitelist");
1449 if (base_path
&& !is_directory(base_path
))
1450 die("base-path '%s' does not exist or is not a directory",
1453 if (log_destination
!= LOG_DESTINATION_STDERR
) {
1454 if (!freopen("/dev/null", "w", stderr
))
1455 die_errno("failed to redirect stderr to /dev/null");
1458 if (inetd_mode
|| serve_mode
)
1463 die("--detach not supported on this platform");
1467 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1469 /* prepare argv for serving-processes */
1470 strvec_push(&cld_argv
, argv
[0]); /* git-daemon */
1471 strvec_push(&cld_argv
, "--serve");
1472 for (i
= 1; i
< argc
; ++i
)
1473 strvec_push(&cld_argv
, argv
[i
]);
1475 return serve(&listen_addr
, listen_port
, cred
);