6 #include <sys/socket.h>
10 #include <netinet/in.h>
11 #include <arpa/inet.h>
14 static int log_syslog;
17 static const char daemon_usage[] = "git-daemon [--verbose] [--syslog] [--inetd | --port=n] [--export-all] [directory...]";
19 /* List of acceptable pathname prefixes */
20 static char **ok_paths = NULL;
22 /* If this is set, git-daemon-export-ok is not required */
23 static int export_all_trees = 0;
26 static void logreport(int priority, const char *err, va_list params)
28 /* We should do a single write so that it is atomic and output
29 * of several processes do not get intermingled. */
34 /* sizeof(buf) should be big enough for "[pid] \n" */
35 buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
37 maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
38 msglen = vsnprintf(buf + buflen, maxlen, err, params);
41 syslog(priority, "%s", buf);
45 /* maxlen counted our own LF but also counts space given to
46 * vsnprintf for the terminating NUL. We want to make sure that
47 * we have space for our own LF and NUL after the "meat" of the
48 * message, so truncate it at maxlen - 1.
50 if (msglen > maxlen - 1)
53 msglen = 0; /* Protect against weird return values. */
59 write(2, buf, buflen);
62 static void logerror(const char *err, ...)
65 va_start(params, err);
66 logreport(LOG_ERR, err, params);
70 static void loginfo(const char *err, ...)
75 va_start(params, err);
76 logreport(LOG_INFO, err, params);
80 static int path_ok(const char *dir)
89 } else if ( *p == '/' || *p == '\0' ) {
90 if ( sl && ndot > 0 && ndot < 3 )
91 return 0; /* . or .. in path */
94 break; /* End of string and all is good */
101 if ( ok_paths && *ok_paths ) {
103 int dirlen = strlen(dir); /* read_packet_line can return embedded \0 */
105 for ( pp = ok_paths ; *pp ; pp++ ) {
106 int len = strlen(*pp);
107 if ( len <= dirlen &&
108 !strncmp(*pp, dir, len) &&
109 (dir[len] == '/' || dir[len] == '\0') ) {
116 return 0; /* Path not in whitelist */
119 return 1; /* Path acceptable */
122 static int upload(char *dir, int dirlen)
124 loginfo("Request for '%s'", dir);
127 logerror("Forbidden directory: %s\n", dir);
131 if (chdir(dir) < 0) {
132 logerror("Cannot chdir('%s'): %s", dir, strerror(errno));
139 * Security on the cheap.
141 * We want a readable HEAD, usable "objects" directory, and
142 * a "git-daemon-export-ok" flag that says that the other side
143 * is ok with us doing this.
145 if ((!export_all_trees && access("git-daemon-export-ok", F_OK)) ||
146 access("objects/00", X_OK) ||
147 access("HEAD", R_OK)) {
148 logerror("Not a valid git-daemon-enabled repository: '%s'", dir);
153 * We'll ignore SIGTERM from now on, we have a
156 signal(SIGTERM, SIG_IGN);
158 /* git-upload-pack only ever reads stuff, so this is safe */
159 execlp("git-upload-pack", "git-upload-pack", ".", NULL);
163 static int execute(void)
165 static char line[1000];
168 len = packet_read_line(0, line, sizeof(line));
170 if (len && line[len-1] == '\n')
173 if (!strncmp("git-upload-pack /", line, 17))
174 return upload(line + 16, len - 16);
176 logerror("Protocol error: '%s'", line);
182 * We count spawned/reaped separately, just to avoid any
183 * races when updating them from signals. The SIGCHLD handler
184 * will only update children_reaped, and the fork logic will
185 * only update children_spawned.
187 * MAX_CHILDREN should be a power-of-two to make the modulus
188 * operation cheap. It should also be at least twice
189 * the maximum number of connections we will ever allow.
191 #define MAX_CHILDREN 128
193 static int max_connections = 25;
195 /* These are updated by the signal handler */
196 static volatile unsigned int children_reaped = 0;
197 static pid_t dead_child[MAX_CHILDREN];
199 /* These are updated by the main loop */
200 static unsigned int children_spawned = 0;
201 static unsigned int children_deleted = 0;
203 static struct child {
206 struct sockaddr_storage address;
207 } live_child[MAX_CHILDREN];
209 static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
211 live_child[idx].pid = pid;
212 live_child[idx].addrlen = addrlen;
213 memcpy(&live_child[idx].address, addr, addrlen);
217 * Walk from "deleted" to "spawned", and remove child "pid".
219 * We move everything up by one, since the new "deleted" will
222 static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
226 deleted %= MAX_CHILDREN;
227 spawned %= MAX_CHILDREN;
228 if (live_child[deleted].pid == pid) {
229 live_child[deleted].pid = -1;
232 n = live_child[deleted];
235 deleted = (deleted + 1) % MAX_CHILDREN;
236 if (deleted == spawned)
237 die("could not find dead child %d\n", pid);
238 m = live_child[deleted];
239 live_child[deleted] = n;
247 * This gets called if the number of connections grows
248 * past "max_connections".
250 * We _should_ start off by searching for connections
251 * from the same IP, and if there is some address wth
252 * multiple connections, we should kill that first.
254 * As it is, we just "randomly" kill 25% of the connections,
255 * and our pseudo-random generator sucks too. I have no
258 * Really, this is just a place-holder for a _real_ algorithm.
260 static void kill_some_children(int signo, unsigned start, unsigned stop)
262 start %= MAX_CHILDREN;
263 stop %= MAX_CHILDREN;
264 while (start != stop) {
266 kill(live_child[start].pid, signo);
267 start = (start + 1) % MAX_CHILDREN;
271 static void check_max_connections(void)
275 unsigned spawned, reaped, deleted;
277 spawned = children_spawned;
278 reaped = children_reaped;
279 deleted = children_deleted;
281 while (deleted < reaped) {
282 pid_t pid = dead_child[deleted % MAX_CHILDREN];
283 remove_child(pid, deleted, spawned);
286 children_deleted = deleted;
288 active = spawned - deleted;
289 if (active <= max_connections)
292 /* Kill some unstarted connections with SIGTERM */
293 kill_some_children(SIGTERM, deleted, spawned);
294 if (active <= max_connections << 1)
297 /* If the SIGTERM thing isn't helping use SIGKILL */
298 kill_some_children(SIGKILL, deleted, spawned);
303 static void handle(int incoming, struct sockaddr *addr, int addrlen)
306 char addrbuf[256] = "";
316 idx = children_spawned % MAX_CHILDREN;
318 add_child(idx, pid, addr, addrlen);
320 check_max_connections();
328 if (addr->sa_family == AF_INET) {
329 struct sockaddr_in *sin_addr = (void *) addr;
330 inet_ntop(AF_INET, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
331 port = sin_addr->sin_port;
334 } else if (addr->sa_family == AF_INET6) {
335 struct sockaddr_in6 *sin6_addr = (void *) addr;
338 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
339 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
342 port = sin6_addr->sin6_port;
345 loginfo("Connection from %s:%d", addrbuf, port);
350 static void child_handler(int signo)
354 pid_t pid = waitpid(-1, &status, WNOHANG);
357 unsigned reaped = children_reaped;
358 dead_child[reaped % MAX_CHILDREN] = pid;
359 children_reaped = reaped + 1;
360 /* XXX: Custom logging, since we don't wanna getpid() */
363 if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
364 dead = " (with error)";
366 syslog(LOG_INFO, "[%d] Disconnected%s", pid, dead);
368 fprintf(stderr, "[%d] Disconnected%s\n", pid, dead);
378 static int socksetup(int port, int **socklist_p)
380 int socknum = 0, *socklist = NULL;
382 char pbuf[NI_MAXSERV];
384 struct addrinfo hints, *ai0, *ai;
387 sprintf(pbuf, "%d", port);
388 memset(&hints, 0, sizeof(hints));
389 hints.ai_family = AF_UNSPEC;
390 hints.ai_socktype = SOCK_STREAM;
391 hints.ai_protocol = IPPROTO_TCP;
392 hints.ai_flags = AI_PASSIVE;
394 gai = getaddrinfo(NULL, pbuf, &hints, &ai0);
396 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
398 for (ai = ai0; ai; ai = ai->ai_next) {
402 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
405 if (sockfd >= FD_SETSIZE) {
406 error("too large socket descriptor.");
412 if (ai->ai_family == AF_INET6) {
414 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
416 /* Note: error is not fatal */
420 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
422 continue; /* not fatal */
424 if (listen(sockfd, 5) < 0) {
426 continue; /* not fatal */
429 newlist = realloc(socklist, sizeof(int) * (socknum + 1));
431 die("memory allocation failed: %s", strerror(errno));
434 socklist[socknum++] = sockfd;
442 *socklist_p = socklist;
448 static int socksetup(int port, int **socklist_p)
450 struct sockaddr_in sin;
453 sockfd = socket(AF_INET, SOCK_STREAM, 0);
457 memset(&sin, 0, sizeof sin);
458 sin.sin_family = AF_INET;
459 sin.sin_addr.s_addr = htonl(INADDR_ANY);
460 sin.sin_port = htons(port);
462 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
467 *socklist_p = malloc(sizeof(int));
469 die("memory allocation failed: %s", strerror(errno));
470 **socklist_p = sockfd;
475 static int service_loop(int socknum, int *socklist)
480 pfd = calloc(socknum, sizeof(struct pollfd));
482 die("memory allocation failed: %s", strerror(errno));
484 for (i = 0; i < socknum; i++) {
485 pfd[i].fd = socklist[i];
486 pfd[i].events = POLLIN;
492 if (poll(pfd, socknum, 0) < 0) {
493 if (errno != EINTR) {
494 error("poll failed, resuming: %s",
501 for (i = 0; i < socknum; i++) {
502 if (pfd[i].revents & POLLIN) {
503 struct sockaddr_storage ss;
504 int sslen = sizeof(ss);
505 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
513 die("accept returned %s", strerror(errno));
516 handle(incoming, (struct sockaddr *)&ss, sslen);
522 static int serve(int port)
524 int socknum, *socklist;
526 signal(SIGCHLD, child_handler);
528 socknum = socksetup(port, &socklist);
530 die("unable to allocate any listen sockets on port %u", port);
532 return service_loop(socknum, socklist);
535 int main(int argc, char **argv)
537 int port = DEFAULT_GIT_PORT;
541 for (i = 1; i < argc; i++) {
544 if (!strncmp(arg, "--port=", 7)) {
547 n = strtoul(arg+7, &end, 0);
548 if (arg[7] && !*end) {
553 if (!strcmp(arg, "--inetd")) {
557 if (!strcmp(arg, "--verbose")) {
561 if (!strcmp(arg, "--syslog")) {
563 openlog("git-daemon", 0, LOG_DAEMON);
566 if (!strcmp(arg, "--export-all")) {
567 export_all_trees = 1;
570 if (!strcmp(arg, "--")) {
571 ok_paths = &argv[i+1];
573 } else if (arg[0] != '-') {
582 fclose(stderr); //FIXME: workaround