3 #include "run-command.h"
5 #include "string-list.h"
8 #define initgroups(x, y) (0) /* nothing */
11 static int log_syslog
;
14 static int informative_errors
;
16 static const char daemon_usage
[] =
17 "git daemon [--verbose] [--syslog] [--export-all]\n"
18 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
19 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
20 " [--user-path | --user-path=<path>]\n"
21 " [--interpolated-path=<path>]\n"
22 " [--reuseaddr] [--pid-file=<file>]\n"
23 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
24 " [--access-hook=<path>]\n"
25 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
26 " [--detach] [--user=<user> [--group=<group>]]\n"
29 /* List of acceptable pathname prefixes */
30 static const char **ok_paths
;
31 static int strict_paths
;
33 /* If this is set, git-daemon-export-ok is not required */
34 static int export_all_trees
;
36 /* Take all paths relative to this one if non-NULL */
37 static const char *base_path
;
38 static const char *interpolated_path
;
39 static int base_path_relaxed
;
41 /* If defined, ~user notation is allowed and the string is inserted
42 * after ~user/. E.g. a request to git://host/~alice/frotz would
43 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
45 static const char *user_path
;
47 /* Timeout, and initial timeout */
48 static unsigned int timeout
;
49 static unsigned int init_timeout
;
52 struct strbuf hostname
;
53 struct strbuf canon_hostname
;
54 struct strbuf ip_address
;
55 struct strbuf tcp_port
;
56 unsigned int hostname_lookup_done
:1;
57 unsigned int saw_extended_args
:1;
60 static void lookup_hostname(struct hostinfo
*hi
);
62 static const char *get_canon_hostname(struct hostinfo
*hi
)
65 return hi
->canon_hostname
.buf
;
68 static const char *get_ip_address(struct hostinfo
*hi
)
71 return hi
->ip_address
.buf
;
74 static void logreport(int priority
, const char *err
, va_list params
)
78 vsnprintf(buf
, sizeof(buf
), err
, params
);
79 syslog(priority
, "%s", buf
);
82 * Since stderr is set to buffered mode, the
83 * logging of different processes will not overlap
84 * unless they overflow the (rather big) buffers.
86 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
87 vfprintf(stderr
, err
, params
);
93 __attribute__((format (printf
, 1, 2)))
94 static void logerror(const char *err
, ...)
97 va_start(params
, err
);
98 logreport(LOG_ERR
, err
, params
);
102 __attribute__((format (printf
, 1, 2)))
103 static void loginfo(const char *err
, ...)
108 va_start(params
, err
);
109 logreport(LOG_INFO
, err
, params
);
113 static void NORETURN
daemon_die(const char *err
, va_list params
)
115 logreport(LOG_ERR
, err
, params
);
119 struct expand_path_context
{
120 const char *directory
;
121 struct hostinfo
*hostinfo
;
124 static size_t expand_path(struct strbuf
*sb
, const char *placeholder
, void *ctx
)
126 struct expand_path_context
*context
= ctx
;
127 struct hostinfo
*hi
= context
->hostinfo
;
129 switch (placeholder
[0]) {
131 strbuf_addbuf(sb
, &hi
->hostname
);
134 if (placeholder
[1] == 'H') {
135 strbuf_addstr(sb
, get_canon_hostname(hi
));
140 if (placeholder
[1] == 'P') {
141 strbuf_addstr(sb
, get_ip_address(hi
));
146 strbuf_addbuf(sb
, &hi
->tcp_port
);
149 strbuf_addstr(sb
, context
->directory
);
155 static const char *path_ok(const char *directory
, struct hostinfo
*hi
)
157 static char rpath
[PATH_MAX
];
158 static char interp_path
[PATH_MAX
];
165 if (daemon_avoid_alias(dir
)) {
166 logerror("'%s': aliased", dir
);
172 logerror("'%s': User-path not allowed", dir
);
176 /* Got either "~alice" or "~alice/foo";
177 * rewrite them to "~alice/%s" or
180 int namlen
, restlen
= strlen(dir
);
181 const char *slash
= strchr(dir
, '/');
183 slash
= dir
+ restlen
;
184 namlen
= slash
- dir
;
186 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
187 rlen
= snprintf(rpath
, sizeof(rpath
), "%.*s/%s%.*s",
188 namlen
, dir
, user_path
, restlen
, slash
);
189 if (rlen
>= sizeof(rpath
)) {
190 logerror("user-path too large: %s", rpath
);
196 else if (interpolated_path
&& hi
->saw_extended_args
) {
197 struct strbuf expanded_path
= STRBUF_INIT
;
198 struct expand_path_context context
;
200 context
.directory
= directory
;
201 context
.hostinfo
= hi
;
204 /* Allow only absolute */
205 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
209 strbuf_expand(&expanded_path
, interpolated_path
,
210 expand_path
, &context
);
212 rlen
= strlcpy(interp_path
, expanded_path
.buf
,
213 sizeof(interp_path
));
214 if (rlen
>= sizeof(interp_path
)) {
215 logerror("interpolated path too large: %s",
220 strbuf_release(&expanded_path
);
221 loginfo("Interpolated dir '%s'", interp_path
);
225 else if (base_path
) {
227 /* Allow only absolute */
228 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
231 rlen
= snprintf(rpath
, sizeof(rpath
), "%s%s", base_path
, dir
);
232 if (rlen
>= sizeof(rpath
)) {
233 logerror("base-path too large: %s", rpath
);
239 path
= enter_repo(dir
, strict_paths
);
240 if (!path
&& base_path
&& base_path_relaxed
) {
242 * if we fail and base_path_relaxed is enabled, try without
243 * prefixing the base path
246 path
= enter_repo(dir
, strict_paths
);
250 logerror("'%s' does not appear to be a git repository", dir
);
254 if ( ok_paths
&& *ok_paths
) {
256 int pathlen
= strlen(path
);
258 /* The validation is done on the paths after enter_repo
259 * appends optional {.git,.git/.git} and friends, but
260 * it does not use getcwd(). So if your /pub is
261 * a symlink to /mnt/pub, you can whitelist /pub and
262 * do not have to say /mnt/pub.
265 for ( pp
= ok_paths
; *pp
; pp
++ ) {
266 int len
= strlen(*pp
);
267 if (len
<= pathlen
&&
268 !memcmp(*pp
, path
, len
) &&
269 (path
[len
] == '\0' ||
270 (!strict_paths
&& path
[len
] == '/')))
275 /* be backwards compatible */
280 logerror("'%s': not in whitelist", path
);
281 return NULL
; /* Fallthrough. Deny by default */
284 typedef int (*daemon_service_fn
)(void);
285 struct daemon_service
{
287 const char *config_name
;
288 daemon_service_fn fn
;
293 static int daemon_error(const char *dir
, const char *msg
)
295 if (!informative_errors
)
296 msg
= "access denied or repository not exported";
297 packet_write_fmt(1, "ERR %s: %s", msg
, dir
);
301 static const char *access_hook
;
303 static int run_access_hook(struct daemon_service
*service
, const char *dir
,
304 const char *path
, struct hostinfo
*hi
)
306 struct child_process child
= CHILD_PROCESS_INIT
;
307 struct strbuf buf
= STRBUF_INIT
;
309 const char **arg
= argv
;
313 *arg
++ = access_hook
;
314 *arg
++ = service
->name
;
316 *arg
++ = hi
->hostname
.buf
;
317 *arg
++ = get_canon_hostname(hi
);
318 *arg
++ = get_ip_address(hi
);
319 *arg
++ = hi
->tcp_port
.buf
;
327 if (start_command(&child
)) {
328 logerror("daemon access hook '%s' failed to start",
332 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
333 logerror("failed to read from pipe to daemon access hook '%s'",
338 if (close(child
.out
) < 0) {
339 logerror("failed to close pipe to daemon access hook '%s'",
343 if (finish_command(&child
))
347 strbuf_release(&buf
);
354 strbuf_addstr(&buf
, "service rejected");
355 eol
= strchr(buf
.buf
, '\n');
359 daemon_error(dir
, buf
.buf
);
360 strbuf_release(&buf
);
364 static int run_service(const char *dir
, struct daemon_service
*service
,
368 int enabled
= service
->enabled
;
369 struct strbuf var
= STRBUF_INIT
;
371 loginfo("Request %s for '%s'", service
->name
, dir
);
373 if (!enabled
&& !service
->overridable
) {
374 logerror("'%s': service not enabled.", service
->name
);
376 return daemon_error(dir
, "service not enabled");
379 if (!(path
= path_ok(dir
, hi
)))
380 return daemon_error(dir
, "no such repository");
383 * Security on the cheap.
385 * We want a readable HEAD, usable "objects" directory, and
386 * a "git-daemon-export-ok" flag that says that the other side
387 * is ok with us doing this.
389 * path_ok() uses enter_repo() and does whitelist checking.
390 * We only need to make sure the repository is exported.
393 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
394 logerror("'%s': repository not exported.", path
);
396 return daemon_error(dir
, "repository not exported");
399 if (service
->overridable
) {
400 strbuf_addf(&var
, "daemon.%s", service
->config_name
);
401 git_config_get_bool(var
.buf
, &enabled
);
402 strbuf_release(&var
);
405 logerror("'%s': service not enabled for '%s'",
406 service
->name
, path
);
408 return daemon_error(dir
, "service not enabled");
412 * Optionally, a hook can choose to deny access to the
413 * repository depending on the phase of the moon.
415 if (access_hook
&& run_access_hook(service
, dir
, path
, hi
))
419 * We'll ignore SIGTERM from now on, we have a
422 signal(SIGTERM
, SIG_IGN
);
424 return service
->fn();
427 static void copy_to_log(int fd
)
429 struct strbuf line
= STRBUF_INIT
;
432 fp
= fdopen(fd
, "r");
434 logerror("fdopen of error channel failed");
439 while (strbuf_getline_lf(&line
, fp
) != EOF
) {
440 logerror("%s", line
.buf
);
441 strbuf_setlen(&line
, 0);
444 strbuf_release(&line
);
448 static int run_service_command(struct child_process
*cld
)
450 argv_array_push(&cld
->args
, ".");
453 if (start_command(cld
))
459 copy_to_log(cld
->err
);
461 return finish_command(cld
);
464 static int upload_pack(void)
466 struct child_process cld
= CHILD_PROCESS_INIT
;
467 argv_array_pushl(&cld
.args
, "upload-pack", "--strict", NULL
);
468 argv_array_pushf(&cld
.args
, "--timeout=%u", timeout
);
469 return run_service_command(&cld
);
472 static int upload_archive(void)
474 struct child_process cld
= CHILD_PROCESS_INIT
;
475 argv_array_push(&cld
.args
, "upload-archive");
476 return run_service_command(&cld
);
479 static int receive_pack(void)
481 struct child_process cld
= CHILD_PROCESS_INIT
;
482 argv_array_push(&cld
.args
, "receive-pack");
483 return run_service_command(&cld
);
486 static struct daemon_service daemon_service
[] = {
487 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
488 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
489 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
492 static void enable_service(const char *name
, int ena
)
495 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
496 if (!strcmp(daemon_service
[i
].name
, name
)) {
497 daemon_service
[i
].enabled
= ena
;
501 die("No such service %s", name
);
504 static void make_service_overridable(const char *name
, int ena
)
507 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
508 if (!strcmp(daemon_service
[i
].name
, name
)) {
509 daemon_service
[i
].overridable
= ena
;
513 die("No such service %s", name
);
516 static void parse_host_and_port(char *hostport
, char **host
,
519 if (*hostport
== '[') {
522 end
= strchr(hostport
, ']');
524 die("Invalid request ('[' without ']')");
526 *host
= hostport
+ 1;
529 else if (end
[1] == ':')
532 die("Garbage after end of host part");
535 *port
= strrchr(hostport
, ':');
544 * Sanitize a string from the client so that it's OK to be inserted into a
545 * filesystem path. Specifically, we disallow slashes, runs of "..", and
546 * trailing and leading dots, which means that the client cannot escape
547 * our base path via ".." traversal.
549 static void sanitize_client(struct strbuf
*out
, const char *in
)
554 if (*in
== '.' && (!out
->len
|| out
->buf
[out
->len
- 1] == '.'))
556 strbuf_addch(out
, *in
);
559 while (out
->len
&& out
->buf
[out
->len
- 1] == '.')
560 strbuf_setlen(out
, out
->len
- 1);
564 * Like sanitize_client, but we also perform any canonicalization
565 * to make life easier on the admin.
567 static void canonicalize_client(struct strbuf
*out
, const char *in
)
569 sanitize_client(out
, in
);
574 * Read the host as supplied by the client connection.
576 static void parse_host_arg(struct hostinfo
*hi
, char *extra_args
, int buflen
)
580 char *end
= extra_args
+ buflen
;
582 if (extra_args
< end
&& *extra_args
) {
583 hi
->saw_extended_args
= 1;
584 if (strncasecmp("host=", extra_args
, 5) == 0) {
585 val
= extra_args
+ 5;
586 vallen
= strlen(val
) + 1;
588 /* Split <host>:<port> at colon. */
591 parse_host_and_port(val
, &host
, &port
);
593 sanitize_client(&hi
->tcp_port
, port
);
594 canonicalize_client(&hi
->hostname
, host
);
595 hi
->hostname_lookup_done
= 0;
598 /* On to the next one */
599 extra_args
= val
+ vallen
;
601 if (extra_args
< end
&& *extra_args
)
602 die("Invalid request");
607 * Locate canonical hostname and its IP address.
609 static void lookup_hostname(struct hostinfo
*hi
)
611 if (!hi
->hostname_lookup_done
&& hi
->hostname
.len
) {
613 struct addrinfo hints
;
616 static char addrbuf
[HOST_NAME_MAX
+ 1];
618 memset(&hints
, 0, sizeof(hints
));
619 hints
.ai_flags
= AI_CANONNAME
;
621 gai
= getaddrinfo(hi
->hostname
.buf
, NULL
, &hints
, &ai
);
623 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
625 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
626 addrbuf
, sizeof(addrbuf
));
627 strbuf_addstr(&hi
->ip_address
, addrbuf
);
629 if (ai
->ai_canonname
)
630 sanitize_client(&hi
->canon_hostname
,
633 strbuf_addbuf(&hi
->canon_hostname
,
639 struct hostent
*hent
;
640 struct sockaddr_in sa
;
642 static char addrbuf
[HOST_NAME_MAX
+ 1];
644 hent
= gethostbyname(hi
->hostname
.buf
);
646 ap
= hent
->h_addr_list
;
647 memset(&sa
, 0, sizeof sa
);
648 sa
.sin_family
= hent
->h_addrtype
;
649 sa
.sin_port
= htons(0);
650 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
652 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
653 addrbuf
, sizeof(addrbuf
));
655 sanitize_client(&hi
->canon_hostname
, hent
->h_name
);
656 strbuf_addstr(&hi
->ip_address
, addrbuf
);
659 hi
->hostname_lookup_done
= 1;
663 static void hostinfo_init(struct hostinfo
*hi
)
665 memset(hi
, 0, sizeof(*hi
));
666 strbuf_init(&hi
->hostname
, 0);
667 strbuf_init(&hi
->canon_hostname
, 0);
668 strbuf_init(&hi
->ip_address
, 0);
669 strbuf_init(&hi
->tcp_port
, 0);
672 static void hostinfo_clear(struct hostinfo
*hi
)
674 strbuf_release(&hi
->hostname
);
675 strbuf_release(&hi
->canon_hostname
);
676 strbuf_release(&hi
->ip_address
);
677 strbuf_release(&hi
->tcp_port
);
680 static void set_keep_alive(int sockfd
)
684 if (setsockopt(sockfd
, SOL_SOCKET
, SO_KEEPALIVE
, &ka
, sizeof(ka
)) < 0) {
685 if (errno
!= ENOTSOCK
)
686 logerror("unable to set SO_KEEPALIVE on socket: %s",
691 static int execute(void)
693 char *line
= packet_buffer
;
695 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
701 loginfo("Connection from %s:%s", addr
, port
);
704 alarm(init_timeout
? init_timeout
: timeout
);
705 pktlen
= packet_read(0, NULL
, NULL
, packet_buffer
, sizeof(packet_buffer
), 0);
710 loginfo("Extended attributes (%d bytes) exist <%.*s>",
712 (int) pktlen
- len
, line
+ len
+ 1);
713 if (len
&& line
[len
-1] == '\n') {
719 parse_host_arg(&hi
, line
+ len
+ 1, pktlen
- len
- 1);
721 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
722 struct daemon_service
*s
= &(daemon_service
[i
]);
725 if (skip_prefix(line
, "git-", &arg
) &&
726 skip_prefix(arg
, s
->name
, &arg
) &&
729 * Note: The directory here is probably context sensitive,
730 * and might depend on the actual service being performed.
732 int rc
= run_service(arg
, s
, &hi
);
739 logerror("Protocol error: '%s'", line
);
743 static int addrcmp(const struct sockaddr_storage
*s1
,
744 const struct sockaddr_storage
*s2
)
746 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
747 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
749 if (sa1
->sa_family
!= sa2
->sa_family
)
750 return sa1
->sa_family
- sa2
->sa_family
;
751 if (sa1
->sa_family
== AF_INET
)
752 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
753 &((struct sockaddr_in
*)s2
)->sin_addr
,
754 sizeof(struct in_addr
));
756 if (sa1
->sa_family
== AF_INET6
)
757 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
758 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
759 sizeof(struct in6_addr
));
764 static int max_connections
= 32;
766 static unsigned int live_children
;
768 static struct child
{
770 struct child_process cld
;
771 struct sockaddr_storage address
;
774 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
776 struct child
*newborn
, **cradle
;
778 newborn
= xcalloc(1, sizeof(*newborn
));
780 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
781 memcpy(&newborn
->address
, addr
, addrlen
);
782 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
783 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
785 newborn
->next
= *cradle
;
790 * This gets called if the number of connections grows
791 * past "max_connections".
793 * We kill the newest connection from a duplicate IP.
795 static void kill_some_child(void)
797 const struct child
*blanket
, *next
;
799 if (!(blanket
= firstborn
))
802 for (; (next
= blanket
->next
); blanket
= next
)
803 if (!addrcmp(&blanket
->address
, &next
->address
)) {
804 kill(blanket
->cld
.pid
, SIGTERM
);
809 static void check_dead_children(void)
814 struct child
**cradle
, *blanket
;
815 for (cradle
= &firstborn
; (blanket
= *cradle
);)
816 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
817 const char *dead
= "";
819 dead
= " (with error)";
820 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
822 /* remove the child */
823 *cradle
= blanket
->next
;
825 child_process_clear(&blanket
->cld
);
828 cradle
= &blanket
->next
;
831 static struct argv_array cld_argv
= ARGV_ARRAY_INIT
;
832 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
834 struct child_process cld
= CHILD_PROCESS_INIT
;
836 if (max_connections
&& live_children
>= max_connections
) {
838 sleep(1); /* give it some time to die */
839 check_dead_children();
840 if (live_children
>= max_connections
) {
842 logerror("Too many children, dropping connection");
847 if (addr
->sa_family
== AF_INET
) {
849 struct sockaddr_in
*sin_addr
= (void *) addr
;
850 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, buf
, sizeof(buf
));
851 argv_array_pushf(&cld
.env_array
, "REMOTE_ADDR=%s", buf
);
852 argv_array_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
853 ntohs(sin_addr
->sin_port
));
855 } else if (addr
->sa_family
== AF_INET6
) {
857 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
858 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(buf
));
859 argv_array_pushf(&cld
.env_array
, "REMOTE_ADDR=[%s]", buf
);
860 argv_array_pushf(&cld
.env_array
, "REMOTE_PORT=%d",
861 ntohs(sin6_addr
->sin6_port
));
865 cld
.argv
= cld_argv
.argv
;
867 cld
.out
= dup(incoming
);
869 if (start_command(&cld
))
870 logerror("unable to fork");
872 add_child(&cld
, addr
, addrlen
);
875 static void child_handler(int signo
)
878 * Otherwise empty handler because systemcalls will get interrupted
879 * upon signal receipt
880 * SysV needs the handler to be rearmed
882 signal(SIGCHLD
, child_handler
);
885 static int set_reuse_addr(int sockfd
)
891 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
901 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
904 static char ip
[INET_ADDRSTRLEN
];
906 static char ip
[INET6_ADDRSTRLEN
];
912 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
916 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
919 xsnprintf(ip
, sizeof(ip
), "<unknown>");
926 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
929 char pbuf
[NI_MAXSERV
];
930 struct addrinfo hints
, *ai0
, *ai
;
934 xsnprintf(pbuf
, sizeof(pbuf
), "%d", listen_port
);
935 memset(&hints
, 0, sizeof(hints
));
936 hints
.ai_family
= AF_UNSPEC
;
937 hints
.ai_socktype
= SOCK_STREAM
;
938 hints
.ai_protocol
= IPPROTO_TCP
;
939 hints
.ai_flags
= AI_PASSIVE
;
941 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
943 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
947 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
950 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
953 if (sockfd
>= FD_SETSIZE
) {
954 logerror("Socket descriptor too large");
960 if (ai
->ai_family
== AF_INET6
) {
962 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
964 /* Note: error is not fatal */
968 if (set_reuse_addr(sockfd
)) {
969 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
974 set_keep_alive(sockfd
);
976 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
977 logerror("Could not bind to %s: %s",
978 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
981 continue; /* not fatal */
983 if (listen(sockfd
, 5) < 0) {
984 logerror("Could not listen to %s: %s",
985 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
988 continue; /* not fatal */
991 flags
= fcntl(sockfd
, F_GETFD
, 0);
993 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
995 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
996 socklist
->list
[socklist
->nr
++] = sockfd
;
1007 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
1009 struct sockaddr_in sin
;
1013 memset(&sin
, 0, sizeof sin
);
1014 sin
.sin_family
= AF_INET
;
1015 sin
.sin_port
= htons(listen_port
);
1018 /* Well, host better be an IP address here. */
1019 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
1022 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
1025 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
1029 if (set_reuse_addr(sockfd
)) {
1030 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
1035 set_keep_alive(sockfd
);
1037 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
1038 logerror("Could not bind to %s: %s",
1039 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
1045 if (listen(sockfd
, 5) < 0) {
1046 logerror("Could not listen to %s: %s",
1047 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
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
;
1064 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
1066 if (!listen_addr
->nr
)
1067 setup_named_sock(NULL
, listen_port
, socklist
);
1070 for (i
= 0; i
< listen_addr
->nr
; i
++) {
1071 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
1072 listen_port
, socklist
);
1075 logerror("unable to allocate any listen sockets for host %s on port %u",
1076 listen_addr
->items
[i
].string
, listen_port
);
1081 static int service_loop(struct socketlist
*socklist
)
1086 pfd
= xcalloc(socklist
->nr
, sizeof(struct pollfd
));
1088 for (i
= 0; i
< socklist
->nr
; i
++) {
1089 pfd
[i
].fd
= socklist
->list
[i
];
1090 pfd
[i
].events
= POLLIN
;
1093 signal(SIGCHLD
, child_handler
);
1098 check_dead_children();
1100 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1101 if (errno
!= EINTR
) {
1102 logerror("Poll failed, resuming: %s",
1109 for (i
= 0; i
< socklist
->nr
; i
++) {
1110 if (pfd
[i
].revents
& POLLIN
) {
1113 struct sockaddr_in sai
;
1115 struct sockaddr_in6 sai6
;
1118 socklen_t sslen
= sizeof(ss
);
1119 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1127 die_errno("accept returned");
1130 handle(incoming
, &ss
.sa
, sslen
);
1136 #ifdef NO_POSIX_GOODIES
1140 static void drop_privileges(struct credentials
*cred
)
1145 static struct credentials
*prepare_credentials(const char *user_name
,
1146 const char *group_name
)
1148 die("--user not supported on this platform");
1153 struct credentials
{
1154 struct passwd
*pass
;
1158 static void drop_privileges(struct credentials
*cred
)
1160 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1161 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1162 die("cannot drop privileges");
1165 static struct credentials
*prepare_credentials(const char *user_name
,
1166 const char *group_name
)
1168 static struct credentials c
;
1170 c
.pass
= getpwnam(user_name
);
1172 die("user not found - %s", user_name
);
1175 c
.gid
= c
.pass
->pw_gid
;
1177 struct group
*group
= getgrnam(group_name
);
1179 die("group not found - %s", group_name
);
1181 c
.gid
= group
->gr_gid
;
1188 static int serve(struct string_list
*listen_addr
, int listen_port
,
1189 struct credentials
*cred
)
1191 struct socketlist socklist
= { NULL
, 0, 0 };
1193 socksetup(listen_addr
, listen_port
, &socklist
);
1194 if (socklist
.nr
== 0)
1195 die("unable to allocate any listen sockets on port %u",
1198 drop_privileges(cred
);
1200 loginfo("Ready to rumble");
1202 return service_loop(&socklist
);
1205 int cmd_main(int argc
, const char **argv
)
1207 int listen_port
= 0;
1208 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1209 int serve_mode
= 0, inetd_mode
= 0;
1210 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1212 struct credentials
*cred
= NULL
;
1215 for (i
= 1; i
< argc
; i
++) {
1216 const char *arg
= argv
[i
];
1219 if (skip_prefix(arg
, "--listen=", &v
)) {
1220 string_list_append(&listen_addr
, xstrdup_tolower(v
));
1223 if (skip_prefix(arg
, "--port=", &v
)) {
1226 n
= strtoul(v
, &end
, 0);
1232 if (!strcmp(arg
, "--serve")) {
1236 if (!strcmp(arg
, "--inetd")) {
1241 if (!strcmp(arg
, "--verbose")) {
1245 if (!strcmp(arg
, "--syslog")) {
1249 if (!strcmp(arg
, "--export-all")) {
1250 export_all_trees
= 1;
1253 if (skip_prefix(arg
, "--access-hook=", &v
)) {
1257 if (skip_prefix(arg
, "--timeout=", &v
)) {
1261 if (skip_prefix(arg
, "--init-timeout=", &v
)) {
1262 init_timeout
= atoi(v
);
1265 if (skip_prefix(arg
, "--max-connections=", &v
)) {
1266 max_connections
= atoi(v
);
1267 if (max_connections
< 0)
1268 max_connections
= 0; /* unlimited */
1271 if (!strcmp(arg
, "--strict-paths")) {
1275 if (skip_prefix(arg
, "--base-path=", &v
)) {
1279 if (!strcmp(arg
, "--base-path-relaxed")) {
1280 base_path_relaxed
= 1;
1283 if (skip_prefix(arg
, "--interpolated-path=", &v
)) {
1284 interpolated_path
= v
;
1287 if (!strcmp(arg
, "--reuseaddr")) {
1291 if (!strcmp(arg
, "--user-path")) {
1295 if (skip_prefix(arg
, "--user-path=", &v
)) {
1299 if (skip_prefix(arg
, "--pid-file=", &v
)) {
1303 if (!strcmp(arg
, "--detach")) {
1308 if (skip_prefix(arg
, "--user=", &v
)) {
1312 if (skip_prefix(arg
, "--group=", &v
)) {
1316 if (skip_prefix(arg
, "--enable=", &v
)) {
1317 enable_service(v
, 1);
1320 if (skip_prefix(arg
, "--disable=", &v
)) {
1321 enable_service(v
, 0);
1324 if (skip_prefix(arg
, "--allow-override=", &v
)) {
1325 make_service_overridable(v
, 1);
1328 if (skip_prefix(arg
, "--forbid-override=", &v
)) {
1329 make_service_overridable(v
, 0);
1332 if (!strcmp(arg
, "--informative-errors")) {
1333 informative_errors
= 1;
1336 if (!strcmp(arg
, "--no-informative-errors")) {
1337 informative_errors
= 0;
1340 if (!strcmp(arg
, "--")) {
1341 ok_paths
= &argv
[i
+1];
1343 } else if (arg
[0] != '-') {
1344 ok_paths
= &argv
[i
];
1348 usage(daemon_usage
);
1352 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1353 set_die_routine(daemon_die
);
1355 /* avoid splitting a message in the middle */
1356 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1358 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1359 die("--detach, --user and --group are incompatible with --inetd");
1361 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1362 die("--listen= and --port= are incompatible with --inetd");
1363 else if (listen_port
== 0)
1364 listen_port
= DEFAULT_GIT_PORT
;
1366 if (group_name
&& !user_name
)
1367 die("--group supplied without --user");
1370 cred
= prepare_credentials(user_name
, group_name
);
1372 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1373 die("option --strict-paths requires a whitelist");
1375 if (base_path
&& !is_directory(base_path
))
1376 die("base-path '%s' does not exist or is not a directory",
1380 if (!freopen("/dev/null", "w", stderr
))
1381 die_errno("failed to redirect stderr to /dev/null");
1384 if (inetd_mode
|| serve_mode
)
1389 die("--detach not supported on this platform");
1393 write_file(pid_file
, "%"PRIuMAX
, (uintmax_t) getpid());
1395 /* prepare argv for serving-processes */
1396 argv_array_push(&cld_argv
, argv
[0]); /* git-daemon */
1397 argv_array_push(&cld_argv
, "--serve");
1398 for (i
= 1; i
< argc
; ++i
)
1399 argv_array_push(&cld_argv
, argv
[i
]);
1401 return serve(&listen_addr
, listen_port
, cred
);