4 #include "run-command.h"
6 #include "string-list.h"
9 #define HOST_NAME_MAX 256
17 #define initgroups(x, y) (0) /* nothing */
20 static int log_syslog
;
23 static int informative_errors
;
25 static const char daemon_usage
[] =
26 "git daemon [--verbose] [--syslog] [--export-all]\n"
27 " [--timeout=<n>] [--init-timeout=<n>] [--max-connections=<n>]\n"
28 " [--strict-paths] [--base-path=<path>] [--base-path-relaxed]\n"
29 " [--user-path | --user-path=<path>]\n"
30 " [--interpolated-path=<path>]\n"
31 " [--reuseaddr] [--pid-file=<file>]\n"
32 " [--(enable|disable|allow-override|forbid-override)=<service>]\n"
33 " [--access-hook=<path>]\n"
34 " [--inetd | [--listen=<host_or_ipaddr>] [--port=<n>]\n"
35 " [--detach] [--user=<user> [--group=<group>]]\n"
38 /* List of acceptable pathname prefixes */
39 static char **ok_paths
;
40 static int strict_paths
;
42 /* If this is set, git-daemon-export-ok is not required */
43 static int export_all_trees
;
45 /* Take all paths relative to this one if non-NULL */
46 static char *base_path
;
47 static char *interpolated_path
;
48 static int base_path_relaxed
;
50 /* Flag indicating client sent extra args. */
51 static int saw_extended_args
;
53 /* If defined, ~user notation is allowed and the string is inserted
54 * after ~user/. E.g. a request to git://host/~alice/frotz would
55 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
57 static const char *user_path
;
59 /* Timeout, and initial timeout */
60 static unsigned int timeout
;
61 static unsigned int init_timeout
;
63 static char *hostname
;
64 static char *canon_hostname
;
65 static char *ip_address
;
66 static char *tcp_port
;
68 static void logreport(int priority
, const char *err
, va_list params
)
72 vsnprintf(buf
, sizeof(buf
), err
, params
);
73 syslog(priority
, "%s", buf
);
76 * Since stderr is set to buffered mode, the
77 * logging of different processes will not overlap
78 * unless they overflow the (rather big) buffers.
80 fprintf(stderr
, "[%"PRIuMAX
"] ", (uintmax_t)getpid());
81 vfprintf(stderr
, err
, params
);
87 __attribute__((format (printf
, 1, 2)))
88 static void logerror(const char *err
, ...)
91 va_start(params
, err
);
92 logreport(LOG_ERR
, err
, params
);
96 __attribute__((format (printf
, 1, 2)))
97 static void loginfo(const char *err
, ...)
102 va_start(params
, err
);
103 logreport(LOG_INFO
, err
, params
);
107 static void NORETURN
daemon_die(const char *err
, va_list params
)
109 logreport(LOG_ERR
, err
, params
);
113 static const char *path_ok(char *directory
)
115 static char rpath
[PATH_MAX
];
116 static char interp_path
[PATH_MAX
];
122 if (daemon_avoid_alias(dir
)) {
123 logerror("'%s': aliased", dir
);
129 logerror("'%s': User-path not allowed", dir
);
133 /* Got either "~alice" or "~alice/foo";
134 * rewrite them to "~alice/%s" or
137 int namlen
, restlen
= strlen(dir
);
138 char *slash
= strchr(dir
, '/');
140 slash
= dir
+ restlen
;
141 namlen
= slash
- dir
;
143 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
144 snprintf(rpath
, PATH_MAX
, "%.*s/%s%.*s",
145 namlen
, dir
, user_path
, restlen
, slash
);
149 else if (interpolated_path
&& saw_extended_args
) {
150 struct strbuf expanded_path
= STRBUF_INIT
;
151 struct strbuf_expand_dict_entry dict
[6];
153 dict
[0].placeholder
= "H"; dict
[0].value
= hostname
;
154 dict
[1].placeholder
= "CH"; dict
[1].value
= canon_hostname
;
155 dict
[2].placeholder
= "IP"; dict
[2].value
= ip_address
;
156 dict
[3].placeholder
= "P"; dict
[3].value
= tcp_port
;
157 dict
[4].placeholder
= "D"; dict
[4].value
= directory
;
158 dict
[5].placeholder
= NULL
; dict
[5].value
= NULL
;
160 /* Allow only absolute */
161 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
165 strbuf_expand(&expanded_path
, interpolated_path
,
166 strbuf_expand_dict_cb
, &dict
);
167 strlcpy(interp_path
, expanded_path
.buf
, PATH_MAX
);
168 strbuf_release(&expanded_path
);
169 loginfo("Interpolated dir '%s'", interp_path
);
173 else if (base_path
) {
175 /* Allow only absolute */
176 logerror("'%s': Non-absolute path denied (base-path active)", dir
);
179 snprintf(rpath
, PATH_MAX
, "%s%s", base_path
, dir
);
183 path
= enter_repo(dir
, strict_paths
);
184 if (!path
&& base_path
&& base_path_relaxed
) {
186 * if we fail and base_path_relaxed is enabled, try without
187 * prefixing the base path
190 path
= enter_repo(dir
, strict_paths
);
194 logerror("'%s' does not appear to be a git repository", dir
);
198 if ( ok_paths
&& *ok_paths
) {
200 int pathlen
= strlen(path
);
202 /* The validation is done on the paths after enter_repo
203 * appends optional {.git,.git/.git} and friends, but
204 * it does not use getcwd(). So if your /pub is
205 * a symlink to /mnt/pub, you can whitelist /pub and
206 * do not have to say /mnt/pub.
209 for ( pp
= ok_paths
; *pp
; pp
++ ) {
210 int len
= strlen(*pp
);
211 if (len
<= pathlen
&&
212 !memcmp(*pp
, path
, len
) &&
213 (path
[len
] == '\0' ||
214 (!strict_paths
&& path
[len
] == '/')))
219 /* be backwards compatible */
224 logerror("'%s': not in whitelist", path
);
225 return NULL
; /* Fallthrough. Deny by default */
228 typedef int (*daemon_service_fn
)(void);
229 struct daemon_service
{
231 const char *config_name
;
232 daemon_service_fn fn
;
237 static struct daemon_service
*service_looking_at
;
238 static int service_enabled
;
240 static int git_daemon_config(const char *var
, const char *value
, void *cb
)
242 if (!prefixcmp(var
, "daemon.") &&
243 !strcmp(var
+ 7, service_looking_at
->config_name
)) {
244 service_enabled
= git_config_bool(var
, value
);
248 /* we are not interested in parsing any other configuration here */
252 static int daemon_error(const char *dir
, const char *msg
)
254 if (!informative_errors
)
255 msg
= "access denied or repository not exported";
256 packet_write(1, "ERR %s: %s", msg
, dir
);
260 static char *access_hook
;
262 static int run_access_hook(struct daemon_service
*service
, const char *dir
, const char *path
)
264 struct child_process child
;
265 struct strbuf buf
= STRBUF_INIT
;
267 const char **arg
= argv
;
271 #define STRARG(x) ((x) ? (x) : "")
272 *arg
++ = access_hook
;
273 *arg
++ = service
->name
;
275 *arg
++ = STRARG(hostname
);
276 *arg
++ = STRARG(canon_hostname
);
277 *arg
++ = STRARG(ip_address
);
278 *arg
++ = STRARG(tcp_port
);
282 memset(&child
, 0, sizeof(child
));
288 if (start_command(&child
)) {
289 logerror("daemon access hook '%s' failed to start",
293 if (strbuf_read(&buf
, child
.out
, 0) < 0) {
294 logerror("failed to read from pipe to daemon access hook '%s'",
299 if (close(child
.out
) < 0) {
300 logerror("failed to close pipe to daemon access hook '%s'",
304 if (finish_command(&child
))
308 strbuf_release(&buf
);
315 strbuf_addstr(&buf
, "service rejected");
316 eol
= strchr(buf
.buf
, '\n');
320 daemon_error(dir
, buf
.buf
);
321 strbuf_release(&buf
);
325 static int run_service(char *dir
, struct daemon_service
*service
)
328 int enabled
= service
->enabled
;
330 loginfo("Request %s for '%s'", service
->name
, dir
);
332 if (!enabled
&& !service
->overridable
) {
333 logerror("'%s': service not enabled.", service
->name
);
335 return daemon_error(dir
, "service not enabled");
338 if (!(path
= path_ok(dir
)))
339 return daemon_error(dir
, "no such repository");
342 * Security on the cheap.
344 * We want a readable HEAD, usable "objects" directory, and
345 * a "git-daemon-export-ok" flag that says that the other side
346 * is ok with us doing this.
348 * path_ok() uses enter_repo() and does whitelist checking.
349 * We only need to make sure the repository is exported.
352 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
353 logerror("'%s': repository not exported.", path
);
355 return daemon_error(dir
, "repository not exported");
358 if (service
->overridable
) {
359 service_looking_at
= service
;
360 service_enabled
= -1;
361 git_config(git_daemon_config
, NULL
);
362 if (0 <= service_enabled
)
363 enabled
= service_enabled
;
366 logerror("'%s': service not enabled for '%s'",
367 service
->name
, path
);
369 return daemon_error(dir
, "service not enabled");
373 * Optionally, a hook can choose to deny access to the
374 * repository depending on the phase of the moon.
376 if (access_hook
&& run_access_hook(service
, dir
, path
))
380 * We'll ignore SIGTERM from now on, we have a
383 signal(SIGTERM
, SIG_IGN
);
385 return service
->fn();
388 static void copy_to_log(int fd
)
390 struct strbuf line
= STRBUF_INIT
;
393 fp
= fdopen(fd
, "r");
395 logerror("fdopen of error channel failed");
400 while (strbuf_getline(&line
, fp
, '\n') != EOF
) {
401 logerror("%s", line
.buf
);
402 strbuf_setlen(&line
, 0);
405 strbuf_release(&line
);
409 static int run_service_command(const char **argv
)
411 struct child_process cld
;
413 memset(&cld
, 0, sizeof(cld
));
417 if (start_command(&cld
))
423 copy_to_log(cld
.err
);
425 return finish_command(&cld
);
428 static int upload_pack(void)
430 /* Timeout as string */
431 char timeout_buf
[64];
432 const char *argv
[] = { "upload-pack", "--strict", NULL
, ".", NULL
};
434 argv
[2] = timeout_buf
;
436 snprintf(timeout_buf
, sizeof timeout_buf
, "--timeout=%u", timeout
);
437 return run_service_command(argv
);
440 static int upload_archive(void)
442 static const char *argv
[] = { "upload-archive", ".", NULL
};
443 return run_service_command(argv
);
446 static int receive_pack(void)
448 static const char *argv
[] = { "receive-pack", ".", NULL
};
449 return run_service_command(argv
);
452 static struct daemon_service daemon_service
[] = {
453 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
454 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
455 { "receive-pack", "receivepack", receive_pack
, 0, 1 },
458 static void enable_service(const char *name
, int ena
)
461 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
462 if (!strcmp(daemon_service
[i
].name
, name
)) {
463 daemon_service
[i
].enabled
= ena
;
467 die("No such service %s", name
);
470 static void make_service_overridable(const char *name
, int ena
)
473 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
474 if (!strcmp(daemon_service
[i
].name
, name
)) {
475 daemon_service
[i
].overridable
= ena
;
479 die("No such service %s", name
);
482 static char *xstrdup_tolower(const char *str
)
484 char *p
, *dup
= xstrdup(str
);
485 for (p
= dup
; *p
; p
++)
490 static void parse_host_and_port(char *hostport
, char **host
,
493 if (*hostport
== '[') {
496 end
= strchr(hostport
, ']');
498 die("Invalid request ('[' without ']')");
500 *host
= hostport
+ 1;
503 else if (end
[1] == ':')
506 die("Garbage after end of host part");
509 *port
= strrchr(hostport
, ':');
518 * Read the host as supplied by the client connection.
520 static void parse_host_arg(char *extra_args
, int buflen
)
524 char *end
= extra_args
+ buflen
;
526 if (extra_args
< end
&& *extra_args
) {
527 saw_extended_args
= 1;
528 if (strncasecmp("host=", extra_args
, 5) == 0) {
529 val
= extra_args
+ 5;
530 vallen
= strlen(val
) + 1;
532 /* Split <host>:<port> at colon. */
535 parse_host_and_port(val
, &host
, &port
);
538 tcp_port
= xstrdup(port
);
541 hostname
= xstrdup_tolower(host
);
544 /* On to the next one */
545 extra_args
= val
+ vallen
;
547 if (extra_args
< end
&& *extra_args
)
548 die("Invalid request");
552 * Locate canonical hostname and its IP address.
556 struct addrinfo hints
;
559 static char addrbuf
[HOST_NAME_MAX
+ 1];
561 memset(&hints
, 0, sizeof(hints
));
562 hints
.ai_flags
= AI_CANONNAME
;
564 gai
= getaddrinfo(hostname
, NULL
, &hints
, &ai
);
566 struct sockaddr_in
*sin_addr
= (void *)ai
->ai_addr
;
568 inet_ntop(AF_INET
, &sin_addr
->sin_addr
,
569 addrbuf
, sizeof(addrbuf
));
571 ip_address
= xstrdup(addrbuf
);
573 free(canon_hostname
);
574 canon_hostname
= xstrdup(ai
->ai_canonname
?
575 ai
->ai_canonname
: ip_address
);
580 struct hostent
*hent
;
581 struct sockaddr_in sa
;
583 static char addrbuf
[HOST_NAME_MAX
+ 1];
585 hent
= gethostbyname(hostname
);
587 ap
= hent
->h_addr_list
;
588 memset(&sa
, 0, sizeof sa
);
589 sa
.sin_family
= hent
->h_addrtype
;
590 sa
.sin_port
= htons(0);
591 memcpy(&sa
.sin_addr
, *ap
, hent
->h_length
);
593 inet_ntop(hent
->h_addrtype
, &sa
.sin_addr
,
594 addrbuf
, sizeof(addrbuf
));
596 free(canon_hostname
);
597 canon_hostname
= xstrdup(hent
->h_name
);
599 ip_address
= xstrdup(addrbuf
);
605 static int execute(void)
607 static char line
[1000];
609 char *addr
= getenv("REMOTE_ADDR"), *port
= getenv("REMOTE_PORT");
612 loginfo("Connection from %s:%s", addr
, port
);
614 alarm(init_timeout
? init_timeout
: timeout
);
615 pktlen
= packet_read_line(0, line
, sizeof(line
));
620 loginfo("Extended attributes (%d bytes) exist <%.*s>",
622 (int) pktlen
- len
, line
+ len
+ 1);
623 if (len
&& line
[len
-1] == '\n') {
629 free(canon_hostname
);
632 hostname
= canon_hostname
= ip_address
= tcp_port
= NULL
;
635 parse_host_arg(line
+ len
+ 1, pktlen
- len
- 1);
637 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
638 struct daemon_service
*s
= &(daemon_service
[i
]);
639 int namelen
= strlen(s
->name
);
640 if (!prefixcmp(line
, "git-") &&
641 !strncmp(s
->name
, line
+ 4, namelen
) &&
642 line
[namelen
+ 4] == ' ') {
644 * Note: The directory here is probably context sensitive,
645 * and might depend on the actual service being performed.
647 return run_service(line
+ namelen
+ 5, s
);
651 logerror("Protocol error: '%s'", line
);
655 static int addrcmp(const struct sockaddr_storage
*s1
,
656 const struct sockaddr_storage
*s2
)
658 const struct sockaddr
*sa1
= (const struct sockaddr
*) s1
;
659 const struct sockaddr
*sa2
= (const struct sockaddr
*) s2
;
661 if (sa1
->sa_family
!= sa2
->sa_family
)
662 return sa1
->sa_family
- sa2
->sa_family
;
663 if (sa1
->sa_family
== AF_INET
)
664 return memcmp(&((struct sockaddr_in
*)s1
)->sin_addr
,
665 &((struct sockaddr_in
*)s2
)->sin_addr
,
666 sizeof(struct in_addr
));
668 if (sa1
->sa_family
== AF_INET6
)
669 return memcmp(&((struct sockaddr_in6
*)s1
)->sin6_addr
,
670 &((struct sockaddr_in6
*)s2
)->sin6_addr
,
671 sizeof(struct in6_addr
));
676 static int max_connections
= 32;
678 static unsigned int live_children
;
680 static struct child
{
682 struct child_process cld
;
683 struct sockaddr_storage address
;
686 static void add_child(struct child_process
*cld
, struct sockaddr
*addr
, socklen_t addrlen
)
688 struct child
*newborn
, **cradle
;
690 newborn
= xcalloc(1, sizeof(*newborn
));
692 memcpy(&newborn
->cld
, cld
, sizeof(*cld
));
693 memcpy(&newborn
->address
, addr
, addrlen
);
694 for (cradle
= &firstborn
; *cradle
; cradle
= &(*cradle
)->next
)
695 if (!addrcmp(&(*cradle
)->address
, &newborn
->address
))
697 newborn
->next
= *cradle
;
702 * This gets called if the number of connections grows
703 * past "max_connections".
705 * We kill the newest connection from a duplicate IP.
707 static void kill_some_child(void)
709 const struct child
*blanket
, *next
;
711 if (!(blanket
= firstborn
))
714 for (; (next
= blanket
->next
); blanket
= next
)
715 if (!addrcmp(&blanket
->address
, &next
->address
)) {
716 kill(blanket
->cld
.pid
, SIGTERM
);
721 static void check_dead_children(void)
726 struct child
**cradle
, *blanket
;
727 for (cradle
= &firstborn
; (blanket
= *cradle
);)
728 if ((pid
= waitpid(blanket
->cld
.pid
, &status
, WNOHANG
)) > 1) {
729 const char *dead
= "";
731 dead
= " (with error)";
732 loginfo("[%"PRIuMAX
"] Disconnected%s", (uintmax_t)pid
, dead
);
734 /* remove the child */
735 *cradle
= blanket
->next
;
739 cradle
= &blanket
->next
;
742 static char **cld_argv
;
743 static void handle(int incoming
, struct sockaddr
*addr
, socklen_t addrlen
)
745 struct child_process cld
= { NULL
};
746 char addrbuf
[300] = "REMOTE_ADDR=", portbuf
[300];
747 char *env
[] = { addrbuf
, portbuf
, NULL
};
749 if (max_connections
&& live_children
>= max_connections
) {
751 sleep(1); /* give it some time to die */
752 check_dead_children();
753 if (live_children
>= max_connections
) {
755 logerror("Too many children, dropping connection");
760 if (addr
->sa_family
== AF_INET
) {
761 struct sockaddr_in
*sin_addr
= (void *) addr
;
762 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, addrbuf
+ 12,
763 sizeof(addrbuf
) - 12);
764 snprintf(portbuf
, sizeof(portbuf
), "REMOTE_PORT=%d",
765 ntohs(sin_addr
->sin_port
));
767 } else if (addr
&& addr
->sa_family
== AF_INET6
) {
768 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
770 char *buf
= addrbuf
+ 12;
771 *buf
++ = '['; *buf
= '\0'; /* stpcpy() is cool */
772 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
,
773 sizeof(addrbuf
) - 13);
776 snprintf(portbuf
, sizeof(portbuf
), "REMOTE_PORT=%d",
777 ntohs(sin6_addr
->sin6_port
));
781 cld
.env
= (const char **)env
;
782 cld
.argv
= (const char **)cld_argv
;
784 cld
.out
= dup(incoming
);
786 if (start_command(&cld
))
787 logerror("unable to fork");
789 add_child(&cld
, addr
, addrlen
);
793 static void child_handler(int signo
)
796 * Otherwise empty handler because systemcalls will get interrupted
797 * upon signal receipt
798 * SysV needs the handler to be rearmed
800 signal(SIGCHLD
, child_handler
);
803 static int set_reuse_addr(int sockfd
)
809 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
819 static const char *ip2str(int family
, struct sockaddr
*sin
, socklen_t len
)
822 static char ip
[INET_ADDRSTRLEN
];
824 static char ip
[INET6_ADDRSTRLEN
];
830 inet_ntop(family
, &((struct sockaddr_in6
*)sin
)->sin6_addr
, ip
, len
);
834 inet_ntop(family
, &((struct sockaddr_in
*)sin
)->sin_addr
, ip
, len
);
837 strcpy(ip
, "<unknown>");
844 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
848 char pbuf
[NI_MAXSERV
];
849 struct addrinfo hints
, *ai0
, *ai
;
853 sprintf(pbuf
, "%d", listen_port
);
854 memset(&hints
, 0, sizeof(hints
));
855 hints
.ai_family
= AF_UNSPEC
;
856 hints
.ai_socktype
= SOCK_STREAM
;
857 hints
.ai_protocol
= IPPROTO_TCP
;
858 hints
.ai_flags
= AI_PASSIVE
;
860 gai
= getaddrinfo(listen_addr
, pbuf
, &hints
, &ai0
);
862 logerror("getaddrinfo() for %s failed: %s", listen_addr
, gai_strerror(gai
));
866 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
869 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
872 if (sockfd
>= FD_SETSIZE
) {
873 logerror("Socket descriptor too large");
879 if (ai
->ai_family
== AF_INET6
) {
881 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
883 /* Note: error is not fatal */
887 if (set_reuse_addr(sockfd
)) {
888 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
893 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
894 logerror("Could not bind to %s: %s",
895 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
898 continue; /* not fatal */
900 if (listen(sockfd
, 5) < 0) {
901 logerror("Could not listen to %s: %s",
902 ip2str(ai
->ai_family
, ai
->ai_addr
, ai
->ai_addrlen
),
905 continue; /* not fatal */
908 flags
= fcntl(sockfd
, F_GETFD
, 0);
910 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
912 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
913 socklist
->list
[socklist
->nr
++] = sockfd
;
927 static int setup_named_sock(char *listen_addr
, int listen_port
, struct socketlist
*socklist
)
929 struct sockaddr_in sin
;
933 memset(&sin
, 0, sizeof sin
);
934 sin
.sin_family
= AF_INET
;
935 sin
.sin_port
= htons(listen_port
);
938 /* Well, host better be an IP address here. */
939 if (inet_pton(AF_INET
, listen_addr
, &sin
.sin_addr
.s_addr
) <= 0)
942 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
945 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
949 if (set_reuse_addr(sockfd
)) {
950 logerror("Could not set SO_REUSEADDR: %s", strerror(errno
));
955 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
956 logerror("Could not listen to %s: %s",
957 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
963 if (listen(sockfd
, 5) < 0) {
964 logerror("Could not listen to %s: %s",
965 ip2str(AF_INET
, (struct sockaddr
*)&sin
, sizeof(sin
)),
971 flags
= fcntl(sockfd
, F_GETFD
, 0);
973 fcntl(sockfd
, F_SETFD
, flags
| FD_CLOEXEC
);
975 ALLOC_GROW(socklist
->list
, socklist
->nr
+ 1, socklist
->alloc
);
976 socklist
->list
[socklist
->nr
++] = sockfd
;
982 static void socksetup(struct string_list
*listen_addr
, int listen_port
, struct socketlist
*socklist
)
984 if (!listen_addr
->nr
)
985 setup_named_sock(NULL
, listen_port
, socklist
);
988 for (i
= 0; i
< listen_addr
->nr
; i
++) {
989 socknum
= setup_named_sock(listen_addr
->items
[i
].string
,
990 listen_port
, socklist
);
993 logerror("unable to allocate any listen sockets for host %s on port %u",
994 listen_addr
->items
[i
].string
, listen_port
);
999 static int service_loop(struct socketlist
*socklist
)
1004 pfd
= xcalloc(socklist
->nr
, sizeof(struct pollfd
));
1006 for (i
= 0; i
< socklist
->nr
; i
++) {
1007 pfd
[i
].fd
= socklist
->list
[i
];
1008 pfd
[i
].events
= POLLIN
;
1011 signal(SIGCHLD
, child_handler
);
1016 check_dead_children();
1018 if (poll(pfd
, socklist
->nr
, -1) < 0) {
1019 if (errno
!= EINTR
) {
1020 logerror("Poll failed, resuming: %s",
1027 for (i
= 0; i
< socklist
->nr
; i
++) {
1028 if (pfd
[i
].revents
& POLLIN
) {
1031 struct sockaddr_in sai
;
1033 struct sockaddr_in6 sai6
;
1036 socklen_t sslen
= sizeof(ss
);
1037 int incoming
= accept(pfd
[i
].fd
, &ss
.sa
, &sslen
);
1045 die_errno("accept returned");
1048 handle(incoming
, &ss
.sa
, sslen
);
1054 /* if any standard file descriptor is missing open it to /dev/null */
1055 static void sanitize_stdfds(void)
1057 int fd
= open("/dev/null", O_RDWR
, 0);
1058 while (fd
!= -1 && fd
< 2)
1061 die_errno("open /dev/null or dup failed");
1066 #ifdef NO_POSIX_GOODIES
1070 static void drop_privileges(struct credentials
*cred
)
1075 static void daemonize(void)
1077 die("--detach not supported on this platform");
1080 static struct credentials
*prepare_credentials(const char *user_name
,
1081 const char *group_name
)
1083 die("--user not supported on this platform");
1088 struct credentials
{
1089 struct passwd
*pass
;
1093 static void drop_privileges(struct credentials
*cred
)
1095 if (cred
&& (initgroups(cred
->pass
->pw_name
, cred
->gid
) ||
1096 setgid (cred
->gid
) || setuid(cred
->pass
->pw_uid
)))
1097 die("cannot drop privileges");
1100 static struct credentials
*prepare_credentials(const char *user_name
,
1101 const char *group_name
)
1103 static struct credentials c
;
1105 c
.pass
= getpwnam(user_name
);
1107 die("user not found - %s", user_name
);
1110 c
.gid
= c
.pass
->pw_gid
;
1112 struct group
*group
= getgrnam(group_name
);
1114 die("group not found - %s", group_name
);
1116 c
.gid
= group
->gr_gid
;
1122 static void daemonize(void)
1128 die_errno("fork failed");
1133 die_errno("setsid failed");
1141 static void store_pid(const char *path
)
1143 FILE *f
= fopen(path
, "w");
1145 die_errno("cannot open pid file '%s'", path
);
1146 if (fprintf(f
, "%"PRIuMAX
"\n", (uintmax_t) getpid()) < 0 || fclose(f
) != 0)
1147 die_errno("failed to write pid file '%s'", path
);
1150 static int serve(struct string_list
*listen_addr
, int listen_port
,
1151 struct credentials
*cred
)
1153 struct socketlist socklist
= { NULL
, 0, 0 };
1155 socksetup(listen_addr
, listen_port
, &socklist
);
1156 if (socklist
.nr
== 0)
1157 die("unable to allocate any listen sockets on port %u",
1160 drop_privileges(cred
);
1162 loginfo("Ready to rumble");
1164 return service_loop(&socklist
);
1167 int main(int argc
, char **argv
)
1169 int listen_port
= 0;
1170 struct string_list listen_addr
= STRING_LIST_INIT_NODUP
;
1171 int serve_mode
= 0, inetd_mode
= 0;
1172 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
1174 struct credentials
*cred
= NULL
;
1177 git_setup_gettext();
1179 git_extract_argv0_path(argv
[0]);
1181 for (i
= 1; i
< argc
; i
++) {
1182 char *arg
= argv
[i
];
1184 if (!prefixcmp(arg
, "--listen=")) {
1185 string_list_append(&listen_addr
, xstrdup_tolower(arg
+ 9));
1188 if (!prefixcmp(arg
, "--port=")) {
1191 n
= strtoul(arg
+7, &end
, 0);
1192 if (arg
[7] && !*end
) {
1197 if (!strcmp(arg
, "--serve")) {
1201 if (!strcmp(arg
, "--inetd")) {
1206 if (!strcmp(arg
, "--verbose")) {
1210 if (!strcmp(arg
, "--syslog")) {
1214 if (!strcmp(arg
, "--export-all")) {
1215 export_all_trees
= 1;
1218 if (!prefixcmp(arg
, "--access-hook=")) {
1219 access_hook
= arg
+ 14;
1222 if (!prefixcmp(arg
, "--timeout=")) {
1223 timeout
= atoi(arg
+10);
1226 if (!prefixcmp(arg
, "--init-timeout=")) {
1227 init_timeout
= atoi(arg
+15);
1230 if (!prefixcmp(arg
, "--max-connections=")) {
1231 max_connections
= atoi(arg
+18);
1232 if (max_connections
< 0)
1233 max_connections
= 0; /* unlimited */
1236 if (!strcmp(arg
, "--strict-paths")) {
1240 if (!prefixcmp(arg
, "--base-path=")) {
1244 if (!strcmp(arg
, "--base-path-relaxed")) {
1245 base_path_relaxed
= 1;
1248 if (!prefixcmp(arg
, "--interpolated-path=")) {
1249 interpolated_path
= arg
+20;
1252 if (!strcmp(arg
, "--reuseaddr")) {
1256 if (!strcmp(arg
, "--user-path")) {
1260 if (!prefixcmp(arg
, "--user-path=")) {
1261 user_path
= arg
+ 12;
1264 if (!prefixcmp(arg
, "--pid-file=")) {
1265 pid_file
= arg
+ 11;
1268 if (!strcmp(arg
, "--detach")) {
1273 if (!prefixcmp(arg
, "--user=")) {
1274 user_name
= arg
+ 7;
1277 if (!prefixcmp(arg
, "--group=")) {
1278 group_name
= arg
+ 8;
1281 if (!prefixcmp(arg
, "--enable=")) {
1282 enable_service(arg
+ 9, 1);
1285 if (!prefixcmp(arg
, "--disable=")) {
1286 enable_service(arg
+ 10, 0);
1289 if (!prefixcmp(arg
, "--allow-override=")) {
1290 make_service_overridable(arg
+ 17, 1);
1293 if (!prefixcmp(arg
, "--forbid-override=")) {
1294 make_service_overridable(arg
+ 18, 0);
1297 if (!prefixcmp(arg
, "--informative-errors")) {
1298 informative_errors
= 1;
1301 if (!prefixcmp(arg
, "--no-informative-errors")) {
1302 informative_errors
= 0;
1305 if (!strcmp(arg
, "--")) {
1306 ok_paths
= &argv
[i
+1];
1308 } else if (arg
[0] != '-') {
1309 ok_paths
= &argv
[i
];
1313 usage(daemon_usage
);
1317 openlog("git-daemon", LOG_PID
, LOG_DAEMON
);
1318 set_die_routine(daemon_die
);
1320 /* avoid splitting a message in the middle */
1321 setvbuf(stderr
, NULL
, _IOFBF
, 4096);
1323 if (inetd_mode
&& (detach
|| group_name
|| user_name
))
1324 die("--detach, --user and --group are incompatible with --inetd");
1326 if (inetd_mode
&& (listen_port
|| (listen_addr
.nr
> 0)))
1327 die("--listen= and --port= are incompatible with --inetd");
1328 else if (listen_port
== 0)
1329 listen_port
= DEFAULT_GIT_PORT
;
1331 if (group_name
&& !user_name
)
1332 die("--group supplied without --user");
1335 cred
= prepare_credentials(user_name
, group_name
);
1337 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1338 die("option --strict-paths requires a whitelist");
1340 if (base_path
&& !is_directory(base_path
))
1341 die("base-path '%s' does not exist or is not a directory",
1345 if (!freopen("/dev/null", "w", stderr
))
1346 die_errno("failed to redirect stderr to /dev/null");
1349 if (inetd_mode
|| serve_mode
)
1358 store_pid(pid_file
);
1360 /* prepare argv for serving-processes */
1361 cld_argv
= xmalloc(sizeof (char *) * (argc
+ 2));
1362 cld_argv
[0] = argv
[0]; /* git-daemon */
1363 cld_argv
[1] = "--serve";
1364 for (i
= 1; i
< argc
; ++i
)
1365 cld_argv
[i
+1] = argv
[i
];
1366 cld_argv
[argc
+1] = NULL
;
1368 return serve(&listen_addr
, listen_port
, cred
);