Merge with master.kernel.org:/pub/scm/git/git.git
[git.git] / daemon.c
1 #include "cache.h"
2 #include "pkt-line.h"
3 #include <alloca.h>
4 #include <signal.h>
5 #include <sys/wait.h>
6 #include <sys/socket.h>
7 #include <sys/time.h>
8 #include <sys/poll.h>
9 #include <netdb.h>
10 #include <netinet/in.h>
11 #include <arpa/inet.h>
12 #include <syslog.h>
13
14 static int log_syslog;
15 static int verbose;
16
17 static const char daemon_usage[] = "git-daemon [--verbose] [--syslog] [--inetd | --port=n] [--export-all] [directory...]";
18
19 /* List of acceptable pathname prefixes */
20 static char **ok_paths = NULL;
21
22 /* If this is set, git-daemon-export-ok is not required */
23 static int export_all_trees = 0;
24
25
26 static void logreport(int priority, const char *err, va_list params)
27 {
28         /* We should do a single write so that it is atomic and output
29          * of several processes do not get intermingled. */
30         char buf[1024];
31         int buflen;
32         int maxlen, msglen;
33
34         /* sizeof(buf) should be big enough for "[pid] \n" */
35         buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
36
37         maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
38         msglen = vsnprintf(buf + buflen, maxlen, err, params);
39
40         if (log_syslog) {
41                 syslog(priority, "%s", buf);
42                 return;
43         }
44
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.
49          */
50         if (msglen > maxlen - 1)
51                 msglen = maxlen - 1;
52         else if (msglen < 0)
53                 msglen = 0; /* Protect against weird return values. */
54         buflen += msglen;
55
56         buf[buflen++] = '\n';
57         buf[buflen] = '\0';
58
59         write(2, buf, buflen);
60 }
61
62 static void logerror(const char *err, ...)
63 {
64         va_list params;
65         va_start(params, err);
66         logreport(LOG_ERR, err, params);
67         va_end(params);
68 }
69
70 static void loginfo(const char *err, ...)
71 {
72         va_list params;
73         if (!verbose)
74                 return;
75         va_start(params, err);
76         logreport(LOG_INFO, err, params);
77         va_end(params);
78 }
79
80 static int path_ok(const char *dir)
81 {
82         const char *p = dir;
83         char **pp;
84         int sl = 1, ndot = 0;
85
86         for (;;) {
87                 if ( *p == '.' ) {
88                         ndot++;
89                 } else if ( *p == '/' || *p == '\0' ) {
90                         if ( sl && ndot > 0 && ndot < 3 )
91                                 return 0; /* . or .. in path */
92                         sl = 1;
93                         if ( *p == '\0' )
94                                 break; /* End of string and all is good */
95                 } else {
96                         sl = ndot = 0;
97                 }
98                 p++;
99         }
100
101         if ( ok_paths && *ok_paths ) {
102                 int ok = 0;
103                 int dirlen = strlen(dir); /* read_packet_line can return embedded \0 */
104
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') ) {
110                                 ok = 1;
111                                 break;
112                         }
113                 }
114
115                 if ( !ok )
116                         return 0; /* Path not in whitelist */
117         }
118
119         return 1;               /* Path acceptable */
120 }
121
122 static int upload(char *dir, int dirlen)
123 {
124         loginfo("Request for '%s'", dir);
125
126         if (!path_ok(dir)) {
127                 logerror("Forbidden directory: %s\n", dir);
128                 return -1;
129         }
130
131         if (chdir(dir) < 0) {
132                 logerror("Cannot chdir('%s'): %s", dir, strerror(errno));
133                 return -1;
134         }
135
136         chdir(".git");
137
138         /*
139          * Security on the cheap.
140          *
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.
144          */
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);
149                 return -1;
150         }
151
152         /*
153          * We'll ignore SIGTERM from now on, we have a
154          * good client.
155          */
156         signal(SIGTERM, SIG_IGN);
157
158         /* git-upload-pack only ever reads stuff, so this is safe */
159         execlp("git-upload-pack", "git-upload-pack", ".", NULL);
160         return -1;
161 }
162
163 static int execute(void)
164 {
165         static char line[1000];
166         int len;
167
168         len = packet_read_line(0, line, sizeof(line));
169
170         if (len && line[len-1] == '\n')
171                 line[--len] = 0;
172
173         if (!strncmp("git-upload-pack /", line, 17))
174                 return upload(line + 16, len - 16);
175
176         logerror("Protocol error: '%s'", line);
177         return -1;
178 }
179
180
181 /*
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.
186  *
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.
190  */
191 #define MAX_CHILDREN 128
192
193 static int max_connections = 25;
194
195 /* These are updated by the signal handler */
196 static volatile unsigned int children_reaped = 0;
197 static pid_t dead_child[MAX_CHILDREN];
198
199 /* These are updated by the main loop */
200 static unsigned int children_spawned = 0;
201 static unsigned int children_deleted = 0;
202
203 static struct child {
204         pid_t pid;
205         int addrlen;
206         struct sockaddr_storage address;
207 } live_child[MAX_CHILDREN];
208
209 static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
210 {
211         live_child[idx].pid = pid;
212         live_child[idx].addrlen = addrlen;
213         memcpy(&live_child[idx].address, addr, addrlen);
214 }
215
216 /*
217  * Walk from "deleted" to "spawned", and remove child "pid".
218  *
219  * We move everything up by one, since the new "deleted" will
220  * be one higher.
221  */
222 static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
223 {
224         struct child n;
225
226         deleted %= MAX_CHILDREN;
227         spawned %= MAX_CHILDREN;
228         if (live_child[deleted].pid == pid) {
229                 live_child[deleted].pid = -1;
230                 return;
231         }
232         n = live_child[deleted];
233         for (;;) {
234                 struct child m;
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;
240                 if (m.pid == pid)
241                         return;
242                 n = m;
243         }
244 }
245
246 /*
247  * This gets called if the number of connections grows
248  * past "max_connections".
249  *
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.
253  *
254  * As it is, we just "randomly" kill 25% of the connections,
255  * and our pseudo-random generator sucks too. I have no
256  * shame.
257  *
258  * Really, this is just a place-holder for a _real_ algorithm.
259  */
260 static void kill_some_children(int signo, unsigned start, unsigned stop)
261 {
262         start %= MAX_CHILDREN;
263         stop %= MAX_CHILDREN;
264         while (start != stop) {
265                 if (!(start & 3))
266                         kill(live_child[start].pid, signo);
267                 start = (start + 1) % MAX_CHILDREN;
268         }
269 }
270
271 static void check_max_connections(void)
272 {
273         for (;;) {
274                 int active;
275                 unsigned spawned, reaped, deleted;
276
277                 spawned = children_spawned;
278                 reaped = children_reaped;
279                 deleted = children_deleted;
280
281                 while (deleted < reaped) {
282                         pid_t pid = dead_child[deleted % MAX_CHILDREN];
283                         remove_child(pid, deleted, spawned);
284                         deleted++;
285                 }
286                 children_deleted = deleted;
287
288                 active = spawned - deleted;
289                 if (active <= max_connections)
290                         break;
291
292                 /* Kill some unstarted connections with SIGTERM */
293                 kill_some_children(SIGTERM, deleted, spawned);
294                 if (active <= max_connections << 1)
295                         break;
296
297                 /* If the SIGTERM thing isn't helping use SIGKILL */
298                 kill_some_children(SIGKILL, deleted, spawned);
299                 sleep(1);
300         }
301 }
302
303 static void handle(int incoming, struct sockaddr *addr, int addrlen)
304 {
305         pid_t pid = fork();
306         char addrbuf[256] = "";
307         int port = -1;
308
309         if (pid) {
310                 unsigned idx;
311
312                 close(incoming);
313                 if (pid < 0)
314                         return;
315
316                 idx = children_spawned % MAX_CHILDREN;
317                 children_spawned++;
318                 add_child(idx, pid, addr, addrlen);
319
320                 check_max_connections();
321                 return;
322         }
323
324         dup2(incoming, 0);
325         dup2(incoming, 1);
326         close(incoming);
327
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;
332
333 #ifndef NO_IPV6
334         } else if (addr->sa_family == AF_INET6) {
335                 struct sockaddr_in6 *sin6_addr = (void *) addr;
336
337                 char *buf = addrbuf;
338                 *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
339                 inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
340                 strcat(buf, "]");
341
342                 port = sin6_addr->sin6_port;
343 #endif
344         }
345         loginfo("Connection from %s:%d", addrbuf, port);
346
347         exit(execute());
348 }
349
350 static void child_handler(int signo)
351 {
352         for (;;) {
353                 int status;
354                 pid_t pid = waitpid(-1, &status, WNOHANG);
355
356                 if (pid > 0) {
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() */
361                         if (verbose) {
362                                 char *dead = "";
363                                 if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
364                                         dead = " (with error)";
365                                 if (log_syslog)
366                                         syslog(LOG_INFO, "[%d] Disconnected%s", pid, dead);
367                                 else
368                                         fprintf(stderr, "[%d] Disconnected%s\n", pid, dead);
369                         }
370                         continue;
371                 }
372                 break;
373         }
374 }
375
376 #ifndef NO_IPV6
377
378 static int socksetup(int port, int **socklist_p)
379 {
380         int socknum = 0, *socklist = NULL;
381         int maxfd = -1;
382         char pbuf[NI_MAXSERV];
383
384         struct addrinfo hints, *ai0, *ai;
385         int gai;
386
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;
393
394         gai = getaddrinfo(NULL, pbuf, &hints, &ai0);
395         if (gai)
396                 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
397
398         for (ai = ai0; ai; ai = ai->ai_next) {
399                 int sockfd;
400                 int *newlist;
401
402                 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
403                 if (sockfd < 0)
404                         continue;
405                 if (sockfd >= FD_SETSIZE) {
406                         error("too large socket descriptor.");
407                         close(sockfd);
408                         continue;
409                 }
410
411 #ifdef IPV6_V6ONLY
412                 if (ai->ai_family == AF_INET6) {
413                         int on = 1;
414                         setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
415                                    &on, sizeof(on));
416                         /* Note: error is not fatal */
417                 }
418 #endif
419
420                 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
421                         close(sockfd);
422                         continue;       /* not fatal */
423                 }
424                 if (listen(sockfd, 5) < 0) {
425                         close(sockfd);
426                         continue;       /* not fatal */
427                 }
428
429                 newlist = realloc(socklist, sizeof(int) * (socknum + 1));
430                 if (!newlist)
431                         die("memory allocation failed: %s", strerror(errno));
432
433                 socklist = newlist;
434                 socklist[socknum++] = sockfd;
435
436                 if (maxfd < sockfd)
437                         maxfd = sockfd;
438         }
439
440         freeaddrinfo(ai0);
441
442         *socklist_p = socklist;
443         return socknum;
444 }
445
446 #else /* NO_IPV6 */
447
448 static int socksetup(int port, int **socklist_p)
449 {
450         struct sockaddr_in sin;
451         int sockfd;
452
453         sockfd = socket(AF_INET, SOCK_STREAM, 0);
454         if (sockfd < 0)
455                 return 0;
456
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);
461
462         if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
463                 close(sockfd);
464                 return 0;
465         }
466
467         *socklist_p = malloc(sizeof(int));
468         if ( !*socklist_p )
469                 die("memory allocation failed: %s", strerror(errno));
470         **socklist_p = sockfd;
471 }
472
473 #endif
474
475 static int service_loop(int socknum, int *socklist)
476 {
477         struct pollfd *pfd;
478         int i;
479
480         pfd = calloc(socknum, sizeof(struct pollfd));
481         if (!pfd)
482                 die("memory allocation failed: %s", strerror(errno));
483
484         for (i = 0; i < socknum; i++) {
485                 pfd[i].fd = socklist[i];
486                 pfd[i].events = POLLIN;
487         }
488         
489         for (;;) {
490                 int i;
491
492                 if (poll(pfd, socknum, 0) < 0) {
493                         if (errno != EINTR) {
494                                 error("poll failed, resuming: %s",
495                                       strerror(errno));
496                                 sleep(1);
497                         }
498                         continue;
499                 }
500
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);
506                                 if (incoming < 0) {
507                                         switch (errno) {
508                                         case EAGAIN:
509                                         case EINTR:
510                                         case ECONNABORTED:
511                                                 continue;
512                                         default:
513                                                 die("accept returned %s", strerror(errno));
514                                         }
515                                 }
516                                 handle(incoming, (struct sockaddr *)&ss, sslen);
517                         }
518                 }
519         }
520 }
521
522 static int serve(int port)
523 {
524         int socknum, *socklist;
525         
526         signal(SIGCHLD, child_handler);
527         
528         socknum = socksetup(port, &socklist);
529         if (socknum == 0)
530                 die("unable to allocate any listen sockets on port %u", port);
531         
532         return service_loop(socknum, socklist);
533 }       
534
535 int main(int argc, char **argv)
536 {
537         int port = DEFAULT_GIT_PORT;
538         int inetd_mode = 0;
539         int i;
540
541         for (i = 1; i < argc; i++) {
542                 char *arg = argv[i];
543
544                 if (!strncmp(arg, "--port=", 7)) {
545                         char *end;
546                         unsigned long n;
547                         n = strtoul(arg+7, &end, 0);
548                         if (arg[7] && !*end) {
549                                 port = n;
550                                 continue;
551                         }
552                 }
553                 if (!strcmp(arg, "--inetd")) {
554                         inetd_mode = 1;
555                         continue;
556                 }
557                 if (!strcmp(arg, "--verbose")) {
558                         verbose = 1;
559                         continue;
560                 }
561                 if (!strcmp(arg, "--syslog")) {
562                         log_syslog = 1;
563                         openlog("git-daemon", 0, LOG_DAEMON);
564                         continue;
565                 }
566                 if (!strcmp(arg, "--export-all")) {
567                         export_all_trees = 1;
568                         continue;
569                 }
570                 if (!strcmp(arg, "--")) {
571                         ok_paths = &argv[i+1];
572                         break;
573                 } else if (arg[0] != '-') {
574                         ok_paths = &argv[i];
575                         break;
576                 }
577
578                 usage(daemon_usage);
579         }
580
581         if (inetd_mode) {
582                 fclose(stderr); //FIXME: workaround
583                 return execute();
584         } else {
585                 return serve(port);
586         }
587 }