4 #include "run-command.h"
6 #include "string-list.h"
9 #define initgroups(x, y) (0) /* nothing */
12 static int log_syslog
;
15 static int informative_errors
;
17 static const char daemon_usage
[] =
18 "git daemon [--verbose] [--syslog] [--export-all]\n"
19 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
20 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
21 " [--user-path | --user-path=<path>]\n"
22 " [--interpolated-path=<path>]\n"
23 " [--reuseaddr] [--pid-file=<file>]\n"
24 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
25 " [--access-hook=<path>]\n"
26 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
27 " [--detach] [--user=<user> [--group=<group>]]\n"
30 /* List of acceptable pathname prefixes */
31 static const char **ok_paths
;
32 static int strict_paths
;
34 /* If this is set, git-daemon-export-ok is not required */
35 static int export_all_trees
;
37 /* Take all paths relative to this one if non-NULL */
38 static const char *base_path
;
39 static const char *interpolated_path
;
40 static int base_path_relaxed
;
42 /* If defined, ~user notation is allowed and the string is inserted
43 * after ~user/. E.g. a request to git://host/~alice/frotz would
44 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
46 static const char *user_path
;
48 /* Timeout, and initial timeout */
49 static unsigned int timeout
;
50 static unsigned int init_timeout
;
53 struct strbuf hostname
;
54 struct strbuf canon_hostname
;
55 struct strbuf ip_address
;
56 struct strbuf tcp_port
;
57 unsigned int hostname_lookup_done
:1;
58 unsigned int saw_extended_args
:1;
61 static void lookup_hostname(struct hostinfo
*hi
);
63 static const char *get_canon_hostname(struct hostinfo
*hi
)
66 return hi
->canon_hostname
.buf
;
69 static const char *get_ip_address(struct hostinfo
*hi
)
72 return hi
->ip_address
.buf
;
75 static void logreport(int priority
, const char *err
, va_list params
)
79 vsnprintf(buf
, sizeof(buf
), err
, params
);
80 syslog(priority
, "%s", buf
);
83 * Since stderr is set to buffered mode, the
84 * logging of different processes will not overlap
85 * unless they overflow the (rather big) buffers.
87 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
88 vfprintf(stderr
, err
, params
);
94 __attribute__((format (printf
, 1, 2)))
95 static void logerror(const char *err
, ...)
98 va_start(params
, err
);
99 logreport(LOG_ERR
, err
, params
);
103 __attribute__((format (printf
, 1, 2)))
104 static void loginfo(const char *err
, ...)
109 va_start(params
, err
);
110 logreport(LOG_INFO
, err
, params
);
114 static void NORETURN
daemon_die(const char *err
, va_list params
)
116 logreport(LOG_ERR
, err
, params
);
120 struct expand_path_context
{
121 const char *directory
;
122 struct hostinfo
*hostinfo
;
125 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
127 struct expand_path_context
*context
= ctx
;
128 struct hostinfo
*hi
= context
->hostinfo
;
130 switch (placeholder
[0]) {
132 strbuf_addbuf(sb
, &hi
->hostname
);
135 if (placeholder
[1] == 'H') {
136 strbuf_addstr(sb
, get_canon_hostname(hi
));
141 if (placeholder
[1] == 'P') {
142 strbuf_addstr(sb
, get_ip_address(hi
));
147 strbuf_addbuf(sb
, &hi
->tcp_port
);
150 strbuf_addstr(sb
, context
->directory
);
156 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
158 static char rpath
[PATH_MAX
];
159 static char interp_path
[PATH_MAX
];
166 if (daemon_avoid_alias(dir
)) {
167 logerror("'%s': aliased", dir
);
173 logerror("'%s': User-path not allowed", dir
);
177 /* Got either "~alice" or "~alice/foo";
178 * rewrite them to "~alice/%s" or
181 int namlen
, restlen
= strlen(dir
);
182 const char *slash
= strchr(dir
, '/');
184 slash
= dir
+ restlen
;
185 namlen
= slash
- dir
;
187 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
188 rlen
= snprintf(rpath
, sizeof(rpath
), "%.*s/%s%.*s",
189 namlen
, dir
, user_path
, restlen
, slash
);
190 if (rlen
>= sizeof(rpath
)) {
191 logerror("user-path too large: %s", rpath
);
197 else if (interpolated_path
&& hi
->saw_extended_args
) {
198 struct strbuf expanded_path
= STRBUF_INIT
;
199 struct expand_path_context context
;
201 context
.directory
= directory
;
202 context
.hostinfo
= hi
;
205 /* Allow only absolute */
206 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
210 strbuf_expand(&expanded_path
, interpolated_path
,
211 expand_path
, &context
);
213 rlen
= strlcpy(interp_path
, expanded_path
.buf
,
214 sizeof(interp_path
));
215 if (rlen
>= sizeof(interp_path
)) {
216 logerror("interpolated path too large: %s",
221 strbuf_release(&expanded_path
);
222 loginfo("Interpolated dir '%s'", interp_path
);
226 else if (base_path
) {
228 /* Allow only absolute */
229 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
232 rlen
= snprintf(rpath
, sizeof(rpath
), "%s%s", base_path
, dir
);
233 if (rlen
>= sizeof(rpath
)) {
234 logerror("base-path too large: %s", rpath
);
240 path
= enter_repo(dir
, strict_paths
);
241 if (!path
&& base_path
&& base_path_relaxed
) {
243 * if we fail and base_path_relaxed is enabled, try without
244 * prefixing the base path
247 path
= enter_repo(dir
, strict_paths
);
251 logerror("'%s' does not appear to be a git repository", dir
);
255 if ( ok_paths
&& *ok_paths
) {
257 int pathlen
= strlen(path
);
259 /* The validation is done on the paths after enter_repo
260 * appends optional {.git,.git/.git} and friends, but
261 * it does not use getcwd(). So if your /pub is
262 * a symlink to /mnt/pub, you can whitelist /pub and
263 * do not have to say /mnt/pub.
266 for ( pp
= ok_paths
; *pp
; pp
++ ) {
267 int len
= strlen(*pp
);
268 if (len
<= pathlen
&&
269 !memcmp(*pp
, path
, len
) &&
270 (path
[len
] == '\0' ||
271 (!strict_paths
&& path
[len
] == '/')))
276 /* be backwards compatible */
281 logerror("'%s': not in whitelist", path
);
282 return NULL
; /* Fallthrough. Deny by default */
285 typedef int (*daemon_service_fn
)(const struct argv_array
*env
);
286 struct daemon_service
{
288 const char *config_name
;
289 daemon_service_fn fn
;
294 static int daemon_error(const char *dir
, const char *msg
)
296 if (!informative_errors
)
297 msg
= "access denied or repository not exported";
298 packet_write_fmt(1, "ERR %s: %s", msg
, dir
);
302 static const char *access_hook
;
304 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
305 const char *path
, struct hostinfo
*hi
)
307 struct child_process child
= CHILD_PROCESS_INIT
;
308 struct strbuf buf
= STRBUF_INIT
;
310 const char **arg
= argv
;
314 *arg
++ = access_hook
;
315 *arg
++ = service
->name
;
317 *arg
++ = hi
->hostname
.buf
;
318 *arg
++ = get_canon_hostname(hi
);
319 *arg
++ = get_ip_address(hi
);
320 *arg
++ = hi
->tcp_port
.buf
;
328 if (start_command(&child
)) {
329 logerror("daemon access hook '%s' failed to start",
333 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
334 logerror("failed to read from pipe to daemon access hook '%s'",
339 if (close(child
.out
) < 0) {
340 logerror("failed to close pipe to daemon access hook '%s'",
344 if (finish_command(&child
))
348 strbuf_release(&buf
);
355 strbuf_addstr(&buf
, "service rejected");
356 eol
= strchr(buf
.buf
, '\n');
360 daemon_error(dir
, buf
.buf
);
361 strbuf_release(&buf
);
365 static int run_service(const char *dir
, struct daemon_service
*service
,
366 struct hostinfo
*hi
, const struct argv_array
*env
)
369 int enabled
= service
->enabled
;
370 struct strbuf var
= STRBUF_INIT
;
372 loginfo("Request %s for '%s'", service
->name
, dir
);
374 if (!enabled
&& !service
->overridable
) {
375 logerror("'%s': service not enabled.", service
->name
);
377 return daemon_error(dir
, "service not enabled");
380 if (!(path
= path_ok(dir
, hi
)))
381 return daemon_error(dir
, "no such repository");
384 * Security on the cheap.
386 * We want a readable HEAD, usable "objects" directory, and
387 * a "git-daemon-export-ok" flag that says that the other side
388 * is ok with us doing this.
390 * path_ok() uses enter_repo() and does whitelist checking.
391 * We only need to make sure the repository is exported.
394 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
395 logerror("'%s': repository not exported.", path
);
397 return daemon_error(dir
, "repository not exported");
400 if (service
->overridable
) {
401 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
402 git_config_get_bool(var
.buf
, &enabled
);
403 strbuf_release(&var
);
406 logerror("'%s': service not enabled for '%s'",
407 service
->name
, path
);
409 return daemon_error(dir
, "service not enabled");
413 * Optionally, a hook can choose to deny access to the
414 * repository depending on the phase of the moon.
416 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
420 * We'll ignore SIGTERM from now on, we have a
423 signal(SIGTERM
, SIG_IGN
);
425 return service
->fn(env
);
428 static void copy_to_log(int fd
)
430 struct strbuf line
= STRBUF_INIT
;
433 fp
= fdopen(fd
, "r");
435 logerror("fdopen of error channel failed");
440 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
441 logerror("%s", line
.buf
);
442 strbuf_setlen(&line
, 0);
445 strbuf_release(&line
);
449 static int run_service_command(struct child_process
*cld
)
451 argv_array_push(&cld
->args
, ".");
454 if (start_command(cld
))
460 copy_to_log(cld
->err
);
462 return finish_command(cld
);
465 static int upload_pack(const struct argv_array
*env
)
467 struct child_process cld
= CHILD_PROCESS_INIT
;
468 argv_array_pushl(&cld
.args
, "upload-pack", "--strict", NULL
);
469 argv_array_pushf(&cld
.args
, "--timeout=%u", timeout
);
471 argv_array_pushv(&cld
.env_array
, env
->argv
);
473 return run_service_command(&cld
);
476 static int upload_archive(const struct argv_array
*env
)
478 struct child_process cld
= CHILD_PROCESS_INIT
;
479 argv_array_push(&cld
.args
, "upload-archive");
481 argv_array_pushv(&cld
.env_array
, env
->argv
);
483 return run_service_command(&cld
);
486 static int receive_pack(const struct argv_array
*env
)
488 struct child_process cld
= CHILD_PROCESS_INIT
;
489 argv_array_push(&cld
.args
, "receive-pack");
491 argv_array_pushv(&cld
.env_array
, env
->argv
);
493 return run_service_command(&cld
);
496 static struct daemon_service daemon_service
[] = {
497 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
498 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
499 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
502 static void enable_service(const char *name
, int ena
)
505 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
506 if (!strcmp(daemon_service
[i
].name
, name
)) {
507 daemon_service
[i
].enabled
= ena
;
511 die("No such service %s", name
);
514 static void make_service_overridable(const char *name
, int ena
)
517 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
518 if (!strcmp(daemon_service
[i
].name
, name
)) {
519 daemon_service
[i
].overridable
= ena
;
523 die("No such service %s", name
);
526 static void parse_host_and_port(char *hostport
, char **host
,
529 if (*hostport
== '[') {
532 end
= strchr(hostport
, ']');
534 die("Invalid request ('[' without ']')");
536 *host
= hostport
+ 1;
539 else if (end
[1] == ':')
542 die("Garbage after end of host part");
545 *port
= strrchr(hostport
, ':');
554 * Sanitize a string from the client so that it's OK to be inserted into a
555 * filesystem path. Specifically, we disallow slashes, runs of "..", and
556 * trailing and leading dots, which means that the client cannot escape
557 * our base path via ".." traversal.
559 static void sanitize_client(struct strbuf
*out
, const char *in
)
564 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
566 strbuf_addch(out
, *in
);
569 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
570 strbuf_setlen(out
, out
->len
- 1);
574 * Like sanitize_client, but we also perform any canonicalization
575 * to make life easier on the admin.
577 static void canonicalize_client(struct strbuf
*out
, const char *in
)
579 sanitize_client(out
, in
);
584 * Read the host as supplied by the client connection.
586 * Returns a pointer to the character after the NUL byte terminating the host
587 * arguemnt, or 'extra_args' if there is no host arguemnt.
589 static char *parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
593 char *end
= extra_args
+ buflen
;
595 if (extra_args
< end
&& *extra_args
) {
596 hi
->saw_extended_args
= 1;
597 if (strncasecmp("host=", extra_args
, 5) == 0) {
598 val
= extra_args
+ 5;
599 vallen
= strlen(val
) + 1;
601 /* Split <host>:<port> at colon. */
604 parse_host_and_port(val
, &host
, &port
);
606 sanitize_client(&hi
->tcp_port
, port
);
607 canonicalize_client(&hi
->hostname
, host
);
608 hi
->hostname_lookup_done
= 0;
611 /* On to the next one */
612 extra_args
= val
+ vallen
;
614 if (extra_args
< end
&& *extra_args
)
615 die("Invalid request");
621 static void parse_extra_args(struct hostinfo
*hi
, struct argv_array
*env
,
622 char *extra_args
, int buflen
)
624 const char *end
= extra_args
+ buflen
;
625 struct strbuf git_protocol
= STRBUF_INIT
;
627 /* First look for the host argument */
628 extra_args
= parse_host_arg(hi
, extra_args
, buflen
);
630 /* Look for additional arguments places after a second NUL byte */
631 for (; extra_args
< end
; extra_args
+= strlen(extra_args
) + 1) {
632 const char *arg
= extra_args
;
635 * Parse the extra arguments, adding most to 'git_protocol'
636 * which will be used to set the 'GIT_PROTOCOL' envvar in the
637 * service that will be run.
639 * If there ends up being a particular arg in the future that
640 * git-daemon needs to parse specificly (like the 'host' arg)
641 * then it can be parsed here and not added to 'git_protocol'.
644 if (git_protocol
.len
> 0)
645 strbuf_addch(&git_protocol
, ':');
646 strbuf_addstr(&git_protocol
, arg
);
650 if (git_protocol
.len
> 0)
651 argv_array_pushf(env
, GIT_PROTOCOL_ENVIRONMENT
"=%s",
653 strbuf_release(&git_protocol
);
657 * Locate canonical hostname and its IP address.
659 static void lookup_hostname(struct hostinfo
*hi
)
661 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
663 struct addrinfo hints
;
666 static char addrbuf
[HOST_NAME_MAX
+ 1];
668 memset(&hints
, 0, sizeof(hints
));
669 hints
.ai_flags
= AI_CANONNAME
;
671 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
673 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
675 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
676 addrbuf
, sizeof(addrbuf
));
677 strbuf_addstr(&hi
->ip_address
, addrbuf
);
679 if (ai
->ai_canonname
)
680 sanitize_client(&hi
->canon_hostname
,
683 strbuf_addbuf(&hi
->canon_hostname
,
689 struct hostent
*hent
;
690 struct sockaddr_in sa
;
692 static char addrbuf
[HOST_NAME_MAX
+ 1];
694 hent
= gethostbyname(hi
->hostname
.buf
);
696 ap
= hent
->h_addr_list
;
697 memset(&sa
, 0, sizeof sa
);
698 sa
.sin_family
= hent
->h_addrtype
;
699 sa
.sin_port
= htons(0);
700 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
702 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
703 addrbuf
, sizeof(addrbuf
));
705 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
706 strbuf_addstr(&hi
->ip_address
, addrbuf
);
709 hi
->hostname_lookup_done
= 1;
713 static void hostinfo_init(struct hostinfo
*hi
)
715 memset(hi
, 0, sizeof(*hi
));
716 strbuf_init(&hi
->hostname
, 0);
717 strbuf_init(&hi
->canon_hostname
, 0);
718 strbuf_init(&hi
->ip_address
, 0);
719 strbuf_init(&hi
->tcp_port
, 0);
722 static void hostinfo_clear(struct hostinfo
*hi
)
724 strbuf_release(&hi
->hostname
);
725 strbuf_release(&hi
->canon_hostname
);
726 strbuf_release(&hi
->ip_address
);
727 strbuf_release(&hi
->tcp_port
);
730 static void set_keep_alive(int sockfd
)
734 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0) {
735 if (errno
!= ENOTSOCK
)
736 logerror("unable to set SO_KEEPALIVE on socket: %s",
741 static int execute(void)
743 char *line
= packet_buffer
;
745 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
747 struct argv_array env
= ARGV_ARRAY_INIT
;
752 loginfo("Connection from %s:%s", addr
, port
);
755 alarm(init_timeout
? init_timeout
: timeout
);
756 pktlen
= packet_read(0, NULL
, NULL
, packet_buffer
, sizeof(packet_buffer
), 0);
761 loginfo("Extended attributes (%d bytes) exist <%.*s>",
763 (int) pktlen
- len
, line
+ len
+ 1);
764 if (len
&& line
[len
-1] == '\n') {
769 /* parse additional args hidden behind a NUL byte */
771 parse_extra_args(&hi
, &env
, line
+ len
+ 1, pktlen
- len
- 1);
773 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
774 struct daemon_service
*s
= &(daemon_service
[i
]);
777 if (skip_prefix(line
, "git-", &arg
) &&
778 skip_prefix(arg
, s
->name
, &arg
) &&
781 * Note: The directory here is probably context sensitive,
782 * and might depend on the actual service being performed.
784 int rc
= run_service(arg
, s
, &hi
, &env
);
786 argv_array_clear(&env
);
792 argv_array_clear(&env
);
793 logerror("Protocol error: '%s'", line
);
797 static int addrcmp(const struct sockaddr_storage
*s1
,
798 const struct sockaddr_storage
*s2
)
800 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
801 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
803 if (sa1
->sa_family
!= sa2
->sa_family
)
804 return sa1
->sa_family
- sa2
->sa_family
;
805 if (sa1
->sa_family
== AF_INET
)
806 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
807 &((struct sockaddr_in
*)s2
)->sin_addr
,
808 sizeof(struct in_addr
));
810 if (sa1
->sa_family
== AF_INET6
)
811 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
812 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
813 sizeof(struct in6_addr
));
818 static int max_connections
= 32;
820 static unsigned int live_children
;
822 static struct child
{
824 struct child_process cld
;
825 struct sockaddr_storage address
;
828 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
830 struct child
*newborn
, **cradle
;
832 newborn
= xcalloc(1, sizeof(*newborn
));
834 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
835 memcpy(&newborn
->address
, addr
, addrlen
);
836 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
837 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
839 newborn
->next
= *cradle
;
844 * This gets called if the number of connections grows
845 * past "max_connections".
847 * We kill the newest connection from a duplicate IP.
849 static void kill_some_child(void)
851 const struct child
*blanket
, *next
;
853 if (!(blanket
= firstborn
))
856 for (; (next
= blanket
->next
); blanket
= next
)
857 if (!addrcmp(&blanket
->address
, &next
->address
)) {
858 kill(blanket
->cld
.pid
, SIGTERM
);
863 static void check_dead_children(void)
868 struct child
**cradle
, *blanket
;
869 for (cradle
= &firstborn
; (blanket
= *cradle
);)
870 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
871 const char *dead
= "";
873 dead
= " (with error)";
874 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
876 /* remove the child */
877 *cradle
= blanket
->next
;
879 child_process_clear(&blanket
->cld
);
882 cradle
= &blanket
->next
;
885 static struct argv_array cld_argv
= ARGV_ARRAY_INIT
;
886 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
888 struct child_process cld
= CHILD_PROCESS_INIT
;
890 if (max_connections
&& live_children
>= max_connections
) {
892 sleep(1); /* give it some time to die */
893 check_dead_children();
894 if (live_children
>= max_connections
) {
896 logerror("Too many children, dropping connection");
901 if (addr
->sa_family
== AF_INET
) {
903 struct sockaddr_in
*sin_addr
= (void *) addr
;
904 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
905 argv_array_pushf(&cld
.env_array
, "REMOTE_ADDR=%s", buf
);
906 argv_array_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
907 ntohs(sin_addr
->sin_port
));
909 } else if (addr
->sa_family
== AF_INET6
) {
911 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
912 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
913 argv_array_pushf(&cld
.env_array
, "REMOTE_ADDR=[%s]", buf
);
914 argv_array_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
915 ntohs(sin6_addr
->sin6_port
));
919 cld
.argv
= cld_argv
.argv
;
921 cld
.out
= dup(incoming
);
923 if (start_command(&cld
))
924 logerror("unable to fork");
926 add_child(&cld
, addr
, addrlen
);
929 static void child_handler(int signo
)
932 * Otherwise empty handler because systemcalls will get interrupted
933 * upon signal receipt
934 * SysV needs the handler to be rearmed
936 signal(SIGCHLD
, child_handler
);
939 static int set_reuse_addr(int sockfd
)
945 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
955 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
958 static char ip
[INET_ADDRSTRLEN
];
960 static char ip
[INET6_ADDRSTRLEN
];
966 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
970 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
973 xsnprintf(ip
, sizeof(ip
), "<unknown>");
980 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
983 char pbuf
[NI_MAXSERV
];
984 struct addrinfo hints
, *ai0
, *ai
;
988 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
989 memset(&hints
, 0, sizeof(hints
));
990 hints
.ai_family
= AF_UNSPEC
;
991 hints
.ai_socktype
= SOCK_STREAM
;
992 hints
.ai_protocol
= IPPROTO_TCP
;
993 hints
.ai_flags
= AI_PASSIVE
;
995 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
997 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
1001 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
1004 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
1007 if (sockfd
>= FD_SETSIZE
) {
1008 logerror("Socket descriptor too large");
1014 if (ai
->ai_family
== AF_INET6
) {
1016 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
1018 /* Note: error is not fatal */
1022 if (set_reuse_addr(sockfd
)) {
1023 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1028 set_keep_alive(sockfd
);
1030 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1031 logerror("Could not bind to %s: %s",
1032 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1035 continue; /* not fatal */
1037 if (listen(sockfd
, 5) < 0) {
1038 logerror("Could not listen to %s: %s",
1039 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
1042 continue; /* not fatal */
1045 flags
= fcntl(sockfd
, F_GETFD
, 0);
1047 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1049 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1050 socklist
->list
[socklist
->nr
++] = sockfd
;
1061 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1063 struct sockaddr_in sin
;
1067 memset(&sin
, 0, sizeof sin
);
1068 sin
.sin_family
= AF_INET
;
1069 sin
.sin_port
= htons(listen_port
);
1072 /* Well, host better be an IP address here. */
1073 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1076 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1079 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1083 if (set_reuse_addr(sockfd
)) {
1084 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1089 set_keep_alive(sockfd
);
1091 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1092 logerror("Could not bind to %s: %s",
1093 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1099 if (listen(sockfd
, 5) < 0) {
1100 logerror("Could not listen to %s: %s",
1101 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1107 flags
= fcntl(sockfd
, F_GETFD
, 0);
1109 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1111 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1112 socklist
->list
[socklist
->nr
++] = sockfd
;
1118 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1120 if (!listen_addr
->nr
)
1121 setup_named_sock(NULL
, listen_port
, socklist
);
1124 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1125 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1126 listen_port
, socklist
);
1129 logerror("unable to allocate any listen sockets for host %s on port %u",
1130 listen_addr
->items
[i
].string
, listen_port
);
1135 static int service_loop(struct socketlist
*socklist
)
1140 pfd
= xcalloc(socklist
->nr
, sizeof(struct pollfd
));
1142 for (i
= 0; i
< socklist
->nr
; i
++) {
1143 pfd
[i
].fd
= socklist
->list
[i
];
1144 pfd
[i
].events
= POLLIN
;
1147 signal(SIGCHLD
, child_handler
);
1152 check_dead_children();
1154 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1155 if (errno
!= EINTR
) {
1156 logerror("Poll failed, resuming: %s",
1163 for (i
= 0; i
< socklist
->nr
; i
++) {
1164 if (pfd
[i
].revents
& POLLIN
) {
1167 struct sockaddr_in sai
;
1169 struct sockaddr_in6 sai6
;
1172 socklen_t sslen
= sizeof(ss
);
1173 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1181 die_errno("accept returned");
1184 handle(incoming
, &ss
.sa
, sslen
);
1190 #ifdef NO_POSIX_GOODIES
1194 static void drop_privileges(struct credentials
*cred
)
1199 static struct credentials
*prepare_credentials(const char *user_name
,
1200 const char *group_name
)
1202 die("--user not supported on this platform");
1207 struct credentials
{
1208 struct passwd
*pass
;
1212 static void drop_privileges(struct credentials
*cred
)
1214 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1215 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1216 die("cannot drop privileges");
1219 static struct credentials
*prepare_credentials(const char *user_name
,
1220 const char *group_name
)
1222 static struct credentials c
;
1224 c
.pass
= getpwnam(user_name
);
1226 die("user not found - %s", user_name
);
1229 c
.gid
= c
.pass
->pw_gid
;
1231 struct group
*group
= getgrnam(group_name
);
1233 die("group not found - %s", group_name
);
1235 c
.gid
= group
->gr_gid
;
1242 static int serve(struct string_list
*listen_addr
, int listen_port
,
1243 struct credentials
*cred
)
1245 struct socketlist socklist
= { NULL
, 0, 0 };
1247 socksetup(listen_addr
, listen_port
, &socklist
);
1248 if (socklist
.nr
== 0)
1249 die("unable to allocate any listen sockets on port %u",
1252 drop_privileges(cred
);
1254 loginfo("Ready to rumble");
1256 return service_loop(&socklist
);
1259 int cmd_main(int argc
, const char **argv
)
1261 int listen_port
= 0;
1262 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1263 int serve_mode
= 0, inetd_mode
= 0;
1264 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1266 struct credentials
*cred
= NULL
;
1269 for (i
= 1; i
< argc
; i
++) {
1270 const char *arg
= argv
[i
];
1273 if (skip_prefix(arg
, "--listen=", &v
)) {
1274 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1277 if (skip_prefix(arg
, "--port=", &v
)) {
1280 n
= strtoul(v
, &end
, 0);
1286 if (!strcmp(arg
, "--serve")) {
1290 if (!strcmp(arg
, "--inetd")) {
1295 if (!strcmp(arg
, "--verbose")) {
1299 if (!strcmp(arg
, "--syslog")) {
1303 if (!strcmp(arg
, "--export-all")) {
1304 export_all_trees
= 1;
1307 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1311 if (skip_prefix(arg
, "--timeout=", &v
)) {
1315 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1316 init_timeout
= atoi(v
);
1319 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1320 max_connections
= atoi(v
);
1321 if (max_connections
< 0)
1322 max_connections
= 0; /* unlimited */
1325 if (!strcmp(arg
, "--strict-paths")) {
1329 if (skip_prefix(arg
, "--base-path=", &v
)) {
1333 if (!strcmp(arg
, "--base-path-relaxed")) {
1334 base_path_relaxed
= 1;
1337 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1338 interpolated_path
= v
;
1341 if (!strcmp(arg
, "--reuseaddr")) {
1345 if (!strcmp(arg
, "--user-path")) {
1349 if (skip_prefix(arg
, "--user-path=", &v
)) {
1353 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1357 if (!strcmp(arg
, "--detach")) {
1362 if (skip_prefix(arg
, "--user=", &v
)) {
1366 if (skip_prefix(arg
, "--group=", &v
)) {
1370 if (skip_prefix(arg
, "--enable=", &v
)) {
1371 enable_service(v
, 1);
1374 if (skip_prefix(arg
, "--disable=", &v
)) {
1375 enable_service(v
, 0);
1378 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1379 make_service_overridable(v
, 1);
1382 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1383 make_service_overridable(v
, 0);
1386 if (!strcmp(arg
, "--informative-errors")) {
1387 informative_errors
= 1;
1390 if (!strcmp(arg
, "--no-informative-errors")) {
1391 informative_errors
= 0;
1394 if (!strcmp(arg
, "--")) {
1395 ok_paths
= &argv
[i
+1];
1397 } else if (arg
[0] != '-') {
1398 ok_paths
= &argv
[i
];
1402 usage(daemon_usage
);
1406 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1407 set_die_routine(daemon_die
);
1409 /* avoid splitting a message in the middle */
1410 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1412 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1413 die("--detach, --user and --group are incompatible with --inetd");
1415 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1416 die("--listen= and --port= are incompatible with --inetd");
1417 else if (listen_port
== 0)
1418 listen_port
= DEFAULT_GIT_PORT
;
1420 if (group_name
&& !user_name
)
1421 die("--group supplied without --user");
1424 cred
= prepare_credentials(user_name
, group_name
);
1426 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1427 die("option --strict-paths requires a whitelist");
1429 if (base_path
&& !is_directory(base_path
))
1430 die("base-path '%s' does not exist or is not a directory",
1434 if (!freopen("/dev/null", "w", stderr
))
1435 die_errno("failed to redirect stderr to /dev/null");
1438 if (inetd_mode
|| serve_mode
)
1443 die("--detach not supported on this platform");
1447 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1449 /* prepare argv for serving-processes */
1450 argv_array_push(&cld_argv
, argv
[0]); /* git-daemon */
1451 argv_array_push(&cld_argv
, "--serve");
1452 for (i
= 1; i
< argc
; ++i
)
1453 argv_array_push(&cld_argv
, argv
[i
]);
1455 return serve(&listen_addr
, listen_port
, cred
);