5 #include "run-command.h"
7 #include "string-list.h"
10 #define initgroups(x, y) (0) /* nothing */
13 static enum log_destination
{
14 LOG_DESTINATION_UNSET
= -1,
15 LOG_DESTINATION_NONE
= 0,
16 LOG_DESTINATION_STDERR
= 1,
17 LOG_DESTINATION_SYSLOG
= 2,
18 } log_destination
= LOG_DESTINATION_UNSET
;
21 static int informative_errors
;
23 static const char daemon_usage
[] =
24 "git daemon [--verbose] [--syslog] [--export-all]\n"
25 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
26 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
27 " [--user-path | --user-path=<path>]\n"
28 " [--interpolated-path=<path>]\n"
29 " [--reuseaddr] [--pid-file=<file>]\n"
30 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
31 " [--access-hook=<path>]\n"
32 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
33 " [--detach] [--user=<user> [--group=<group>]]\n"
34 " [--log-destination=(stderr|syslog|none)]\n"
37 /* List of acceptable pathname prefixes */
38 static const char **ok_paths
;
39 static int strict_paths
;
41 /* If this is set, git-daemon-export-ok is not required */
42 static int export_all_trees
;
44 /* Take all paths relative to this one if non-NULL */
45 static const char *base_path
;
46 static const char *interpolated_path
;
47 static int base_path_relaxed
;
49 /* If defined, ~user notation is allowed and the string is inserted
50 * after ~user/. E.g. a request to git://host/~alice/frotz would
51 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
53 static const char *user_path
;
55 /* Timeout, and initial timeout */
56 static unsigned int timeout
;
57 static unsigned int init_timeout
;
60 struct strbuf hostname
;
61 struct strbuf canon_hostname
;
62 struct strbuf ip_address
;
63 struct strbuf tcp_port
;
64 unsigned int hostname_lookup_done
:1;
65 unsigned int saw_extended_args
:1;
67 #define HOSTINFO_INIT { \
68 .hostname = STRBUF_INIT, \
69 .canon_hostname = STRBUF_INIT, \
70 .ip_address = STRBUF_INIT, \
71 .tcp_port = STRBUF_INIT, \
74 static void lookup_hostname(struct hostinfo
*hi
);
76 static const char *get_canon_hostname(struct hostinfo
*hi
)
79 return hi
->canon_hostname
.buf
;
82 static const char *get_ip_address(struct hostinfo
*hi
)
85 return hi
->ip_address
.buf
;
88 static void logreport(int priority
, const char *err
, va_list params
)
90 switch (log_destination
) {
91 case LOG_DESTINATION_SYSLOG
: {
93 vsnprintf(buf
, sizeof(buf
), err
, params
);
94 syslog(priority
, "%s", buf
);
97 case LOG_DESTINATION_STDERR
:
99 * Since stderr is set to buffered mode, the
100 * logging of different processes will not overlap
101 * unless they overflow the (rather big) buffers.
103 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
104 vfprintf(stderr
, err
, params
);
108 case LOG_DESTINATION_NONE
:
110 case LOG_DESTINATION_UNSET
:
111 BUG("log destination not initialized correctly");
115 __attribute__((format (printf
, 1, 2)))
116 static void logerror(const char *err
, ...)
119 va_start(params
, err
);
120 logreport(LOG_ERR
, err
, params
);
124 __attribute__((format (printf
, 1, 2)))
125 static void loginfo(const char *err
, ...)
130 va_start(params
, err
);
131 logreport(LOG_INFO
, err
, params
);
135 static void NORETURN
daemon_die(const char *err
, va_list params
)
137 logreport(LOG_ERR
, err
, params
);
141 struct expand_path_context
{
142 const char *directory
;
143 struct hostinfo
*hostinfo
;
146 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
148 struct expand_path_context
*context
= ctx
;
149 struct hostinfo
*hi
= context
->hostinfo
;
151 switch (placeholder
[0]) {
153 strbuf_addbuf(sb
, &hi
->hostname
);
156 if (placeholder
[1] == 'H') {
157 strbuf_addstr(sb
, get_canon_hostname(hi
));
162 if (placeholder
[1] == 'P') {
163 strbuf_addstr(sb
, get_ip_address(hi
));
168 strbuf_addbuf(sb
, &hi
->tcp_port
);
171 strbuf_addstr(sb
, context
->directory
);
177 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
179 static char rpath
[PATH_MAX
];
180 static char interp_path
[PATH_MAX
];
187 if (daemon_avoid_alias(dir
)) {
188 logerror("'%s': aliased", dir
);
194 logerror("'%s': User-path not allowed", dir
);
198 /* Got either "~alice" or "~alice/foo";
199 * rewrite them to "~alice/%s" or
202 int namlen
, restlen
= strlen(dir
);
203 const char *slash
= strchr(dir
, '/');
205 slash
= dir
+ restlen
;
206 namlen
= slash
- dir
;
208 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
209 rlen
= snprintf(rpath
, sizeof(rpath
), "%.*s/%s%.*s",
210 namlen
, dir
, user_path
, restlen
, slash
);
211 if (rlen
>= sizeof(rpath
)) {
212 logerror("user-path too large: %s", rpath
);
218 else if (interpolated_path
&& hi
->saw_extended_args
) {
219 struct strbuf expanded_path
= STRBUF_INIT
;
220 struct expand_path_context context
;
222 context
.directory
= directory
;
223 context
.hostinfo
= hi
;
226 /* Allow only absolute */
227 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
231 strbuf_expand(&expanded_path
, interpolated_path
,
232 expand_path
, &context
);
234 rlen
= strlcpy(interp_path
, expanded_path
.buf
,
235 sizeof(interp_path
));
236 strbuf_release(&expanded_path
);
237 if (rlen
>= sizeof(interp_path
)) {
238 logerror("interpolated path too large: %s",
243 loginfo("Interpolated dir '%s'", interp_path
);
247 else if (base_path
) {
249 /* Allow only absolute */
250 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
253 rlen
= snprintf(rpath
, sizeof(rpath
), "%s%s", base_path
, dir
);
254 if (rlen
>= sizeof(rpath
)) {
255 logerror("base-path too large: %s", rpath
);
261 path
= enter_repo(dir
, strict_paths
);
262 if (!path
&& base_path
&& base_path_relaxed
) {
264 * if we fail and base_path_relaxed is enabled, try without
265 * prefixing the base path
268 path
= enter_repo(dir
, strict_paths
);
272 logerror("'%s' does not appear to be a git repository", dir
);
276 if ( ok_paths
&& *ok_paths
) {
278 int pathlen
= strlen(path
);
280 /* The validation is done on the paths after enter_repo
281 * appends optional {.git,.git/.git} and friends, but
282 * it does not use getcwd(). So if your /pub is
283 * a symlink to /mnt/pub, you can include /pub and
284 * do not have to say /mnt/pub.
287 for ( pp
= ok_paths
; *pp
; pp
++ ) {
288 int len
= strlen(*pp
);
289 if (len
<= pathlen
&&
290 !memcmp(*pp
, path
, len
) &&
291 (path
[len
] == '\0' ||
292 (!strict_paths
&& path
[len
] == '/')))
297 /* be backwards compatible */
302 logerror("'%s': not in directory list", path
);
303 return NULL
; /* Fallthrough. Deny by default */
306 typedef int (*daemon_service_fn
)(const struct strvec
*env
);
307 struct daemon_service
{
309 const char *config_name
;
310 daemon_service_fn fn
;
315 static int daemon_error(const char *dir
, const char *msg
)
317 if (!informative_errors
)
318 msg
= "access denied or repository not exported";
319 packet_write_fmt(1, "ERR %s: %s", msg
, dir
);
323 static const char *access_hook
;
325 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
326 const char *path
, struct hostinfo
*hi
)
328 struct child_process child
= CHILD_PROCESS_INIT
;
329 struct strbuf buf
= STRBUF_INIT
;
333 strvec_push(&child
.args
, access_hook
);
334 strvec_push(&child
.args
, service
->name
);
335 strvec_push(&child
.args
, path
);
336 strvec_push(&child
.args
, hi
->hostname
.buf
);
337 strvec_push(&child
.args
, get_canon_hostname(hi
));
338 strvec_push(&child
.args
, get_ip_address(hi
));
339 strvec_push(&child
.args
, hi
->tcp_port
.buf
);
345 if (start_command(&child
)) {
346 logerror("daemon access hook '%s' failed to start",
350 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
351 logerror("failed to read from pipe to daemon access hook '%s'",
356 if (close(child
.out
) < 0) {
357 logerror("failed to close pipe to daemon access hook '%s'",
361 if (finish_command(&child
))
365 strbuf_release(&buf
);
372 strbuf_addstr(&buf
, "service rejected");
373 eol
= strchr(buf
.buf
, '\n');
377 daemon_error(dir
, buf
.buf
);
378 strbuf_release(&buf
);
382 static int run_service(const char *dir
, struct daemon_service
*service
,
383 struct hostinfo
*hi
, const struct strvec
*env
)
386 int enabled
= service
->enabled
;
387 struct strbuf var
= STRBUF_INIT
;
389 loginfo("Request %s for '%s'", service
->name
, dir
);
391 if (!enabled
&& !service
->overridable
) {
392 logerror("'%s': service not enabled.", service
->name
);
394 return daemon_error(dir
, "service not enabled");
397 if (!(path
= path_ok(dir
, hi
)))
398 return daemon_error(dir
, "no such repository");
401 * Security on the cheap.
403 * We want a readable HEAD, usable "objects" directory, and
404 * a "git-daemon-export-ok" flag that says that the other side
405 * is ok with us doing this.
407 * path_ok() uses enter_repo() and checks for included directories.
408 * We only need to make sure the repository is exported.
411 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
412 logerror("'%s': repository not exported.", path
);
414 return daemon_error(dir
, "repository not exported");
417 if (service
->overridable
) {
418 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
419 git_config_get_bool(var
.buf
, &enabled
);
420 strbuf_release(&var
);
423 logerror("'%s': service not enabled for '%s'",
424 service
->name
, path
);
426 return daemon_error(dir
, "service not enabled");
430 * Optionally, a hook can choose to deny access to the
431 * repository depending on the phase of the moon.
433 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
437 * We'll ignore SIGTERM from now on, we have a
440 signal(SIGTERM
, SIG_IGN
);
442 return service
->fn(env
);
445 static void copy_to_log(int fd
)
447 struct strbuf line
= STRBUF_INIT
;
450 fp
= fdopen(fd
, "r");
452 logerror("fdopen of error channel failed");
457 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
458 logerror("%s", line
.buf
);
459 strbuf_setlen(&line
, 0);
462 strbuf_release(&line
);
466 static int run_service_command(struct child_process
*cld
)
468 strvec_push(&cld
->args
, ".");
471 if (start_command(cld
))
477 copy_to_log(cld
->err
);
479 return finish_command(cld
);
482 static int upload_pack(const struct strvec
*env
)
484 struct child_process cld
= CHILD_PROCESS_INIT
;
485 strvec_pushl(&cld
.args
, "upload-pack", "--strict", NULL
);
486 strvec_pushf(&cld
.args
, "--timeout=%u", timeout
);
488 strvec_pushv(&cld
.env
, env
->v
);
490 return run_service_command(&cld
);
493 static int upload_archive(const struct strvec
*env
)
495 struct child_process cld
= CHILD_PROCESS_INIT
;
496 strvec_push(&cld
.args
, "upload-archive");
498 strvec_pushv(&cld
.env
, env
->v
);
500 return run_service_command(&cld
);
503 static int receive_pack(const struct strvec
*env
)
505 struct child_process cld
= CHILD_PROCESS_INIT
;
506 strvec_push(&cld
.args
, "receive-pack");
508 strvec_pushv(&cld
.env
, env
->v
);
510 return run_service_command(&cld
);
513 static struct daemon_service daemon_service
[] = {
514 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
515 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
516 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
519 static void enable_service(const char *name
, int ena
)
522 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
523 if (!strcmp(daemon_service
[i
].name
, name
)) {
524 daemon_service
[i
].enabled
= ena
;
528 die("No such service %s", name
);
531 static void make_service_overridable(const char *name
, int ena
)
534 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
535 if (!strcmp(daemon_service
[i
].name
, name
)) {
536 daemon_service
[i
].overridable
= ena
;
540 die("No such service %s", name
);
543 static void parse_host_and_port(char *hostport
, char **host
,
546 if (*hostport
== '[') {
549 end
= strchr(hostport
, ']');
551 die("Invalid request ('[' without ']')");
553 *host
= hostport
+ 1;
556 else if (end
[1] == ':')
559 die("Garbage after end of host part");
562 *port
= strrchr(hostport
, ':');
571 * Sanitize a string from the client so that it's OK to be inserted into a
572 * filesystem path. Specifically, we disallow directory separators, runs
573 * of "..", and trailing and leading dots, which means that the client
574 * cannot escape our base path via ".." traversal.
576 static void sanitize_client(struct strbuf
*out
, const char *in
)
581 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
583 strbuf_addch(out
, *in
);
586 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
587 strbuf_setlen(out
, out
->len
- 1);
591 * Like sanitize_client, but we also perform any canonicalization
592 * to make life easier on the admin.
594 static void canonicalize_client(struct strbuf
*out
, const char *in
)
596 sanitize_client(out
, in
);
601 * Read the host as supplied by the client connection.
603 * Returns a pointer to the character after the NUL byte terminating the host
604 * argument, or 'extra_args' if there is no host argument.
606 static char *parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
610 char *end
= extra_args
+ buflen
;
612 if (extra_args
< end
&& *extra_args
) {
613 hi
->saw_extended_args
= 1;
614 if (strncasecmp("host=", extra_args
, 5) == 0) {
615 val
= extra_args
+ 5;
616 vallen
= strlen(val
) + 1;
617 loginfo("Extended attribute \"host\": %s", val
);
619 /* Split <host>:<port> at colon. */
622 parse_host_and_port(val
, &host
, &port
);
624 sanitize_client(&hi
->tcp_port
, port
);
625 canonicalize_client(&hi
->hostname
, host
);
626 hi
->hostname_lookup_done
= 0;
629 /* On to the next one */
630 extra_args
= val
+ vallen
;
632 if (extra_args
< end
&& *extra_args
)
633 die("Invalid request");
639 static void parse_extra_args(struct hostinfo
*hi
, struct strvec
*env
,
640 char *extra_args
, int buflen
)
642 const char *end
= extra_args
+ buflen
;
643 struct strbuf git_protocol
= STRBUF_INIT
;
645 /* First look for the host argument */
646 extra_args
= parse_host_arg(hi
, extra_args
, buflen
);
648 /* Look for additional arguments places after a second NUL byte */
649 for (; extra_args
< end
; extra_args
+= strlen(extra_args
) + 1) {
650 const char *arg
= extra_args
;
653 * Parse the extra arguments, adding most to 'git_protocol'
654 * which will be used to set the 'GIT_PROTOCOL' envvar in the
655 * service that will be run.
657 * If there ends up being a particular arg in the future that
658 * git-daemon needs to parse specifically (like the 'host' arg)
659 * then it can be parsed here and not added to 'git_protocol'.
662 if (git_protocol
.len
> 0)
663 strbuf_addch(&git_protocol
, ':');
664 strbuf_addstr(&git_protocol
, arg
);
668 if (git_protocol
.len
> 0) {
669 loginfo("Extended attribute \"protocol\": %s", git_protocol
.buf
);
670 strvec_pushf(env
, GIT_PROTOCOL_ENVIRONMENT
"=%s",
673 strbuf_release(&git_protocol
);
677 * Locate canonical hostname and its IP address.
679 static void lookup_hostname(struct hostinfo
*hi
)
681 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
683 struct addrinfo hints
;
686 static char addrbuf
[HOST_NAME_MAX
+ 1];
688 memset(&hints
, 0, sizeof(hints
));
689 hints
.ai_flags
= AI_CANONNAME
;
691 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
693 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
695 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
696 addrbuf
, sizeof(addrbuf
));
697 strbuf_addstr(&hi
->ip_address
, addrbuf
);
699 if (ai
->ai_canonname
)
700 sanitize_client(&hi
->canon_hostname
,
703 strbuf_addbuf(&hi
->canon_hostname
,
709 struct hostent
*hent
;
710 struct sockaddr_in sa
;
712 static char addrbuf
[HOST_NAME_MAX
+ 1];
714 hent
= gethostbyname(hi
->hostname
.buf
);
716 ap
= hent
->h_addr_list
;
717 memset(&sa
, 0, sizeof sa
);
718 sa
.sin_family
= hent
->h_addrtype
;
719 sa
.sin_port
= htons(0);
720 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
722 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
723 addrbuf
, sizeof(addrbuf
));
725 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
726 strbuf_addstr(&hi
->ip_address
, addrbuf
);
729 hi
->hostname_lookup_done
= 1;
733 static void hostinfo_clear(struct hostinfo
*hi
)
735 strbuf_release(&hi
->hostname
);
736 strbuf_release(&hi
->canon_hostname
);
737 strbuf_release(&hi
->ip_address
);
738 strbuf_release(&hi
->tcp_port
);
741 static void set_keep_alive(int sockfd
)
745 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0) {
746 if (errno
!= ENOTSOCK
)
747 logerror("unable to set SO_KEEPALIVE on socket: %s",
752 static int execute(void)
754 char *line
= packet_buffer
;
756 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
757 struct hostinfo hi
= HOSTINFO_INIT
;
758 struct strvec env
= STRVEC_INIT
;
761 loginfo("Connection from %s:%s", addr
, port
);
764 alarm(init_timeout
? init_timeout
: timeout
);
765 pktlen
= packet_read(0, packet_buffer
, sizeof(packet_buffer
), 0);
769 if (len
&& line
[len
-1] == '\n')
772 /* parse additional args hidden behind a NUL byte */
774 parse_extra_args(&hi
, &env
, line
+ len
+ 1, pktlen
- len
- 1);
776 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
777 struct daemon_service
*s
= &(daemon_service
[i
]);
780 if (skip_prefix(line
, "git-", &arg
) &&
781 skip_prefix(arg
, s
->name
, &arg
) &&
784 * Note: The directory here is probably context sensitive,
785 * and might depend on the actual service being performed.
787 int rc
= run_service(arg
, s
, &hi
, &env
);
796 logerror("Protocol error: '%s'", line
);
800 static int addrcmp(const struct sockaddr_storage
*s1
,
801 const struct sockaddr_storage
*s2
)
803 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
804 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
806 if (sa1
->sa_family
!= sa2
->sa_family
)
807 return sa1
->sa_family
- sa2
->sa_family
;
808 if (sa1
->sa_family
== AF_INET
)
809 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
810 &((struct sockaddr_in
*)s2
)->sin_addr
,
811 sizeof(struct in_addr
));
813 if (sa1
->sa_family
== AF_INET6
)
814 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
815 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
816 sizeof(struct in6_addr
));
821 static int max_connections
= 32;
823 static unsigned int live_children
;
825 static struct child
{
827 struct child_process cld
;
828 struct sockaddr_storage address
;
831 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
833 struct child
*newborn
, **cradle
;
835 CALLOC_ARRAY(newborn
, 1);
837 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
838 memcpy(&newborn
->address
, addr
, addrlen
);
839 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
840 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
842 newborn
->next
= *cradle
;
847 * This gets called if the number of connections grows
848 * past "max_connections".
850 * We kill the newest connection from a duplicate IP.
852 static void kill_some_child(void)
854 const struct child
*blanket
, *next
;
856 if (!(blanket
= firstborn
))
859 for (; (next
= blanket
->next
); blanket
= next
)
860 if (!addrcmp(&blanket
->address
, &next
->address
)) {
861 kill(blanket
->cld
.pid
, SIGTERM
);
866 static void check_dead_children(void)
871 struct child
**cradle
, *blanket
;
872 for (cradle
= &firstborn
; (blanket
= *cradle
);)
873 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
874 const char *dead
= "";
876 dead
= " (with error)";
877 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
879 /* remove the child */
880 *cradle
= blanket
->next
;
882 child_process_clear(&blanket
->cld
);
885 cradle
= &blanket
->next
;
888 static struct strvec cld_argv
= STRVEC_INIT
;
889 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
891 struct child_process cld
= CHILD_PROCESS_INIT
;
893 if (max_connections
&& live_children
>= max_connections
) {
895 sleep(1); /* give it some time to die */
896 check_dead_children();
897 if (live_children
>= max_connections
) {
899 logerror("Too many children, dropping connection");
904 if (addr
->sa_family
== AF_INET
) {
906 struct sockaddr_in
*sin_addr
= (void *) addr
;
907 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
908 strvec_pushf(&cld
.env
, "REMOTE_ADDR=%s", buf
);
909 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
910 ntohs(sin_addr
->sin_port
));
912 } else if (addr
->sa_family
== AF_INET6
) {
914 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
915 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
916 strvec_pushf(&cld
.env
, "REMOTE_ADDR=[%s]", buf
);
917 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
918 ntohs(sin6_addr
->sin6_port
));
922 strvec_pushv(&cld
.args
, cld_argv
.v
);
924 cld
.out
= dup(incoming
);
926 if (start_command(&cld
))
927 logerror("unable to fork");
929 add_child(&cld
, addr
, addrlen
);
932 static void child_handler(int signo UNUSED
)
935 * Otherwise empty handler because systemcalls will get interrupted
936 * upon signal receipt
937 * SysV needs the handler to be rearmed
939 signal(SIGCHLD
, child_handler
);
942 static int set_reuse_addr(int sockfd
)
948 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
958 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
961 static char ip
[INET_ADDRSTRLEN
];
963 static char ip
[INET6_ADDRSTRLEN
];
969 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
973 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
976 xsnprintf(ip
, sizeof(ip
), "<unknown>");
983 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
986 char pbuf
[NI_MAXSERV
];
987 struct addrinfo hints
, *ai0
, *ai
;
991 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
992 memset(&hints
, 0, sizeof(hints
));
993 hints
.ai_family
= AF_UNSPEC
;
994 hints
.ai_socktype
= SOCK_STREAM
;
995 hints
.ai_protocol
= IPPROTO_TCP
;
996 hints
.ai_flags
= AI_PASSIVE
;
998 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
1000 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
1004 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
1007 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
1010 if (sockfd
>= FD_SETSIZE
) {
1011 logerror("Socket descriptor too large");
1017 if (ai
->ai_family
== AF_INET6
) {
1019 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
1021 /* Note: error is not fatal */
1025 if (set_reuse_addr(sockfd
)) {
1026 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1031 set_keep_alive(sockfd
);
1033 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1034 logerror("Could not bind to %s: %s",
1035 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1038 continue; /* not fatal */
1040 if (listen(sockfd
, 5) < 0) {
1041 logerror("Could not listen to %s: %s",
1042 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1045 continue; /* not fatal */
1048 flags
= fcntl(sockfd
, F_GETFD
, 0);
1050 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1052 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1053 socklist
->list
[socklist
->nr
++] = sockfd
;
1064 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1066 struct sockaddr_in sin
;
1070 memset(&sin
, 0, sizeof sin
);
1071 sin
.sin_family
= AF_INET
;
1072 sin
.sin_port
= htons(listen_port
);
1075 /* Well, host better be an IP address here. */
1076 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1079 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1082 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1086 if (set_reuse_addr(sockfd
)) {
1087 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1092 set_keep_alive(sockfd
);
1094 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1095 logerror("Could not bind to %s: %s",
1096 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1102 if (listen(sockfd
, 5) < 0) {
1103 logerror("Could not listen to %s: %s",
1104 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1110 flags
= fcntl(sockfd
, F_GETFD
, 0);
1112 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1114 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1115 socklist
->list
[socklist
->nr
++] = sockfd
;
1121 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1123 if (!listen_addr
->nr
)
1124 setup_named_sock(NULL
, listen_port
, socklist
);
1127 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1128 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1129 listen_port
, socklist
);
1132 logerror("unable to allocate any listen sockets for host %s on port %u",
1133 listen_addr
->items
[i
].string
, listen_port
);
1138 static int service_loop(struct socketlist
*socklist
)
1143 CALLOC_ARRAY(pfd
, socklist
->nr
);
1145 for (i
= 0; i
< socklist
->nr
; i
++) {
1146 pfd
[i
].fd
= socklist
->list
[i
];
1147 pfd
[i
].events
= POLLIN
;
1150 signal(SIGCHLD
, child_handler
);
1155 check_dead_children();
1157 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1158 if (errno
!= EINTR
) {
1159 logerror("Poll failed, resuming: %s",
1166 for (i
= 0; i
< socklist
->nr
; i
++) {
1167 if (pfd
[i
].revents
& POLLIN
) {
1170 struct sockaddr_in sai
;
1172 struct sockaddr_in6 sai6
;
1175 socklen_t sslen
= sizeof(ss
);
1176 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1184 die_errno("accept returned");
1187 handle(incoming
, &ss
.sa
, sslen
);
1193 #ifdef NO_POSIX_GOODIES
1197 static void drop_privileges(struct credentials
*cred
)
1202 static struct credentials
*prepare_credentials(const char *user_name
,
1203 const char *group_name
)
1205 die("--user not supported on this platform");
1210 struct credentials
{
1211 struct passwd
*pass
;
1215 static void drop_privileges(struct credentials
*cred
)
1217 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1218 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1219 die("cannot drop privileges");
1222 static struct credentials
*prepare_credentials(const char *user_name
,
1223 const char *group_name
)
1225 static struct credentials c
;
1227 c
.pass
= getpwnam(user_name
);
1229 die("user not found - %s", user_name
);
1232 c
.gid
= c
.pass
->pw_gid
;
1234 struct group
*group
= getgrnam(group_name
);
1236 die("group not found - %s", group_name
);
1238 c
.gid
= group
->gr_gid
;
1245 static int serve(struct string_list
*listen_addr
, int listen_port
,
1246 struct credentials
*cred
)
1248 struct socketlist socklist
= { NULL
, 0, 0 };
1250 socksetup(listen_addr
, listen_port
, &socklist
);
1251 if (socklist
.nr
== 0)
1252 die("unable to allocate any listen sockets on port %u",
1255 drop_privileges(cred
);
1257 loginfo("Ready to rumble");
1259 return service_loop(&socklist
);
1262 int cmd_main(int argc
, const char **argv
)
1264 int listen_port
= 0;
1265 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1266 int serve_mode
= 0, inetd_mode
= 0;
1267 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1269 struct credentials
*cred
= NULL
;
1272 for (i
= 1; i
< argc
; i
++) {
1273 const char *arg
= argv
[i
];
1276 if (skip_prefix(arg
, "--listen=", &v
)) {
1277 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1280 if (skip_prefix(arg
, "--port=", &v
)) {
1283 n
= strtoul(v
, &end
, 0);
1289 if (!strcmp(arg
, "--serve")) {
1293 if (!strcmp(arg
, "--inetd")) {
1297 if (!strcmp(arg
, "--verbose")) {
1301 if (!strcmp(arg
, "--syslog")) {
1302 log_destination
= LOG_DESTINATION_SYSLOG
;
1305 if (skip_prefix(arg
, "--log-destination=", &v
)) {
1306 if (!strcmp(v
, "syslog")) {
1307 log_destination
= LOG_DESTINATION_SYSLOG
;
1309 } else if (!strcmp(v
, "stderr")) {
1310 log_destination
= LOG_DESTINATION_STDERR
;
1312 } else if (!strcmp(v
, "none")) {
1313 log_destination
= LOG_DESTINATION_NONE
;
1316 die("unknown log destination '%s'", v
);
1318 if (!strcmp(arg
, "--export-all")) {
1319 export_all_trees
= 1;
1322 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1326 if (skip_prefix(arg
, "--timeout=", &v
)) {
1330 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1331 init_timeout
= atoi(v
);
1334 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1335 max_connections
= atoi(v
);
1336 if (max_connections
< 0)
1337 max_connections
= 0; /* unlimited */
1340 if (!strcmp(arg
, "--strict-paths")) {
1344 if (skip_prefix(arg
, "--base-path=", &v
)) {
1348 if (!strcmp(arg
, "--base-path-relaxed")) {
1349 base_path_relaxed
= 1;
1352 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1353 interpolated_path
= v
;
1356 if (!strcmp(arg
, "--reuseaddr")) {
1360 if (!strcmp(arg
, "--user-path")) {
1364 if (skip_prefix(arg
, "--user-path=", &v
)) {
1368 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1372 if (!strcmp(arg
, "--detach")) {
1376 if (skip_prefix(arg
, "--user=", &v
)) {
1380 if (skip_prefix(arg
, "--group=", &v
)) {
1384 if (skip_prefix(arg
, "--enable=", &v
)) {
1385 enable_service(v
, 1);
1388 if (skip_prefix(arg
, "--disable=", &v
)) {
1389 enable_service(v
, 0);
1392 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1393 make_service_overridable(v
, 1);
1396 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1397 make_service_overridable(v
, 0);
1400 if (!strcmp(arg
, "--informative-errors")) {
1401 informative_errors
= 1;
1404 if (!strcmp(arg
, "--no-informative-errors")) {
1405 informative_errors
= 0;
1408 if (!strcmp(arg
, "--")) {
1409 ok_paths
= &argv
[i
+1];
1411 } else if (arg
[0] != '-') {
1412 ok_paths
= &argv
[i
];
1416 usage(daemon_usage
);
1419 if (log_destination
== LOG_DESTINATION_UNSET
) {
1420 if (inetd_mode
|| detach
)
1421 log_destination
= LOG_DESTINATION_SYSLOG
;
1423 log_destination
= LOG_DESTINATION_STDERR
;
1426 if (log_destination
== LOG_DESTINATION_SYSLOG
) {
1427 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1428 set_die_routine(daemon_die
);
1430 /* avoid splitting a message in the middle */
1431 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1433 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1434 die("--detach, --user and --group are incompatible with --inetd");
1436 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1437 die("--listen= and --port= are incompatible with --inetd");
1438 else if (listen_port
== 0)
1439 listen_port
= DEFAULT_GIT_PORT
;
1441 if (group_name
&& !user_name
)
1442 die("--group supplied without --user");
1445 cred
= prepare_credentials(user_name
, group_name
);
1447 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1448 die("option --strict-paths requires '<directory>' arguments");
1450 if (base_path
&& !is_directory(base_path
))
1451 die("base-path '%s' does not exist or is not a directory",
1454 if (log_destination
!= LOG_DESTINATION_STDERR
) {
1455 if (!freopen("/dev/null", "w", stderr
))
1456 die_errno("failed to redirect stderr to /dev/null");
1459 if (inetd_mode
|| serve_mode
)
1464 die("--detach not supported on this platform");
1468 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1470 /* prepare argv for serving-processes */
1471 strvec_push(&cld_argv
, argv
[0]); /* git-daemon */
1472 strvec_push(&cld_argv
, "--serve");
1473 for (i
= 1; i
< argc
; ++i
)
1474 strvec_push(&cld_argv
, argv
[i
]);
1476 return serve(&listen_addr
, listen_port
, cred
);