3 #include <sys/socket.h>
7 #include <netinet/in.h>
13 static int log_syslog
;
16 static const char daemon_usage
[] =
17 "git-daemon [--verbose] [--syslog] [--inetd | --port=n] [--export-all]\n"
18 " [--timeout=n] [--init-timeout=n] [--strict-paths] [directory...]";
20 /* List of acceptable pathname prefixes */
21 static char **ok_paths
= NULL
;
22 static int strict_paths
= 0;
24 /* If this is set, git-daemon-export-ok is not required */
25 static int export_all_trees
= 0;
27 /* Timeout, and initial timeout */
28 static unsigned int timeout
= 0;
29 static unsigned int init_timeout
= 0;
31 static void logreport(int priority
, const char *err
, va_list params
)
33 /* We should do a single write so that it is atomic and output
34 * of several processes do not get intermingled. */
39 /* sizeof(buf) should be big enough for "[pid] \n" */
40 buflen
= snprintf(buf
, sizeof(buf
), "[%ld] ", (long) getpid());
42 maxlen
= sizeof(buf
) - buflen
- 1; /* -1 for our own LF */
43 msglen
= vsnprintf(buf
+ buflen
, maxlen
, err
, params
);
46 syslog(priority
, "%s", buf
);
50 /* maxlen counted our own LF but also counts space given to
51 * vsnprintf for the terminating NUL. We want to make sure that
52 * we have space for our own LF and NUL after the "meat" of the
53 * message, so truncate it at maxlen - 1.
55 if (msglen
> maxlen
- 1)
58 msglen
= 0; /* Protect against weird return values. */
64 write(2, buf
, buflen
);
67 static void logerror(const char *err
, ...)
70 va_start(params
, err
);
71 logreport(LOG_ERR
, err
, params
);
75 static void loginfo(const char *err
, ...)
80 va_start(params
, err
);
81 logreport(LOG_INFO
, err
, params
);
85 static int avoid_alias(char *p
)
90 * This resurrects the belts and suspenders paranoia check by HPA
91 * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
92 * does not do getcwd() based path canonicalizations.
94 * sl becomes true immediately after seeing '/' and continues to
95 * be true as long as dots continue after that without intervening
98 if (!p
|| (*p
!= '/' && *p
!= '~'))
108 else if (ch
== '/') {
110 /* reject //, /./ and /../ */
115 if (0 < ndot
&& ndot
< 3)
116 /* reject /.$ and /..$ */
125 else if (ch
== '/') {
132 static char *path_ok(char *dir
)
136 if (avoid_alias(dir
)) {
137 logerror("'%s': aliased", dir
);
141 path
= enter_repo(dir
, strict_paths
);
144 logerror("'%s': unable to chdir or not a git archive", dir
);
148 if ( ok_paths
&& *ok_paths
) {
150 int pathlen
= strlen(path
);
152 /* The validation is done on the paths after enter_repo
153 * appends optional {.git,.git/.git} and friends, but
154 * it does not use getcwd(). So if your /pub is
155 * a symlink to /mnt/pub, you can whitelist /pub and
156 * do not have to say /mnt/pub.
159 for ( pp
= ok_paths
; *pp
; pp
++ ) {
160 int len
= strlen(*pp
);
161 if (len
<= pathlen
&&
162 !memcmp(*pp
, path
, len
) &&
163 (path
[len
] == '\0' ||
164 (!strict_paths
&& path
[len
] == '/')))
169 /* be backwards compatible */
174 logerror("'%s': not in whitelist", path
);
175 return NULL
; /* Fallthrough. Deny by default */
178 static int upload(char *dir
)
180 /* Timeout as string */
181 char timeout_buf
[64];
184 loginfo("Request for '%s'", dir
);
186 if (!(path
= path_ok(dir
)))
190 * Security on the cheap.
192 * We want a readable HEAD, usable "objects" directory, and
193 * a "git-daemon-export-ok" flag that says that the other side
194 * is ok with us doing this.
196 * path_ok() uses enter_repo() and does whitelist checking.
197 * We only need to make sure the repository is exported.
200 if (!export_all_trees
&& access("git-daemon-export-ok", F_OK
)) {
201 logerror("'%s': repository not exported.", path
);
207 * We'll ignore SIGTERM from now on, we have a
210 signal(SIGTERM
, SIG_IGN
);
212 snprintf(timeout_buf
, sizeof timeout_buf
, "--timeout=%u", timeout
);
214 /* git-upload-pack only ever reads stuff, so this is safe */
215 execlp("git-upload-pack", "git-upload-pack", "--strict", timeout_buf
, ".", NULL
);
219 static int execute(void)
221 static char line
[1000];
224 alarm(init_timeout
? init_timeout
: timeout
);
225 len
= packet_read_line(0, line
, sizeof(line
));
228 if (len
&& line
[len
-1] == '\n')
231 if (!strncmp("git-upload-pack ", line
, 16))
232 return upload(line
+16);
234 logerror("Protocol error: '%s'", line
);
240 * We count spawned/reaped separately, just to avoid any
241 * races when updating them from signals. The SIGCHLD handler
242 * will only update children_reaped, and the fork logic will
243 * only update children_spawned.
245 * MAX_CHILDREN should be a power-of-two to make the modulus
246 * operation cheap. It should also be at least twice
247 * the maximum number of connections we will ever allow.
249 #define MAX_CHILDREN 128
251 static int max_connections
= 25;
253 /* These are updated by the signal handler */
254 static volatile unsigned int children_reaped
= 0;
255 static pid_t dead_child
[MAX_CHILDREN
];
257 /* These are updated by the main loop */
258 static unsigned int children_spawned
= 0;
259 static unsigned int children_deleted
= 0;
261 static struct child
{
264 struct sockaddr_storage address
;
265 } live_child
[MAX_CHILDREN
];
267 static void add_child(int idx
, pid_t pid
, struct sockaddr
*addr
, int addrlen
)
269 live_child
[idx
].pid
= pid
;
270 live_child
[idx
].addrlen
= addrlen
;
271 memcpy(&live_child
[idx
].address
, addr
, addrlen
);
275 * Walk from "deleted" to "spawned", and remove child "pid".
277 * We move everything up by one, since the new "deleted" will
280 static void remove_child(pid_t pid
, unsigned deleted
, unsigned spawned
)
284 deleted
%= MAX_CHILDREN
;
285 spawned
%= MAX_CHILDREN
;
286 if (live_child
[deleted
].pid
== pid
) {
287 live_child
[deleted
].pid
= -1;
290 n
= live_child
[deleted
];
293 deleted
= (deleted
+ 1) % MAX_CHILDREN
;
294 if (deleted
== spawned
)
295 die("could not find dead child %d\n", pid
);
296 m
= live_child
[deleted
];
297 live_child
[deleted
] = n
;
305 * This gets called if the number of connections grows
306 * past "max_connections".
308 * We _should_ start off by searching for connections
309 * from the same IP, and if there is some address wth
310 * multiple connections, we should kill that first.
312 * As it is, we just "randomly" kill 25% of the connections,
313 * and our pseudo-random generator sucks too. I have no
316 * Really, this is just a place-holder for a _real_ algorithm.
318 static void kill_some_children(int signo
, unsigned start
, unsigned stop
)
320 start
%= MAX_CHILDREN
;
321 stop
%= MAX_CHILDREN
;
322 while (start
!= stop
) {
324 kill(live_child
[start
].pid
, signo
);
325 start
= (start
+ 1) % MAX_CHILDREN
;
329 static void check_max_connections(void)
333 unsigned spawned
, reaped
, deleted
;
335 spawned
= children_spawned
;
336 reaped
= children_reaped
;
337 deleted
= children_deleted
;
339 while (deleted
< reaped
) {
340 pid_t pid
= dead_child
[deleted
% MAX_CHILDREN
];
341 remove_child(pid
, deleted
, spawned
);
344 children_deleted
= deleted
;
346 active
= spawned
- deleted
;
347 if (active
<= max_connections
)
350 /* Kill some unstarted connections with SIGTERM */
351 kill_some_children(SIGTERM
, deleted
, spawned
);
352 if (active
<= max_connections
<< 1)
355 /* If the SIGTERM thing isn't helping use SIGKILL */
356 kill_some_children(SIGKILL
, deleted
, spawned
);
361 static void handle(int incoming
, struct sockaddr
*addr
, int addrlen
)
364 char addrbuf
[256] = "";
374 idx
= children_spawned
% MAX_CHILDREN
;
376 add_child(idx
, pid
, addr
, addrlen
);
378 check_max_connections();
386 if (addr
->sa_family
== AF_INET
) {
387 struct sockaddr_in
*sin_addr
= (void *) addr
;
388 inet_ntop(AF_INET
, &sin_addr
->sin_addr
, addrbuf
, sizeof(addrbuf
));
389 port
= sin_addr
->sin_port
;
392 } else if (addr
->sa_family
== AF_INET6
) {
393 struct sockaddr_in6
*sin6_addr
= (void *) addr
;
396 *buf
++ = '['; *buf
= '\0'; /* stpcpy() is cool */
397 inet_ntop(AF_INET6
, &sin6_addr
->sin6_addr
, buf
, sizeof(addrbuf
) - 1);
400 port
= sin6_addr
->sin6_port
;
403 loginfo("Connection from %s:%d", addrbuf
, port
);
408 static void child_handler(int signo
)
412 pid_t pid
= waitpid(-1, &status
, WNOHANG
);
415 unsigned reaped
= children_reaped
;
416 dead_child
[reaped
% MAX_CHILDREN
] = pid
;
417 children_reaped
= reaped
+ 1;
418 /* XXX: Custom logging, since we don't wanna getpid() */
421 if (!WIFEXITED(status
) || WEXITSTATUS(status
) > 0)
422 dead
= " (with error)";
424 syslog(LOG_INFO
, "[%d] Disconnected%s", pid
, dead
);
426 fprintf(stderr
, "[%d] Disconnected%s\n", pid
, dead
);
436 static int socksetup(int port
, int **socklist_p
)
438 int socknum
= 0, *socklist
= NULL
;
440 char pbuf
[NI_MAXSERV
];
442 struct addrinfo hints
, *ai0
, *ai
;
445 sprintf(pbuf
, "%d", port
);
446 memset(&hints
, 0, sizeof(hints
));
447 hints
.ai_family
= AF_UNSPEC
;
448 hints
.ai_socktype
= SOCK_STREAM
;
449 hints
.ai_protocol
= IPPROTO_TCP
;
450 hints
.ai_flags
= AI_PASSIVE
;
452 gai
= getaddrinfo(NULL
, pbuf
, &hints
, &ai0
);
454 die("getaddrinfo() failed: %s\n", gai_strerror(gai
));
456 for (ai
= ai0
; ai
; ai
= ai
->ai_next
) {
460 sockfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
463 if (sockfd
>= FD_SETSIZE
) {
464 error("too large socket descriptor.");
470 if (ai
->ai_family
== AF_INET6
) {
472 setsockopt(sockfd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
474 /* Note: error is not fatal */
478 if (bind(sockfd
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
480 continue; /* not fatal */
482 if (listen(sockfd
, 5) < 0) {
484 continue; /* not fatal */
487 newlist
= realloc(socklist
, sizeof(int) * (socknum
+ 1));
489 die("memory allocation failed: %s", strerror(errno
));
492 socklist
[socknum
++] = sockfd
;
500 *socklist_p
= socklist
;
506 static int socksetup(int port
, int **socklist_p
)
508 struct sockaddr_in sin
;
511 sockfd
= socket(AF_INET
, SOCK_STREAM
, 0);
515 memset(&sin
, 0, sizeof sin
);
516 sin
.sin_family
= AF_INET
;
517 sin
.sin_addr
.s_addr
= htonl(INADDR_ANY
);
518 sin
.sin_port
= htons(port
);
520 if ( bind(sockfd
, (struct sockaddr
*)&sin
, sizeof sin
) < 0 ) {
525 if (listen(sockfd
, 5) < 0) {
530 *socklist_p
= xmalloc(sizeof(int));
531 **socklist_p
= sockfd
;
537 static int service_loop(int socknum
, int *socklist
)
542 pfd
= xcalloc(socknum
, sizeof(struct pollfd
));
544 for (i
= 0; i
< socknum
; i
++) {
545 pfd
[i
].fd
= socklist
[i
];
546 pfd
[i
].events
= POLLIN
;
549 signal(SIGCHLD
, child_handler
);
554 if (poll(pfd
, socknum
, -1) < 0) {
555 if (errno
!= EINTR
) {
556 error("poll failed, resuming: %s",
563 for (i
= 0; i
< socknum
; i
++) {
564 if (pfd
[i
].revents
& POLLIN
) {
565 struct sockaddr_storage ss
;
566 unsigned int sslen
= sizeof(ss
);
567 int incoming
= accept(pfd
[i
].fd
, (struct sockaddr
*)&ss
, &sslen
);
575 die("accept returned %s", strerror(errno
));
578 handle(incoming
, (struct sockaddr
*)&ss
, sslen
);
584 static int serve(int port
)
586 int socknum
, *socklist
;
588 socknum
= socksetup(port
, &socklist
);
590 die("unable to allocate any listen sockets on port %u", port
);
592 return service_loop(socknum
, socklist
);
595 int main(int argc
, char **argv
)
597 int port
= DEFAULT_GIT_PORT
;
601 for (i
= 1; i
< argc
; i
++) {
604 if (!strncmp(arg
, "--port=", 7)) {
607 n
= strtoul(arg
+7, &end
, 0);
608 if (arg
[7] && !*end
) {
613 if (!strcmp(arg
, "--inetd")) {
618 if (!strcmp(arg
, "--verbose")) {
622 if (!strcmp(arg
, "--syslog")) {
626 if (!strcmp(arg
, "--export-all")) {
627 export_all_trees
= 1;
630 if (!strncmp(arg
, "--timeout=", 10)) {
631 timeout
= atoi(arg
+10);
634 if (!strncmp(arg
, "--init-timeout=", 15)) {
635 init_timeout
= atoi(arg
+15);
638 if (!strcmp(arg
, "--strict-paths")) {
642 if (!strcmp(arg
, "--")) {
643 ok_paths
= &argv
[i
+1];
645 } else if (arg
[0] != '-') {
654 openlog("git-daemon", 0, LOG_DAEMON
);
656 if (strict_paths
&& (!ok_paths
|| !*ok_paths
)) {
658 die("git-daemon: option --strict-paths requires a whitelist");
660 logerror("option --strict-paths requires a whitelist");
665 fclose(stderr
); //FIXME: workaround