git-daemon support for user-relative paths.
[alt-git.git] / daemon.c
blobac4c94bc709350471d66180d427a7e5df91c6235
1 #include <signal.h>
2 #include <sys/wait.h>
3 #include <sys/socket.h>
4 #include <sys/time.h>
5 #include <sys/poll.h>
6 #include <netdb.h>
7 #include <netinet/in.h>
8 #include <arpa/inet.h>
9 #include <syslog.h>
10 #include "pkt-line.h"
11 #include "cache.h"
13 static int log_syslog;
14 static int verbose;
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. */
35 char buf[1024];
36 int buflen;
37 int maxlen, msglen;
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);
45 if (log_syslog) {
46 syslog(priority, "%s", buf);
47 return;
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)
56 msglen = maxlen - 1;
57 else if (msglen < 0)
58 msglen = 0; /* Protect against weird return values. */
59 buflen += msglen;
61 buf[buflen++] = '\n';
62 buf[buflen] = '\0';
64 write(2, buf, buflen);
67 static void logerror(const char *err, ...)
69 va_list params;
70 va_start(params, err);
71 logreport(LOG_ERR, err, params);
72 va_end(params);
75 static void loginfo(const char *err, ...)
77 va_list params;
78 if (!verbose)
79 return;
80 va_start(params, err);
81 logreport(LOG_INFO, err, params);
82 va_end(params);
85 static char *path_ok(char *dir)
87 char *path = enter_repo(dir, strict_paths);
89 if (!path) {
90 logerror("'%s': unable to chdir or not a git archive", dir);
91 return NULL;
94 if ( ok_paths && *ok_paths ) {
95 char **pp = NULL;
96 int dirlen = strlen(dir);
97 int pathlen = strlen(path);
99 for ( pp = ok_paths ; *pp ; pp++ ) {
100 int len = strlen(*pp);
101 /* because of symlinks we must match both what the
102 * user passed and the canonicalized path, otherwise
103 * the user can send a string matching either a whitelist
104 * entry or an actual directory exactly and still not
105 * get through */
106 if (len <= pathlen && !memcmp(*pp, path, len)) {
107 if (path[len] == '\0' || (!strict_paths && path[len] == '/'))
108 return path;
110 if (len <= dirlen && !memcmp(*pp, dir, len)) {
111 if (dir[len] == '\0' || (!strict_paths && dir[len] == '/'))
112 return path;
116 else {
117 /* be backwards compatible */
118 if (!strict_paths)
119 return path;
122 logerror("'%s': not in whitelist", path);
123 return NULL; /* Fallthrough. Deny by default */
126 static int upload(char *dir)
128 /* Timeout as string */
129 char timeout_buf[64];
130 const char *path;
132 loginfo("Request for '%s'", dir);
134 if (!(path = path_ok(dir)))
135 return -1;
138 * Security on the cheap.
140 * We want a readable HEAD, usable "objects" directory, and
141 * a "git-daemon-export-ok" flag that says that the other side
142 * is ok with us doing this.
144 * path_ok() uses enter_repo() and does whitelist checking.
145 * We only need to make sure the repository is exported.
148 if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
149 logerror("'%s': repository not exported.", path);
150 errno = EACCES;
151 return -1;
155 * We'll ignore SIGTERM from now on, we have a
156 * good client.
158 signal(SIGTERM, SIG_IGN);
160 snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
162 /* git-upload-pack only ever reads stuff, so this is safe */
163 execlp("git-upload-pack", "git-upload-pack", "--strict", timeout_buf, path, NULL);
164 return -1;
167 static int execute(void)
169 static char line[1000];
170 int len;
172 alarm(init_timeout ? init_timeout : timeout);
173 len = packet_read_line(0, line, sizeof(line));
174 alarm(0);
176 if (len && line[len-1] == '\n')
177 line[--len] = 0;
179 if (!strncmp("git-upload-pack ", line, 16))
180 return upload(line+16);
182 logerror("Protocol error: '%s'", line);
183 return -1;
188 * We count spawned/reaped separately, just to avoid any
189 * races when updating them from signals. The SIGCHLD handler
190 * will only update children_reaped, and the fork logic will
191 * only update children_spawned.
193 * MAX_CHILDREN should be a power-of-two to make the modulus
194 * operation cheap. It should also be at least twice
195 * the maximum number of connections we will ever allow.
197 #define MAX_CHILDREN 128
199 static int max_connections = 25;
201 /* These are updated by the signal handler */
202 static volatile unsigned int children_reaped = 0;
203 static pid_t dead_child[MAX_CHILDREN];
205 /* These are updated by the main loop */
206 static unsigned int children_spawned = 0;
207 static unsigned int children_deleted = 0;
209 static struct child {
210 pid_t pid;
211 int addrlen;
212 struct sockaddr_storage address;
213 } live_child[MAX_CHILDREN];
215 static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
217 live_child[idx].pid = pid;
218 live_child[idx].addrlen = addrlen;
219 memcpy(&live_child[idx].address, addr, addrlen);
223 * Walk from "deleted" to "spawned", and remove child "pid".
225 * We move everything up by one, since the new "deleted" will
226 * be one higher.
228 static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
230 struct child n;
232 deleted %= MAX_CHILDREN;
233 spawned %= MAX_CHILDREN;
234 if (live_child[deleted].pid == pid) {
235 live_child[deleted].pid = -1;
236 return;
238 n = live_child[deleted];
239 for (;;) {
240 struct child m;
241 deleted = (deleted + 1) % MAX_CHILDREN;
242 if (deleted == spawned)
243 die("could not find dead child %d\n", pid);
244 m = live_child[deleted];
245 live_child[deleted] = n;
246 if (m.pid == pid)
247 return;
248 n = m;
253 * This gets called if the number of connections grows
254 * past "max_connections".
256 * We _should_ start off by searching for connections
257 * from the same IP, and if there is some address wth
258 * multiple connections, we should kill that first.
260 * As it is, we just "randomly" kill 25% of the connections,
261 * and our pseudo-random generator sucks too. I have no
262 * shame.
264 * Really, this is just a place-holder for a _real_ algorithm.
266 static void kill_some_children(int signo, unsigned start, unsigned stop)
268 start %= MAX_CHILDREN;
269 stop %= MAX_CHILDREN;
270 while (start != stop) {
271 if (!(start & 3))
272 kill(live_child[start].pid, signo);
273 start = (start + 1) % MAX_CHILDREN;
277 static void check_max_connections(void)
279 for (;;) {
280 int active;
281 unsigned spawned, reaped, deleted;
283 spawned = children_spawned;
284 reaped = children_reaped;
285 deleted = children_deleted;
287 while (deleted < reaped) {
288 pid_t pid = dead_child[deleted % MAX_CHILDREN];
289 remove_child(pid, deleted, spawned);
290 deleted++;
292 children_deleted = deleted;
294 active = spawned - deleted;
295 if (active <= max_connections)
296 break;
298 /* Kill some unstarted connections with SIGTERM */
299 kill_some_children(SIGTERM, deleted, spawned);
300 if (active <= max_connections << 1)
301 break;
303 /* If the SIGTERM thing isn't helping use SIGKILL */
304 kill_some_children(SIGKILL, deleted, spawned);
305 sleep(1);
309 static void handle(int incoming, struct sockaddr *addr, int addrlen)
311 pid_t pid = fork();
312 char addrbuf[256] = "";
313 int port = -1;
315 if (pid) {
316 unsigned idx;
318 close(incoming);
319 if (pid < 0)
320 return;
322 idx = children_spawned % MAX_CHILDREN;
323 children_spawned++;
324 add_child(idx, pid, addr, addrlen);
326 check_max_connections();
327 return;
330 dup2(incoming, 0);
331 dup2(incoming, 1);
332 close(incoming);
334 if (addr->sa_family == AF_INET) {
335 struct sockaddr_in *sin_addr = (void *) addr;
336 inet_ntop(AF_INET, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
337 port = sin_addr->sin_port;
339 #ifndef NO_IPV6
340 } else if (addr->sa_family == AF_INET6) {
341 struct sockaddr_in6 *sin6_addr = (void *) addr;
343 char *buf = addrbuf;
344 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
345 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
346 strcat(buf, "]");
348 port = sin6_addr->sin6_port;
349 #endif
351 loginfo("Connection from %s:%d", addrbuf, port);
353 exit(execute());
356 static void child_handler(int signo)
358 for (;;) {
359 int status;
360 pid_t pid = waitpid(-1, &status, WNOHANG);
362 if (pid > 0) {
363 unsigned reaped = children_reaped;
364 dead_child[reaped % MAX_CHILDREN] = pid;
365 children_reaped = reaped + 1;
366 /* XXX: Custom logging, since we don't wanna getpid() */
367 if (verbose) {
368 char *dead = "";
369 if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
370 dead = " (with error)";
371 if (log_syslog)
372 syslog(LOG_INFO, "[%d] Disconnected%s", pid, dead);
373 else
374 fprintf(stderr, "[%d] Disconnected%s\n", pid, dead);
376 continue;
378 break;
382 #ifndef NO_IPV6
384 static int socksetup(int port, int **socklist_p)
386 int socknum = 0, *socklist = NULL;
387 int maxfd = -1;
388 char pbuf[NI_MAXSERV];
390 struct addrinfo hints, *ai0, *ai;
391 int gai;
393 sprintf(pbuf, "%d", port);
394 memset(&hints, 0, sizeof(hints));
395 hints.ai_family = AF_UNSPEC;
396 hints.ai_socktype = SOCK_STREAM;
397 hints.ai_protocol = IPPROTO_TCP;
398 hints.ai_flags = AI_PASSIVE;
400 gai = getaddrinfo(NULL, pbuf, &hints, &ai0);
401 if (gai)
402 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
404 for (ai = ai0; ai; ai = ai->ai_next) {
405 int sockfd;
406 int *newlist;
408 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
409 if (sockfd < 0)
410 continue;
411 if (sockfd >= FD_SETSIZE) {
412 error("too large socket descriptor.");
413 close(sockfd);
414 continue;
417 #ifdef IPV6_V6ONLY
418 if (ai->ai_family == AF_INET6) {
419 int on = 1;
420 setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
421 &on, sizeof(on));
422 /* Note: error is not fatal */
424 #endif
426 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
427 close(sockfd);
428 continue; /* not fatal */
430 if (listen(sockfd, 5) < 0) {
431 close(sockfd);
432 continue; /* not fatal */
435 newlist = realloc(socklist, sizeof(int) * (socknum + 1));
436 if (!newlist)
437 die("memory allocation failed: %s", strerror(errno));
439 socklist = newlist;
440 socklist[socknum++] = sockfd;
442 if (maxfd < sockfd)
443 maxfd = sockfd;
446 freeaddrinfo(ai0);
448 *socklist_p = socklist;
449 return socknum;
452 #else /* NO_IPV6 */
454 static int socksetup(int port, int **socklist_p)
456 struct sockaddr_in sin;
457 int sockfd;
459 sockfd = socket(AF_INET, SOCK_STREAM, 0);
460 if (sockfd < 0)
461 return 0;
463 memset(&sin, 0, sizeof sin);
464 sin.sin_family = AF_INET;
465 sin.sin_addr.s_addr = htonl(INADDR_ANY);
466 sin.sin_port = htons(port);
468 if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
469 close(sockfd);
470 return 0;
473 *socklist_p = xmalloc(sizeof(int));
474 **socklist_p = sockfd;
477 #endif
479 static int service_loop(int socknum, int *socklist)
481 struct pollfd *pfd;
482 int i;
484 pfd = xcalloc(socknum, sizeof(struct pollfd));
486 for (i = 0; i < socknum; i++) {
487 pfd[i].fd = socklist[i];
488 pfd[i].events = POLLIN;
491 signal(SIGCHLD, child_handler);
493 for (;;) {
494 int i;
496 if (poll(pfd, socknum, -1) < 0) {
497 if (errno != EINTR) {
498 error("poll failed, resuming: %s",
499 strerror(errno));
500 sleep(1);
502 continue;
505 for (i = 0; i < socknum; i++) {
506 if (pfd[i].revents & POLLIN) {
507 struct sockaddr_storage ss;
508 unsigned int sslen = sizeof(ss);
509 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
510 if (incoming < 0) {
511 switch (errno) {
512 case EAGAIN:
513 case EINTR:
514 case ECONNABORTED:
515 continue;
516 default:
517 die("accept returned %s", strerror(errno));
520 handle(incoming, (struct sockaddr *)&ss, sslen);
526 static int serve(int port)
528 int socknum, *socklist;
530 socknum = socksetup(port, &socklist);
531 if (socknum == 0)
532 die("unable to allocate any listen sockets on port %u", port);
534 return service_loop(socknum, socklist);
537 int main(int argc, char **argv)
539 int port = DEFAULT_GIT_PORT;
540 int inetd_mode = 0;
541 int i;
543 for (i = 1; i < argc; i++) {
544 char *arg = argv[i];
546 if (!strncmp(arg, "--port=", 7)) {
547 char *end;
548 unsigned long n;
549 n = strtoul(arg+7, &end, 0);
550 if (arg[7] && !*end) {
551 port = n;
552 continue;
555 if (!strcmp(arg, "--inetd")) {
556 inetd_mode = 1;
557 log_syslog = 1;
558 continue;
560 if (!strcmp(arg, "--verbose")) {
561 verbose = 1;
562 continue;
564 if (!strcmp(arg, "--syslog")) {
565 log_syslog = 1;
566 continue;
568 if (!strcmp(arg, "--export-all")) {
569 export_all_trees = 1;
570 continue;
572 if (!strncmp(arg, "--timeout=", 10)) {
573 timeout = atoi(arg+10);
574 continue;
576 if (!strncmp(arg, "--init-timeout=", 15)) {
577 init_timeout = atoi(arg+15);
578 continue;
580 if (!strcmp(arg, "--strict-paths")) {
581 strict_paths = 1;
582 continue;
584 if (!strcmp(arg, "--")) {
585 ok_paths = &argv[i+1];
586 break;
587 } else if (arg[0] != '-') {
588 ok_paths = &argv[i];
589 break;
592 usage(daemon_usage);
595 if (log_syslog)
596 openlog("git-daemon", 0, LOG_DAEMON);
598 if (strict_paths && (!ok_paths || !*ok_paths)) {
599 if (!inetd_mode)
600 die("git-daemon: option --strict-paths requires a whitelist");
602 logerror("option --strict-paths requires a whitelist");
603 exit (1);
606 if (inetd_mode) {
607 fclose(stderr); //FIXME: workaround
608 return execute();
611 return serve(port);