]> asedeno.scripts.mit.edu Git - git.git/blob - daemon.c
Removed memory leaks from interpolation table uses.
[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 <pwd.h>
11 #include <grp.h>
12 #include <limits.h>
13 #include "pkt-line.h"
14 #include "cache.h"
15 #include "exec_cmd.h"
16 #include "interpolate.h"
17
18 static int log_syslog;
19 static int verbose;
20 static int reuseaddr;
21
22 static const char daemon_usage[] =
23 "git-daemon [--verbose] [--syslog] [--export-all]\n"
24 "           [--timeout=n] [--init-timeout=n] [--strict-paths]\n"
25 "           [--base-path=path] [--user-path | --user-path=path]\n"
26 "           [--interpolated-path=path]\n"
27 "           [--reuseaddr] [--detach] [--pid-file=file]\n"
28 "           [--[enable|disable|allow-override|forbid-override]=service]\n"
29 "           [--inetd | [--listen=host_or_ipaddr] [--port=n]\n"
30 "                      [--user=user [--group=group]]\n"
31 "           [directory...]";
32
33 /* List of acceptable pathname prefixes */
34 static char **ok_paths;
35 static int strict_paths;
36
37 /* If this is set, git-daemon-export-ok is not required */
38 static int export_all_trees;
39
40 /* Take all paths relative to this one if non-NULL */
41 static char *base_path;
42 static char *interpolated_path;
43
44 /* Flag indicating client sent extra args. */
45 static int saw_extended_args;
46
47 /* If defined, ~user notation is allowed and the string is inserted
48  * after ~user/.  E.g. a request to git://host/~alice/frotz would
49  * go to /home/alice/pub_git/frotz with --user-path=pub_git.
50  */
51 static const char *user_path;
52
53 /* Timeout, and initial timeout */
54 static unsigned int timeout;
55 static unsigned int init_timeout;
56
57 /*
58  * Static table for now.  Ugh.
59  * Feel free to make dynamic as needed.
60  */
61 #define INTERP_SLOT_HOST        (0)
62 #define INTERP_SLOT_CANON_HOST  (1)
63 #define INTERP_SLOT_IP          (2)
64 #define INTERP_SLOT_PORT        (3)
65 #define INTERP_SLOT_DIR         (4)
66 #define INTERP_SLOT_PERCENT     (5)
67
68 static struct interp interp_table[] = {
69         { "%H", 0},
70         { "%CH", 0},
71         { "%IP", 0},
72         { "%P", 0},
73         { "%D", 0},
74         { "%%", 0},
75 };
76
77
78 static void logreport(int priority, const char *err, va_list params)
79 {
80         /* We should do a single write so that it is atomic and output
81          * of several processes do not get intermingled. */
82         char buf[1024];
83         int buflen;
84         int maxlen, msglen;
85
86         /* sizeof(buf) should be big enough for "[pid] \n" */
87         buflen = snprintf(buf, sizeof(buf), "[%ld] ", (long) getpid());
88
89         maxlen = sizeof(buf) - buflen - 1; /* -1 for our own LF */
90         msglen = vsnprintf(buf + buflen, maxlen, err, params);
91
92         if (log_syslog) {
93                 syslog(priority, "%s", buf);
94                 return;
95         }
96
97         /* maxlen counted our own LF but also counts space given to
98          * vsnprintf for the terminating NUL.  We want to make sure that
99          * we have space for our own LF and NUL after the "meat" of the
100          * message, so truncate it at maxlen - 1.
101          */
102         if (msglen > maxlen - 1)
103                 msglen = maxlen - 1;
104         else if (msglen < 0)
105                 msglen = 0; /* Protect against weird return values. */
106         buflen += msglen;
107
108         buf[buflen++] = '\n';
109         buf[buflen] = '\0';
110
111         write(2, buf, buflen);
112 }
113
114 static void logerror(const char *err, ...)
115 {
116         va_list params;
117         va_start(params, err);
118         logreport(LOG_ERR, err, params);
119         va_end(params);
120 }
121
122 static void loginfo(const char *err, ...)
123 {
124         va_list params;
125         if (!verbose)
126                 return;
127         va_start(params, err);
128         logreport(LOG_INFO, err, params);
129         va_end(params);
130 }
131
132 static void NORETURN daemon_die(const char *err, va_list params)
133 {
134         logreport(LOG_ERR, err, params);
135         exit(1);
136 }
137
138 static int avoid_alias(char *p)
139 {
140         int sl, ndot;
141
142         /* 
143          * This resurrects the belts and suspenders paranoia check by HPA
144          * done in <435560F7.4080006@zytor.com> thread, now enter_repo()
145          * does not do getcwd() based path canonicalizations.
146          *
147          * sl becomes true immediately after seeing '/' and continues to
148          * be true as long as dots continue after that without intervening
149          * non-dot character.
150          */
151         if (!p || (*p != '/' && *p != '~'))
152                 return -1;
153         sl = 1; ndot = 0;
154         p++;
155
156         while (1) {
157                 char ch = *p++;
158                 if (sl) {
159                         if (ch == '.')
160                                 ndot++;
161                         else if (ch == '/') {
162                                 if (ndot < 3)
163                                         /* reject //, /./ and /../ */
164                                         return -1;
165                                 ndot = 0;
166                         }
167                         else if (ch == 0) {
168                                 if (0 < ndot && ndot < 3)
169                                         /* reject /.$ and /..$ */
170                                         return -1;
171                                 return 0;
172                         }
173                         else
174                                 sl = ndot = 0;
175                 }
176                 else if (ch == 0)
177                         return 0;
178                 else if (ch == '/') {
179                         sl = 1;
180                         ndot = 0;
181                 }
182         }
183 }
184
185 static char *path_ok(struct interp *itable)
186 {
187         static char rpath[PATH_MAX];
188         static char interp_path[PATH_MAX];
189         char *path;
190         char *dir;
191
192         dir = itable[INTERP_SLOT_DIR].value;
193
194         if (avoid_alias(dir)) {
195                 logerror("'%s': aliased", dir);
196                 return NULL;
197         }
198
199         if (*dir == '~') {
200                 if (!user_path) {
201                         logerror("'%s': User-path not allowed", dir);
202                         return NULL;
203                 }
204                 if (*user_path) {
205                         /* Got either "~alice" or "~alice/foo";
206                          * rewrite them to "~alice/%s" or
207                          * "~alice/%s/foo".
208                          */
209                         int namlen, restlen = strlen(dir);
210                         char *slash = strchr(dir, '/');
211                         if (!slash)
212                                 slash = dir + restlen;
213                         namlen = slash - dir;
214                         restlen -= namlen;
215                         loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
216                         snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
217                                  namlen, dir, user_path, restlen, slash);
218                         dir = rpath;
219                 }
220         }
221         else if (interpolated_path && saw_extended_args) {
222                 if (*dir != '/') {
223                         /* Allow only absolute */
224                         logerror("'%s': Non-absolute path denied (interpolated-path active)", dir);
225                         return NULL;
226                 }
227
228                 interpolate(interp_path, PATH_MAX, interpolated_path,
229                             interp_table, ARRAY_SIZE(interp_table));
230                 loginfo("Interpolated dir '%s'", interp_path);
231
232                 dir = interp_path;
233         }
234         else if (base_path) {
235                 if (*dir != '/') {
236                         /* Allow only absolute */
237                         logerror("'%s': Non-absolute path denied (base-path active)", dir);
238                         return NULL;
239                 }
240                 snprintf(rpath, PATH_MAX, "%s%s", base_path, dir);
241                 dir = rpath;
242         }
243
244         path = enter_repo(dir, strict_paths);
245
246         if (!path) {
247                 logerror("'%s': unable to chdir or not a git archive", dir);
248                 return NULL;
249         }
250
251         if ( ok_paths && *ok_paths ) {
252                 char **pp;
253                 int pathlen = strlen(path);
254
255                 /* The validation is done on the paths after enter_repo
256                  * appends optional {.git,.git/.git} and friends, but 
257                  * it does not use getcwd().  So if your /pub is
258                  * a symlink to /mnt/pub, you can whitelist /pub and
259                  * do not have to say /mnt/pub.
260                  * Do not say /pub/.
261                  */
262                 for ( pp = ok_paths ; *pp ; pp++ ) {
263                         int len = strlen(*pp);
264                         if (len <= pathlen &&
265                             !memcmp(*pp, path, len) &&
266                             (path[len] == '\0' ||
267                              (!strict_paths && path[len] == '/')))
268                                 return path;
269                 }
270         }
271         else {
272                 /* be backwards compatible */
273                 if (!strict_paths)
274                         return path;
275         }
276
277         logerror("'%s': not in whitelist", path);
278         return NULL;            /* Fallthrough. Deny by default */
279 }
280
281 typedef int (*daemon_service_fn)(void);
282 struct daemon_service {
283         const char *name;
284         const char *config_name;
285         daemon_service_fn fn;
286         int enabled;
287         int overridable;
288 };
289
290 static struct daemon_service *service_looking_at;
291 static int service_enabled;
292
293 static int git_daemon_config(const char *var, const char *value)
294 {
295         if (!strncmp(var, "daemon.", 7) &&
296             !strcmp(var + 7, service_looking_at->config_name)) {
297                 service_enabled = git_config_bool(var, value);
298                 return 0;
299         }
300
301         /* we are not interested in parsing any other configuration here */
302         return 0;
303 }
304
305 static int run_service(struct interp *itable, struct daemon_service *service)
306 {
307         const char *path;
308         int enabled = service->enabled;
309
310         loginfo("Request %s for '%s'",
311                 service->name,
312                 itable[INTERP_SLOT_DIR].value);
313
314         if (!enabled && !service->overridable) {
315                 logerror("'%s': service not enabled.", service->name);
316                 errno = EACCES;
317                 return -1;
318         }
319
320         if (!(path = path_ok(itable)))
321                 return -1;
322
323         /*
324          * Security on the cheap.
325          *
326          * We want a readable HEAD, usable "objects" directory, and
327          * a "git-daemon-export-ok" flag that says that the other side
328          * is ok with us doing this.
329          *
330          * path_ok() uses enter_repo() and does whitelist checking.
331          * We only need to make sure the repository is exported.
332          */
333
334         if (!export_all_trees && access("git-daemon-export-ok", F_OK)) {
335                 logerror("'%s': repository not exported.", path);
336                 errno = EACCES;
337                 return -1;
338         }
339
340         if (service->overridable) {
341                 service_looking_at = service;
342                 service_enabled = -1;
343                 git_config(git_daemon_config);
344                 if (0 <= service_enabled)
345                         enabled = service_enabled;
346         }
347         if (!enabled) {
348                 logerror("'%s': service not enabled for '%s'",
349                          service->name, path);
350                 errno = EACCES;
351                 return -1;
352         }
353
354         /*
355          * We'll ignore SIGTERM from now on, we have a
356          * good client.
357          */
358         signal(SIGTERM, SIG_IGN);
359
360         return service->fn();
361 }
362
363 static int upload_pack(void)
364 {
365         /* Timeout as string */
366         char timeout_buf[64];
367
368         snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
369
370         /* git-upload-pack only ever reads stuff, so this is safe */
371         execl_git_cmd("upload-pack", "--strict", timeout_buf, ".", NULL);
372         return -1;
373 }
374
375 static int upload_archive(void)
376 {
377         execl_git_cmd("upload-archive", ".", NULL);
378         return -1;
379 }
380
381 static struct daemon_service daemon_service[] = {
382         { "upload-archive", "uploadarch", upload_archive, 0, 1 },
383         { "upload-pack", "uploadpack", upload_pack, 1, 1 },
384 };
385
386 static void enable_service(const char *name, int ena) {
387         int i;
388         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
389                 if (!strcmp(daemon_service[i].name, name)) {
390                         daemon_service[i].enabled = ena;
391                         return;
392                 }
393         }
394         die("No such service %s", name);
395 }
396
397 static void make_service_overridable(const char *name, int ena) {
398         int i;
399         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
400                 if (!strcmp(daemon_service[i].name, name)) {
401                         daemon_service[i].overridable = ena;
402                         return;
403                 }
404         }
405         die("No such service %s", name);
406 }
407
408 /*
409  * Separate the "extra args" information as supplied by the client connection.
410  * Any resulting data is squirrelled away in the given interpolation table.
411  */
412 static void parse_extra_args(struct interp *table, char *extra_args, int buflen)
413 {
414         char *val;
415         int vallen;
416         char *end = extra_args + buflen;
417
418         while (extra_args < end && *extra_args) {
419                 saw_extended_args = 1;
420                 if (strncasecmp("host=", extra_args, 5) == 0) {
421                         val = extra_args + 5;
422                         vallen = strlen(val) + 1;
423                         if (*val) {
424                                 /* Split <host>:<port> at colon. */
425                                 char *host = val;
426                                 char *port = strrchr(host, ':');
427                                 if (port) {
428                                         *port = 0;
429                                         port++;
430                                         interp_set_entry(table, INTERP_SLOT_PORT, port);
431                                 }
432                                 interp_set_entry(table, INTERP_SLOT_HOST, host);
433                         }
434
435                         /* On to the next one */
436                         extra_args = val + vallen;
437                 }
438         }
439 }
440
441 void fill_in_extra_table_entries(struct interp *itable)
442 {
443         char *hp;
444
445         /*
446          * Replace literal host with lowercase-ized hostname.
447          */
448         hp = interp_table[INTERP_SLOT_HOST].value;
449         for ( ; *hp; hp++)
450                 *hp = tolower(*hp);
451
452         /*
453          * Locate canonical hostname and its IP address.
454          */
455 #ifndef NO_IPV6
456         {
457                 struct addrinfo hints;
458                 struct addrinfo *ai, *ai0;
459                 int gai;
460                 static char addrbuf[HOST_NAME_MAX + 1];
461
462                 memset(&hints, 0, sizeof(hints));
463                 hints.ai_flags = AI_CANONNAME;
464
465                 gai = getaddrinfo(interp_table[INTERP_SLOT_HOST].value, 0, &hints, &ai0);
466                 if (!gai) {
467                         for (ai = ai0; ai; ai = ai->ai_next) {
468                                 struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
469
470                                 inet_ntop(AF_INET, &sin_addr->sin_addr,
471                                           addrbuf, sizeof(addrbuf));
472                                 interp_set_entry(interp_table,
473                                                  INTERP_SLOT_CANON_HOST, ai->ai_canonname);
474                                 interp_set_entry(interp_table,
475                                                  INTERP_SLOT_IP, addrbuf);
476                                 break;
477                         }
478                         freeaddrinfo(ai0);
479                 }
480         }
481 #else
482         {
483                 struct hostent *hent;
484                 struct sockaddr_in sa;
485                 char **ap;
486                 static char addrbuf[HOST_NAME_MAX + 1];
487
488                 hent = gethostbyname(interp_table[INTERP_SLOT_HOST].value);
489
490                 ap = hent->h_addr_list;
491                 memset(&sa, 0, sizeof sa);
492                 sa.sin_family = hent->h_addrtype;
493                 sa.sin_port = htons(0);
494                 memcpy(&sa.sin_addr, *ap, hent->h_length);
495
496                 inet_ntop(hent->h_addrtype, &sa.sin_addr,
497                           addrbuf, sizeof(addrbuf));
498
499                 interp_set_entry(interp_table, INTERP_SLOT_CANON_HOST, hent->h_name);
500                 interp_set_entry(interp_table, INTERP_SLOT_IP, addrbuf);
501         }
502 #endif
503 }
504
505
506 static int execute(struct sockaddr *addr)
507 {
508         static char line[1000];
509         int pktlen, len, i;
510
511         if (addr) {
512                 char addrbuf[256] = "";
513                 int port = -1;
514
515                 if (addr->sa_family == AF_INET) {
516                         struct sockaddr_in *sin_addr = (void *) addr;
517                         inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
518                         port = sin_addr->sin_port;
519 #ifndef NO_IPV6
520                 } else if (addr && addr->sa_family == AF_INET6) {
521                         struct sockaddr_in6 *sin6_addr = (void *) addr;
522
523                         char *buf = addrbuf;
524                         *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
525                         inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
526                         strcat(buf, "]");
527
528                         port = sin6_addr->sin6_port;
529 #endif
530                 }
531                 loginfo("Connection from %s:%d", addrbuf, port);
532         }
533
534         alarm(init_timeout ? init_timeout : timeout);
535         pktlen = packet_read_line(0, line, sizeof(line));
536         alarm(0);
537
538         len = strlen(line);
539         if (pktlen != len)
540                 loginfo("Extended attributes (%d bytes) exist <%.*s>",
541                         (int) pktlen - len,
542                         (int) pktlen - len, line + len + 1);
543         if (len && line[len-1] == '\n')
544                 line[--len] = 0;
545
546         /*
547          * Initialize the path interpolation table for this connection.
548          */
549         interp_clear_table(interp_table, ARRAY_SIZE(interp_table));
550         interp_set_entry(interp_table, INTERP_SLOT_PERCENT, "%");
551
552         if (len != pktlen) {
553             parse_extra_args(interp_table, line + len + 1, pktlen - len - 1);
554             fill_in_extra_table_entries(interp_table);
555         }
556
557         for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
558                 struct daemon_service *s = &(daemon_service[i]);
559                 int namelen = strlen(s->name);
560                 if (!strncmp("git-", line, 4) &&
561                     !strncmp(s->name, line + 4, namelen) &&
562                     line[namelen + 4] == ' ') {
563                         /*
564                          * Note: The directory here is probably context sensitive,
565                          * and might depend on the actual service being performed.
566                          */
567                         interp_set_entry(interp_table,
568                                          INTERP_SLOT_DIR, line + namelen + 5);
569                         return run_service(interp_table, s);
570                 }
571         }
572
573         logerror("Protocol error: '%s'", line);
574         return -1;
575 }
576
577
578 /*
579  * We count spawned/reaped separately, just to avoid any
580  * races when updating them from signals. The SIGCHLD handler
581  * will only update children_reaped, and the fork logic will
582  * only update children_spawned.
583  *
584  * MAX_CHILDREN should be a power-of-two to make the modulus
585  * operation cheap. It should also be at least twice
586  * the maximum number of connections we will ever allow.
587  */
588 #define MAX_CHILDREN 128
589
590 static int max_connections = 25;
591
592 /* These are updated by the signal handler */
593 static volatile unsigned int children_reaped;
594 static pid_t dead_child[MAX_CHILDREN];
595
596 /* These are updated by the main loop */
597 static unsigned int children_spawned;
598 static unsigned int children_deleted;
599
600 static struct child {
601         pid_t pid;
602         int addrlen;
603         struct sockaddr_storage address;
604 } live_child[MAX_CHILDREN];
605
606 static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
607 {
608         live_child[idx].pid = pid;
609         live_child[idx].addrlen = addrlen;
610         memcpy(&live_child[idx].address, addr, addrlen);
611 }
612
613 /*
614  * Walk from "deleted" to "spawned", and remove child "pid".
615  *
616  * We move everything up by one, since the new "deleted" will
617  * be one higher.
618  */
619 static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
620 {
621         struct child n;
622
623         deleted %= MAX_CHILDREN;
624         spawned %= MAX_CHILDREN;
625         if (live_child[deleted].pid == pid) {
626                 live_child[deleted].pid = -1;
627                 return;
628         }
629         n = live_child[deleted];
630         for (;;) {
631                 struct child m;
632                 deleted = (deleted + 1) % MAX_CHILDREN;
633                 if (deleted == spawned)
634                         die("could not find dead child %d\n", pid);
635                 m = live_child[deleted];
636                 live_child[deleted] = n;
637                 if (m.pid == pid)
638                         return;
639                 n = m;
640         }
641 }
642
643 /*
644  * This gets called if the number of connections grows
645  * past "max_connections".
646  *
647  * We _should_ start off by searching for connections
648  * from the same IP, and if there is some address wth
649  * multiple connections, we should kill that first.
650  *
651  * As it is, we just "randomly" kill 25% of the connections,
652  * and our pseudo-random generator sucks too. I have no
653  * shame.
654  *
655  * Really, this is just a place-holder for a _real_ algorithm.
656  */
657 static void kill_some_children(int signo, unsigned start, unsigned stop)
658 {
659         start %= MAX_CHILDREN;
660         stop %= MAX_CHILDREN;
661         while (start != stop) {
662                 if (!(start & 3))
663                         kill(live_child[start].pid, signo);
664                 start = (start + 1) % MAX_CHILDREN;
665         }
666 }
667
668 static void check_max_connections(void)
669 {
670         for (;;) {
671                 int active;
672                 unsigned spawned, reaped, deleted;
673
674                 spawned = children_spawned;
675                 reaped = children_reaped;
676                 deleted = children_deleted;
677
678                 while (deleted < reaped) {
679                         pid_t pid = dead_child[deleted % MAX_CHILDREN];
680                         remove_child(pid, deleted, spawned);
681                         deleted++;
682                 }
683                 children_deleted = deleted;
684
685                 active = spawned - deleted;
686                 if (active <= max_connections)
687                         break;
688
689                 /* Kill some unstarted connections with SIGTERM */
690                 kill_some_children(SIGTERM, deleted, spawned);
691                 if (active <= max_connections << 1)
692                         break;
693
694                 /* If the SIGTERM thing isn't helping use SIGKILL */
695                 kill_some_children(SIGKILL, deleted, spawned);
696                 sleep(1);
697         }
698 }
699
700 static void handle(int incoming, struct sockaddr *addr, int addrlen)
701 {
702         pid_t pid = fork();
703
704         if (pid) {
705                 unsigned idx;
706
707                 close(incoming);
708                 if (pid < 0)
709                         return;
710
711                 idx = children_spawned % MAX_CHILDREN;
712                 children_spawned++;
713                 add_child(idx, pid, addr, addrlen);
714
715                 check_max_connections();
716                 return;
717         }
718
719         dup2(incoming, 0);
720         dup2(incoming, 1);
721         close(incoming);
722
723         exit(execute(addr));
724 }
725
726 static void child_handler(int signo)
727 {
728         for (;;) {
729                 int status;
730                 pid_t pid = waitpid(-1, &status, WNOHANG);
731
732                 if (pid > 0) {
733                         unsigned reaped = children_reaped;
734                         dead_child[reaped % MAX_CHILDREN] = pid;
735                         children_reaped = reaped + 1;
736                         /* XXX: Custom logging, since we don't wanna getpid() */
737                         if (verbose) {
738                                 const char *dead = "";
739                                 if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
740                                         dead = " (with error)";
741                                 if (log_syslog)
742                                         syslog(LOG_INFO, "[%d] Disconnected%s", pid, dead);
743                                 else
744                                         fprintf(stderr, "[%d] Disconnected%s\n", pid, dead);
745                         }
746                         continue;
747                 }
748                 break;
749         }
750 }
751
752 static int set_reuse_addr(int sockfd)
753 {
754         int on = 1;
755
756         if (!reuseaddr)
757                 return 0;
758         return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
759                           &on, sizeof(on));
760 }
761
762 #ifndef NO_IPV6
763
764 static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
765 {
766         int socknum = 0, *socklist = NULL;
767         int maxfd = -1;
768         char pbuf[NI_MAXSERV];
769         struct addrinfo hints, *ai0, *ai;
770         int gai;
771
772         sprintf(pbuf, "%d", listen_port);
773         memset(&hints, 0, sizeof(hints));
774         hints.ai_family = AF_UNSPEC;
775         hints.ai_socktype = SOCK_STREAM;
776         hints.ai_protocol = IPPROTO_TCP;
777         hints.ai_flags = AI_PASSIVE;
778
779         gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
780         if (gai)
781                 die("getaddrinfo() failed: %s\n", gai_strerror(gai));
782
783         for (ai = ai0; ai; ai = ai->ai_next) {
784                 int sockfd;
785
786                 sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
787                 if (sockfd < 0)
788                         continue;
789                 if (sockfd >= FD_SETSIZE) {
790                         error("too large socket descriptor.");
791                         close(sockfd);
792                         continue;
793                 }
794
795 #ifdef IPV6_V6ONLY
796                 if (ai->ai_family == AF_INET6) {
797                         int on = 1;
798                         setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
799                                    &on, sizeof(on));
800                         /* Note: error is not fatal */
801                 }
802 #endif
803
804                 if (set_reuse_addr(sockfd)) {
805                         close(sockfd);
806                         continue;
807                 }
808
809                 if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
810                         close(sockfd);
811                         continue;       /* not fatal */
812                 }
813                 if (listen(sockfd, 5) < 0) {
814                         close(sockfd);
815                         continue;       /* not fatal */
816                 }
817
818                 socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
819                 socklist[socknum++] = sockfd;
820
821                 if (maxfd < sockfd)
822                         maxfd = sockfd;
823         }
824
825         freeaddrinfo(ai0);
826
827         *socklist_p = socklist;
828         return socknum;
829 }
830
831 #else /* NO_IPV6 */
832
833 static int socksetup(char *lisen_addr, int listen_port, int **socklist_p)
834 {
835         struct sockaddr_in sin;
836         int sockfd;
837
838         memset(&sin, 0, sizeof sin);
839         sin.sin_family = AF_INET;
840         sin.sin_port = htons(listen_port);
841
842         if (listen_addr) {
843                 /* Well, host better be an IP address here. */
844                 if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
845                         return 0;
846         } else {
847                 sin.sin_addr.s_addr = htonl(INADDR_ANY);
848         }
849
850         sockfd = socket(AF_INET, SOCK_STREAM, 0);
851         if (sockfd < 0)
852                 return 0;
853
854         if (set_reuse_addr(sockfd)) {
855                 close(sockfd);
856                 return 0;
857         }
858
859         if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
860                 close(sockfd);
861                 return 0;
862         }
863
864         if (listen(sockfd, 5) < 0) {
865                 close(sockfd);
866                 return 0;
867         }
868
869         *socklist_p = xmalloc(sizeof(int));
870         **socklist_p = sockfd;
871         return 1;
872 }
873
874 #endif
875
876 static int service_loop(int socknum, int *socklist)
877 {
878         struct pollfd *pfd;
879         int i;
880
881         pfd = xcalloc(socknum, sizeof(struct pollfd));
882
883         for (i = 0; i < socknum; i++) {
884                 pfd[i].fd = socklist[i];
885                 pfd[i].events = POLLIN;
886         }
887
888         signal(SIGCHLD, child_handler);
889
890         for (;;) {
891                 int i;
892
893                 if (poll(pfd, socknum, -1) < 0) {
894                         if (errno != EINTR) {
895                                 error("poll failed, resuming: %s",
896                                       strerror(errno));
897                                 sleep(1);
898                         }
899                         continue;
900                 }
901
902                 for (i = 0; i < socknum; i++) {
903                         if (pfd[i].revents & POLLIN) {
904                                 struct sockaddr_storage ss;
905                                 unsigned int sslen = sizeof(ss);
906                                 int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
907                                 if (incoming < 0) {
908                                         switch (errno) {
909                                         case EAGAIN:
910                                         case EINTR:
911                                         case ECONNABORTED:
912                                                 continue;
913                                         default:
914                                                 die("accept returned %s", strerror(errno));
915                                         }
916                                 }
917                                 handle(incoming, (struct sockaddr *)&ss, sslen);
918                         }
919                 }
920         }
921 }
922
923 /* if any standard file descriptor is missing open it to /dev/null */
924 static void sanitize_stdfds(void)
925 {
926         int fd = open("/dev/null", O_RDWR, 0);
927         while (fd != -1 && fd < 2)
928                 fd = dup(fd);
929         if (fd == -1)
930                 die("open /dev/null or dup failed: %s", strerror(errno));
931         if (fd > 2)
932                 close(fd);
933 }
934
935 static void daemonize(void)
936 {
937         switch (fork()) {
938                 case 0:
939                         break;
940                 case -1:
941                         die("fork failed: %s", strerror(errno));
942                 default:
943                         exit(0);
944         }
945         if (setsid() == -1)
946                 die("setsid failed: %s", strerror(errno));
947         close(0);
948         close(1);
949         close(2);
950         sanitize_stdfds();
951 }
952
953 static void store_pid(const char *path)
954 {
955         FILE *f = fopen(path, "w");
956         if (!f)
957                 die("cannot open pid file %s: %s", path, strerror(errno));
958         fprintf(f, "%d\n", getpid());
959         fclose(f);
960 }
961
962 static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
963 {
964         int socknum, *socklist;
965
966         socknum = socksetup(listen_addr, listen_port, &socklist);
967         if (socknum == 0)
968                 die("unable to allocate any listen sockets on host %s port %u",
969                     listen_addr, listen_port);
970
971         if (pass && gid &&
972             (initgroups(pass->pw_name, gid) || setgid (gid) ||
973              setuid(pass->pw_uid)))
974                 die("cannot drop privileges");
975
976         return service_loop(socknum, socklist);
977 }
978
979 int main(int argc, char **argv)
980 {
981         int listen_port = 0;
982         char *listen_addr = NULL;
983         int inetd_mode = 0;
984         const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
985         int detach = 0;
986         struct passwd *pass = NULL;
987         struct group *group;
988         gid_t gid = 0;
989         int i;
990
991         /* Without this we cannot rely on waitpid() to tell
992          * what happened to our children.
993          */
994         signal(SIGCHLD, SIG_DFL);
995
996         for (i = 1; i < argc; i++) {
997                 char *arg = argv[i];
998
999                 if (!strncmp(arg, "--listen=", 9)) {
1000                     char *p = arg + 9;
1001                     char *ph = listen_addr = xmalloc(strlen(arg + 9) + 1);
1002                     while (*p)
1003                         *ph++ = tolower(*p++);
1004                     *ph = 0;
1005                     continue;
1006                 }
1007                 if (!strncmp(arg, "--port=", 7)) {
1008                         char *end;
1009                         unsigned long n;
1010                         n = strtoul(arg+7, &end, 0);
1011                         if (arg[7] && !*end) {
1012                                 listen_port = n;
1013                                 continue;
1014                         }
1015                 }
1016                 if (!strcmp(arg, "--inetd")) {
1017                         inetd_mode = 1;
1018                         log_syslog = 1;
1019                         continue;
1020                 }
1021                 if (!strcmp(arg, "--verbose")) {
1022                         verbose = 1;
1023                         continue;
1024                 }
1025                 if (!strcmp(arg, "--syslog")) {
1026                         log_syslog = 1;
1027                         continue;
1028                 }
1029                 if (!strcmp(arg, "--export-all")) {
1030                         export_all_trees = 1;
1031                         continue;
1032                 }
1033                 if (!strncmp(arg, "--timeout=", 10)) {
1034                         timeout = atoi(arg+10);
1035                         continue;
1036                 }
1037                 if (!strncmp(arg, "--init-timeout=", 15)) {
1038                         init_timeout = atoi(arg+15);
1039                         continue;
1040                 }
1041                 if (!strcmp(arg, "--strict-paths")) {
1042                         strict_paths = 1;
1043                         continue;
1044                 }
1045                 if (!strncmp(arg, "--base-path=", 12)) {
1046                         base_path = arg+12;
1047                         continue;
1048                 }
1049                 if (!strncmp(arg, "--interpolated-path=", 20)) {
1050                         interpolated_path = arg+20;
1051                         continue;
1052                 }
1053                 if (!strcmp(arg, "--reuseaddr")) {
1054                         reuseaddr = 1;
1055                         continue;
1056                 }
1057                 if (!strcmp(arg, "--user-path")) {
1058                         user_path = "";
1059                         continue;
1060                 }
1061                 if (!strncmp(arg, "--user-path=", 12)) {
1062                         user_path = arg + 12;
1063                         continue;
1064                 }
1065                 if (!strncmp(arg, "--pid-file=", 11)) {
1066                         pid_file = arg + 11;
1067                         continue;
1068                 }
1069                 if (!strcmp(arg, "--detach")) {
1070                         detach = 1;
1071                         log_syslog = 1;
1072                         continue;
1073                 }
1074                 if (!strncmp(arg, "--user=", 7)) {
1075                         user_name = arg + 7;
1076                         continue;
1077                 }
1078                 if (!strncmp(arg, "--group=", 8)) {
1079                         group_name = arg + 8;
1080                         continue;
1081                 }
1082                 if (!strncmp(arg, "--enable=", 9)) {
1083                         enable_service(arg + 9, 1);
1084                         continue;
1085                 }
1086                 if (!strncmp(arg, "--disable=", 10)) {
1087                         enable_service(arg + 10, 0);
1088                         continue;
1089                 }
1090                 if (!strncmp(arg, "--allow-override=", 17)) {
1091                         make_service_overridable(arg + 17, 1);
1092                         continue;
1093                 }
1094                 if (!strncmp(arg, "--forbid-override=", 18)) {
1095                         make_service_overridable(arg + 18, 0);
1096                         continue;
1097                 }
1098                 if (!strcmp(arg, "--")) {
1099                         ok_paths = &argv[i+1];
1100                         break;
1101                 } else if (arg[0] != '-') {
1102                         ok_paths = &argv[i];
1103                         break;
1104                 }
1105
1106                 usage(daemon_usage);
1107         }
1108
1109         if (inetd_mode && (group_name || user_name))
1110                 die("--user and --group are incompatible with --inetd");
1111
1112         if (inetd_mode && (listen_port || listen_addr))
1113                 die("--listen= and --port= are incompatible with --inetd");
1114         else if (listen_port == 0)
1115                 listen_port = DEFAULT_GIT_PORT;
1116
1117         if (group_name && !user_name)
1118                 die("--group supplied without --user");
1119
1120         if (user_name) {
1121                 pass = getpwnam(user_name);
1122                 if (!pass)
1123                         die("user not found - %s", user_name);
1124
1125                 if (!group_name)
1126                         gid = pass->pw_gid;
1127                 else {
1128                         group = getgrnam(group_name);
1129                         if (!group)
1130                                 die("group not found - %s", group_name);
1131
1132                         gid = group->gr_gid;
1133                 }
1134         }
1135
1136         if (log_syslog) {
1137                 openlog("git-daemon", 0, LOG_DAEMON);
1138                 set_die_routine(daemon_die);
1139         }
1140
1141         if (strict_paths && (!ok_paths || !*ok_paths))
1142                 die("option --strict-paths requires a whitelist");
1143
1144         if (inetd_mode) {
1145                 struct sockaddr_storage ss;
1146                 struct sockaddr *peer = (struct sockaddr *)&ss;
1147                 socklen_t slen = sizeof(ss);
1148
1149                 freopen("/dev/null", "w", stderr);
1150
1151                 if (getpeername(0, peer, &slen))
1152                         peer = NULL;
1153
1154                 return execute(peer);
1155         }
1156
1157         if (detach)
1158                 daemonize();
1159         else
1160                 sanitize_stdfds();
1161
1162         if (pid_file)
1163                 store_pid(pid_file);
1164
1165         return serve(listen_addr, listen_port, pass, gid);
1166 }