4 #include "run-command.h"
6 #include "string-list.h"
9 #define HOST_NAME_MAX 256
13 #define initgroups(x, y) (0) /* nothing */
16 static int log_syslog
;
19 static int informative_errors
;
21 static const char daemon_usage
[] =
22 "git daemon [--verbose] [--syslog] [--export-all]\n"
23 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
24 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
25 " [--user-path | --user-path=<path>]\n"
26 " [--interpolated-path=<path>]\n"
27 " [--reuseaddr] [--pid-file=<file>]\n"
28 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
29 " [--access-hook=<path>]\n"
30 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
31 " [--detach] [--user=<user> [--group=<group>]]\n"
34 /* List of acceptable pathname prefixes */
35 static char **ok_paths
;
36 static int strict_paths
;
38 /* If this is set, git-daemon-export-ok is not required */
39 static int export_all_trees
;
41 /* Take all paths relative to this one if non-NULL */
42 static const char *base_path
;
43 static const char *interpolated_path
;
44 static int base_path_relaxed
;
46 /* If defined, ~user notation is allowed and the string is inserted
47 * after ~user/. E.g. a request to git://host/~alice/frotz would
48 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
50 static const char *user_path
;
52 /* Timeout, and initial timeout */
53 static unsigned int timeout
;
54 static unsigned int init_timeout
;
57 struct strbuf hostname
;
58 struct strbuf canon_hostname
;
59 struct strbuf ip_address
;
60 struct strbuf tcp_port
;
61 unsigned int hostname_lookup_done
:1;
62 unsigned int saw_extended_args
:1;
65 static void lookup_hostname(struct hostinfo
*hi
);
67 static const char *get_canon_hostname(struct hostinfo
*hi
)
70 return hi
->canon_hostname
.buf
;
73 static const char *get_ip_address(struct hostinfo
*hi
)
76 return hi
->ip_address
.buf
;
79 static void logreport(int priority
, const char *err
, va_list params
)
83 vsnprintf(buf
, sizeof(buf
), err
, params
);
84 syslog(priority
, "%s", buf
);
87 * Since stderr is set to buffered mode, the
88 * logging of different processes will not overlap
89 * unless they overflow the (rather big) buffers.
91 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
92 vfprintf(stderr
, err
, params
);
98 __attribute__((format (printf
, 1, 2)))
99 static void logerror(const char *err
, ...)
102 va_start(params
, err
);
103 logreport(LOG_ERR
, err
, params
);
107 __attribute__((format (printf
, 1, 2)))
108 static void loginfo(const char *err
, ...)
113 va_start(params
, err
);
114 logreport(LOG_INFO
, err
, params
);
118 static void NORETURN
daemon_die(const char *err
, va_list params
)
120 logreport(LOG_ERR
, err
, params
);
124 struct expand_path_context
{
125 const char *directory
;
126 struct hostinfo
*hostinfo
;
129 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
131 struct expand_path_context
*context
= ctx
;
132 struct hostinfo
*hi
= context
->hostinfo
;
134 switch (placeholder
[0]) {
136 strbuf_addbuf(sb
, &hi
->hostname
);
139 if (placeholder
[1] == 'H') {
140 strbuf_addstr(sb
, get_canon_hostname(hi
));
145 if (placeholder
[1] == 'P') {
146 strbuf_addstr(sb
, get_ip_address(hi
));
151 strbuf_addbuf(sb
, &hi
->tcp_port
);
154 strbuf_addstr(sb
, context
->directory
);
160 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
162 static char rpath
[PATH_MAX
];
163 static char interp_path
[PATH_MAX
];
170 if (daemon_avoid_alias(dir
)) {
171 logerror("'%s': aliased", dir
);
177 logerror("'%s': User-path not allowed", dir
);
181 /* Got either "~alice" or "~alice/foo";
182 * rewrite them to "~alice/%s" or
185 int namlen
, restlen
= strlen(dir
);
186 const char *slash
= strchr(dir
, '/');
188 slash
= dir
+ restlen
;
189 namlen
= slash
- dir
;
191 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
192 rlen
= snprintf(rpath
, sizeof(rpath
), "%.*s/%s%.*s",
193 namlen
, dir
, user_path
, restlen
, slash
);
194 if (rlen
>= sizeof(rpath
)) {
195 logerror("user-path too large: %s", rpath
);
201 else if (interpolated_path
&& hi
->saw_extended_args
) {
202 struct strbuf expanded_path
= STRBUF_INIT
;
203 struct expand_path_context context
;
205 context
.directory
= directory
;
206 context
.hostinfo
= hi
;
209 /* Allow only absolute */
210 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
214 strbuf_expand(&expanded_path
, interpolated_path
,
215 expand_path
, &context
);
217 rlen
= strlcpy(interp_path
, expanded_path
.buf
,
218 sizeof(interp_path
));
219 if (rlen
>= sizeof(interp_path
)) {
220 logerror("interpolated path too large: %s",
225 strbuf_release(&expanded_path
);
226 loginfo("Interpolated dir '%s'", interp_path
);
230 else if (base_path
) {
232 /* Allow only absolute */
233 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
236 rlen
= snprintf(rpath
, sizeof(rpath
), "%s%s", base_path
, dir
);
237 if (rlen
>= sizeof(rpath
)) {
238 logerror("base-path too large: %s", rpath
);
244 path
= enter_repo(dir
, strict_paths
);
245 if (!path
&& base_path
&& base_path_relaxed
) {
247 * if we fail and base_path_relaxed is enabled, try without
248 * prefixing the base path
251 path
= enter_repo(dir
, strict_paths
);
255 logerror("'%s' does not appear to be a git repository", dir
);
259 if ( ok_paths
&& *ok_paths
) {
261 int pathlen
= strlen(path
);
263 /* The validation is done on the paths after enter_repo
264 * appends optional {.git,.git/.git} and friends, but
265 * it does not use getcwd(). So if your /pub is
266 * a symlink to /mnt/pub, you can whitelist /pub and
267 * do not have to say /mnt/pub.
270 for ( pp
= ok_paths
; *pp
; pp
++ ) {
271 int len
= strlen(*pp
);
272 if (len
<= pathlen
&&
273 !memcmp(*pp
, path
, len
) &&
274 (path
[len
] == '\0' ||
275 (!strict_paths
&& path
[len
] == '/')))
280 /* be backwards compatible */
285 logerror("'%s': not in whitelist", path
);
286 return NULL
; /* Fallthrough. Deny by default */
289 typedef int (*daemon_service_fn
)(void);
290 struct daemon_service
{
292 const char *config_name
;
293 daemon_service_fn fn
;
298 static int daemon_error(const char *dir
, const char *msg
)
300 if (!informative_errors
)
301 msg
= "access denied or repository not exported";
302 packet_write(1, "ERR %s: %s", msg
, dir
);
306 static const char *access_hook
;
308 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
309 const char *path
, struct hostinfo
*hi
)
311 struct child_process child
= CHILD_PROCESS_INIT
;
312 struct strbuf buf
= STRBUF_INIT
;
314 const char **arg
= argv
;
318 *arg
++ = access_hook
;
319 *arg
++ = service
->name
;
321 *arg
++ = hi
->hostname
.buf
;
322 *arg
++ = get_canon_hostname(hi
);
323 *arg
++ = get_ip_address(hi
);
324 *arg
++ = hi
->tcp_port
.buf
;
332 if (start_command(&child
)) {
333 logerror("daemon access hook '%s' failed to start",
337 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
338 logerror("failed to read from pipe to daemon access hook '%s'",
343 if (close(child
.out
) < 0) {
344 logerror("failed to close pipe to daemon access hook '%s'",
348 if (finish_command(&child
))
352 strbuf_release(&buf
);
359 strbuf_addstr(&buf
, "service rejected");
360 eol
= strchr(buf
.buf
, '\n');
364 daemon_error(dir
, buf
.buf
);
365 strbuf_release(&buf
);
369 static int run_service(const char *dir
, struct daemon_service
*service
,
373 int enabled
= service
->enabled
;
374 struct strbuf var
= STRBUF_INIT
;
376 loginfo("Request %s for '%s'", service
->name
, dir
);
378 if (!enabled
&& !service
->overridable
) {
379 logerror("'%s': service not enabled.", service
->name
);
381 return daemon_error(dir
, "service not enabled");
384 if (!(path
= path_ok(dir
, hi
)))
385 return daemon_error(dir
, "no such repository");
388 * Security on the cheap.
390 * We want a readable HEAD, usable "objects" directory, and
391 * a "git-daemon-export-ok" flag that says that the other side
392 * is ok with us doing this.
394 * path_ok() uses enter_repo() and does whitelist checking.
395 * We only need to make sure the repository is exported.
398 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
399 logerror("'%s': repository not exported.", path
);
401 return daemon_error(dir
, "repository not exported");
404 if (service
->overridable
) {
405 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
406 git_config_get_bool(var
.buf
, &enabled
);
407 strbuf_release(&var
);
410 logerror("'%s': service not enabled for '%s'",
411 service
->name
, path
);
413 return daemon_error(dir
, "service not enabled");
417 * Optionally, a hook can choose to deny access to the
418 * repository depending on the phase of the moon.
420 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
424 * We'll ignore SIGTERM from now on, we have a
427 signal(SIGTERM
, SIG_IGN
);
429 return service
->fn();
432 static void copy_to_log(int fd
)
434 struct strbuf line
= STRBUF_INIT
;
437 fp
= fdopen(fd
, "r");
439 logerror("fdopen of error channel failed");
444 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
445 logerror("%s", line
.buf
);
446 strbuf_setlen(&line
, 0);
449 strbuf_release(&line
);
453 static int run_service_command(const char **argv
)
455 struct child_process cld
= CHILD_PROCESS_INIT
;
460 if (start_command(&cld
))
466 copy_to_log(cld
.err
);
468 return finish_command(&cld
);
471 static int upload_pack(void)
473 /* Timeout as string */
474 char timeout_buf
[64];
475 const char *argv
[] = { "upload-pack", "--strict", NULL
, ".", NULL
};
477 argv
[2] = timeout_buf
;
479 snprintf(timeout_buf
, sizeof timeout_buf
, "--timeout=%u", timeout
);
480 return run_service_command(argv
);
483 static int upload_archive(void)
485 static const char *argv
[] = { "upload-archive", ".", NULL
};
486 return run_service_command(argv
);
489 static int receive_pack(void)
491 static const char *argv
[] = { "receive-pack", ".", NULL
};
492 return run_service_command(argv
);
495 static struct daemon_service daemon_service
[] = {
496 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
497 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
498 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
501 static void enable_service(const char *name
, int ena
)
504 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
505 if (!strcmp(daemon_service
[i
].name
, name
)) {
506 daemon_service
[i
].enabled
= ena
;
510 die("No such service %s", name
);
513 static void make_service_overridable(const char *name
, int ena
)
516 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
517 if (!strcmp(daemon_service
[i
].name
, name
)) {
518 daemon_service
[i
].overridable
= ena
;
522 die("No such service %s", name
);
525 static void parse_host_and_port(char *hostport
, char **host
,
528 if (*hostport
== '[') {
531 end
= strchr(hostport
, ']');
533 die("Invalid request ('[' without ']')");
535 *host
= hostport
+ 1;
538 else if (end
[1] == ':')
541 die("Garbage after end of host part");
544 *port
= strrchr(hostport
, ':');
553 * Sanitize a string from the client so that it's OK to be inserted into a
554 * filesystem path. Specifically, we disallow slashes, runs of "..", and
555 * trailing and leading dots, which means that the client cannot escape
556 * our base path via ".." traversal.
558 static void sanitize_client(struct strbuf
*out
, const char *in
)
563 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
565 strbuf_addch(out
, *in
);
568 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
569 strbuf_setlen(out
, out
->len
- 1);
573 * Like sanitize_client, but we also perform any canonicalization
574 * to make life easier on the admin.
576 static void canonicalize_client(struct strbuf
*out
, const char *in
)
578 sanitize_client(out
, in
);
583 * Read the host as supplied by the client connection.
585 static void parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
589 char *end
= extra_args
+ buflen
;
591 if (extra_args
< end
&& *extra_args
) {
592 hi
->saw_extended_args
= 1;
593 if (strncasecmp("host=", extra_args
, 5) == 0) {
594 val
= extra_args
+ 5;
595 vallen
= strlen(val
) + 1;
597 /* Split <host>:<port> at colon. */
600 parse_host_and_port(val
, &host
, &port
);
602 sanitize_client(&hi
->tcp_port
, port
);
603 canonicalize_client(&hi
->hostname
, host
);
604 hi
->hostname_lookup_done
= 0;
607 /* On to the next one */
608 extra_args
= val
+ vallen
;
610 if (extra_args
< end
&& *extra_args
)
611 die("Invalid request");
616 * Locate canonical hostname and its IP address.
618 static void lookup_hostname(struct hostinfo
*hi
)
620 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
622 struct addrinfo hints
;
625 static char addrbuf
[HOST_NAME_MAX
+ 1];
627 memset(&hints
, 0, sizeof(hints
));
628 hints
.ai_flags
= AI_CANONNAME
;
630 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
632 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
634 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
635 addrbuf
, sizeof(addrbuf
));
636 strbuf_addstr(&hi
->ip_address
, addrbuf
);
638 if (ai
->ai_canonname
)
639 sanitize_client(&hi
->canon_hostname
,
642 strbuf_addbuf(&hi
->canon_hostname
,
648 struct hostent
*hent
;
649 struct sockaddr_in sa
;
651 static char addrbuf
[HOST_NAME_MAX
+ 1];
653 hent
= gethostbyname(hi
->hostname
.buf
);
655 ap
= hent
->h_addr_list
;
656 memset(&sa
, 0, sizeof sa
);
657 sa
.sin_family
= hent
->h_addrtype
;
658 sa
.sin_port
= htons(0);
659 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
661 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
662 addrbuf
, sizeof(addrbuf
));
664 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
665 strbuf_addstr(&hi
->ip_address
, addrbuf
);
668 hi
->hostname_lookup_done
= 1;
672 static void hostinfo_init(struct hostinfo
*hi
)
674 memset(hi
, 0, sizeof(*hi
));
675 strbuf_init(&hi
->hostname
, 0);
676 strbuf_init(&hi
->canon_hostname
, 0);
677 strbuf_init(&hi
->ip_address
, 0);
678 strbuf_init(&hi
->tcp_port
, 0);
681 static void hostinfo_clear(struct hostinfo
*hi
)
683 strbuf_release(&hi
->hostname
);
684 strbuf_release(&hi
->canon_hostname
);
685 strbuf_release(&hi
->ip_address
);
686 strbuf_release(&hi
->tcp_port
);
689 static int execute(void)
691 char *line
= packet_buffer
;
693 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
699 loginfo("Connection from %s:%s", addr
, port
);
701 alarm(init_timeout
? init_timeout
: timeout
);
702 pktlen
= packet_read(0, NULL
, NULL
, packet_buffer
, sizeof(packet_buffer
), 0);
707 loginfo("Extended attributes (%d bytes) exist <%.*s>",
709 (int) pktlen
- len
, line
+ len
+ 1);
710 if (len
&& line
[len
-1] == '\n') {
716 parse_host_arg(&hi
, line
+ len
+ 1, pktlen
- len
- 1);
718 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
719 struct daemon_service
*s
= &(daemon_service
[i
]);
722 if (skip_prefix(line
, "git-", &arg
) &&
723 skip_prefix(arg
, s
->name
, &arg
) &&
726 * Note: The directory here is probably context sensitive,
727 * and might depend on the actual service being performed.
729 int rc
= run_service(arg
, s
, &hi
);
736 logerror("Protocol error: '%s'", line
);
740 static int addrcmp(const struct sockaddr_storage
*s1
,
741 const struct sockaddr_storage
*s2
)
743 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
744 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
746 if (sa1
->sa_family
!= sa2
->sa_family
)
747 return sa1
->sa_family
- sa2
->sa_family
;
748 if (sa1
->sa_family
== AF_INET
)
749 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
750 &((struct sockaddr_in
*)s2
)->sin_addr
,
751 sizeof(struct in_addr
));
753 if (sa1
->sa_family
== AF_INET6
)
754 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
755 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
756 sizeof(struct in6_addr
));
761 static int max_connections
= 32;
763 static unsigned int live_children
;
765 static struct child
{
767 struct child_process cld
;
768 struct sockaddr_storage address
;
771 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
773 struct child
*newborn
, **cradle
;
775 newborn
= xcalloc(1, sizeof(*newborn
));
777 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
778 memcpy(&newborn
->address
, addr
, addrlen
);
779 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
780 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
782 newborn
->next
= *cradle
;
787 * This gets called if the number of connections grows
788 * past "max_connections".
790 * We kill the newest connection from a duplicate IP.
792 static void kill_some_child(void)
794 const struct child
*blanket
, *next
;
796 if (!(blanket
= firstborn
))
799 for (; (next
= blanket
->next
); blanket
= next
)
800 if (!addrcmp(&blanket
->address
, &next
->address
)) {
801 kill(blanket
->cld
.pid
, SIGTERM
);
806 static void check_dead_children(void)
811 struct child
**cradle
, *blanket
;
812 for (cradle
= &firstborn
; (blanket
= *cradle
);)
813 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
814 const char *dead
= "";
816 dead
= " (with error)";
817 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
819 /* remove the child */
820 *cradle
= blanket
->next
;
822 child_process_clear(&blanket
->cld
);
825 cradle
= &blanket
->next
;
828 static struct argv_array cld_argv
= ARGV_ARRAY_INIT
;
829 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
831 struct child_process cld
= CHILD_PROCESS_INIT
;
833 if (max_connections
&& live_children
>= max_connections
) {
835 sleep(1); /* give it some time to die */
836 check_dead_children();
837 if (live_children
>= max_connections
) {
839 logerror("Too many children, dropping connection");
844 if (addr
->sa_family
== AF_INET
) {
846 struct sockaddr_in
*sin_addr
= (void *) addr
;
847 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
848 argv_array_pushf(&cld
.env_array
, "REMOTE_ADDR=%s", buf
);
849 argv_array_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
850 ntohs(sin_addr
->sin_port
));
852 } else if (addr
->sa_family
== AF_INET6
) {
854 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
855 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
856 argv_array_pushf(&cld
.env_array
, "REMOTE_ADDR=[%s]", buf
);
857 argv_array_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
858 ntohs(sin6_addr
->sin6_port
));
862 cld
.argv
= cld_argv
.argv
;
864 cld
.out
= dup(incoming
);
866 if (start_command(&cld
))
867 logerror("unable to fork");
869 add_child(&cld
, addr
, addrlen
);
872 static void child_handler(int signo
)
875 * Otherwise empty handler because systemcalls will get interrupted
876 * upon signal receipt
877 * SysV needs the handler to be rearmed
879 signal(SIGCHLD
, child_handler
);
882 static int set_reuse_addr(int sockfd
)
888 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
898 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
901 static char ip
[INET_ADDRSTRLEN
];
903 static char ip
[INET6_ADDRSTRLEN
];
909 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
913 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
916 xsnprintf(ip
, sizeof(ip
), "<unknown>");
923 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
926 char pbuf
[NI_MAXSERV
];
927 struct addrinfo hints
, *ai0
, *ai
;
931 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
932 memset(&hints
, 0, sizeof(hints
));
933 hints
.ai_family
= AF_UNSPEC
;
934 hints
.ai_socktype
= SOCK_STREAM
;
935 hints
.ai_protocol
= IPPROTO_TCP
;
936 hints
.ai_flags
= AI_PASSIVE
;
938 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
940 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
944 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
947 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
950 if (sockfd
>= FD_SETSIZE
) {
951 logerror("Socket descriptor too large");
957 if (ai
->ai_family
== AF_INET6
) {
959 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
961 /* Note: error is not fatal */
965 if (set_reuse_addr(sockfd
)) {
966 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
971 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
972 logerror("Could not bind to %s: %s",
973 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
976 continue; /* not fatal */
978 if (listen(sockfd
, 5) < 0) {
979 logerror("Could not listen to %s: %s",
980 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
983 continue; /* not fatal */
986 flags
= fcntl(sockfd
, F_GETFD
, 0);
988 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
990 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
991 socklist
->list
[socklist
->nr
++] = sockfd
;
1002 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1004 struct sockaddr_in sin
;
1008 memset(&sin
, 0, sizeof sin
);
1009 sin
.sin_family
= AF_INET
;
1010 sin
.sin_port
= htons(listen_port
);
1013 /* Well, host better be an IP address here. */
1014 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1017 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1020 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1024 if (set_reuse_addr(sockfd
)) {
1025 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1030 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1031 logerror("Could not bind to %s: %s",
1032 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1038 if (listen(sockfd
, 5) < 0) {
1039 logerror("Could not listen to %s: %s",
1040 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1046 flags
= fcntl(sockfd
, F_GETFD
, 0);
1048 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1050 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1051 socklist
->list
[socklist
->nr
++] = sockfd
;
1057 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1059 if (!listen_addr
->nr
)
1060 setup_named_sock(NULL
, listen_port
, socklist
);
1063 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1064 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1065 listen_port
, socklist
);
1068 logerror("unable to allocate any listen sockets for host %s on port %u",
1069 listen_addr
->items
[i
].string
, listen_port
);
1074 static int service_loop(struct socketlist
*socklist
)
1079 pfd
= xcalloc(socklist
->nr
, sizeof(struct pollfd
));
1081 for (i
= 0; i
< socklist
->nr
; i
++) {
1082 pfd
[i
].fd
= socklist
->list
[i
];
1083 pfd
[i
].events
= POLLIN
;
1086 signal(SIGCHLD
, child_handler
);
1091 check_dead_children();
1093 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1094 if (errno
!= EINTR
) {
1095 logerror("Poll failed, resuming: %s",
1102 for (i
= 0; i
< socklist
->nr
; i
++) {
1103 if (pfd
[i
].revents
& POLLIN
) {
1106 struct sockaddr_in sai
;
1108 struct sockaddr_in6 sai6
;
1111 socklen_t sslen
= sizeof(ss
);
1112 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1120 die_errno("accept returned");
1123 handle(incoming
, &ss
.sa
, sslen
);
1129 #ifdef NO_POSIX_GOODIES
1133 static void drop_privileges(struct credentials
*cred
)
1138 static struct credentials
*prepare_credentials(const char *user_name
,
1139 const char *group_name
)
1141 die("--user not supported on this platform");
1146 struct credentials
{
1147 struct passwd
*pass
;
1151 static void drop_privileges(struct credentials
*cred
)
1153 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1154 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1155 die("cannot drop privileges");
1158 static struct credentials
*prepare_credentials(const char *user_name
,
1159 const char *group_name
)
1161 static struct credentials c
;
1163 c
.pass
= getpwnam(user_name
);
1165 die("user not found - %s", user_name
);
1168 c
.gid
= c
.pass
->pw_gid
;
1170 struct group
*group
= getgrnam(group_name
);
1172 die("group not found - %s", group_name
);
1174 c
.gid
= group
->gr_gid
;
1181 static int serve(struct string_list
*listen_addr
, int listen_port
,
1182 struct credentials
*cred
)
1184 struct socketlist socklist
= { NULL
, 0, 0 };
1186 socksetup(listen_addr
, listen_port
, &socklist
);
1187 if (socklist
.nr
== 0)
1188 die("unable to allocate any listen sockets on port %u",
1191 drop_privileges(cred
);
1193 loginfo("Ready to rumble");
1195 return service_loop(&socklist
);
1198 int main(int argc
, char **argv
)
1200 int listen_port
= 0;
1201 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1202 int serve_mode
= 0, inetd_mode
= 0;
1203 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1205 struct credentials
*cred
= NULL
;
1208 git_setup_gettext();
1210 git_extract_argv0_path(argv
[0]);
1212 for (i
= 1; i
< argc
; i
++) {
1213 char *arg
= argv
[i
];
1216 if (skip_prefix(arg
, "--listen=", &v
)) {
1217 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1220 if (skip_prefix(arg
, "--port=", &v
)) {
1223 n
= strtoul(v
, &end
, 0);
1229 if (!strcmp(arg
, "--serve")) {
1233 if (!strcmp(arg
, "--inetd")) {
1238 if (!strcmp(arg
, "--verbose")) {
1242 if (!strcmp(arg
, "--syslog")) {
1246 if (!strcmp(arg
, "--export-all")) {
1247 export_all_trees
= 1;
1250 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1254 if (skip_prefix(arg
, "--timeout=", &v
)) {
1258 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1259 init_timeout
= atoi(v
);
1262 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1263 max_connections
= atoi(v
);
1264 if (max_connections
< 0)
1265 max_connections
= 0; /* unlimited */
1268 if (!strcmp(arg
, "--strict-paths")) {
1272 if (skip_prefix(arg
, "--base-path=", &v
)) {
1276 if (!strcmp(arg
, "--base-path-relaxed")) {
1277 base_path_relaxed
= 1;
1280 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1281 interpolated_path
= v
;
1284 if (!strcmp(arg
, "--reuseaddr")) {
1288 if (!strcmp(arg
, "--user-path")) {
1292 if (skip_prefix(arg
, "--user-path=", &v
)) {
1296 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1300 if (!strcmp(arg
, "--detach")) {
1305 if (skip_prefix(arg
, "--user=", &v
)) {
1309 if (skip_prefix(arg
, "--group=", &v
)) {
1313 if (skip_prefix(arg
, "--enable=", &v
)) {
1314 enable_service(v
, 1);
1317 if (skip_prefix(arg
, "--disable=", &v
)) {
1318 enable_service(v
, 0);
1321 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1322 make_service_overridable(v
, 1);
1325 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1326 make_service_overridable(v
, 0);
1329 if (!strcmp(arg
, "--informative-errors")) {
1330 informative_errors
= 1;
1333 if (!strcmp(arg
, "--no-informative-errors")) {
1334 informative_errors
= 0;
1337 if (!strcmp(arg
, "--")) {
1338 ok_paths
= &argv
[i
+1];
1340 } else if (arg
[0] != '-') {
1341 ok_paths
= &argv
[i
];
1345 usage(daemon_usage
);
1349 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1350 set_die_routine(daemon_die
);
1352 /* avoid splitting a message in the middle */
1353 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1355 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1356 die("--detach, --user and --group are incompatible with --inetd");
1358 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1359 die("--listen= and --port= are incompatible with --inetd");
1360 else if (listen_port
== 0)
1361 listen_port
= DEFAULT_GIT_PORT
;
1363 if (group_name
&& !user_name
)
1364 die("--group supplied without --user");
1367 cred
= prepare_credentials(user_name
, group_name
);
1369 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1370 die("option --strict-paths requires a whitelist");
1372 if (base_path
&& !is_directory(base_path
))
1373 die("base-path '%s' does not exist or is not a directory",
1377 if (!freopen("/dev/null", "w", stderr
))
1378 die_errno("failed to redirect stderr to /dev/null");
1381 if (inetd_mode
|| serve_mode
)
1386 die("--detach not supported on this platform");
1391 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1393 /* prepare argv for serving-processes */
1394 argv_array_push(&cld_argv
, argv
[0]); /* git-daemon */
1395 argv_array_push(&cld_argv
, "--serve");
1396 for (i
= 1; i
< argc
; ++i
)
1397 argv_array_push(&cld_argv
, argv
[i
]);
1399 return serve(&listen_addr
, listen_port
, cred
);