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