git-daemon support for user-relative paths.
[git.git] / daemon.c
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"
12
13 static int log_syslog;
14 static int verbose;
15
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...]";
19
20 /* List of acceptable pathname prefixes */
21 static char **ok_paths = NULL;
22 static int strict_paths = 0;
23
24 /* If this is set, git-daemon-export-ok is not required */
25 static int export_all_trees = 0;
26
27 /* Timeout, and initial timeout */
28 static unsigned int timeout = 0;
29 static unsigned int init_timeout = 0;
30
31 static void logreport(int priority, const char *err, va_list params)
32 {
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;
38
39         /* sizeof(buf) should be big enough for "[pid] \n" */
40         buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
41
42         maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
43         msglen = vsnprintf(buf + buflen, maxlen, err, params);
44
45         if (log_syslog) {
46                 syslog(priority, "%s", buf);
47                 return;
48         }
49
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.
54          */
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;
60
61         buf[buflen++] = '\n';
62         buf[buflen] = '\0';
63
64         write(2, buf, buflen);
65 }
66
67 static void logerror(const char *err, ...)
68 {
69         va_list params;
70         va_start(params, err);
71         logreport(LOG_ERR, err, params);
72         va_end(params);
73 }
74
75 static void loginfo(const char *err, ...)
76 {
77         va_list params;
78         if (!verbose)
79                 return;
80         va_start(params, err);
81         logreport(LOG_INFO, err, params);
82         va_end(params);
83 }
84
85 static char *path_ok(char *dir)
86 {
87         char *path = enter_repo(dir, strict_paths);
88
89         if (!path) {
90                 logerror("'%s': unable to chdir or not a git archive", dir);
91                 return NULL;
92         }
93
94         if ( ok_paths && *ok_paths ) {
95                 char **pp = NULL;
96                 int dirlen = strlen(dir);
97                 int pathlen = strlen(path);
98
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;
109                         }
110                         if (len <= dirlen && !memcmp(*pp, dir, len)) {
111                                 if (dir[len] == '\0' || (!strict_paths && dir[len] == '/'))
112                                         return path;
113                         }
114                 }
115         }
116         else {
117                 /* be backwards compatible */
118                 if (!strict_paths)
119                         return path;
120         }
121
122         logerror("'%s': not in whitelist", path);
123         return NULL;            /* Fallthrough. Deny by default */
124 }
125
126 static int upload(char *dir)
127 {
128         /* Timeout as string */
129         char timeout_buf[64];
130         const char *path;
131
132         loginfo("Request for '%s'", dir);
133
134         if (!(path = path_ok(dir)))
135                 return -1;
136
137         /*
138          * Security on the cheap.
139          *
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.
143          *
144          * path_ok() uses enter_repo() and does whitelist checking.
145          * We only need to make sure the repository is exported.
146          */
147
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;
152         }
153
154         /*
155          * We'll ignore SIGTERM from now on, we have a
156          * good client.
157          */
158         signal(SIGTERM, SIG_IGN);
159
160         snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
161
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;
165 }
166
167 static int execute(void)
168 {
169         static char line[1000];
170         int len;
171
172         alarm(init_timeout ? init_timeout : timeout);
173         len = packet_read_line(0, line, sizeof(line));
174         alarm(0);
175
176         if (len && line[len-1] == '\n')
177                 line[--len] = 0;
178
179         if (!strncmp("git-upload-pack ", line, 16))
180                 return upload(line+16);
181
182         logerror("Protocol error: '%s'", line);
183         return -1;
184 }
185
186
187 /*
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.
192  *
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.
196  */
197 #define MAX_CHILDREN 128
198
199 static int max_connections = 25;
200
201 /* These are updated by the signal handler */
202 static volatile unsigned int children_reaped = 0;
203 static pid_t dead_child[MAX_CHILDREN];
204
205 /* These are updated by the main loop */
206 static unsigned int children_spawned = 0;
207 static unsigned int children_deleted = 0;
208
209 static struct child {
210         pid_t pid;
211         int addrlen;
212         struct sockaddr_storage address;
213 } live_child[MAX_CHILDREN];
214
215 static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
216 {
217         live_child[idx].pid = pid;
218         live_child[idx].addrlen = addrlen;
219         memcpy(&live_child[idx].address, addr, addrlen);
220 }
221
222 /*
223  * Walk from "deleted" to "spawned", and remove child "pid".
224  *
225  * We move everything up by one, since the new "deleted" will
226  * be one higher.
227  */
228 static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
229 {
230         struct child n;
231
232         deleted %= MAX_CHILDREN;
233         spawned %= MAX_CHILDREN;
234         if (live_child[deleted].pid == pid) {
235                 live_child[deleted].pid = -1;
236                 return;
237         }
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;
249         }
250 }
251
252 /*
253  * This gets called if the number of connections grows
254  * past "max_connections".
255  *
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.
259  *
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.
263  *
264  * Really, this is just a place-holder for a _real_ algorithm.
265  */
266 static void kill_some_children(int signo, unsigned start, unsigned stop)
267 {
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;
274         }
275 }
276
277 static void check_max_connections(void)
278 {
279         for (;;) {
280                 int active;
281                 unsigned spawned, reaped, deleted;
282
283                 spawned = children_spawned;
284                 reaped = children_reaped;
285                 deleted = children_deleted;
286
287                 while (deleted < reaped) {
288                         pid_t pid = dead_child[deleted % MAX_CHILDREN];
289                         remove_child(pid, deleted, spawned);
290                         deleted++;
291                 }
292                 children_deleted = deleted;
293
294                 active = spawned - deleted;
295                 if (active <= max_connections)
296                         break;
297
298                 /* Kill some unstarted connections with SIGTERM */
299                 kill_some_children(SIGTERM, deleted, spawned);
300                 if (active <= max_connections << 1)
301                         break;
302
303                 /* If the SIGTERM thing isn't helping use SIGKILL */
304                 kill_some_children(SIGKILL, deleted, spawned);
305                 sleep(1);
306         }
307 }
308
309 static void handle(int incoming, struct sockaddr *addr, int addrlen)
310 {
311         pid_t pid = fork();
312         char addrbuf[256] = "";
313         int port = -1;
314
315         if (pid) {
316                 unsigned idx;
317
318                 close(incoming);
319                 if (pid < 0)
320                         return;
321
322                 idx = children_spawned % MAX_CHILDREN;
323                 children_spawned++;
324                 add_child(idx, pid, addr, addrlen);
325
326                 check_max_connections();
327                 return;
328         }
329
330         dup2(incoming, 0);
331         dup2(incoming, 1);
332         close(incoming);
333
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;
338
339 #ifndef NO_IPV6
340         } else if (addr->sa_family == AF_INET6) {
341                 struct sockaddr_in6 *sin6_addr = (void *) addr;
342
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, "]");
347
348                 port = sin6_addr->sin6_port;
349 #endif
350         }
351         loginfo("Connection from %s:%d", addrbuf, port);
352
353         exit(execute());
354 }
355
356 static void child_handler(int signo)
357 {
358         for (;;) {
359                 int status;
360                 pid_t pid = waitpid(-1, &status, WNOHANG);
361
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);
375                         }
376                         continue;
377                 }
378                 break;
379         }
380 }
381
382 #ifndef NO_IPV6
383
384 static int socksetup(int port, int **socklist_p)
385 {
386         int socknum = 0, *socklist = NULL;
387         int maxfd = -1;
388         char pbuf[NI_MAXSERV];
389
390         struct addrinfo hints, *ai0, *ai;
391         int gai;
392
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;
399
400         gai = getaddrinfo(NULL, pbuf, &hints, &ai0);
401         if (gai)
402                 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
403
404         for (ai = ai0; ai; ai = ai->ai_next) {
405                 int sockfd;
406                 int *newlist;
407
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;
415                 }
416
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 */
423                 }
424 #endif
425
426                 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
427                         close(sockfd);
428                         continue;       /* not fatal */
429                 }
430                 if (listen(sockfd, 5) < 0) {
431                         close(sockfd);
432                         continue;       /* not fatal */
433                 }
434
435                 newlist = realloc(socklist, sizeof(int) * (socknum + 1));
436                 if (!newlist)
437                         die("memory allocation failed: %s", strerror(errno));
438
439                 socklist = newlist;
440                 socklist[socknum++] = sockfd;
441
442                 if (maxfd < sockfd)
443                         maxfd = sockfd;
444         }
445
446         freeaddrinfo(ai0);
447
448         *socklist_p = socklist;
449         return socknum;
450 }
451
452 #else /* NO_IPV6 */
453
454 static int socksetup(int port, int **socklist_p)
455 {
456         struct sockaddr_in sin;
457         int sockfd;
458
459         sockfd = socket(AF_INET, SOCK_STREAM, 0);
460         if (sockfd < 0)
461                 return 0;
462
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);
467
468         if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
469                 close(sockfd);
470                 return 0;
471         }
472
473         *socklist_p = xmalloc(sizeof(int));
474         **socklist_p = sockfd;
475 }
476
477 #endif
478
479 static int service_loop(int socknum, int *socklist)
480 {
481         struct pollfd *pfd;
482         int i;
483
484         pfd = xcalloc(socknum, sizeof(struct pollfd));
485
486         for (i = 0; i < socknum; i++) {
487                 pfd[i].fd = socklist[i];
488                 pfd[i].events = POLLIN;
489         }
490
491         signal(SIGCHLD, child_handler);
492
493         for (;;) {
494                 int i;
495
496                 if (poll(pfd, socknum, -1) < 0) {
497                         if (errno != EINTR) {
498                                 error("poll failed, resuming: %s",
499                                       strerror(errno));
500                                 sleep(1);
501                         }
502                         continue;
503                 }
504
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));
518                                         }
519                                 }
520                                 handle(incoming, (struct sockaddr *)&ss, sslen);
521                         }
522                 }
523         }
524 }
525
526 static int serve(int port)
527 {
528         int socknum, *socklist;
529
530         socknum = socksetup(port, &socklist);
531         if (socknum == 0)
532                 die("unable to allocate any listen sockets on port %u", port);
533
534         return service_loop(socknum, socklist);
535 }
536
537 int main(int argc, char **argv)
538 {
539         int port = DEFAULT_GIT_PORT;
540         int inetd_mode = 0;
541         int i;
542
543         for (i = 1; i < argc; i++) {
544                 char *arg = argv[i];
545
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;
553                         }
554                 }
555                 if (!strcmp(arg, "--inetd")) {
556                         inetd_mode = 1;
557                         log_syslog = 1;
558                         continue;
559                 }
560                 if (!strcmp(arg, "--verbose")) {
561                         verbose = 1;
562                         continue;
563                 }
564                 if (!strcmp(arg, "--syslog")) {
565                         log_syslog = 1;
566                         continue;
567                 }
568                 if (!strcmp(arg, "--export-all")) {
569                         export_all_trees = 1;
570                         continue;
571                 }
572                 if (!strncmp(arg, "--timeout=", 10)) {
573                         timeout = atoi(arg+10);
574                         continue;
575                 }
576                 if (!strncmp(arg, "--init-timeout=", 15)) {
577                         init_timeout = atoi(arg+15);
578                         continue;
579                 }
580                 if (!strcmp(arg, "--strict-paths")) {
581                         strict_paths = 1;
582                         continue;
583                 }
584                 if (!strcmp(arg, "--")) {
585                         ok_paths = &argv[i+1];
586                         break;
587                 } else if (arg[0] != '-') {
588                         ok_paths = &argv[i];
589                         break;
590                 }
591
592                 usage(daemon_usage);
593         }
594
595         if (log_syslog)
596                 openlog("git-daemon", 0, LOG_DAEMON);
597
598         if (strict_paths && (!ok_paths || !*ok_paths)) {
599                 if (!inetd_mode)
600                         die("git-daemon: option --strict-paths requires a whitelist");
601
602                 logerror("option --strict-paths requires a whitelist");
603                 exit (1);
604         }
605
606         if (inetd_mode) {
607                 fclose(stderr); //FIXME: workaround
608                 return execute();
609         }
610
611         return serve(port);
612 }