5 #include <sys/socket.h>
8 #include <netinet/in.h>
12 static int log_syslog;
15 static const char daemon_usage[] = "git-daemon [--verbose] [--syslog] [--inetd | --port=n] [--export-all] [directory...]";
17 /* List of acceptable pathname prefixes */
18 static char **ok_paths = NULL;
20 /* If this is set, git-daemon-export-ok is not required */
21 static int export_all_trees = 0;
24 static void logreport(int priority, const char *err, va_list params)
26 /* We should do a single write so that it is atomic and output
27 * of several processes do not get intermingled. */
32 /* sizeof(buf) should be big enough for "[pid] \n" */
33 buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
35 maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
36 msglen = vsnprintf(buf + buflen, maxlen, err, params);
39 syslog(priority, "%s", buf);
43 /* maxlen counted our own LF but also counts space given to
44 * vsnprintf for the terminating NUL. We want to make sure that
45 * we have space for our own LF and NUL after the "meat" of the
46 * message, so truncate it at maxlen - 1.
48 if (msglen > maxlen - 1)
51 msglen = 0; /* Protect against weird return values. */
57 write(2, buf, buflen);
60 static void logerror(const char *err, ...)
63 va_start(params, err);
64 logreport(LOG_ERR, err, params);
68 static void loginfo(const char *err, ...)
73 va_start(params, err);
74 logreport(LOG_INFO, err, params);
78 static int path_ok(const char *dir)
84 /* The pathname here should be an absolute path. */
93 } else if ( *p == '\0' ) {
94 /* Reject "." and ".." at the end of the path */
95 if ( sl && ndot > 0 && ndot < 3 )
100 } else if ( *p == '/' ) {
101 /* Refuse "", "." or ".." */
102 if ( sl && ndot < 3 )
112 if ( ok_paths && *ok_paths ) {
114 int dirlen = strlen(dir);
116 for ( pp = ok_paths ; *pp ; pp++ ) {
117 int len = strlen(*pp);
118 if ( len <= dirlen &&
119 !strncmp(*pp, dir, len) &&
120 (dir[len] == '/' || dir[len] == '\0') ) {
127 return 0; /* Path not in whitelist */
130 return 1; /* Path acceptable */
133 static int set_dir(const char *dir)
144 * Security on the cheap.
146 * We want a readable HEAD, usable "objects" directory, and
147 * a "git-daemon-export-ok" flag that says that the other side
148 * is ok with us doing this.
150 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
155 if (access("objects/", X_OK) || access("HEAD", R_OK)) {
160 /* If all this passed, we're OK */
164 static int upload(char *dir)
166 /* Try paths in this order */
167 static const char *paths[] = { "%s", "%s/.git", "%s.git", "%s.git/.git", NULL };
169 /* Enough for the longest path above including final null */
170 int buflen = strlen(dir)+10;
171 char *dirbuf = xmalloc(buflen);
173 loginfo("Request for '%s'", dir);
175 for ( pp = paths ; *pp ; pp++ ) {
176 snprintf(dirbuf, buflen, *pp, dir);
177 if ( !set_dir(dirbuf) )
182 logerror("Cannot set directory '%s': %s", dir, strerror(errno));
187 * We'll ignore SIGTERM from now on, we have a
190 signal(SIGTERM, SIG_IGN);
192 /* git-upload-pack only ever reads stuff, so this is safe */
193 execlp("git-upload-pack", "git-upload-pack", ".", NULL);
197 static int execute(void)
199 static char line[1000];
202 len = packet_read_line(0, line, sizeof(line));
204 if (len && line[len-1] == '\n')
207 if (!strncmp("git-upload-pack /", line, 17))
208 return upload(line+16);
210 logerror("Protocol error: '%s'", line);
216 * We count spawned/reaped separately, just to avoid any
217 * races when updating them from signals. The SIGCHLD handler
218 * will only update children_reaped, and the fork logic will
219 * only update children_spawned.
221 * MAX_CHILDREN should be a power-of-two to make the modulus
222 * operation cheap. It should also be at least twice
223 * the maximum number of connections we will ever allow.
225 #define MAX_CHILDREN 128
227 static int max_connections = 25;
229 /* These are updated by the signal handler */
230 static volatile unsigned int children_reaped = 0;
231 static pid_t dead_child[MAX_CHILDREN];
233 /* These are updated by the main loop */
234 static unsigned int children_spawned = 0;
235 static unsigned int children_deleted = 0;
237 static struct child {
240 struct sockaddr_storage address;
241 } live_child[MAX_CHILDREN];
243 static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
245 live_child[idx].pid = pid;
246 live_child[idx].addrlen = addrlen;
247 memcpy(&live_child[idx].address, addr, addrlen);
251 * Walk from "deleted" to "spawned", and remove child "pid".
253 * We move everything up by one, since the new "deleted" will
256 static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
260 deleted %= MAX_CHILDREN;
261 spawned %= MAX_CHILDREN;
262 if (live_child[deleted].pid == pid) {
263 live_child[deleted].pid = -1;
266 n = live_child[deleted];
269 deleted = (deleted + 1) % MAX_CHILDREN;
270 if (deleted == spawned)
271 die("could not find dead child %d\n", pid);
272 m = live_child[deleted];
273 live_child[deleted] = n;
281 * This gets called if the number of connections grows
282 * past "max_connections".
284 * We _should_ start off by searching for connections
285 * from the same IP, and if there is some address wth
286 * multiple connections, we should kill that first.
288 * As it is, we just "randomly" kill 25% of the connections,
289 * and our pseudo-random generator sucks too. I have no
292 * Really, this is just a place-holder for a _real_ algorithm.
294 static void kill_some_children(int signo, unsigned start, unsigned stop)
296 start %= MAX_CHILDREN;
297 stop %= MAX_CHILDREN;
298 while (start != stop) {
300 kill(live_child[start].pid, signo);
301 start = (start + 1) % MAX_CHILDREN;
305 static void check_max_connections(void)
309 unsigned spawned, reaped, deleted;
311 spawned = children_spawned;
312 reaped = children_reaped;
313 deleted = children_deleted;
315 while (deleted < reaped) {
316 pid_t pid = dead_child[deleted % MAX_CHILDREN];
317 remove_child(pid, deleted, spawned);
320 children_deleted = deleted;
322 active = spawned - deleted;
323 if (active <= max_connections)
326 /* Kill some unstarted connections with SIGTERM */
327 kill_some_children(SIGTERM, deleted, spawned);
328 if (active <= max_connections << 1)
331 /* If the SIGTERM thing isn't helping use SIGKILL */
332 kill_some_children(SIGKILL, deleted, spawned);
337 static void handle(int incoming, struct sockaddr *addr, int addrlen)
340 char addrbuf[256] = "";
350 idx = children_spawned % MAX_CHILDREN;
352 add_child(idx, pid, addr, addrlen);
354 check_max_connections();
362 if (addr->sa_family == AF_INET) {
363 struct sockaddr_in *sin_addr = (void *) addr;
364 inet_ntop(AF_INET, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
365 port = sin_addr->sin_port;
367 } else if (addr->sa_family == AF_INET6) {
368 struct sockaddr_in6 *sin6_addr = (void *) addr;
371 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
372 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
375 port = sin6_addr->sin6_port;
377 loginfo("Connection from %s:%d", addrbuf, port);
382 static void child_handler(int signo)
386 pid_t pid = waitpid(-1, &status, WNOHANG);
389 unsigned reaped = children_reaped;
390 dead_child[reaped % MAX_CHILDREN] = pid;
391 children_reaped = reaped + 1;
392 /* XXX: Custom logging, since we don't wanna getpid() */
395 if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
396 dead = " (with error)";
398 syslog(LOG_INFO, "[%d] Disconnected%s", pid, dead);
400 fprintf(stderr, "[%d] Disconnected%s\n", pid, dead);
408 static int serve(int port)
410 struct addrinfo hints, *ai0, *ai;
412 int socknum = 0, *socklist = NULL;
414 fd_set fds_init, fds;
415 char pbuf[NI_MAXSERV];
417 signal(SIGCHLD, child_handler);
419 sprintf(pbuf, "%d", port);
420 memset(&hints, 0, sizeof(hints));
421 hints.ai_family = AF_UNSPEC;
422 hints.ai_socktype = SOCK_STREAM;
423 hints.ai_protocol = IPPROTO_TCP;
424 hints.ai_flags = AI_PASSIVE;
426 gai = getaddrinfo(NULL, pbuf, &hints, &ai0);
428 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
432 for (ai = ai0; ai; ai = ai->ai_next) {
436 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
439 if (sockfd >= FD_SETSIZE) {
440 error("too large socket descriptor.");
446 if (ai->ai_family == AF_INET6) {
448 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
450 /* Note: error is not fatal */
454 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
456 continue; /* not fatal */
458 if (listen(sockfd, 5) < 0) {
460 continue; /* not fatal */
463 newlist = realloc(socklist, sizeof(int) * (socknum + 1));
465 die("memory allocation failed: %s", strerror(errno));
468 socklist[socknum++] = sockfd;
470 FD_SET(sockfd, &fds_init);
478 die("unable to allocate any listen sockets on port %u", port);
484 if (select(maxfd + 1, &fds, NULL, NULL, NULL) < 0) {
485 if (errno != EINTR) {
486 error("select failed, resuming: %s",
493 for (i = 0; i < socknum; i++) {
494 int sockfd = socklist[i];
496 if (FD_ISSET(sockfd, &fds)) {
497 struct sockaddr_storage ss;
498 int sslen = sizeof(ss);
499 int incoming = accept(sockfd, (struct sockaddr *)&ss, &sslen);
507 die("accept returned %s", strerror(errno));
510 handle(incoming, (struct sockaddr *)&ss, sslen);
516 int main(int argc, char **argv)
518 int port = DEFAULT_GIT_PORT;
522 for (i = 1; i < argc; i++) {
525 if (!strncmp(arg, "--port=", 7)) {
528 n = strtoul(arg+7, &end, 0);
529 if (arg[7] && !*end) {
534 if (!strcmp(arg, "--inetd")) {
538 if (!strcmp(arg, "--verbose")) {
542 if (!strcmp(arg, "--syslog")) {
544 openlog("git-daemon", 0, LOG_DAEMON);
547 if (!strcmp(arg, "--export-all")) {
548 export_all_trees = 1;
551 if (!strcmp(arg, "--")) {
552 ok_paths = &argv[i+1];
554 } else if (arg[0] != '-') {
563 fclose(stderr); //FIXME: workaround