3 #include <sys/socket.h>
7 #include <netinet/in.h>
15 #include "interpolate.h"
17 static int log_syslog
;
21 static const char daemon_usage
[] =
22 "git-daemon [--verbose] [--syslog] [--inetd | --port=n] [--export-all]\n"
23 " [--timeout=n] [--init-timeout=n] [--strict-paths]\n"
24 " [--base-path=path] [--user-path | --user-path=path]\n"
25 " [--interpolated-path=path]\n"
26 " [--reuseaddr] [--detach] [--pid-file=file]\n"
27 " [--[enable|disable|allow-override|forbid-override]=service]\n"
28 " [--user=user [[--group=group]] [directory...]";
30 /* List of acceptable pathname prefixes */
31 static char **ok_paths
;
32 static int strict_paths
;
34 /* If this is set, git-daemon-export-ok is not required */
35 static int export_all_trees
;
37 /* Take all paths relative to this one if non-NULL */
38 static char *base_path
;
39 static char *interpolated_path
;
41 /* Flag indicating client sent extra args. */
42 static int saw_extended_args
;
44 /* If defined, ~user notation is allowed and the string is inserted
45 * after ~user/. E.g. a request to git://host/~alice/frotz would
46 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
48 static const char *user_path
;
50 /* Timeout, and initial timeout */
51 static unsigned int timeout
;
52 static unsigned int init_timeout
;
55 * Static table for now. Ugh.
56 * Feel free to make dynamic as needed.
58 #define INTERP_SLOT_HOST (0)
59 #define INTERP_SLOT_DIR (1)
60 #define INTERP_SLOT_PERCENT (2)
62 static struct interp interp_table
[] = {
69 static void logreport(int priority
, const char *err
, va_list params
)
71 /* We should do a single write so that it is atomic and output
72 * of several processes do not get intermingled. */
77 /* sizeof(buf) should be big enough for "[pid] \n" */
78 buflen
= snprintf(buf
, sizeof(buf
), "[%ld] ", (long) getpid());
80 maxlen
= sizeof(buf
) - buflen
- 1; /* -1 for our own LF */
81 msglen
= vsnprintf(buf
+ buflen
, maxlen
, err
, params
);
84 syslog(priority
, "%s", buf
);
88 /* maxlen counted our own LF but also counts space given to
89 * vsnprintf for the terminating NUL. We want to make sure that
90 * we have space for our own LF and NUL after the "meat" of the
91 * message, so truncate it at maxlen - 1.
93 if (msglen
> maxlen
- 1)
96 msglen
= 0; /* Protect against weird return values. */
102 write(2, buf
, buflen
);
105 static void logerror(const char *err
, ...)
108 va_start(params
, err
);
109 logreport(LOG_ERR
, err
, params
);
113 static void loginfo(const char *err
, ...)
118 va_start(params
, err
);
119 logreport(LOG_INFO
, err
, params
);
123 static void NORETURN
daemon_die(const char *err
, va_list params
)
125 logreport(LOG_ERR
, err
, params
);
129 static int avoid_alias(char *p
)
134 * This resurrects the belts and suspenders paranoia check by HPA
135 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
136 * does not do getcwd() based path canonicalizations.
138 * sl becomes true immediately after seeing '/' and continues to
139 * be true as long as dots continue after that without intervening
142 if (!p
|| (*p
!= '/' && *p
!= '~'))
152 else if (ch
== '/') {
154 /* reject //, /./ and /../ */
159 if (0 < ndot
&& ndot
< 3)
160 /* reject /.$ and /..$ */
169 else if (ch
== '/') {
176 static char *path_ok(struct interp
*itable
)
178 static char rpath
[PATH_MAX
];
179 static char interp_path
[PATH_MAX
];
183 dir
= itable
[INTERP_SLOT_DIR
].value
;
185 if (avoid_alias(dir
)) {
186 logerror("'%s': aliased", dir
);
192 logerror("'%s': User-path not allowed", dir
);
196 /* Got either "~alice" or "~alice/foo";
197 * rewrite them to "~alice/%s" or
200 int namlen
, restlen
= strlen(dir
);
201 char *slash
= strchr(dir
, '/');
203 slash
= dir
+ restlen
;
204 namlen
= slash
- dir
;
206 loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path
, dir
, namlen
, restlen
, slash
);
207 snprintf(rpath
, PATH_MAX
, "%.*s/%s%.*s",
208 namlen
, dir
, user_path
, restlen
, slash
);
212 else if (interpolated_path
&& saw_extended_args
) {
214 /* Allow only absolute */
215 logerror("'%s': Non-absolute path denied (interpolated-path active)", dir
);
219 interpolate(interp_path
, PATH_MAX
, interpolated_path
,
220 interp_table
, ARRAY_SIZE(interp_table
));
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 snprintf(rpath
, PATH_MAX
, "%s%s", base_path
, dir
);
235 path
= enter_repo(dir
, strict_paths
);
238 logerror("'%s': unable to chdir or not a git archive", dir
);
242 if ( ok_paths
&& *ok_paths
) {
244 int pathlen
= strlen(path
);
246 /* The validation is done on the paths after enter_repo
247 * appends optional {.git,.git/.git} and friends, but
248 * it does not use getcwd(). So if your /pub is
249 * a symlink to /mnt/pub, you can whitelist /pub and
250 * do not have to say /mnt/pub.
253 for ( pp
= ok_paths
; *pp
; pp
++ ) {
254 int len
= strlen(*pp
);
255 if (len
<= pathlen
&&
256 !memcmp(*pp
, path
, len
) &&
257 (path
[len
] == '\0' ||
258 (!strict_paths
&& path
[len
] == '/')))
263 /* be backwards compatible */
268 logerror("'%s': not in whitelist", path
);
269 return NULL
; /* Fallthrough. Deny by default */
272 typedef int (*daemon_service_fn
)(void);
273 struct daemon_service
{
275 const char *config_name
;
276 daemon_service_fn fn
;
281 static struct daemon_service
*service_looking_at
;
282 static int service_enabled
;
284 static int git_daemon_config(const char *var
, const char *value
)
286 if (!strncmp(var
, "daemon.", 7) &&
287 !strcmp(var
+ 7, service_looking_at
->config_name
)) {
288 service_enabled
= git_config_bool(var
, value
);
292 /* we are not interested in parsing any other configuration here */
296 static int run_service(struct interp
*itable
, struct daemon_service
*service
)
299 int enabled
= service
->enabled
;
301 loginfo("Request %s for '%s'",
303 itable
[INTERP_SLOT_DIR
].value
);
305 if (!enabled
&& !service
->overridable
) {
306 logerror("'%s': service not enabled.", service
->name
);
311 if (!(path
= path_ok(itable
)))
315 * Security on the cheap.
317 * We want a readable HEAD, usable "objects" directory, and
318 * a "git-daemon-export-ok" flag that says that the other side
319 * is ok with us doing this.
321 * path_ok() uses enter_repo() and does whitelist checking.
322 * We only need to make sure the repository is exported.
325 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
326 logerror("'%s': repository not exported.", path
);
331 if (service
->overridable
) {
332 service_looking_at
= service
;
333 service_enabled
= -1;
334 git_config(git_daemon_config
);
335 if (0 <= service_enabled
)
336 enabled
= service_enabled
;
339 logerror("'%s': service not enabled for '%s'",
340 service
->name
, path
);
346 * We'll ignore SIGTERM from now on, we have a
349 signal(SIGTERM
, SIG_IGN
);
351 return service
->fn();
354 static int upload_pack(void)
356 /* Timeout as string */
357 char timeout_buf
[64];
359 snprintf(timeout_buf
, sizeof timeout_buf
, "--timeout=%u", timeout
);
361 /* git-upload-pack only ever reads stuff, so this is safe */
362 execl_git_cmd("upload-pack", "--strict", timeout_buf
, ".", NULL
);
366 static int upload_archive(void)
368 execl_git_cmd("upload-archive", ".", NULL
);
372 static struct daemon_service daemon_service
[] = {
373 { "upload-archive", "uploadarch", upload_archive
, 0, 1 },
374 { "upload-pack", "uploadpack", upload_pack
, 1, 1 },
377 static void enable_service(const char *name
, int ena
) {
379 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
380 if (!strcmp(daemon_service
[i
].name
, name
)) {
381 daemon_service
[i
].enabled
= ena
;
385 die("No such service %s", name
);
388 static void make_service_overridable(const char *name
, int ena
) {
390 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
391 if (!strcmp(daemon_service
[i
].name
, name
)) {
392 daemon_service
[i
].overridable
= ena
;
396 die("No such service %s", name
);
399 static void parse_extra_args(char *extra_args
, int buflen
)
403 char *end
= extra_args
+ buflen
;
405 while (extra_args
< end
&& *extra_args
) {
406 saw_extended_args
= 1;
407 if (strncasecmp("host=", extra_args
, 5) == 0) {
408 val
= extra_args
+ 5;
409 vallen
= strlen(val
) + 1;
411 char *save
= xmalloc(vallen
);
412 interp_table
[INTERP_SLOT_HOST
].value
= save
;
413 strlcpy(save
, val
, vallen
);
415 /* On to the next one */
416 extra_args
= val
+ vallen
;
421 static int execute(struct sockaddr
*addr
)
423 static char line
[1000];
427 char addrbuf
[256] = "";
430 if (addr
->sa_family
== AF_INET
) {
431 struct sockaddr_in
*sin_addr
= (void *) addr
;
432 inet_ntop(addr
->sa_family
, &sin_addr
->sin_addr
, addrbuf
, sizeof(addrbuf
));
433 port
= sin_addr
->sin_port
;
435 } else if (addr
&& addr
->sa_family
== AF_INET6
) {
436 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
439 *buf
++ = '['; *buf
= '\0'; /* stpcpy() is cool */
440 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(addrbuf
) - 1);
443 port
= sin6_addr
->sin6_port
;
446 loginfo("Connection from %s:%d", addrbuf
, port
);
449 alarm(init_timeout
? init_timeout
: timeout
);
450 pktlen
= packet_read_line(0, line
, sizeof(line
));
455 loginfo("Extended attributes (%d bytes) exist <%.*s>",
457 (int) pktlen
- len
, line
+ len
+ 1);
458 if (len
&& line
[len
-1] == '\n')
462 parse_extra_args(line
+ len
+ 1, pktlen
- len
- 1);
464 for (i
= 0; i
< ARRAY_SIZE(daemon_service
); i
++) {
465 struct daemon_service
*s
= &(daemon_service
[i
]);
466 int namelen
= strlen(s
->name
);
467 if (!strncmp("git-", line
, 4) &&
468 !strncmp(s
->name
, line
+ 4, namelen
) &&
469 line
[namelen
+ 4] == ' ') {
470 interp_table
[INTERP_SLOT_DIR
].value
= line
+namelen
+5;
471 return run_service(interp_table
, s
);
475 logerror("Protocol error: '%s'", line
);
481 * We count spawned/reaped separately, just to avoid any
482 * races when updating them from signals. The SIGCHLD handler
483 * will only update children_reaped, and the fork logic will
484 * only update children_spawned.
486 * MAX_CHILDREN should be a power-of-two to make the modulus
487 * operation cheap. It should also be at least twice
488 * the maximum number of connections we will ever allow.
490 #define MAX_CHILDREN 128
492 static int max_connections
= 25;
494 /* These are updated by the signal handler */
495 static volatile unsigned int children_reaped
;
496 static pid_t dead_child
[MAX_CHILDREN
];
498 /* These are updated by the main loop */
499 static unsigned int children_spawned
;
500 static unsigned int children_deleted
;
502 static struct child
{
505 struct sockaddr_storage address
;
506 } live_child
[MAX_CHILDREN
];
508 static void add_child(int idx
, pid_t pid
, struct sockaddr
*addr
, int addrlen
)
510 live_child
[idx
].pid
= pid
;
511 live_child
[idx
].addrlen
= addrlen
;
512 memcpy(&live_child
[idx
].address
, addr
, addrlen
);
516 * Walk from "deleted" to "spawned", and remove child "pid".
518 * We move everything up by one, since the new "deleted" will
521 static void remove_child(pid_t pid
, unsigned deleted
, unsigned spawned
)
525 deleted
%= MAX_CHILDREN
;
526 spawned
%= MAX_CHILDREN
;
527 if (live_child
[deleted
].pid
== pid
) {
528 live_child
[deleted
].pid
= -1;
531 n
= live_child
[deleted
];
534 deleted
= (deleted
+ 1) % MAX_CHILDREN
;
535 if (deleted
== spawned
)
536 die("could not find dead child %d\n", pid
);
537 m
= live_child
[deleted
];
538 live_child
[deleted
] = n
;
546 * This gets called if the number of connections grows
547 * past "max_connections".
549 * We _should_ start off by searching for connections
550 * from the same IP, and if there is some address wth
551 * multiple connections, we should kill that first.
553 * As it is, we just "randomly" kill 25% of the connections,
554 * and our pseudo-random generator sucks too. I have no
557 * Really, this is just a place-holder for a _real_ algorithm.
559 static void kill_some_children(int signo
, unsigned start
, unsigned stop
)
561 start
%= MAX_CHILDREN
;
562 stop
%= MAX_CHILDREN
;
563 while (start
!= stop
) {
565 kill(live_child
[start
].pid
, signo
);
566 start
= (start
+ 1) % MAX_CHILDREN
;
570 static void check_max_connections(void)
574 unsigned spawned
, reaped
, deleted
;
576 spawned
= children_spawned
;
577 reaped
= children_reaped
;
578 deleted
= children_deleted
;
580 while (deleted
< reaped
) {
581 pid_t pid
= dead_child
[deleted
% MAX_CHILDREN
];
582 remove_child(pid
, deleted
, spawned
);
585 children_deleted
= deleted
;
587 active
= spawned
- deleted
;
588 if (active
<= max_connections
)
591 /* Kill some unstarted connections with SIGTERM */
592 kill_some_children(SIGTERM
, deleted
, spawned
);
593 if (active
<= max_connections
<< 1)
596 /* If the SIGTERM thing isn't helping use SIGKILL */
597 kill_some_children(SIGKILL
, deleted
, spawned
);
602 static void handle(int incoming
, struct sockaddr
*addr
, int addrlen
)
613 idx
= children_spawned
% MAX_CHILDREN
;
615 add_child(idx
, pid
, addr
, addrlen
);
617 check_max_connections();
628 static void child_handler(int signo
)
632 pid_t pid
= waitpid(-1, &status
, WNOHANG
);
635 unsigned reaped
= children_reaped
;
636 dead_child
[reaped
% MAX_CHILDREN
] = pid
;
637 children_reaped
= reaped
+ 1;
638 /* XXX: Custom logging, since we don't wanna getpid() */
640 const char *dead
= "";
641 if (!WIFEXITED(status
) || WEXITSTATUS(status
) > 0)
642 dead
= " (with error)";
644 syslog(LOG_INFO
, "[%d] Disconnected%s", pid
, dead
);
646 fprintf(stderr
, "[%d] Disconnected%s\n", pid
, dead
);
654 static int set_reuse_addr(int sockfd
)
660 return setsockopt(sockfd
, SOL_SOCKET
, SO_REUSEADDR
,
666 static int socksetup(int port
, int **socklist_p
)
668 int socknum
= 0, *socklist
= NULL
;
670 char pbuf
[NI_MAXSERV
];
672 struct addrinfo hints
, *ai0
, *ai
;
675 sprintf(pbuf
, "%d", port
);
676 memset(&hints
, 0, sizeof(hints
));
677 hints
.ai_family
= AF_UNSPEC
;
678 hints
.ai_socktype
= SOCK_STREAM
;
679 hints
.ai_protocol
= IPPROTO_TCP
;
680 hints
.ai_flags
= AI_PASSIVE
;
682 gai
= getaddrinfo(NULL
, pbuf
, &hints
, &ai0
);
684 die("getaddrinfo() failed: %s\n", gai_strerror(gai
));
686 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
689 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
692 if (sockfd
>= FD_SETSIZE
) {
693 error("too large socket descriptor.");
699 if (ai
->ai_family
== AF_INET6
) {
701 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
703 /* Note: error is not fatal */
707 if (set_reuse_addr(sockfd
)) {
712 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
714 continue; /* not fatal */
716 if (listen(sockfd
, 5) < 0) {
718 continue; /* not fatal */
721 socklist
= xrealloc(socklist
, sizeof(int) * (socknum
+ 1));
722 socklist
[socknum
++] = sockfd
;
730 *socklist_p
= socklist
;
736 static int socksetup(int port
, int **socklist_p
)
738 struct sockaddr_in sin
;
741 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
745 memset(&sin
, 0, sizeof sin
);
746 sin
.sin_family
= AF_INET
;
747 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
748 sin
.sin_port
= htons(port
);
750 if (set_reuse_addr(sockfd
)) {
755 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
760 if (listen(sockfd
, 5) < 0) {
765 *socklist_p
= xmalloc(sizeof(int));
766 **socklist_p
= sockfd
;
772 static int service_loop(int socknum
, int *socklist
)
777 pfd
= xcalloc(socknum
, sizeof(struct pollfd
));
779 for (i
= 0; i
< socknum
; i
++) {
780 pfd
[i
].fd
= socklist
[i
];
781 pfd
[i
].events
= POLLIN
;
784 signal(SIGCHLD
, child_handler
);
789 if (poll(pfd
, socknum
, -1) < 0) {
790 if (errno
!= EINTR
) {
791 error("poll failed, resuming: %s",
798 for (i
= 0; i
< socknum
; i
++) {
799 if (pfd
[i
].revents
& POLLIN
) {
800 struct sockaddr_storage ss
;
801 unsigned int sslen
= sizeof(ss
);
802 int incoming
= accept(pfd
[i
].fd
, (struct sockaddr
*)&ss
, &sslen
);
810 die("accept returned %s", strerror(errno
));
813 handle(incoming
, (struct sockaddr
*)&ss
, sslen
);
819 /* if any standard file descriptor is missing open it to /dev/null */
820 static void sanitize_stdfds(void)
822 int fd
= open("/dev/null", O_RDWR
, 0);
823 while (fd
!= -1 && fd
< 2)
826 die("open /dev/null or dup failed: %s", strerror(errno
));
831 static void daemonize(void)
837 die("fork failed: %s", strerror(errno
));
842 die("setsid failed: %s", strerror(errno
));
849 static void store_pid(const char *path
)
851 FILE *f
= fopen(path
, "w");
853 die("cannot open pid file %s: %s", path
, strerror(errno
));
854 fprintf(f
, "%d\n", getpid());
858 static int serve(int port
, struct passwd
*pass
, gid_t gid
)
860 int socknum
, *socklist
;
862 socknum
= socksetup(port
, &socklist
);
864 die("unable to allocate any listen sockets on port %u", port
);
867 (initgroups(pass
->pw_name
, gid
) || setgid (gid
) ||
868 setuid(pass
->pw_uid
)))
869 die("cannot drop privileges");
871 return service_loop(socknum
, socklist
);
874 int main(int argc
, char **argv
)
876 int port
= DEFAULT_GIT_PORT
;
878 const char *pid_file
= NULL
, *user_name
= NULL
, *group_name
= NULL
;
880 struct passwd
*pass
= NULL
;
885 /* Without this we cannot rely on waitpid() to tell
886 * what happened to our children.
888 signal(SIGCHLD
, SIG_DFL
);
890 for (i
= 1; i
< argc
; i
++) {
893 if (!strncmp(arg
, "--port=", 7)) {
896 n
= strtoul(arg
+7, &end
, 0);
897 if (arg
[7] && !*end
) {
902 if (!strcmp(arg
, "--inetd")) {
907 if (!strcmp(arg
, "--verbose")) {
911 if (!strcmp(arg
, "--syslog")) {
915 if (!strcmp(arg
, "--export-all")) {
916 export_all_trees
= 1;
919 if (!strncmp(arg
, "--timeout=", 10)) {
920 timeout
= atoi(arg
+10);
923 if (!strncmp(arg
, "--init-timeout=", 15)) {
924 init_timeout
= atoi(arg
+15);
927 if (!strcmp(arg
, "--strict-paths")) {
931 if (!strncmp(arg
, "--base-path=", 12)) {
935 if (!strncmp(arg
, "--interpolated-path=", 20)) {
936 interpolated_path
= arg
+20;
939 if (!strcmp(arg
, "--reuseaddr")) {
943 if (!strcmp(arg
, "--user-path")) {
947 if (!strncmp(arg
, "--user-path=", 12)) {
948 user_path
= arg
+ 12;
951 if (!strncmp(arg
, "--pid-file=", 11)) {
955 if (!strcmp(arg
, "--detach")) {
960 if (!strncmp(arg
, "--user=", 7)) {
964 if (!strncmp(arg
, "--group=", 8)) {
965 group_name
= arg
+ 8;
968 if (!strncmp(arg
, "--enable=", 9)) {
969 enable_service(arg
+ 9, 1);
972 if (!strncmp(arg
, "--disable=", 10)) {
973 enable_service(arg
+ 10, 0);
976 if (!strncmp(arg
, "--allow-override=", 17)) {
977 make_service_overridable(arg
+ 17, 1);
980 if (!strncmp(arg
, "--forbid-override=", 18)) {
981 make_service_overridable(arg
+ 18, 0);
984 if (!strcmp(arg
, "--")) {
985 ok_paths
= &argv
[i
+1];
987 } else if (arg
[0] != '-') {
995 if (inetd_mode
&& (group_name
|| user_name
))
996 die("--user and --group are incompatible with --inetd");
998 if (group_name
&& !user_name
)
999 die("--group supplied without --user");
1002 pass
= getpwnam(user_name
);
1004 die("user not found - %s", user_name
);
1009 group
= getgrnam(group_name
);
1011 die("group not found - %s", group_name
);
1013 gid
= group
->gr_gid
;
1018 openlog("git-daemon", 0, LOG_DAEMON
);
1019 set_die_routine(daemon_die
);
1022 if (strict_paths
&& (!ok_paths
|| !*ok_paths
))
1023 die("option --strict-paths requires a whitelist");
1026 struct sockaddr_storage ss
;
1027 struct sockaddr
*peer
= (struct sockaddr
*)&ss
;
1028 socklen_t slen
= sizeof(ss
);
1030 freopen("/dev/null", "w", stderr
);
1032 if (getpeername(0, peer
, &slen
))
1035 return execute(peer
);
1044 store_pid(pid_file
);
1046 return serve(port
, pass
, gid
);