daemon: do not forbid user relative paths unconditionally under --base-path
[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 #include "exec_cmd.h"
13
14 static int log_syslog;
15 static int verbose;
16
17 static const char daemon_usage[] =
18 "git-daemon [--verbose] [--syslog] [--inetd | --port=n] [--export-all]\n"
19 "           [--timeout=n] [--init-timeout=n] [--strict-paths]\n"
20 "           [--base-path=path] [directory...]";
21
22 /* List of acceptable pathname prefixes */
23 static char **ok_paths = NULL;
24 static int strict_paths = 0;
25
26 /* If this is set, git-daemon-export-ok is not required */
27 static int export_all_trees = 0;
28
29 /* Take all paths relative to this one if non-NULL */
30 static char *base_path = NULL;
31
32 /* Timeout, and initial timeout */
33 static unsigned int timeout = 0;
34 static unsigned int init_timeout = 0;
35
36 static void logreport(int priority, const char *err, va_list params)
37 {
38         /* We should do a single write so that it is atomic and output
39          * of several processes do not get intermingled. */
40         char buf[1024];
41         int buflen;
42         int maxlen, msglen;
43
44         /* sizeof(buf) should be big enough for "[pid] \n" */
45         buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
46
47         maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
48         msglen = vsnprintf(buf + buflen, maxlen, err, params);
49
50         if (log_syslog) {
51                 syslog(priority, "%s", buf);
52                 return;
53         }
54
55         /* maxlen counted our own LF but also counts space given to
56          * vsnprintf for the terminating NUL.  We want to make sure that
57          * we have space for our own LF and NUL after the "meat" of the
58          * message, so truncate it at maxlen - 1.
59          */
60         if (msglen > maxlen - 1)
61                 msglen = maxlen - 1;
62         else if (msglen < 0)
63                 msglen = 0; /* Protect against weird return values. */
64         buflen += msglen;
65
66         buf[buflen++] = '\n';
67         buf[buflen] = '\0';
68
69         write(2, buf, buflen);
70 }
71
72 static void logerror(const char *err, ...)
73 {
74         va_list params;
75         va_start(params, err);
76         logreport(LOG_ERR, err, params);
77         va_end(params);
78 }
79
80 static void loginfo(const char *err, ...)
81 {
82         va_list params;
83         if (!verbose)
84                 return;
85         va_start(params, err);
86         logreport(LOG_INFO, err, params);
87         va_end(params);
88 }
89
90 static int avoid_alias(char *p)
91 {
92         int sl, ndot;
93
94         /* 
95          * This resurrects the belts and suspenders paranoia check by HPA
96          * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
97          * does not do getcwd() based path canonicalizations.
98          *
99          * sl becomes true immediately after seeing '/' and continues to
100          * be true as long as dots continue after that without intervening
101          * non-dot character.
102          */
103         if (!p || (*p != '/' && *p != '~'))
104                 return -1;
105         sl = 1; ndot = 0;
106         p++;
107
108         while (1) {
109                 char ch = *p++;
110                 if (sl) {
111                         if (ch == '.')
112                                 ndot++;
113                         else if (ch == '/') {
114                                 if (ndot < 3)
115                                         /* reject //, /./ and /../ */
116                                         return -1;
117                                 ndot = 0;
118                         }
119                         else if (ch == 0) {
120                                 if (0 < ndot && ndot < 3)
121                                         /* reject /.$ and /..$ */
122                                         return -1;
123                                 return 0;
124                         }
125                         else
126                                 sl = ndot = 0;
127                 }
128                 else if (ch == 0)
129                         return 0;
130                 else if (ch == '/') {
131                         sl = 1;
132                         ndot = 0;
133                 }
134         }
135 }
136
137 static char *path_ok(char *dir)
138 {
139         char *path;
140
141         if (avoid_alias(dir)) {
142                 logerror("'%s': aliased", dir);
143                 return NULL;
144         }
145
146         if (base_path) {
147                 static char rpath[PATH_MAX];
148                 if (!strict_paths && *dir == '~')
149                         ; /* allow user relative paths */
150                 else if (*dir != '/') {
151                         /* otherwise allow only absolute */
152                         logerror("'%s': Non-absolute path denied (base-path active)", dir);
153                         return NULL;
154                 }
155                 else {
156                         snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
157                         dir = rpath;
158                 }
159         }
160
161         path = enter_repo(dir, strict_paths);
162
163         if (!path) {
164                 logerror("'%s': unable to chdir or not a git archive", dir);
165                 return NULL;
166         }
167
168         if ( ok_paths && *ok_paths ) {
169                 char **pp;
170                 int pathlen = strlen(path);
171
172                 /* The validation is done on the paths after enter_repo
173                  * appends optional {.git,.git/.git} and friends, but 
174                  * it does not use getcwd().  So if your /pub is
175                  * a symlink to /mnt/pub, you can whitelist /pub and
176                  * do not have to say /mnt/pub.
177                  * Do not say /pub/.
178                  */
179                 for ( pp = ok_paths ; *pp ; pp++ ) {
180                         int len = strlen(*pp);
181                         if (len <= pathlen &&
182                             !memcmp(*pp, path, len) &&
183                             (path[len] == '\0' ||
184                              (!strict_paths && path[len] == '/')))
185                                 return path;
186                 }
187         }
188         else {
189                 /* be backwards compatible */
190                 if (!strict_paths)
191                         return path;
192         }
193
194         logerror("'%s': not in whitelist", path);
195         return NULL;            /* Fallthrough. Deny by default */
196 }
197
198 static int upload(char *dir)
199 {
200         /* Timeout as string */
201         char timeout_buf[64];
202         const char *path;
203
204         loginfo("Request for '%s'", dir);
205
206         if (!(path = path_ok(dir)))
207                 return -1;
208
209         /*
210          * Security on the cheap.
211          *
212          * We want a readable HEAD, usable "objects" directory, and
213          * a "git-daemon-export-ok" flag that says that the other side
214          * is ok with us doing this.
215          *
216          * path_ok() uses enter_repo() and does whitelist checking.
217          * We only need to make sure the repository is exported.
218          */
219
220         if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
221                 logerror("'%s': repository not exported.", path);
222                 errno = EACCES;
223                 return -1;
224         }
225
226         /*
227          * We'll ignore SIGTERM from now on, we have a
228          * good client.
229          */
230         signal(SIGTERM, SIG_IGN);
231
232         snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
233
234         /* git-upload-pack only ever reads stuff, so this is safe */
235         execl_git_cmd("upload-pack", "--strict", timeout_buf, ".", NULL);
236         return -1;
237 }
238
239 static int execute(void)
240 {
241         static char line[1000];
242         int len;
243
244         alarm(init_timeout ? init_timeout : timeout);
245         len = packet_read_line(0, line, sizeof(line));
246         alarm(0);
247
248         if (len && line[len-1] == '\n')
249                 line[--len] = 0;
250
251         if (!strncmp("git-upload-pack ", line, 16))
252                 return upload(line+16);
253
254         logerror("Protocol error: '%s'", line);
255         return -1;
256 }
257
258
259 /*
260  * We count spawned/reaped separately, just to avoid any
261  * races when updating them from signals. The SIGCHLD handler
262  * will only update children_reaped, and the fork logic will
263  * only update children_spawned.
264  *
265  * MAX_CHILDREN should be a power-of-two to make the modulus
266  * operation cheap. It should also be at least twice
267  * the maximum number of connections we will ever allow.
268  */
269 #define MAX_CHILDREN 128
270
271 static int max_connections = 25;
272
273 /* These are updated by the signal handler */
274 static volatile unsigned int children_reaped = 0;
275 static pid_t dead_child[MAX_CHILDREN];
276
277 /* These are updated by the main loop */
278 static unsigned int children_spawned = 0;
279 static unsigned int children_deleted = 0;
280
281 static struct child {
282         pid_t pid;
283         int addrlen;
284         struct sockaddr_storage address;
285 } live_child[MAX_CHILDREN];
286
287 static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
288 {
289         live_child[idx].pid = pid;
290         live_child[idx].addrlen = addrlen;
291         memcpy(&live_child[idx].address, addr, addrlen);
292 }
293
294 /*
295  * Walk from "deleted" to "spawned", and remove child "pid".
296  *
297  * We move everything up by one, since the new "deleted" will
298  * be one higher.
299  */
300 static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
301 {
302         struct child n;
303
304         deleted %= MAX_CHILDREN;
305         spawned %= MAX_CHILDREN;
306         if (live_child[deleted].pid == pid) {
307                 live_child[deleted].pid = -1;
308                 return;
309         }
310         n = live_child[deleted];
311         for (;;) {
312                 struct child m;
313                 deleted = (deleted + 1) % MAX_CHILDREN;
314                 if (deleted == spawned)
315                         die("could not find dead child %d\n", pid);
316                 m = live_child[deleted];
317                 live_child[deleted] = n;
318                 if (m.pid == pid)
319                         return;
320                 n = m;
321         }
322 }
323
324 /*
325  * This gets called if the number of connections grows
326  * past "max_connections".
327  *
328  * We _should_ start off by searching for connections
329  * from the same IP, and if there is some address wth
330  * multiple connections, we should kill that first.
331  *
332  * As it is, we just "randomly" kill 25% of the connections,
333  * and our pseudo-random generator sucks too. I have no
334  * shame.
335  *
336  * Really, this is just a place-holder for a _real_ algorithm.
337  */
338 static void kill_some_children(int signo, unsigned start, unsigned stop)
339 {
340         start %= MAX_CHILDREN;
341         stop %= MAX_CHILDREN;
342         while (start != stop) {
343                 if (!(start & 3))
344                         kill(live_child[start].pid, signo);
345                 start = (start + 1) % MAX_CHILDREN;
346         }
347 }
348
349 static void check_max_connections(void)
350 {
351         for (;;) {
352                 int active;
353                 unsigned spawned, reaped, deleted;
354
355                 spawned = children_spawned;
356                 reaped = children_reaped;
357                 deleted = children_deleted;
358
359                 while (deleted < reaped) {
360                         pid_t pid = dead_child[deleted % MAX_CHILDREN];
361                         remove_child(pid, deleted, spawned);
362                         deleted++;
363                 }
364                 children_deleted = deleted;
365
366                 active = spawned - deleted;
367                 if (active <= max_connections)
368                         break;
369
370                 /* Kill some unstarted connections with SIGTERM */
371                 kill_some_children(SIGTERM, deleted, spawned);
372                 if (active <= max_connections << 1)
373                         break;
374
375                 /* If the SIGTERM thing isn't helping use SIGKILL */
376                 kill_some_children(SIGKILL, deleted, spawned);
377                 sleep(1);
378         }
379 }
380
381 static void handle(int incoming, struct sockaddr *addr, int addrlen)
382 {
383         pid_t pid = fork();
384         char addrbuf[256] = "";
385         int port = -1;
386
387         if (pid) {
388                 unsigned idx;
389
390                 close(incoming);
391                 if (pid < 0)
392                         return;
393
394                 idx = children_spawned % MAX_CHILDREN;
395                 children_spawned++;
396                 add_child(idx, pid, addr, addrlen);
397
398                 check_max_connections();
399                 return;
400         }
401
402         dup2(incoming, 0);
403         dup2(incoming, 1);
404         close(incoming);
405
406         if (addr->sa_family == AF_INET) {
407                 struct sockaddr_in *sin_addr = (void *) addr;
408                 inet_ntop(AF_INET, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
409                 port = sin_addr->sin_port;
410
411 #ifndef NO_IPV6
412         } else if (addr->sa_family == AF_INET6) {
413                 struct sockaddr_in6 *sin6_addr = (void *) addr;
414
415                 char *buf = addrbuf;
416                 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
417                 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
418                 strcat(buf, "]");
419
420                 port = sin6_addr->sin6_port;
421 #endif
422         }
423         loginfo("Connection from %s:%d", addrbuf, port);
424
425         exit(execute());
426 }
427
428 static void child_handler(int signo)
429 {
430         for (;;) {
431                 int status;
432                 pid_t pid = waitpid(-1, &status, WNOHANG);
433
434                 if (pid > 0) {
435                         unsigned reaped = children_reaped;
436                         dead_child[reaped % MAX_CHILDREN] = pid;
437                         children_reaped = reaped + 1;
438                         /* XXX: Custom logging, since we don't wanna getpid() */
439                         if (verbose) {
440                                 char *dead = "";
441                                 if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
442                                         dead = " (with error)";
443                                 if (log_syslog)
444                                         syslog(LOG_INFO, "[%d] Disconnected%s", pid, dead);
445                                 else
446                                         fprintf(stderr, "[%d] Disconnected%s\n", pid, dead);
447                         }
448                         continue;
449                 }
450                 break;
451         }
452 }
453
454 #ifndef NO_IPV6
455
456 static int socksetup(int port, int **socklist_p)
457 {
458         int socknum = 0, *socklist = NULL;
459         int maxfd = -1;
460         char pbuf[NI_MAXSERV];
461
462         struct addrinfo hints, *ai0, *ai;
463         int gai;
464
465         sprintf(pbuf, "%d", port);
466         memset(&hints, 0, sizeof(hints));
467         hints.ai_family = AF_UNSPEC;
468         hints.ai_socktype = SOCK_STREAM;
469         hints.ai_protocol = IPPROTO_TCP;
470         hints.ai_flags = AI_PASSIVE;
471
472         gai = getaddrinfo(NULL, pbuf, &hints, &ai0);
473         if (gai)
474                 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
475
476         for (ai = ai0; ai; ai = ai->ai_next) {
477                 int sockfd;
478                 int *newlist;
479
480                 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
481                 if (sockfd < 0)
482                         continue;
483                 if (sockfd >= FD_SETSIZE) {
484                         error("too large socket descriptor.");
485                         close(sockfd);
486                         continue;
487                 }
488
489 #ifdef IPV6_V6ONLY
490                 if (ai->ai_family == AF_INET6) {
491                         int on = 1;
492                         setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
493                                    &on, sizeof(on));
494                         /* Note: error is not fatal */
495                 }
496 #endif
497
498                 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
499                         close(sockfd);
500                         continue;       /* not fatal */
501                 }
502                 if (listen(sockfd, 5) < 0) {
503                         close(sockfd);
504                         continue;       /* not fatal */
505                 }
506
507                 newlist = realloc(socklist, sizeof(int) * (socknum + 1));
508                 if (!newlist)
509                         die("memory allocation failed: %s", strerror(errno));
510
511                 socklist = newlist;
512                 socklist[socknum++] = sockfd;
513
514                 if (maxfd < sockfd)
515                         maxfd = sockfd;
516         }
517
518         freeaddrinfo(ai0);
519
520         *socklist_p = socklist;
521         return socknum;
522 }
523
524 #else /* NO_IPV6 */
525
526 static int socksetup(int port, int **socklist_p)
527 {
528         struct sockaddr_in sin;
529         int sockfd;
530
531         sockfd = socket(AF_INET, SOCK_STREAM, 0);
532         if (sockfd < 0)
533                 return 0;
534
535         memset(&sin, 0, sizeof sin);
536         sin.sin_family = AF_INET;
537         sin.sin_addr.s_addr = htonl(INADDR_ANY);
538         sin.sin_port = htons(port);
539
540         if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
541                 close(sockfd);
542                 return 0;
543         }
544
545         if (listen(sockfd, 5) < 0) {
546                 close(sockfd);
547                 return 0;
548         }
549
550         *socklist_p = xmalloc(sizeof(int));
551         **socklist_p = sockfd;
552         return 1;
553 }
554
555 #endif
556
557 static int service_loop(int socknum, int *socklist)
558 {
559         struct pollfd *pfd;
560         int i;
561
562         pfd = xcalloc(socknum, sizeof(struct pollfd));
563
564         for (i = 0; i < socknum; i++) {
565                 pfd[i].fd = socklist[i];
566                 pfd[i].events = POLLIN;
567         }
568
569         signal(SIGCHLD, child_handler);
570
571         for (;;) {
572                 int i;
573
574                 if (poll(pfd, socknum, -1) < 0) {
575                         if (errno != EINTR) {
576                                 error("poll failed, resuming: %s",
577                                       strerror(errno));
578                                 sleep(1);
579                         }
580                         continue;
581                 }
582
583                 for (i = 0; i < socknum; i++) {
584                         if (pfd[i].revents & POLLIN) {
585                                 struct sockaddr_storage ss;
586                                 unsigned int sslen = sizeof(ss);
587                                 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
588                                 if (incoming < 0) {
589                                         switch (errno) {
590                                         case EAGAIN:
591                                         case EINTR:
592                                         case ECONNABORTED:
593                                                 continue;
594                                         default:
595                                                 die("accept returned %s", strerror(errno));
596                                         }
597                                 }
598                                 handle(incoming, (struct sockaddr *)&ss, sslen);
599                         }
600                 }
601         }
602 }
603
604 static int serve(int port)
605 {
606         int socknum, *socklist;
607
608         socknum = socksetup(port, &socklist);
609         if (socknum == 0)
610                 die("unable to allocate any listen sockets on port %u", port);
611
612         return service_loop(socknum, socklist);
613 }
614
615 int main(int argc, char **argv)
616 {
617         int port = DEFAULT_GIT_PORT;
618         int inetd_mode = 0;
619         int i;
620
621         for (i = 1; i < argc; i++) {
622                 char *arg = argv[i];
623
624                 if (!strncmp(arg, "--port=", 7)) {
625                         char *end;
626                         unsigned long n;
627                         n = strtoul(arg+7, &end, 0);
628                         if (arg[7] && !*end) {
629                                 port = n;
630                                 continue;
631                         }
632                 }
633                 if (!strcmp(arg, "--inetd")) {
634                         inetd_mode = 1;
635                         log_syslog = 1;
636                         continue;
637                 }
638                 if (!strcmp(arg, "--verbose")) {
639                         verbose = 1;
640                         continue;
641                 }
642                 if (!strcmp(arg, "--syslog")) {
643                         log_syslog = 1;
644                         continue;
645                 }
646                 if (!strcmp(arg, "--export-all")) {
647                         export_all_trees = 1;
648                         continue;
649                 }
650                 if (!strncmp(arg, "--timeout=", 10)) {
651                         timeout = atoi(arg+10);
652                         continue;
653                 }
654                 if (!strncmp(arg, "--init-timeout=", 15)) {
655                         init_timeout = atoi(arg+15);
656                         continue;
657                 }
658                 if (!strcmp(arg, "--strict-paths")) {
659                         strict_paths = 1;
660                         continue;
661                 }
662                 if (!strncmp(arg, "--base-path=", 12)) {
663                         base_path = arg+12;
664                         continue;
665                 }
666                 if (!strcmp(arg, "--")) {
667                         ok_paths = &argv[i+1];
668                         break;
669                 } else if (arg[0] != '-') {
670                         ok_paths = &argv[i];
671                         break;
672                 }
673
674                 usage(daemon_usage);
675         }
676
677         if (log_syslog)
678                 openlog("git-daemon", 0, LOG_DAEMON);
679
680         if (strict_paths && (!ok_paths || !*ok_paths)) {
681                 if (!inetd_mode)
682                         die("git-daemon: option --strict-paths requires a whitelist");
683
684                 logerror("option --strict-paths requires a whitelist");
685                 exit (1);
686         }
687
688         if (inetd_mode) {
689                 fclose(stderr); //FIXME: workaround
690                 return execute();
691         }
692
693         return serve(port);
694 }