3 #include "run-command.h"
5 #include "string-list.h"
8 #define HOST_NAME_MAX 256
12 #define initgroups(x, y) (0) /* nothing */
15 static int log_syslog
;
18 static int informative_errors
;
20 static const char daemon_usage
[] =
21 "git daemon [--verbose] [--syslog] [--export-all]\n"
22 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
23 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
24 " [--user-path | --user-path=<path>]\n"
25 " [--interpolated-path=<path>]\n"
26 " [--reuseaddr] [--pid-file=<file>]\n"
27 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
28 " [--access-hook=<path>]\n"
29 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
30 " [--detach] [--user=<user> [--group=<group>]]\n"
33 /* List of acceptable pathname prefixes */
34 static const char **ok_paths
;
35 static int strict_paths
;
37 /* If this is set, git-daemon-export-ok is not required */
38 static int export_all_trees
;
40 /* Take all paths relative to this one if non-NULL */
41 static const char *base_path
;
42 static const char *interpolated_path
;
43 static int base_path_relaxed
;
45 /* If defined, ~user notation is allowed and the string is inserted
46 * after ~user/. E.g. a request to git://host/~alice/frotz would
47 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
49 static const char *user_path
;
51 /* Timeout, and initial timeout */
52 static unsigned int timeout
;
53 static unsigned int init_timeout
;
56 struct strbuf hostname
;
57 struct strbuf canon_hostname
;
58 struct strbuf ip_address
;
59 struct strbuf tcp_port
;
60 unsigned int hostname_lookup_done
:1;
61 unsigned int saw_extended_args
:1;
64 static void lookup_hostname(struct hostinfo
*hi
);
66 static const char *get_canon_hostname(struct hostinfo
*hi
)
69 return hi
->canon_hostname
.buf
;
72 static const char *get_ip_address(struct hostinfo
*hi
)
75 return hi
->ip_address
.buf
;
78 static void logreport(int priority
, const char *err
, va_list params
)
82 vsnprintf(buf
, sizeof(buf
), err
, params
);
83 syslog(priority
, "%s", buf
);
86 * Since stderr is set to buffered mode, the
87 * logging of different processes will not overlap
88 * unless they overflow the (rather big) buffers.
90 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
91 vfprintf(stderr
, err
, params
);
97 __attribute__((format (printf
, 1, 2)))
98 static void logerror(const char *err
, ...)
101 va_start(params
, err
);
102 logreport(LOG_ERR
, err
, params
);
106 __attribute__((format (printf
, 1, 2)))
107 static void loginfo(const char *err
, ...)
112 va_start(params
, err
);
113 logreport(LOG_INFO
, err
, params
);
117 static void NORETURN
daemon_die(const char *err
, va_list params
)
119 logreport(LOG_ERR
, err
, params
);
123 struct expand_path_context
{
124 const char *directory
;
125 struct hostinfo
*hostinfo
;
128 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
130 struct expand_path_context
*context
= ctx
;
131 struct hostinfo
*hi
= context
->hostinfo
;
133 switch (placeholder
[0]) {
135 strbuf_addbuf(sb
, &hi
->hostname
);
138 if (placeholder
[1] == 'H') {
139 strbuf_addstr(sb
, get_canon_hostname(hi
));
144 if (placeholder
[1] == 'P') {
145 strbuf_addstr(sb
, get_ip_address(hi
));
150 strbuf_addbuf(sb
, &hi
->tcp_port
);
153 strbuf_addstr(sb
, context
->directory
);
159 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
161 static char rpath
[PATH_MAX
];
162 static char interp_path
[PATH_MAX
];
168 if (daemon_avoid_alias(dir
)) {
169 logerror("'%s': aliased", dir
);
175 logerror("'%s': User-path not allowed", dir
);
179 /* Got either "~alice" or "~alice/foo";
180 * rewrite them to "~alice/%s" or
183 int namlen
, restlen
= strlen(dir
);
184 const char *slash
= strchr(dir
, '/');
186 slash
= dir
+ restlen
;
187 namlen
= slash
- dir
;
189 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
190 snprintf(rpath
, PATH_MAX
, "%.*s/%s%.*s",
191 namlen
, dir
, user_path
, restlen
, slash
);
195 else if (interpolated_path
&& hi
->saw_extended_args
) {
196 struct strbuf expanded_path
= STRBUF_INIT
;
197 struct expand_path_context context
;
199 context
.directory
= directory
;
200 context
.hostinfo
= hi
;
203 /* Allow only absolute */
204 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
208 strbuf_expand(&expanded_path
, interpolated_path
,
209 expand_path
, &context
);
210 strlcpy(interp_path
, expanded_path
.buf
, PATH_MAX
);
211 strbuf_release(&expanded_path
);
212 loginfo("Interpolated dir '%s'", interp_path
);
216 else if (base_path
) {
218 /* Allow only absolute */
219 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
222 snprintf(rpath
, PATH_MAX
, "%s%s", base_path
, dir
);
226 path
= enter_repo(dir
, strict_paths
);
227 if (!path
&& base_path
&& base_path_relaxed
) {
229 * if we fail and base_path_relaxed is enabled, try without
230 * prefixing the base path
233 path
= enter_repo(dir
, strict_paths
);
237 logerror("'%s' does not appear to be a git repository", dir
);
241 if ( ok_paths
&& *ok_paths
) {
243 int pathlen
= strlen(path
);
245 /* The validation is done on the paths after enter_repo
246 * appends optional {.git,.git/.git} and friends, but
247 * it does not use getcwd(). So if your /pub is
248 * a symlink to /mnt/pub, you can whitelist /pub and
249 * do not have to say /mnt/pub.
252 for ( pp
= ok_paths
; *pp
; pp
++ ) {
253 int len
= strlen(*pp
);
254 if (len
<= pathlen
&&
255 !memcmp(*pp
, path
, len
) &&
256 (path
[len
] == '\0' ||
257 (!strict_paths
&& path
[len
] == '/')))
262 /* be backwards compatible */
267 logerror("'%s': not in whitelist", path
);
268 return NULL
; /* Fallthrough. Deny by default */
271 typedef int (*daemon_service_fn
)(void);
272 struct daemon_service
{
274 const char *config_name
;
275 daemon_service_fn fn
;
280 static int daemon_error(const char *dir
, const char *msg
)
282 if (!informative_errors
)
283 msg
= "access denied or repository not exported";
284 packet_write(1, "ERR %s: %s", msg
, dir
);
288 static const char *access_hook
;
290 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
291 const char *path
, struct hostinfo
*hi
)
293 struct child_process child
= CHILD_PROCESS_INIT
;
294 struct strbuf buf
= STRBUF_INIT
;
296 const char **arg
= argv
;
300 *arg
++ = access_hook
;
301 *arg
++ = service
->name
;
303 *arg
++ = hi
->hostname
.buf
;
304 *arg
++ = get_canon_hostname(hi
);
305 *arg
++ = get_ip_address(hi
);
306 *arg
++ = hi
->tcp_port
.buf
;
314 if (start_command(&child
)) {
315 logerror("daemon access hook '%s' failed to start",
319 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
320 logerror("failed to read from pipe to daemon access hook '%s'",
325 if (close(child
.out
) < 0) {
326 logerror("failed to close pipe to daemon access hook '%s'",
330 if (finish_command(&child
))
334 strbuf_release(&buf
);
341 strbuf_addstr(&buf
, "service rejected");
342 eol
= strchr(buf
.buf
, '\n');
346 daemon_error(dir
, buf
.buf
);
347 strbuf_release(&buf
);
351 static int run_service(const char *dir
, struct daemon_service
*service
,
355 int enabled
= service
->enabled
;
356 struct strbuf var
= STRBUF_INIT
;
358 loginfo("Request %s for '%s'", service
->name
, dir
);
360 if (!enabled
&& !service
->overridable
) {
361 logerror("'%s': service not enabled.", service
->name
);
363 return daemon_error(dir
, "service not enabled");
366 if (!(path
= path_ok(dir
, hi
)))
367 return daemon_error(dir
, "no such repository");
370 * Security on the cheap.
372 * We want a readable HEAD, usable "objects" directory, and
373 * a "git-daemon-export-ok" flag that says that the other side
374 * is ok with us doing this.
376 * path_ok() uses enter_repo() and does whitelist checking.
377 * We only need to make sure the repository is exported.
380 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
381 logerror("'%s': repository not exported.", path
);
383 return daemon_error(dir
, "repository not exported");
386 if (service
->overridable
) {
387 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
388 git_config_get_bool(var
.buf
, &enabled
);
389 strbuf_release(&var
);
392 logerror("'%s': service not enabled for '%s'",
393 service
->name
, path
);
395 return daemon_error(dir
, "service not enabled");
399 * Optionally, a hook can choose to deny access to the
400 * repository depending on the phase of the moon.
402 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
406 * We'll ignore SIGTERM from now on, we have a
409 signal(SIGTERM
, SIG_IGN
);
411 return service
->fn();
414 static void copy_to_log(int fd
)
416 struct strbuf line
= STRBUF_INIT
;
419 fp
= fdopen(fd
, "r");
421 logerror("fdopen of error channel failed");
426 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
427 logerror("%s", line
.buf
);
428 strbuf_setlen(&line
, 0);
431 strbuf_release(&line
);
435 static int run_service_command(const char **argv
)
437 struct child_process cld
= CHILD_PROCESS_INIT
;
442 if (start_command(&cld
))
448 copy_to_log(cld
.err
);
450 return finish_command(&cld
);
453 static int upload_pack(void)
455 /* Timeout as string */
456 char timeout_buf
[64];
457 const char *argv
[] = { "upload-pack", "--strict", NULL
, ".", NULL
};
459 argv
[2] = timeout_buf
;
461 snprintf(timeout_buf
, sizeof timeout_buf
, "--timeout=%u", timeout
);
462 return run_service_command(argv
);
465 static int upload_archive(void)
467 static const char *argv
[] = { "upload-archive", ".", NULL
};
468 return run_service_command(argv
);
471 static int receive_pack(void)
473 static const char *argv
[] = { "receive-pack", ".", NULL
};
474 return run_service_command(argv
);
477 static struct daemon_service daemon_service
[] = {
478 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
479 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
480 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
483 static void enable_service(const char *name
, int ena
)
486 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
487 if (!strcmp(daemon_service
[i
].name
, name
)) {
488 daemon_service
[i
].enabled
= ena
;
492 die("No such service %s", name
);
495 static void make_service_overridable(const char *name
, int ena
)
498 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
499 if (!strcmp(daemon_service
[i
].name
, name
)) {
500 daemon_service
[i
].overridable
= ena
;
504 die("No such service %s", name
);
507 static void parse_host_and_port(char *hostport
, char **host
,
510 if (*hostport
== '[') {
513 end
= strchr(hostport
, ']');
515 die("Invalid request ('[' without ']')");
517 *host
= hostport
+ 1;
520 else if (end
[1] == ':')
523 die("Garbage after end of host part");
526 *port
= strrchr(hostport
, ':');
535 * Sanitize a string from the client so that it's OK to be inserted into a
536 * filesystem path. Specifically, we disallow slashes, runs of "..", and
537 * trailing and leading dots, which means that the client cannot escape
538 * our base path via ".." traversal.
540 static void sanitize_client(struct strbuf
*out
, const char *in
)
545 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
547 strbuf_addch(out
, *in
);
550 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
551 strbuf_setlen(out
, out
->len
- 1);
555 * Like sanitize_client, but we also perform any canonicalization
556 * to make life easier on the admin.
558 static void canonicalize_client(struct strbuf
*out
, const char *in
)
560 sanitize_client(out
, in
);
565 * Read the host as supplied by the client connection.
567 static void parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
571 char *end
= extra_args
+ buflen
;
573 if (extra_args
< end
&& *extra_args
) {
574 hi
->saw_extended_args
= 1;
575 if (strncasecmp("host=", extra_args
, 5) == 0) {
576 val
= extra_args
+ 5;
577 vallen
= strlen(val
) + 1;
579 /* Split <host>:<port> at colon. */
582 parse_host_and_port(val
, &host
, &port
);
584 sanitize_client(&hi
->tcp_port
, port
);
585 canonicalize_client(&hi
->hostname
, host
);
586 hi
->hostname_lookup_done
= 0;
589 /* On to the next one */
590 extra_args
= val
+ vallen
;
592 if (extra_args
< end
&& *extra_args
)
593 die("Invalid request");
598 * Locate canonical hostname and its IP address.
600 static void lookup_hostname(struct hostinfo
*hi
)
602 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
604 struct addrinfo hints
;
607 static char addrbuf
[HOST_NAME_MAX
+ 1];
609 memset(&hints
, 0, sizeof(hints
));
610 hints
.ai_flags
= AI_CANONNAME
;
612 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
614 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
616 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
617 addrbuf
, sizeof(addrbuf
));
618 strbuf_addstr(&hi
->ip_address
, addrbuf
);
620 if (ai
->ai_canonname
)
621 sanitize_client(&hi
->canon_hostname
,
624 strbuf_addbuf(&hi
->canon_hostname
,
630 struct hostent
*hent
;
631 struct sockaddr_in sa
;
633 static char addrbuf
[HOST_NAME_MAX
+ 1];
635 hent
= gethostbyname(hi
->hostname
.buf
);
637 ap
= hent
->h_addr_list
;
638 memset(&sa
, 0, sizeof sa
);
639 sa
.sin_family
= hent
->h_addrtype
;
640 sa
.sin_port
= htons(0);
641 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
643 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
644 addrbuf
, sizeof(addrbuf
));
646 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
647 strbuf_addstr(&hi
->ip_address
, addrbuf
);
650 hi
->hostname_lookup_done
= 1;
654 static void hostinfo_init(struct hostinfo
*hi
)
656 memset(hi
, 0, sizeof(*hi
));
657 strbuf_init(&hi
->hostname
, 0);
658 strbuf_init(&hi
->canon_hostname
, 0);
659 strbuf_init(&hi
->ip_address
, 0);
660 strbuf_init(&hi
->tcp_port
, 0);
663 static void hostinfo_clear(struct hostinfo
*hi
)
665 strbuf_release(&hi
->hostname
);
666 strbuf_release(&hi
->canon_hostname
);
667 strbuf_release(&hi
->ip_address
);
668 strbuf_release(&hi
->tcp_port
);
671 static void set_keep_alive(int sockfd
)
675 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0)
676 logerror("unable to set SO_KEEPALIVE on socket: %s",
680 static int execute(void)
682 char *line
= packet_buffer
;
684 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
690 loginfo("Connection from %s:%s", addr
, port
);
693 alarm(init_timeout
? init_timeout
: timeout
);
694 pktlen
= packet_read(0, NULL
, NULL
, packet_buffer
, sizeof(packet_buffer
), 0);
699 loginfo("Extended attributes (%d bytes) exist <%.*s>",
701 (int) pktlen
- len
, line
+ len
+ 1);
702 if (len
&& line
[len
-1] == '\n') {
708 parse_host_arg(&hi
, line
+ len
+ 1, pktlen
- len
- 1);
710 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
711 struct daemon_service
*s
= &(daemon_service
[i
]);
714 if (skip_prefix(line
, "git-", &arg
) &&
715 skip_prefix(arg
, s
->name
, &arg
) &&
718 * Note: The directory here is probably context sensitive,
719 * and might depend on the actual service being performed.
721 int rc
= run_service(arg
, s
, &hi
);
728 logerror("Protocol error: '%s'", line
);
732 static int addrcmp(const struct sockaddr_storage
*s1
,
733 const struct sockaddr_storage
*s2
)
735 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
736 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
738 if (sa1
->sa_family
!= sa2
->sa_family
)
739 return sa1
->sa_family
- sa2
->sa_family
;
740 if (sa1
->sa_family
== AF_INET
)
741 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
742 &((struct sockaddr_in
*)s2
)->sin_addr
,
743 sizeof(struct in_addr
));
745 if (sa1
->sa_family
== AF_INET6
)
746 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
747 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
748 sizeof(struct in6_addr
));
753 static int max_connections
= 32;
755 static unsigned int live_children
;
757 static struct child
{
759 struct child_process cld
;
760 struct sockaddr_storage address
;
763 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
765 struct child
*newborn
, **cradle
;
767 newborn
= xcalloc(1, sizeof(*newborn
));
769 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
770 memcpy(&newborn
->address
, addr
, addrlen
);
771 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
772 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
774 newborn
->next
= *cradle
;
779 * This gets called if the number of connections grows
780 * past "max_connections".
782 * We kill the newest connection from a duplicate IP.
784 static void kill_some_child(void)
786 const struct child
*blanket
, *next
;
788 if (!(blanket
= firstborn
))
791 for (; (next
= blanket
->next
); blanket
= next
)
792 if (!addrcmp(&blanket
->address
, &next
->address
)) {
793 kill(blanket
->cld
.pid
, SIGTERM
);
798 static void check_dead_children(void)
803 struct child
**cradle
, *blanket
;
804 for (cradle
= &firstborn
; (blanket
= *cradle
);)
805 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
806 const char *dead
= "";
808 dead
= " (with error)";
809 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
811 /* remove the child */
812 *cradle
= blanket
->next
;
814 child_process_clear(&blanket
->cld
);
817 cradle
= &blanket
->next
;
820 static struct argv_array cld_argv
= ARGV_ARRAY_INIT
;
821 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
823 struct child_process cld
= CHILD_PROCESS_INIT
;
825 if (max_connections
&& live_children
>= max_connections
) {
827 sleep(1); /* give it some time to die */
828 check_dead_children();
829 if (live_children
>= max_connections
) {
831 logerror("Too many children, dropping connection");
836 if (addr
->sa_family
== AF_INET
) {
838 struct sockaddr_in
*sin_addr
= (void *) addr
;
839 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
840 argv_array_pushf(&cld
.env_array
, "REMOTE_ADDR=%s", buf
);
841 argv_array_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
842 ntohs(sin_addr
->sin_port
));
844 } else if (addr
->sa_family
== AF_INET6
) {
846 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
847 inet_ntop(AF_INET6
, &sin6_addr
->sin6_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(sin6_addr
->sin6_port
));
854 cld
.argv
= cld_argv
.argv
;
856 cld
.out
= dup(incoming
);
858 if (start_command(&cld
))
859 logerror("unable to fork");
861 add_child(&cld
, addr
, addrlen
);
864 static void child_handler(int signo
)
867 * Otherwise empty handler because systemcalls will get interrupted
868 * upon signal receipt
869 * SysV needs the handler to be rearmed
871 signal(SIGCHLD
, child_handler
);
874 static int set_reuse_addr(int sockfd
)
880 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
890 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
893 static char ip
[INET_ADDRSTRLEN
];
895 static char ip
[INET6_ADDRSTRLEN
];
901 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
905 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
908 xsnprintf(ip
, sizeof(ip
), "<unknown>");
915 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
918 char pbuf
[NI_MAXSERV
];
919 struct addrinfo hints
, *ai0
, *ai
;
923 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
924 memset(&hints
, 0, sizeof(hints
));
925 hints
.ai_family
= AF_UNSPEC
;
926 hints
.ai_socktype
= SOCK_STREAM
;
927 hints
.ai_protocol
= IPPROTO_TCP
;
928 hints
.ai_flags
= AI_PASSIVE
;
930 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
932 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
936 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
939 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
942 if (sockfd
>= FD_SETSIZE
) {
943 logerror("Socket descriptor too large");
949 if (ai
->ai_family
== AF_INET6
) {
951 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
953 /* Note: error is not fatal */
957 if (set_reuse_addr(sockfd
)) {
958 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
963 set_keep_alive(sockfd
);
965 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
966 logerror("Could not bind to %s: %s",
967 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
970 continue; /* not fatal */
972 if (listen(sockfd
, 5) < 0) {
973 logerror("Could not listen to %s: %s",
974 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
977 continue; /* not fatal */
980 flags
= fcntl(sockfd
, F_GETFD
, 0);
982 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
984 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
985 socklist
->list
[socklist
->nr
++] = sockfd
;
996 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
998 struct sockaddr_in sin
;
1002 memset(&sin
, 0, sizeof sin
);
1003 sin
.sin_family
= AF_INET
;
1004 sin
.sin_port
= htons(listen_port
);
1007 /* Well, host better be an IP address here. */
1008 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1011 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1014 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1018 if (set_reuse_addr(sockfd
)) {
1019 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1024 set_keep_alive(sockfd
);
1026 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1027 logerror("Could not bind to %s: %s",
1028 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1034 if (listen(sockfd
, 5) < 0) {
1035 logerror("Could not listen to %s: %s",
1036 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1042 flags
= fcntl(sockfd
, F_GETFD
, 0);
1044 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
1046 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
1047 socklist
->list
[socklist
->nr
++] = sockfd
;
1053 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1055 if (!listen_addr
->nr
)
1056 setup_named_sock(NULL
, listen_port
, socklist
);
1059 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1060 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1061 listen_port
, socklist
);
1064 logerror("unable to allocate any listen sockets for host %s on port %u",
1065 listen_addr
->items
[i
].string
, listen_port
);
1070 static int service_loop(struct socketlist
*socklist
)
1075 pfd
= xcalloc(socklist
->nr
, sizeof(struct pollfd
));
1077 for (i
= 0; i
< socklist
->nr
; i
++) {
1078 pfd
[i
].fd
= socklist
->list
[i
];
1079 pfd
[i
].events
= POLLIN
;
1082 signal(SIGCHLD
, child_handler
);
1087 check_dead_children();
1089 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1090 if (errno
!= EINTR
) {
1091 logerror("Poll failed, resuming: %s",
1098 for (i
= 0; i
< socklist
->nr
; i
++) {
1099 if (pfd
[i
].revents
& POLLIN
) {
1102 struct sockaddr_in sai
;
1104 struct sockaddr_in6 sai6
;
1107 socklen_t sslen
= sizeof(ss
);
1108 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1116 die_errno("accept returned");
1119 handle(incoming
, &ss
.sa
, sslen
);
1125 #ifdef NO_POSIX_GOODIES
1129 static void drop_privileges(struct credentials
*cred
)
1134 static struct credentials
*prepare_credentials(const char *user_name
,
1135 const char *group_name
)
1137 die("--user not supported on this platform");
1142 struct credentials
{
1143 struct passwd
*pass
;
1147 static void drop_privileges(struct credentials
*cred
)
1149 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1150 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1151 die("cannot drop privileges");
1154 static struct credentials
*prepare_credentials(const char *user_name
,
1155 const char *group_name
)
1157 static struct credentials c
;
1159 c
.pass
= getpwnam(user_name
);
1161 die("user not found - %s", user_name
);
1164 c
.gid
= c
.pass
->pw_gid
;
1166 struct group
*group
= getgrnam(group_name
);
1168 die("group not found - %s", group_name
);
1170 c
.gid
= group
->gr_gid
;
1177 static int serve(struct string_list
*listen_addr
, int listen_port
,
1178 struct credentials
*cred
)
1180 struct socketlist socklist
= { NULL
, 0, 0 };
1182 socksetup(listen_addr
, listen_port
, &socklist
);
1183 if (socklist
.nr
== 0)
1184 die("unable to allocate any listen sockets on port %u",
1187 drop_privileges(cred
);
1189 loginfo("Ready to rumble");
1191 return service_loop(&socklist
);
1194 int cmd_main(int argc
, const char **argv
)
1196 int listen_port
= 0;
1197 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1198 int serve_mode
= 0, inetd_mode
= 0;
1199 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1201 struct credentials
*cred
= NULL
;
1204 for (i
= 1; i
< argc
; i
++) {
1205 const char *arg
= argv
[i
];
1208 if (skip_prefix(arg
, "--listen=", &v
)) {
1209 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1212 if (skip_prefix(arg
, "--port=", &v
)) {
1215 n
= strtoul(v
, &end
, 0);
1221 if (!strcmp(arg
, "--serve")) {
1225 if (!strcmp(arg
, "--inetd")) {
1230 if (!strcmp(arg
, "--verbose")) {
1234 if (!strcmp(arg
, "--syslog")) {
1238 if (!strcmp(arg
, "--export-all")) {
1239 export_all_trees
= 1;
1242 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1246 if (skip_prefix(arg
, "--timeout=", &v
)) {
1250 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1251 init_timeout
= atoi(v
);
1254 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1255 max_connections
= atoi(v
);
1256 if (max_connections
< 0)
1257 max_connections
= 0; /* unlimited */
1260 if (!strcmp(arg
, "--strict-paths")) {
1264 if (skip_prefix(arg
, "--base-path=", &v
)) {
1268 if (!strcmp(arg
, "--base-path-relaxed")) {
1269 base_path_relaxed
= 1;
1272 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1273 interpolated_path
= v
;
1276 if (!strcmp(arg
, "--reuseaddr")) {
1280 if (!strcmp(arg
, "--user-path")) {
1284 if (skip_prefix(arg
, "--user-path=", &v
)) {
1288 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1292 if (!strcmp(arg
, "--detach")) {
1297 if (skip_prefix(arg
, "--user=", &v
)) {
1301 if (skip_prefix(arg
, "--group=", &v
)) {
1305 if (skip_prefix(arg
, "--enable=", &v
)) {
1306 enable_service(v
, 1);
1309 if (skip_prefix(arg
, "--disable=", &v
)) {
1310 enable_service(v
, 0);
1313 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1314 make_service_overridable(v
, 1);
1317 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1318 make_service_overridable(v
, 0);
1321 if (!strcmp(arg
, "--informative-errors")) {
1322 informative_errors
= 1;
1325 if (!strcmp(arg
, "--no-informative-errors")) {
1326 informative_errors
= 0;
1329 if (!strcmp(arg
, "--")) {
1330 ok_paths
= &argv
[i
+1];
1332 } else if (arg
[0] != '-') {
1333 ok_paths
= &argv
[i
];
1337 usage(daemon_usage
);
1341 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1342 set_die_routine(daemon_die
);
1344 /* avoid splitting a message in the middle */
1345 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1347 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1348 die("--detach, --user and --group are incompatible with --inetd");
1350 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1351 die("--listen= and --port= are incompatible with --inetd");
1352 else if (listen_port
== 0)
1353 listen_port
= DEFAULT_GIT_PORT
;
1355 if (group_name
&& !user_name
)
1356 die("--group supplied without --user");
1359 cred
= prepare_credentials(user_name
, group_name
);
1361 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1362 die("option --strict-paths requires a whitelist");
1364 if (base_path
&& !is_directory(base_path
))
1365 die("base-path '%s' does not exist or is not a directory",
1369 if (!freopen("/dev/null", "w", stderr
))
1370 die_errno("failed to redirect stderr to /dev/null");
1373 if (inetd_mode
|| serve_mode
)
1378 die("--detach not supported on this platform");
1382 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1384 /* prepare argv for serving-processes */
1385 argv_array_push(&cld_argv
, argv
[0]); /* git-daemon */
1386 argv_array_push(&cld_argv
, "--serve");
1387 for (i
= 1; i
< argc
; ++i
)
1388 argv_array_push(&cld_argv
, argv
[i
]);
1390 return serve(&listen_addr
, listen_port
, cred
);