6 #include "run-command.h"
8 #include "string-list.h"
11 #define initgroups(x, y) (0) /* nothing */
14 static enum log_destination
{
15 LOG_DESTINATION_UNSET
= -1,
16 LOG_DESTINATION_NONE
= 0,
17 LOG_DESTINATION_STDERR
= 1,
18 LOG_DESTINATION_SYSLOG
= 2,
19 } log_destination
= LOG_DESTINATION_UNSET
;
22 static int informative_errors
;
24 static const char daemon_usage
[] =
25 "git daemon [--verbose] [--syslog] [--export-all]\n"
26 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
27 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
28 " [--user-path | --user-path=<path>]\n"
29 " [--interpolated-path=<path>]\n"
30 " [--reuseaddr] [--pid-file=<file>]\n"
31 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
32 " [--access-hook=<path>]\n"
33 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
34 " [--detach] [--user=<user> [--group=<group>]]\n"
35 " [--log-destination=(stderr|syslog|none)]\n"
38 /* List of acceptable pathname prefixes */
39 static const char **ok_paths
;
40 static int strict_paths
;
42 /* If this is set, git-daemon-export-ok is not required */
43 static int export_all_trees
;
45 /* Take all paths relative to this one if non-NULL */
46 static const char *base_path
;
47 static const char *interpolated_path
;
48 static int base_path_relaxed
;
50 /* If defined, ~user notation is allowed and the string is inserted
51 * after ~user/. E.g. a request to git://host/~alice/frotz would
52 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
54 static const char *user_path
;
56 /* Timeout, and initial timeout */
57 static unsigned int timeout
;
58 static unsigned int init_timeout
;
61 struct strbuf hostname
;
62 struct strbuf canon_hostname
;
63 struct strbuf ip_address
;
64 struct strbuf tcp_port
;
65 unsigned int hostname_lookup_done
:1;
66 unsigned int saw_extended_args
:1;
68 #define HOSTINFO_INIT { \
69 .hostname = STRBUF_INIT, \
70 .canon_hostname = STRBUF_INIT, \
71 .ip_address = STRBUF_INIT, \
72 .tcp_port = STRBUF_INIT, \
75 static void lookup_hostname(struct hostinfo
*hi
);
77 static const char *get_canon_hostname(struct hostinfo
*hi
)
80 return hi
->canon_hostname
.buf
;
83 static const char *get_ip_address(struct hostinfo
*hi
)
86 return hi
->ip_address
.buf
;
89 static void logreport(int priority
, const char *err
, va_list params
)
91 switch (log_destination
) {
92 case LOG_DESTINATION_SYSLOG
: {
94 vsnprintf(buf
, sizeof(buf
), err
, params
);
95 syslog(priority
, "%s", buf
);
98 case LOG_DESTINATION_STDERR
:
100 * Since stderr is set to buffered mode, the
101 * logging of different processes will not overlap
102 * unless they overflow the (rather big) buffers.
104 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
105 vfprintf(stderr
, err
, params
);
109 case LOG_DESTINATION_NONE
:
111 case LOG_DESTINATION_UNSET
:
112 BUG("log destination not initialized correctly");
116 __attribute__((format (printf
, 1, 2)))
117 static void logerror(const char *err
, ...)
120 va_start(params
, err
);
121 logreport(LOG_ERR
, err
, params
);
125 __attribute__((format (printf
, 1, 2)))
126 static void loginfo(const char *err
, ...)
131 va_start(params
, err
);
132 logreport(LOG_INFO
, err
, params
);
136 static void NORETURN
daemon_die(const char *err
, va_list params
)
138 logreport(LOG_ERR
, err
, params
);
142 struct expand_path_context
{
143 const char *directory
;
144 struct hostinfo
*hostinfo
;
147 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
149 struct expand_path_context
*context
= ctx
;
150 struct hostinfo
*hi
= context
->hostinfo
;
152 switch (placeholder
[0]) {
154 strbuf_addbuf(sb
, &hi
->hostname
);
157 if (placeholder
[1] == 'H') {
158 strbuf_addstr(sb
, get_canon_hostname(hi
));
163 if (placeholder
[1] == 'P') {
164 strbuf_addstr(sb
, get_ip_address(hi
));
169 strbuf_addbuf(sb
, &hi
->tcp_port
);
172 strbuf_addstr(sb
, context
->directory
);
178 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
180 static char rpath
[PATH_MAX
];
181 static char interp_path
[PATH_MAX
];
188 if (daemon_avoid_alias(dir
)) {
189 logerror("'%s': aliased", dir
);
195 logerror("'%s': User-path not allowed", dir
);
199 /* Got either "~alice" or "~alice/foo";
200 * rewrite them to "~alice/%s" or
203 int namlen
, restlen
= strlen(dir
);
204 const char *slash
= strchr(dir
, '/');
206 slash
= dir
+ restlen
;
207 namlen
= slash
- dir
;
209 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
210 rlen
= snprintf(rpath
, sizeof(rpath
), "%.*s/%s%.*s",
211 namlen
, dir
, user_path
, restlen
, slash
);
212 if (rlen
>= sizeof(rpath
)) {
213 logerror("user-path too large: %s", rpath
);
219 else if (interpolated_path
&& hi
->saw_extended_args
) {
220 struct strbuf expanded_path
= STRBUF_INIT
;
221 struct expand_path_context context
;
223 context
.directory
= directory
;
224 context
.hostinfo
= hi
;
227 /* Allow only absolute */
228 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
232 strbuf_expand(&expanded_path
, interpolated_path
,
233 expand_path
, &context
);
235 rlen
= strlcpy(interp_path
, expanded_path
.buf
,
236 sizeof(interp_path
));
237 strbuf_release(&expanded_path
);
238 if (rlen
>= sizeof(interp_path
)) {
239 logerror("interpolated path too large: %s",
244 loginfo("Interpolated dir '%s'", interp_path
);
248 else if (base_path
) {
250 /* Allow only absolute */
251 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
254 rlen
= snprintf(rpath
, sizeof(rpath
), "%s%s", base_path
, dir
);
255 if (rlen
>= sizeof(rpath
)) {
256 logerror("base-path too large: %s", rpath
);
262 path
= enter_repo(dir
, strict_paths
);
263 if (!path
&& base_path
&& base_path_relaxed
) {
265 * if we fail and base_path_relaxed is enabled, try without
266 * prefixing the base path
269 path
= enter_repo(dir
, strict_paths
);
273 logerror("'%s' does not appear to be a git repository", dir
);
277 if ( ok_paths
&& *ok_paths
) {
279 int pathlen
= strlen(path
);
281 /* The validation is done on the paths after enter_repo
282 * appends optional {.git,.git/.git} and friends, but
283 * it does not use getcwd(). So if your /pub is
284 * a symlink to /mnt/pub, you can include /pub and
285 * do not have to say /mnt/pub.
288 for ( pp
= ok_paths
; *pp
; pp
++ ) {
289 int len
= strlen(*pp
);
290 if (len
<= pathlen
&&
291 !memcmp(*pp
, path
, len
) &&
292 (path
[len
] == '\0' ||
293 (!strict_paths
&& path
[len
] == '/')))
298 /* be backwards compatible */
303 logerror("'%s': not in directory list", path
);
304 return NULL
; /* Fallthrough. Deny by default */
307 typedef int (*daemon_service_fn
)(const struct strvec
*env
);
308 struct daemon_service
{
310 const char *config_name
;
311 daemon_service_fn fn
;
316 static int daemon_error(const char *dir
, const char *msg
)
318 if (!informative_errors
)
319 msg
= "access denied or repository not exported";
320 packet_write_fmt(1, "ERR %s: %s", msg
, dir
);
324 static const char *access_hook
;
326 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
327 const char *path
, struct hostinfo
*hi
)
329 struct child_process child
= CHILD_PROCESS_INIT
;
330 struct strbuf buf
= STRBUF_INIT
;
334 strvec_push(&child
.args
, access_hook
);
335 strvec_push(&child
.args
, service
->name
);
336 strvec_push(&child
.args
, path
);
337 strvec_push(&child
.args
, hi
->hostname
.buf
);
338 strvec_push(&child
.args
, get_canon_hostname(hi
));
339 strvec_push(&child
.args
, get_ip_address(hi
));
340 strvec_push(&child
.args
, hi
->tcp_port
.buf
);
346 if (start_command(&child
)) {
347 logerror("daemon access hook '%s' failed to start",
351 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
352 logerror("failed to read from pipe to daemon access hook '%s'",
357 if (close(child
.out
) < 0) {
358 logerror("failed to close pipe to daemon access hook '%s'",
362 if (finish_command(&child
))
366 strbuf_release(&buf
);
373 strbuf_addstr(&buf
, "service rejected");
374 eol
= strchr(buf
.buf
, '\n');
378 daemon_error(dir
, buf
.buf
);
379 strbuf_release(&buf
);
383 static int run_service(const char *dir
, struct daemon_service
*service
,
384 struct hostinfo
*hi
, const struct strvec
*env
)
387 int enabled
= service
->enabled
;
388 struct strbuf var
= STRBUF_INIT
;
390 loginfo("Request %s for '%s'", service
->name
, dir
);
392 if (!enabled
&& !service
->overridable
) {
393 logerror("'%s': service not enabled.", service
->name
);
395 return daemon_error(dir
, "service not enabled");
398 if (!(path
= path_ok(dir
, hi
)))
399 return daemon_error(dir
, "no such repository");
402 * Security on the cheap.
404 * We want a readable HEAD, usable "objects" directory, and
405 * a "git-daemon-export-ok" flag that says that the other side
406 * is ok with us doing this.
408 * path_ok() uses enter_repo() and checks for included directories.
409 * We only need to make sure the repository is exported.
412 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
413 logerror("'%s': repository not exported.", path
);
415 return daemon_error(dir
, "repository not exported");
418 if (service
->overridable
) {
419 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
420 git_config_get_bool(var
.buf
, &enabled
);
421 strbuf_release(&var
);
424 logerror("'%s': service not enabled for '%s'",
425 service
->name
, path
);
427 return daemon_error(dir
, "service not enabled");
431 * Optionally, a hook can choose to deny access to the
432 * repository depending on the phase of the moon.
434 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
438 * We'll ignore SIGTERM from now on, we have a
441 signal(SIGTERM
, SIG_IGN
);
443 return service
->fn(env
);
446 static void copy_to_log(int fd
)
448 struct strbuf line
= STRBUF_INIT
;
451 fp
= fdopen(fd
, "r");
453 logerror("fdopen of error channel failed");
458 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
459 logerror("%s", line
.buf
);
460 strbuf_setlen(&line
, 0);
463 strbuf_release(&line
);
467 static int run_service_command(struct child_process
*cld
)
469 strvec_push(&cld
->args
, ".");
472 if (start_command(cld
))
478 copy_to_log(cld
->err
);
480 return finish_command(cld
);
483 static int upload_pack(const struct strvec
*env
)
485 struct child_process cld
= CHILD_PROCESS_INIT
;
486 strvec_pushl(&cld
.args
, "upload-pack", "--strict", NULL
);
487 strvec_pushf(&cld
.args
, "--timeout=%u", timeout
);
489 strvec_pushv(&cld
.env
, env
->v
);
491 return run_service_command(&cld
);
494 static int upload_archive(const struct strvec
*env
)
496 struct child_process cld
= CHILD_PROCESS_INIT
;
497 strvec_push(&cld
.args
, "upload-archive");
499 strvec_pushv(&cld
.env
, env
->v
);
501 return run_service_command(&cld
);
504 static int receive_pack(const struct strvec
*env
)
506 struct child_process cld
= CHILD_PROCESS_INIT
;
507 strvec_push(&cld
.args
, "receive-pack");
509 strvec_pushv(&cld
.env
, env
->v
);
511 return run_service_command(&cld
);
514 static struct daemon_service daemon_service
[] = {
515 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
516 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
517 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
520 static void enable_service(const char *name
, int ena
)
523 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
524 if (!strcmp(daemon_service
[i
].name
, name
)) {
525 daemon_service
[i
].enabled
= ena
;
529 die("No such service %s", name
);
532 static void make_service_overridable(const char *name
, int ena
)
535 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
536 if (!strcmp(daemon_service
[i
].name
, name
)) {
537 daemon_service
[i
].overridable
= ena
;
541 die("No such service %s", name
);
544 static void parse_host_and_port(char *hostport
, char **host
,
547 if (*hostport
== '[') {
550 end
= strchr(hostport
, ']');
552 die("Invalid request ('[' without ']')");
554 *host
= hostport
+ 1;
557 else if (end
[1] == ':')
560 die("Garbage after end of host part");
563 *port
= strrchr(hostport
, ':');
572 * Sanitize a string from the client so that it's OK to be inserted into a
573 * filesystem path. Specifically, we disallow directory separators, runs
574 * of "..", and trailing and leading dots, which means that the client
575 * cannot escape our base path via ".." traversal.
577 static void sanitize_client(struct strbuf
*out
, const char *in
)
582 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
584 strbuf_addch(out
, *in
);
587 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
588 strbuf_setlen(out
, out
->len
- 1);
592 * Like sanitize_client, but we also perform any canonicalization
593 * to make life easier on the admin.
595 static void canonicalize_client(struct strbuf
*out
, const char *in
)
597 sanitize_client(out
, in
);
602 * Read the host as supplied by the client connection.
604 * Returns a pointer to the character after the NUL byte terminating the host
605 * argument, or 'extra_args' if there is no host argument.
607 static char *parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
611 char *end
= extra_args
+ buflen
;
613 if (extra_args
< end
&& *extra_args
) {
614 hi
->saw_extended_args
= 1;
615 if (strncasecmp("host=", extra_args
, 5) == 0) {
616 val
= extra_args
+ 5;
617 vallen
= strlen(val
) + 1;
618 loginfo("Extended attribute \"host\": %s", val
);
620 /* Split <host>:<port> at colon. */
623 parse_host_and_port(val
, &host
, &port
);
625 sanitize_client(&hi
->tcp_port
, port
);
626 canonicalize_client(&hi
->hostname
, host
);
627 hi
->hostname_lookup_done
= 0;
630 /* On to the next one */
631 extra_args
= val
+ vallen
;
633 if (extra_args
< end
&& *extra_args
)
634 die("Invalid request");
640 static void parse_extra_args(struct hostinfo
*hi
, struct strvec
*env
,
641 char *extra_args
, int buflen
)
643 const char *end
= extra_args
+ buflen
;
644 struct strbuf git_protocol
= STRBUF_INIT
;
646 /* First look for the host argument */
647 extra_args
= parse_host_arg(hi
, extra_args
, buflen
);
649 /* Look for additional arguments places after a second NUL byte */
650 for (; extra_args
< end
; extra_args
+= strlen(extra_args
) + 1) {
651 const char *arg
= extra_args
;
654 * Parse the extra arguments, adding most to 'git_protocol'
655 * which will be used to set the 'GIT_PROTOCOL' envvar in the
656 * service that will be run.
658 * If there ends up being a particular arg in the future that
659 * git-daemon needs to parse specifically (like the 'host' arg)
660 * then it can be parsed here and not added to 'git_protocol'.
663 if (git_protocol
.len
> 0)
664 strbuf_addch(&git_protocol
, ':');
665 strbuf_addstr(&git_protocol
, arg
);
669 if (git_protocol
.len
> 0) {
670 loginfo("Extended attribute \"protocol\": %s", git_protocol
.buf
);
671 strvec_pushf(env
, GIT_PROTOCOL_ENVIRONMENT
"=%s",
674 strbuf_release(&git_protocol
);
678 * Locate canonical hostname and its IP address.
680 static void lookup_hostname(struct hostinfo
*hi
)
682 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
684 struct addrinfo hints
;
687 static char addrbuf
[HOST_NAME_MAX
+ 1];
689 memset(&hints
, 0, sizeof(hints
));
690 hints
.ai_flags
= AI_CANONNAME
;
692 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
694 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
696 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
697 addrbuf
, sizeof(addrbuf
));
698 strbuf_addstr(&hi
->ip_address
, addrbuf
);
700 if (ai
->ai_canonname
)
701 sanitize_client(&hi
->canon_hostname
,
704 strbuf_addbuf(&hi
->canon_hostname
,
710 struct hostent
*hent
;
711 struct sockaddr_in sa
;
713 static char addrbuf
[HOST_NAME_MAX
+ 1];
715 hent
= gethostbyname(hi
->hostname
.buf
);
717 ap
= hent
->h_addr_list
;
718 memset(&sa
, 0, sizeof sa
);
719 sa
.sin_family
= hent
->h_addrtype
;
720 sa
.sin_port
= htons(0);
721 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
723 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
724 addrbuf
, sizeof(addrbuf
));
726 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
727 strbuf_addstr(&hi
->ip_address
, addrbuf
);
730 hi
->hostname_lookup_done
= 1;
734 static void hostinfo_clear(struct hostinfo
*hi
)
736 strbuf_release(&hi
->hostname
);
737 strbuf_release(&hi
->canon_hostname
);
738 strbuf_release(&hi
->ip_address
);
739 strbuf_release(&hi
->tcp_port
);
742 static void set_keep_alive(int sockfd
)
746 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0) {
747 if (errno
!= ENOTSOCK
)
748 logerror("unable to set SO_KEEPALIVE on socket: %s",
753 static int execute(void)
755 char *line
= packet_buffer
;
757 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
758 struct hostinfo hi
= HOSTINFO_INIT
;
759 struct strvec env
= STRVEC_INIT
;
762 loginfo("Connection from %s:%s", addr
, port
);
765 alarm(init_timeout
? init_timeout
: timeout
);
766 pktlen
= packet_read(0, packet_buffer
, sizeof(packet_buffer
), 0);
770 if (len
&& line
[len
-1] == '\n')
773 /* parse additional args hidden behind a NUL byte */
775 parse_extra_args(&hi
, &env
, line
+ len
+ 1, pktlen
- len
- 1);
777 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
778 struct daemon_service
*s
= &(daemon_service
[i
]);
781 if (skip_prefix(line
, "git-", &arg
) &&
782 skip_prefix(arg
, s
->name
, &arg
) &&
785 * Note: The directory here is probably context sensitive,
786 * and might depend on the actual service being performed.
788 int rc
= run_service(arg
, s
, &hi
, &env
);
797 logerror("Protocol error: '%s'", line
);
801 static int addrcmp(const struct sockaddr_storage
*s1
,
802 const struct sockaddr_storage
*s2
)
804 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
805 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
807 if (sa1
->sa_family
!= sa2
->sa_family
)
808 return sa1
->sa_family
- sa2
->sa_family
;
809 if (sa1
->sa_family
== AF_INET
)
810 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
811 &((struct sockaddr_in
*)s2
)->sin_addr
,
812 sizeof(struct in_addr
));
814 if (sa1
->sa_family
== AF_INET6
)
815 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
816 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
817 sizeof(struct in6_addr
));
822 static int max_connections
= 32;
824 static unsigned int live_children
;
826 static struct child
{
828 struct child_process cld
;
829 struct sockaddr_storage address
;
832 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
834 struct child
*newborn
, **cradle
;
836 CALLOC_ARRAY(newborn
, 1);
838 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
839 memcpy(&newborn
->address
, addr
, addrlen
);
840 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
841 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
843 newborn
->next
= *cradle
;
848 * This gets called if the number of connections grows
849 * past "max_connections".
851 * We kill the newest connection from a duplicate IP.
853 static void kill_some_child(void)
855 const struct child
*blanket
, *next
;
857 if (!(blanket
= firstborn
))
860 for (; (next
= blanket
->next
); blanket
= next
)
861 if (!addrcmp(&blanket
->address
, &next
->address
)) {
862 kill(blanket
->cld
.pid
, SIGTERM
);
867 static void check_dead_children(void)
872 struct child
**cradle
, *blanket
;
873 for (cradle
= &firstborn
; (blanket
= *cradle
);)
874 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
875 const char *dead
= "";
877 dead
= " (with error)";
878 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
880 /* remove the child */
881 *cradle
= blanket
->next
;
883 child_process_clear(&blanket
->cld
);
886 cradle
= &blanket
->next
;
889 static struct strvec cld_argv
= STRVEC_INIT
;
890 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
892 struct child_process cld
= CHILD_PROCESS_INIT
;
894 if (max_connections
&& live_children
>= max_connections
) {
896 sleep(1); /* give it some time to die */
897 check_dead_children();
898 if (live_children
>= max_connections
) {
900 logerror("Too many children, dropping connection");
905 if (addr
->sa_family
== AF_INET
) {
907 struct sockaddr_in
*sin_addr
= (void *) addr
;
908 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
909 strvec_pushf(&cld
.env
, "REMOTE_ADDR=%s", buf
);
910 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
911 ntohs(sin_addr
->sin_port
));
913 } else if (addr
->sa_family
== AF_INET6
) {
915 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
916 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
917 strvec_pushf(&cld
.env
, "REMOTE_ADDR=[%s]", buf
);
918 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
919 ntohs(sin6_addr
->sin6_port
));
923 strvec_pushv(&cld
.args
, cld_argv
.v
);
925 cld
.out
= dup(incoming
);
927 if (start_command(&cld
))
928 logerror("unable to fork");
930 add_child(&cld
, addr
, addrlen
);
933 static void child_handler(int signo UNUSED
)
936 * Otherwise empty handler because systemcalls will get interrupted
937 * upon signal receipt
938 * SysV needs the handler to be rearmed
940 signal(SIGCHLD
, child_handler
);
943 static int set_reuse_addr(int sockfd
)
949 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
959 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
962 static char ip
[INET_ADDRSTRLEN
];
964 static char ip
[INET6_ADDRSTRLEN
];
970 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
974 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
977 xsnprintf(ip
, sizeof(ip
), "<unknown>");
984 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
987 char pbuf
[NI_MAXSERV
];
988 struct addrinfo hints
, *ai0
, *ai
;
992 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
993 memset(&hints
, 0, sizeof(hints
));
994 hints
.ai_family
= AF_UNSPEC
;
995 hints
.ai_socktype
= SOCK_STREAM
;
996 hints
.ai_protocol
= IPPROTO_TCP
;
997 hints
.ai_flags
= AI_PASSIVE
;
999 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
1001 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
1005 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
1008 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
1011 if (sockfd
>= FD_SETSIZE
) {
1012 logerror("Socket descriptor too large");
1018 if (ai
->ai_family
== AF_INET6
) {
1020 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
1022 /* Note: error is not fatal */
1026 if (set_reuse_addr(sockfd
)) {
1027 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1032 set_keep_alive(sockfd
);
1034 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1035 logerror("Could not bind to %s: %s",
1036 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1039 continue; /* not fatal */
1041 if (listen(sockfd
, 5) < 0) {
1042 logerror("Could not listen to %s: %s",
1043 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1046 continue; /* not fatal */
1049 flags
= fcntl(sockfd
, F_GETFD
, 0);
1051 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1053 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1054 socklist
->list
[socklist
->nr
++] = sockfd
;
1065 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1067 struct sockaddr_in sin
;
1071 memset(&sin
, 0, sizeof sin
);
1072 sin
.sin_family
= AF_INET
;
1073 sin
.sin_port
= htons(listen_port
);
1076 /* Well, host better be an IP address here. */
1077 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1080 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1083 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1087 if (set_reuse_addr(sockfd
)) {
1088 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1093 set_keep_alive(sockfd
);
1095 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1096 logerror("Could not bind to %s: %s",
1097 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1103 if (listen(sockfd
, 5) < 0) {
1104 logerror("Could not listen to %s: %s",
1105 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1111 flags
= fcntl(sockfd
, F_GETFD
, 0);
1113 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1115 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1116 socklist
->list
[socklist
->nr
++] = sockfd
;
1122 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1124 if (!listen_addr
->nr
)
1125 setup_named_sock(NULL
, listen_port
, socklist
);
1128 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1129 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1130 listen_port
, socklist
);
1133 logerror("unable to allocate any listen sockets for host %s on port %u",
1134 listen_addr
->items
[i
].string
, listen_port
);
1139 static int service_loop(struct socketlist
*socklist
)
1144 CALLOC_ARRAY(pfd
, socklist
->nr
);
1146 for (i
= 0; i
< socklist
->nr
; i
++) {
1147 pfd
[i
].fd
= socklist
->list
[i
];
1148 pfd
[i
].events
= POLLIN
;
1151 signal(SIGCHLD
, child_handler
);
1156 check_dead_children();
1158 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1159 if (errno
!= EINTR
) {
1160 logerror("Poll failed, resuming: %s",
1167 for (i
= 0; i
< socklist
->nr
; i
++) {
1168 if (pfd
[i
].revents
& POLLIN
) {
1171 struct sockaddr_in sai
;
1173 struct sockaddr_in6 sai6
;
1176 socklen_t sslen
= sizeof(ss
);
1177 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1185 die_errno("accept returned");
1188 handle(incoming
, &ss
.sa
, sslen
);
1194 #ifdef NO_POSIX_GOODIES
1198 static void drop_privileges(struct credentials
*cred
)
1203 static struct credentials
*prepare_credentials(const char *user_name
,
1204 const char *group_name
)
1206 die("--user not supported on this platform");
1211 struct credentials
{
1212 struct passwd
*pass
;
1216 static void drop_privileges(struct credentials
*cred
)
1218 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1219 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1220 die("cannot drop privileges");
1223 static struct credentials
*prepare_credentials(const char *user_name
,
1224 const char *group_name
)
1226 static struct credentials c
;
1228 c
.pass
= getpwnam(user_name
);
1230 die("user not found - %s", user_name
);
1233 c
.gid
= c
.pass
->pw_gid
;
1235 struct group
*group
= getgrnam(group_name
);
1237 die("group not found - %s", group_name
);
1239 c
.gid
= group
->gr_gid
;
1246 static int serve(struct string_list
*listen_addr
, int listen_port
,
1247 struct credentials
*cred
)
1249 struct socketlist socklist
= { NULL
, 0, 0 };
1251 socksetup(listen_addr
, listen_port
, &socklist
);
1252 if (socklist
.nr
== 0)
1253 die("unable to allocate any listen sockets on port %u",
1256 drop_privileges(cred
);
1258 loginfo("Ready to rumble");
1260 return service_loop(&socklist
);
1263 int cmd_main(int argc
, const char **argv
)
1265 int listen_port
= 0;
1266 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1267 int serve_mode
= 0, inetd_mode
= 0;
1268 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1270 struct credentials
*cred
= NULL
;
1273 for (i
= 1; i
< argc
; i
++) {
1274 const char *arg
= argv
[i
];
1277 if (skip_prefix(arg
, "--listen=", &v
)) {
1278 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1281 if (skip_prefix(arg
, "--port=", &v
)) {
1284 n
= strtoul(v
, &end
, 0);
1290 if (!strcmp(arg
, "--serve")) {
1294 if (!strcmp(arg
, "--inetd")) {
1298 if (!strcmp(arg
, "--verbose")) {
1302 if (!strcmp(arg
, "--syslog")) {
1303 log_destination
= LOG_DESTINATION_SYSLOG
;
1306 if (skip_prefix(arg
, "--log-destination=", &v
)) {
1307 if (!strcmp(v
, "syslog")) {
1308 log_destination
= LOG_DESTINATION_SYSLOG
;
1310 } else if (!strcmp(v
, "stderr")) {
1311 log_destination
= LOG_DESTINATION_STDERR
;
1313 } else if (!strcmp(v
, "none")) {
1314 log_destination
= LOG_DESTINATION_NONE
;
1317 die("unknown log destination '%s'", v
);
1319 if (!strcmp(arg
, "--export-all")) {
1320 export_all_trees
= 1;
1323 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1327 if (skip_prefix(arg
, "--timeout=", &v
)) {
1331 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1332 init_timeout
= atoi(v
);
1335 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1336 max_connections
= atoi(v
);
1337 if (max_connections
< 0)
1338 max_connections
= 0; /* unlimited */
1341 if (!strcmp(arg
, "--strict-paths")) {
1345 if (skip_prefix(arg
, "--base-path=", &v
)) {
1349 if (!strcmp(arg
, "--base-path-relaxed")) {
1350 base_path_relaxed
= 1;
1353 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1354 interpolated_path
= v
;
1357 if (!strcmp(arg
, "--reuseaddr")) {
1361 if (!strcmp(arg
, "--user-path")) {
1365 if (skip_prefix(arg
, "--user-path=", &v
)) {
1369 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1373 if (!strcmp(arg
, "--detach")) {
1377 if (skip_prefix(arg
, "--user=", &v
)) {
1381 if (skip_prefix(arg
, "--group=", &v
)) {
1385 if (skip_prefix(arg
, "--enable=", &v
)) {
1386 enable_service(v
, 1);
1389 if (skip_prefix(arg
, "--disable=", &v
)) {
1390 enable_service(v
, 0);
1393 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1394 make_service_overridable(v
, 1);
1397 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1398 make_service_overridable(v
, 0);
1401 if (!strcmp(arg
, "--informative-errors")) {
1402 informative_errors
= 1;
1405 if (!strcmp(arg
, "--no-informative-errors")) {
1406 informative_errors
= 0;
1409 if (!strcmp(arg
, "--")) {
1410 ok_paths
= &argv
[i
+1];
1412 } else if (arg
[0] != '-') {
1413 ok_paths
= &argv
[i
];
1417 usage(daemon_usage
);
1420 if (log_destination
== LOG_DESTINATION_UNSET
) {
1421 if (inetd_mode
|| detach
)
1422 log_destination
= LOG_DESTINATION_SYSLOG
;
1424 log_destination
= LOG_DESTINATION_STDERR
;
1427 if (log_destination
== LOG_DESTINATION_SYSLOG
) {
1428 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1429 set_die_routine(daemon_die
);
1431 /* avoid splitting a message in the middle */
1432 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1434 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1435 die("--detach, --user and --group are incompatible with --inetd");
1437 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1438 die("--listen= and --port= are incompatible with --inetd");
1439 else if (listen_port
== 0)
1440 listen_port
= DEFAULT_GIT_PORT
;
1442 if (group_name
&& !user_name
)
1443 die("--group supplied without --user");
1446 cred
= prepare_credentials(user_name
, group_name
);
1448 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1449 die("option --strict-paths requires '<directory>' arguments");
1451 if (base_path
&& !is_directory(base_path
))
1452 die("base-path '%s' does not exist or is not a directory",
1455 if (log_destination
!= LOG_DESTINATION_STDERR
) {
1456 if (!freopen("/dev/null", "w", stderr
))
1457 die_errno("failed to redirect stderr to /dev/null");
1460 if (inetd_mode
|| serve_mode
)
1465 die("--detach not supported on this platform");
1469 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1471 /* prepare argv for serving-processes */
1472 strvec_push(&cld_argv
, argv
[0]); /* git-daemon */
1473 strvec_push(&cld_argv
, "--serve");
1474 for (i
= 1; i
< argc
; ++i
)
1475 strvec_push(&cld_argv
, argv
[i
]);
1477 return serve(&listen_addr
, listen_port
, cred
);