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