5 #include "environment.h"
8 #include "run-command.h"
11 #include "string-list.h"
15 #define initgroups(x, y) (0) /* nothing */
18 static enum log_destination
{
19 LOG_DESTINATION_UNSET
= -1,
20 LOG_DESTINATION_NONE
= 0,
21 LOG_DESTINATION_STDERR
= 1,
22 LOG_DESTINATION_SYSLOG
= 2,
23 } log_destination
= LOG_DESTINATION_UNSET
;
26 static int informative_errors
;
28 static const char daemon_usage
[] =
29 "git daemon [--verbose] [--syslog] [--export-all]\n"
30 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
31 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
32 " [--user-path | --user-path=<path>]\n"
33 " [--interpolated-path=<path>]\n"
34 " [--reuseaddr] [--pid-file=<file>]\n"
35 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
36 " [--access-hook=<path>]\n"
37 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
38 " [--detach] [--user=<user> [--group=<group>]]\n"
39 " [--log-destination=(stderr|syslog|none)]\n"
42 /* List of acceptable pathname prefixes */
43 static const char **ok_paths
;
44 static int strict_paths
;
46 /* If this is set, git-daemon-export-ok is not required */
47 static int export_all_trees
;
49 /* Take all paths relative to this one if non-NULL */
50 static const char *base_path
;
51 static const char *interpolated_path
;
52 static int base_path_relaxed
;
54 /* If defined, ~user notation is allowed and the string is inserted
55 * after ~user/. E.g. a request to git://host/~alice/frotz would
56 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
58 static const char *user_path
;
60 /* Timeout, and initial timeout */
61 static unsigned int timeout
;
62 static unsigned int init_timeout
;
65 struct strbuf hostname
;
66 struct strbuf canon_hostname
;
67 struct strbuf ip_address
;
68 struct strbuf tcp_port
;
69 unsigned int hostname_lookup_done
:1;
70 unsigned int saw_extended_args
:1;
72 #define HOSTINFO_INIT { \
73 .hostname = STRBUF_INIT, \
74 .canon_hostname = STRBUF_INIT, \
75 .ip_address = STRBUF_INIT, \
76 .tcp_port = STRBUF_INIT, \
79 static void lookup_hostname(struct hostinfo
*hi
);
81 static const char *get_canon_hostname(struct hostinfo
*hi
)
84 return hi
->canon_hostname
.buf
;
87 static const char *get_ip_address(struct hostinfo
*hi
)
90 return hi
->ip_address
.buf
;
93 static void logreport(int priority
, const char *err
, va_list params
)
95 switch (log_destination
) {
96 case LOG_DESTINATION_SYSLOG
: {
98 vsnprintf(buf
, sizeof(buf
), err
, params
);
99 syslog(priority
, "%s", buf
);
102 case LOG_DESTINATION_STDERR
:
104 * Since stderr is set to buffered mode, the
105 * logging of different processes will not overlap
106 * unless they overflow the (rather big) buffers.
108 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
109 vfprintf(stderr
, err
, params
);
113 case LOG_DESTINATION_NONE
:
115 case LOG_DESTINATION_UNSET
:
116 BUG("log destination not initialized correctly");
120 __attribute__((format (printf
, 1, 2)))
121 static void logerror(const char *err
, ...)
124 va_start(params
, err
);
125 logreport(LOG_ERR
, err
, params
);
129 __attribute__((format (printf
, 1, 2)))
130 static void loginfo(const char *err
, ...)
135 va_start(params
, err
);
136 logreport(LOG_INFO
, err
, params
);
140 static void NORETURN
daemon_die(const char *err
, va_list params
)
142 logreport(LOG_ERR
, err
, params
);
146 struct expand_path_context
{
147 const char *directory
;
148 struct hostinfo
*hostinfo
;
151 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
153 struct expand_path_context
*context
= ctx
;
154 struct hostinfo
*hi
= context
->hostinfo
;
156 switch (placeholder
[0]) {
158 strbuf_addbuf(sb
, &hi
->hostname
);
161 if (placeholder
[1] == 'H') {
162 strbuf_addstr(sb
, get_canon_hostname(hi
));
167 if (placeholder
[1] == 'P') {
168 strbuf_addstr(sb
, get_ip_address(hi
));
173 strbuf_addbuf(sb
, &hi
->tcp_port
);
176 strbuf_addstr(sb
, context
->directory
);
182 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
184 static char rpath
[PATH_MAX
];
185 static char interp_path
[PATH_MAX
];
192 if (daemon_avoid_alias(dir
)) {
193 logerror("'%s': aliased", dir
);
199 logerror("'%s': User-path not allowed", dir
);
203 /* Got either "~alice" or "~alice/foo";
204 * rewrite them to "~alice/%s" or
207 int namlen
, restlen
= strlen(dir
);
208 const char *slash
= strchr(dir
, '/');
210 slash
= dir
+ restlen
;
211 namlen
= slash
- dir
;
213 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
214 rlen
= snprintf(rpath
, sizeof(rpath
), "%.*s/%s%.*s",
215 namlen
, dir
, user_path
, restlen
, slash
);
216 if (rlen
>= sizeof(rpath
)) {
217 logerror("user-path too large: %s", rpath
);
223 else if (interpolated_path
&& hi
->saw_extended_args
) {
224 struct strbuf expanded_path
= STRBUF_INIT
;
225 struct expand_path_context context
;
227 context
.directory
= directory
;
228 context
.hostinfo
= hi
;
231 /* Allow only absolute */
232 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
236 strbuf_expand(&expanded_path
, interpolated_path
,
237 expand_path
, &context
);
239 rlen
= strlcpy(interp_path
, expanded_path
.buf
,
240 sizeof(interp_path
));
241 strbuf_release(&expanded_path
);
242 if (rlen
>= sizeof(interp_path
)) {
243 logerror("interpolated path too large: %s",
248 loginfo("Interpolated dir '%s'", interp_path
);
252 else if (base_path
) {
254 /* Allow only absolute */
255 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
258 rlen
= snprintf(rpath
, sizeof(rpath
), "%s%s", base_path
, dir
);
259 if (rlen
>= sizeof(rpath
)) {
260 logerror("base-path too large: %s", rpath
);
266 path
= enter_repo(dir
, strict_paths
);
267 if (!path
&& base_path
&& base_path_relaxed
) {
269 * if we fail and base_path_relaxed is enabled, try without
270 * prefixing the base path
273 path
= enter_repo(dir
, strict_paths
);
277 logerror("'%s' does not appear to be a git repository", dir
);
281 if ( ok_paths
&& *ok_paths
) {
283 int pathlen
= strlen(path
);
285 /* The validation is done on the paths after enter_repo
286 * appends optional {.git,.git/.git} and friends, but
287 * it does not use getcwd(). So if your /pub is
288 * a symlink to /mnt/pub, you can include /pub and
289 * do not have to say /mnt/pub.
292 for ( pp
= ok_paths
; *pp
; pp
++ ) {
293 int len
= strlen(*pp
);
294 if (len
<= pathlen
&&
295 !memcmp(*pp
, path
, len
) &&
296 (path
[len
] == '\0' ||
297 (!strict_paths
&& path
[len
] == '/')))
302 /* be backwards compatible */
307 logerror("'%s': not in directory list", path
);
308 return NULL
; /* Fallthrough. Deny by default */
311 typedef int (*daemon_service_fn
)(const struct strvec
*env
);
312 struct daemon_service
{
314 const char *config_name
;
315 daemon_service_fn fn
;
320 static int daemon_error(const char *dir
, const char *msg
)
322 if (!informative_errors
)
323 msg
= "access denied or repository not exported";
324 packet_write_fmt(1, "ERR %s: %s", msg
, dir
);
328 static const char *access_hook
;
330 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
331 const char *path
, struct hostinfo
*hi
)
333 struct child_process child
= CHILD_PROCESS_INIT
;
334 struct strbuf buf
= STRBUF_INIT
;
338 strvec_push(&child
.args
, access_hook
);
339 strvec_push(&child
.args
, service
->name
);
340 strvec_push(&child
.args
, path
);
341 strvec_push(&child
.args
, hi
->hostname
.buf
);
342 strvec_push(&child
.args
, get_canon_hostname(hi
));
343 strvec_push(&child
.args
, get_ip_address(hi
));
344 strvec_push(&child
.args
, hi
->tcp_port
.buf
);
350 if (start_command(&child
)) {
351 logerror("daemon access hook '%s' failed to start",
355 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
356 logerror("failed to read from pipe to daemon access hook '%s'",
361 if (close(child
.out
) < 0) {
362 logerror("failed to close pipe to daemon access hook '%s'",
366 if (finish_command(&child
))
370 strbuf_release(&buf
);
377 strbuf_addstr(&buf
, "service rejected");
378 eol
= strchr(buf
.buf
, '\n');
382 daemon_error(dir
, buf
.buf
);
383 strbuf_release(&buf
);
387 static int run_service(const char *dir
, struct daemon_service
*service
,
388 struct hostinfo
*hi
, const struct strvec
*env
)
391 int enabled
= service
->enabled
;
392 struct strbuf var
= STRBUF_INIT
;
394 loginfo("Request %s for '%s'", service
->name
, dir
);
396 if (!enabled
&& !service
->overridable
) {
397 logerror("'%s': service not enabled.", service
->name
);
399 return daemon_error(dir
, "service not enabled");
402 if (!(path
= path_ok(dir
, hi
)))
403 return daemon_error(dir
, "no such repository");
406 * Security on the cheap.
408 * We want a readable HEAD, usable "objects" directory, and
409 * a "git-daemon-export-ok" flag that says that the other side
410 * is ok with us doing this.
412 * path_ok() uses enter_repo() and checks for included directories.
413 * We only need to make sure the repository is exported.
416 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
417 logerror("'%s': repository not exported.", path
);
419 return daemon_error(dir
, "repository not exported");
422 if (service
->overridable
) {
423 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
424 git_config_get_bool(var
.buf
, &enabled
);
425 strbuf_release(&var
);
428 logerror("'%s': service not enabled for '%s'",
429 service
->name
, path
);
431 return daemon_error(dir
, "service not enabled");
435 * Optionally, a hook can choose to deny access to the
436 * repository depending on the phase of the moon.
438 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
442 * We'll ignore SIGTERM from now on, we have a
445 signal(SIGTERM
, SIG_IGN
);
447 return service
->fn(env
);
450 static void copy_to_log(int fd
)
452 struct strbuf line
= STRBUF_INIT
;
455 fp
= fdopen(fd
, "r");
457 logerror("fdopen of error channel failed");
462 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
463 logerror("%s", line
.buf
);
464 strbuf_setlen(&line
, 0);
467 strbuf_release(&line
);
471 static int run_service_command(struct child_process
*cld
)
473 strvec_push(&cld
->args
, ".");
476 if (start_command(cld
))
482 copy_to_log(cld
->err
);
484 return finish_command(cld
);
487 static int upload_pack(const struct strvec
*env
)
489 struct child_process cld
= CHILD_PROCESS_INIT
;
490 strvec_pushl(&cld
.args
, "upload-pack", "--strict", NULL
);
491 strvec_pushf(&cld
.args
, "--timeout=%u", timeout
);
493 strvec_pushv(&cld
.env
, env
->v
);
495 return run_service_command(&cld
);
498 static int upload_archive(const struct strvec
*env
)
500 struct child_process cld
= CHILD_PROCESS_INIT
;
501 strvec_push(&cld
.args
, "upload-archive");
503 strvec_pushv(&cld
.env
, env
->v
);
505 return run_service_command(&cld
);
508 static int receive_pack(const struct strvec
*env
)
510 struct child_process cld
= CHILD_PROCESS_INIT
;
511 strvec_push(&cld
.args
, "receive-pack");
513 strvec_pushv(&cld
.env
, env
->v
);
515 return run_service_command(&cld
);
518 static struct daemon_service daemon_service
[] = {
519 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
520 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
521 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
524 static void enable_service(const char *name
, int ena
)
527 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
528 if (!strcmp(daemon_service
[i
].name
, name
)) {
529 daemon_service
[i
].enabled
= ena
;
533 die("No such service %s", name
);
536 static void make_service_overridable(const char *name
, int ena
)
539 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
540 if (!strcmp(daemon_service
[i
].name
, name
)) {
541 daemon_service
[i
].overridable
= ena
;
545 die("No such service %s", name
);
548 static void parse_host_and_port(char *hostport
, char **host
,
551 if (*hostport
== '[') {
554 end
= strchr(hostport
, ']');
556 die("Invalid request ('[' without ']')");
558 *host
= hostport
+ 1;
561 else if (end
[1] == ':')
564 die("Garbage after end of host part");
567 *port
= strrchr(hostport
, ':');
576 * Sanitize a string from the client so that it's OK to be inserted into a
577 * filesystem path. Specifically, we disallow directory separators, runs
578 * of "..", and trailing and leading dots, which means that the client
579 * cannot escape our base path via ".." traversal.
581 static void sanitize_client(struct strbuf
*out
, const char *in
)
586 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
588 strbuf_addch(out
, *in
);
591 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
592 strbuf_setlen(out
, out
->len
- 1);
596 * Like sanitize_client, but we also perform any canonicalization
597 * to make life easier on the admin.
599 static void canonicalize_client(struct strbuf
*out
, const char *in
)
601 sanitize_client(out
, in
);
606 * Read the host as supplied by the client connection.
608 * Returns a pointer to the character after the NUL byte terminating the host
609 * argument, or 'extra_args' if there is no host argument.
611 static char *parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
615 char *end
= extra_args
+ buflen
;
617 if (extra_args
< end
&& *extra_args
) {
618 hi
->saw_extended_args
= 1;
619 if (strncasecmp("host=", extra_args
, 5) == 0) {
620 val
= extra_args
+ 5;
621 vallen
= strlen(val
) + 1;
622 loginfo("Extended attribute \"host\": %s", val
);
624 /* Split <host>:<port> at colon. */
627 parse_host_and_port(val
, &host
, &port
);
629 sanitize_client(&hi
->tcp_port
, port
);
630 canonicalize_client(&hi
->hostname
, host
);
631 hi
->hostname_lookup_done
= 0;
634 /* On to the next one */
635 extra_args
= val
+ vallen
;
637 if (extra_args
< end
&& *extra_args
)
638 die("Invalid request");
644 static void parse_extra_args(struct hostinfo
*hi
, struct strvec
*env
,
645 char *extra_args
, int buflen
)
647 const char *end
= extra_args
+ buflen
;
648 struct strbuf git_protocol
= STRBUF_INIT
;
650 /* First look for the host argument */
651 extra_args
= parse_host_arg(hi
, extra_args
, buflen
);
653 /* Look for additional arguments places after a second NUL byte */
654 for (; extra_args
< end
; extra_args
+= strlen(extra_args
) + 1) {
655 const char *arg
= extra_args
;
658 * Parse the extra arguments, adding most to 'git_protocol'
659 * which will be used to set the 'GIT_PROTOCOL' envvar in the
660 * service that will be run.
662 * If there ends up being a particular arg in the future that
663 * git-daemon needs to parse specifically (like the 'host' arg)
664 * then it can be parsed here and not added to 'git_protocol'.
667 if (git_protocol
.len
> 0)
668 strbuf_addch(&git_protocol
, ':');
669 strbuf_addstr(&git_protocol
, arg
);
673 if (git_protocol
.len
> 0) {
674 loginfo("Extended attribute \"protocol\": %s", git_protocol
.buf
);
675 strvec_pushf(env
, GIT_PROTOCOL_ENVIRONMENT
"=%s",
678 strbuf_release(&git_protocol
);
682 * Locate canonical hostname and its IP address.
684 static void lookup_hostname(struct hostinfo
*hi
)
686 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
688 struct addrinfo hints
;
691 static char addrbuf
[HOST_NAME_MAX
+ 1];
693 memset(&hints
, 0, sizeof(hints
));
694 hints
.ai_flags
= AI_CANONNAME
;
696 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
698 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
700 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
701 addrbuf
, sizeof(addrbuf
));
702 strbuf_addstr(&hi
->ip_address
, addrbuf
);
704 if (ai
->ai_canonname
)
705 sanitize_client(&hi
->canon_hostname
,
708 strbuf_addbuf(&hi
->canon_hostname
,
714 struct hostent
*hent
;
715 struct sockaddr_in sa
;
717 static char addrbuf
[HOST_NAME_MAX
+ 1];
719 hent
= gethostbyname(hi
->hostname
.buf
);
721 ap
= hent
->h_addr_list
;
722 memset(&sa
, 0, sizeof sa
);
723 sa
.sin_family
= hent
->h_addrtype
;
724 sa
.sin_port
= htons(0);
725 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
727 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
728 addrbuf
, sizeof(addrbuf
));
730 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
731 strbuf_addstr(&hi
->ip_address
, addrbuf
);
734 hi
->hostname_lookup_done
= 1;
738 static void hostinfo_clear(struct hostinfo
*hi
)
740 strbuf_release(&hi
->hostname
);
741 strbuf_release(&hi
->canon_hostname
);
742 strbuf_release(&hi
->ip_address
);
743 strbuf_release(&hi
->tcp_port
);
746 static void set_keep_alive(int sockfd
)
750 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0) {
751 if (errno
!= ENOTSOCK
)
752 logerror("unable to set SO_KEEPALIVE on socket: %s",
757 static int execute(void)
759 char *line
= packet_buffer
;
761 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
762 struct hostinfo hi
= HOSTINFO_INIT
;
763 struct strvec env
= STRVEC_INIT
;
766 loginfo("Connection from %s:%s", addr
, port
);
769 alarm(init_timeout
? init_timeout
: timeout
);
770 pktlen
= packet_read(0, packet_buffer
, sizeof(packet_buffer
), 0);
774 if (len
&& line
[len
-1] == '\n')
777 /* parse additional args hidden behind a NUL byte */
779 parse_extra_args(&hi
, &env
, line
+ len
+ 1, pktlen
- len
- 1);
781 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
782 struct daemon_service
*s
= &(daemon_service
[i
]);
785 if (skip_prefix(line
, "git-", &arg
) &&
786 skip_prefix(arg
, s
->name
, &arg
) &&
789 * Note: The directory here is probably context sensitive,
790 * and might depend on the actual service being performed.
792 int rc
= run_service(arg
, s
, &hi
, &env
);
801 logerror("Protocol error: '%s'", line
);
805 static int addrcmp(const struct sockaddr_storage
*s1
,
806 const struct sockaddr_storage
*s2
)
808 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
809 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
811 if (sa1
->sa_family
!= sa2
->sa_family
)
812 return sa1
->sa_family
- sa2
->sa_family
;
813 if (sa1
->sa_family
== AF_INET
)
814 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
815 &((struct sockaddr_in
*)s2
)->sin_addr
,
816 sizeof(struct in_addr
));
818 if (sa1
->sa_family
== AF_INET6
)
819 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
820 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
821 sizeof(struct in6_addr
));
826 static int max_connections
= 32;
828 static unsigned int live_children
;
830 static struct child
{
832 struct child_process cld
;
833 struct sockaddr_storage address
;
836 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
838 struct child
*newborn
, **cradle
;
840 CALLOC_ARRAY(newborn
, 1);
842 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
843 memcpy(&newborn
->address
, addr
, addrlen
);
844 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
845 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
847 newborn
->next
= *cradle
;
852 * This gets called if the number of connections grows
853 * past "max_connections".
855 * We kill the newest connection from a duplicate IP.
857 static void kill_some_child(void)
859 const struct child
*blanket
, *next
;
861 if (!(blanket
= firstborn
))
864 for (; (next
= blanket
->next
); blanket
= next
)
865 if (!addrcmp(&blanket
->address
, &next
->address
)) {
866 kill(blanket
->cld
.pid
, SIGTERM
);
871 static void check_dead_children(void)
876 struct child
**cradle
, *blanket
;
877 for (cradle
= &firstborn
; (blanket
= *cradle
);)
878 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
879 const char *dead
= "";
881 dead
= " (with error)";
882 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
884 /* remove the child */
885 *cradle
= blanket
->next
;
887 child_process_clear(&blanket
->cld
);
890 cradle
= &blanket
->next
;
893 static struct strvec cld_argv
= STRVEC_INIT
;
894 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
896 struct child_process cld
= CHILD_PROCESS_INIT
;
898 if (max_connections
&& live_children
>= max_connections
) {
900 sleep(1); /* give it some time to die */
901 check_dead_children();
902 if (live_children
>= max_connections
) {
904 logerror("Too many children, dropping connection");
909 if (addr
->sa_family
== AF_INET
) {
911 struct sockaddr_in
*sin_addr
= (void *) addr
;
912 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
913 strvec_pushf(&cld
.env
, "REMOTE_ADDR=%s", buf
);
914 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
915 ntohs(sin_addr
->sin_port
));
917 } else if (addr
->sa_family
== AF_INET6
) {
919 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
920 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
921 strvec_pushf(&cld
.env
, "REMOTE_ADDR=[%s]", buf
);
922 strvec_pushf(&cld
.env
, "REMOTE_PORT=%d",
923 ntohs(sin6_addr
->sin6_port
));
927 strvec_pushv(&cld
.args
, cld_argv
.v
);
929 cld
.out
= dup(incoming
);
931 if (start_command(&cld
))
932 logerror("unable to fork");
934 add_child(&cld
, addr
, addrlen
);
937 static void child_handler(int signo UNUSED
)
940 * Otherwise empty handler because systemcalls will get interrupted
941 * upon signal receipt
942 * SysV needs the handler to be rearmed
944 signal(SIGCHLD
, child_handler
);
947 static int set_reuse_addr(int sockfd
)
953 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
963 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
966 static char ip
[INET_ADDRSTRLEN
];
968 static char ip
[INET6_ADDRSTRLEN
];
974 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
978 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
981 xsnprintf(ip
, sizeof(ip
), "<unknown>");
988 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
991 char pbuf
[NI_MAXSERV
];
992 struct addrinfo hints
, *ai0
, *ai
;
996 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
997 memset(&hints
, 0, sizeof(hints
));
998 hints
.ai_family
= AF_UNSPEC
;
999 hints
.ai_socktype
= SOCK_STREAM
;
1000 hints
.ai_protocol
= IPPROTO_TCP
;
1001 hints
.ai_flags
= AI_PASSIVE
;
1003 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
1005 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
1009 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
1012 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
1015 if (sockfd
>= FD_SETSIZE
) {
1016 logerror("Socket descriptor too large");
1022 if (ai
->ai_family
== AF_INET6
) {
1024 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
1026 /* Note: error is not fatal */
1030 if (set_reuse_addr(sockfd
)) {
1031 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1036 set_keep_alive(sockfd
);
1038 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1039 logerror("Could not bind to %s: %s",
1040 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1043 continue; /* not fatal */
1045 if (listen(sockfd
, 5) < 0) {
1046 logerror("Could not listen to %s: %s",
1047 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1050 continue; /* not fatal */
1053 flags
= fcntl(sockfd
, F_GETFD
, 0);
1055 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1057 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1058 socklist
->list
[socklist
->nr
++] = sockfd
;
1069 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1071 struct sockaddr_in sin
;
1075 memset(&sin
, 0, sizeof sin
);
1076 sin
.sin_family
= AF_INET
;
1077 sin
.sin_port
= htons(listen_port
);
1080 /* Well, host better be an IP address here. */
1081 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1084 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1087 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1091 if (set_reuse_addr(sockfd
)) {
1092 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1097 set_keep_alive(sockfd
);
1099 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1100 logerror("Could not bind to %s: %s",
1101 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1107 if (listen(sockfd
, 5) < 0) {
1108 logerror("Could not listen to %s: %s",
1109 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1115 flags
= fcntl(sockfd
, F_GETFD
, 0);
1117 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1119 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1120 socklist
->list
[socklist
->nr
++] = sockfd
;
1126 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1128 if (!listen_addr
->nr
)
1129 setup_named_sock(NULL
, listen_port
, socklist
);
1132 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1133 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1134 listen_port
, socklist
);
1137 logerror("unable to allocate any listen sockets for host %s on port %u",
1138 listen_addr
->items
[i
].string
, listen_port
);
1143 static int service_loop(struct socketlist
*socklist
)
1148 CALLOC_ARRAY(pfd
, socklist
->nr
);
1150 for (i
= 0; i
< socklist
->nr
; i
++) {
1151 pfd
[i
].fd
= socklist
->list
[i
];
1152 pfd
[i
].events
= POLLIN
;
1155 signal(SIGCHLD
, child_handler
);
1160 check_dead_children();
1162 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1163 if (errno
!= EINTR
) {
1164 logerror("Poll failed, resuming: %s",
1171 for (i
= 0; i
< socklist
->nr
; i
++) {
1172 if (pfd
[i
].revents
& POLLIN
) {
1175 struct sockaddr_in sai
;
1177 struct sockaddr_in6 sai6
;
1180 socklen_t sslen
= sizeof(ss
);
1181 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1189 die_errno("accept returned");
1192 handle(incoming
, &ss
.sa
, sslen
);
1198 #ifdef NO_POSIX_GOODIES
1202 static void drop_privileges(struct credentials
*cred
)
1207 static struct credentials
*prepare_credentials(const char *user_name
,
1208 const char *group_name
)
1210 die("--user not supported on this platform");
1215 struct credentials
{
1216 struct passwd
*pass
;
1220 static void drop_privileges(struct credentials
*cred
)
1222 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1223 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1224 die("cannot drop privileges");
1227 static struct credentials
*prepare_credentials(const char *user_name
,
1228 const char *group_name
)
1230 static struct credentials c
;
1232 c
.pass
= getpwnam(user_name
);
1234 die("user not found - %s", user_name
);
1237 c
.gid
= c
.pass
->pw_gid
;
1239 struct group
*group
= getgrnam(group_name
);
1241 die("group not found - %s", group_name
);
1243 c
.gid
= group
->gr_gid
;
1250 static int serve(struct string_list
*listen_addr
, int listen_port
,
1251 struct credentials
*cred
)
1253 struct socketlist socklist
= { NULL
, 0, 0 };
1255 socksetup(listen_addr
, listen_port
, &socklist
);
1256 if (socklist
.nr
== 0)
1257 die("unable to allocate any listen sockets on port %u",
1260 drop_privileges(cred
);
1262 loginfo("Ready to rumble");
1264 return service_loop(&socklist
);
1267 int cmd_main(int argc
, const char **argv
)
1269 int listen_port
= 0;
1270 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1271 int serve_mode
= 0, inetd_mode
= 0;
1272 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1274 struct credentials
*cred
= NULL
;
1277 for (i
= 1; i
< argc
; i
++) {
1278 const char *arg
= argv
[i
];
1281 if (skip_prefix(arg
, "--listen=", &v
)) {
1282 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1285 if (skip_prefix(arg
, "--port=", &v
)) {
1288 n
= strtoul(v
, &end
, 0);
1294 if (!strcmp(arg
, "--serve")) {
1298 if (!strcmp(arg
, "--inetd")) {
1302 if (!strcmp(arg
, "--verbose")) {
1306 if (!strcmp(arg
, "--syslog")) {
1307 log_destination
= LOG_DESTINATION_SYSLOG
;
1310 if (skip_prefix(arg
, "--log-destination=", &v
)) {
1311 if (!strcmp(v
, "syslog")) {
1312 log_destination
= LOG_DESTINATION_SYSLOG
;
1314 } else if (!strcmp(v
, "stderr")) {
1315 log_destination
= LOG_DESTINATION_STDERR
;
1317 } else if (!strcmp(v
, "none")) {
1318 log_destination
= LOG_DESTINATION_NONE
;
1321 die("unknown log destination '%s'", v
);
1323 if (!strcmp(arg
, "--export-all")) {
1324 export_all_trees
= 1;
1327 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1331 if (skip_prefix(arg
, "--timeout=", &v
)) {
1335 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1336 init_timeout
= atoi(v
);
1339 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1340 max_connections
= atoi(v
);
1341 if (max_connections
< 0)
1342 max_connections
= 0; /* unlimited */
1345 if (!strcmp(arg
, "--strict-paths")) {
1349 if (skip_prefix(arg
, "--base-path=", &v
)) {
1353 if (!strcmp(arg
, "--base-path-relaxed")) {
1354 base_path_relaxed
= 1;
1357 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1358 interpolated_path
= v
;
1361 if (!strcmp(arg
, "--reuseaddr")) {
1365 if (!strcmp(arg
, "--user-path")) {
1369 if (skip_prefix(arg
, "--user-path=", &v
)) {
1373 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1377 if (!strcmp(arg
, "--detach")) {
1381 if (skip_prefix(arg
, "--user=", &v
)) {
1385 if (skip_prefix(arg
, "--group=", &v
)) {
1389 if (skip_prefix(arg
, "--enable=", &v
)) {
1390 enable_service(v
, 1);
1393 if (skip_prefix(arg
, "--disable=", &v
)) {
1394 enable_service(v
, 0);
1397 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1398 make_service_overridable(v
, 1);
1401 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1402 make_service_overridable(v
, 0);
1405 if (!strcmp(arg
, "--informative-errors")) {
1406 informative_errors
= 1;
1409 if (!strcmp(arg
, "--no-informative-errors")) {
1410 informative_errors
= 0;
1413 if (!strcmp(arg
, "--")) {
1414 ok_paths
= &argv
[i
+1];
1416 } else if (arg
[0] != '-') {
1417 ok_paths
= &argv
[i
];
1421 usage(daemon_usage
);
1424 if (log_destination
== LOG_DESTINATION_UNSET
) {
1425 if (inetd_mode
|| detach
)
1426 log_destination
= LOG_DESTINATION_SYSLOG
;
1428 log_destination
= LOG_DESTINATION_STDERR
;
1431 if (log_destination
== LOG_DESTINATION_SYSLOG
) {
1432 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1433 set_die_routine(daemon_die
);
1435 /* avoid splitting a message in the middle */
1436 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1438 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1439 die("--detach, --user and --group are incompatible with --inetd");
1441 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1442 die("--listen= and --port= are incompatible with --inetd");
1443 else if (listen_port
== 0)
1444 listen_port
= DEFAULT_GIT_PORT
;
1446 if (group_name
&& !user_name
)
1447 die("--group supplied without --user");
1450 cred
= prepare_credentials(user_name
, group_name
);
1452 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1453 die("option --strict-paths requires '<directory>' arguments");
1455 if (base_path
&& !is_directory(base_path
))
1456 die("base-path '%s' does not exist or is not a directory",
1459 if (log_destination
!= LOG_DESTINATION_STDERR
) {
1460 if (!freopen("/dev/null", "w", stderr
))
1461 die_errno("failed to redirect stderr to /dev/null");
1464 if (inetd_mode
|| serve_mode
)
1469 die("--detach not supported on this platform");
1473 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1475 /* prepare argv for serving-processes */
1476 strvec_push(&cld_argv
, argv
[0]); /* git-daemon */
1477 strvec_push(&cld_argv
, "--serve");
1478 for (i
= 1; i
< argc
; ++i
)
1479 strvec_push(&cld_argv
, argv
[i
]);
1481 return serve(&listen_addr
, listen_port
, cred
);