69ea35c22dcff884899a083b678b0a4757e546ad
   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
  18static int log_syslog;
  19static int verbose;
  20static int reuseaddr;
  21
  22static 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 */
  34static char **ok_paths;
  35static int strict_paths;
  36
  37/* If this is set, git-daemon-export-ok is not required */
  38static int export_all_trees;
  39
  40/* Take all paths relative to this one if non-NULL */
  41static char *base_path;
  42static char *interpolated_path;
  43
  44/* Flag indicating client sent extra args. */
  45static 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 */
  51static const char *user_path;
  52
  53/* Timeout, and initial timeout */
  54static unsigned int timeout;
  55static 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
  68static struct interp interp_table[] = {
  69        { "%H", 0},
  70        { "%CH", 0},
  71        { "%IP", 0},
  72        { "%P", 0},
  73        { "%D", 0},
  74        { "%%", "%"},
  75};
  76
  77
  78static 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
 114static 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
 122static 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
 132static void NORETURN daemon_die(const char *err, va_list params)
 133{
 134        logreport(LOG_ERR, err, params);
 135        exit(1);
 136}
 137
 138static 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
 185static 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
 281typedef int (*daemon_service_fn)(void);
 282struct daemon_service {
 283        const char *name;
 284        const char *config_name;
 285        daemon_service_fn fn;
 286        int enabled;
 287        int overridable;
 288};
 289
 290static struct daemon_service *service_looking_at;
 291static int service_enabled;
 292
 293static 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
 305static 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
 363static 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
 375static int upload_archive(void)
 376{
 377        execl_git_cmd("upload-archive", ".", NULL);
 378        return -1;
 379}
 380
 381static struct daemon_service daemon_service[] = {
 382        { "upload-archive", "uploadarch", upload_archive, 0, 1 },
 383        { "upload-pack", "uploadpack", upload_pack, 1, 1 },
 384};
 385
 386static 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
 397static 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
 408static void parse_extra_args(char *extra_args, int buflen)
 409{
 410        char *val;
 411        int vallen;
 412        char *end = extra_args + buflen;
 413
 414        while (extra_args < end && *extra_args) {
 415                saw_extended_args = 1;
 416                if (strncasecmp("host=", extra_args, 5) == 0) {
 417                        val = extra_args + 5;
 418                        vallen = strlen(val) + 1;
 419                        if (*val) {
 420                                char *port;
 421                                char *save = xmalloc(vallen);   /* FIXME: Leak */
 422
 423                                interp_table[INTERP_SLOT_HOST].value = save;
 424                                strlcpy(save, val, vallen);
 425                                port = strrchr(save, ':');
 426                                if (port) {
 427                                        *port = 0;
 428                                        port++;
 429                                        interp_table[INTERP_SLOT_PORT].value = port;
 430                                }
 431                        }
 432                        /* On to the next one */
 433                        extra_args = val + vallen;
 434                }
 435        }
 436}
 437
 438void fill_in_extra_table_entries(struct interp *itable)
 439{
 440        char *hp;
 441        char *canon_host = NULL;
 442        char *ipaddr = NULL;
 443
 444        /*
 445         * Replace literal host with lowercase-ized hostname.
 446         */
 447        hp = interp_table[INTERP_SLOT_HOST].value;
 448        for ( ; *hp; hp++)
 449                *hp = tolower(*hp);
 450
 451        /*
 452         * Locate canonical hostname and its IP address.
 453         */
 454#ifndef NO_IPV6
 455        {
 456                struct addrinfo hints;
 457                struct addrinfo *ai, *ai0;
 458                int gai;
 459                static char addrbuf[HOST_NAME_MAX + 1];
 460
 461                memset(&hints, 0, sizeof(hints));
 462                hints.ai_flags = AI_CANONNAME;
 463
 464                gai = getaddrinfo(interp_table[INTERP_SLOT_HOST].value, 0, &hints, &ai0);
 465                if (!gai) {
 466                        for (ai = ai0; ai; ai = ai->ai_next) {
 467                                struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
 468
 469                                canon_host = xstrdup(ai->ai_canonname);
 470                                inet_ntop(AF_INET, &sin_addr->sin_addr,
 471                                          addrbuf, sizeof(addrbuf));
 472                                ipaddr = addrbuf;
 473                                break;
 474                        }
 475                        freeaddrinfo(ai0);
 476                }
 477        }
 478#else
 479        {
 480                struct hostent *hent;
 481                struct sockaddr_in sa;
 482                char **ap;
 483                static char addrbuf[HOST_NAME_MAX + 1];
 484
 485                hent = gethostbyname(interp_table[INTERP_SLOT_HOST].value);
 486                canon_host = xstrdup(hent->h_name);
 487
 488                ap = hent->h_addr_list;
 489                memset(&sa, 0, sizeof sa);
 490                sa.sin_family = hent->h_addrtype;
 491                sa.sin_port = htons(0);
 492                memcpy(&sa.sin_addr, *ap, hent->h_length);
 493
 494                inet_ntop(hent->h_addrtype, &sa.sin_addr,
 495                          addrbuf, sizeof(addrbuf));
 496                ipaddr = addrbuf;
 497        }
 498#endif
 499
 500        interp_table[INTERP_SLOT_CANON_HOST].value = canon_host;        /* FIXME: Leak */
 501        interp_table[INTERP_SLOT_IP].value = xstrdup(ipaddr);           /* FIXME: Leak */
 502}
 503
 504
 505static int execute(struct sockaddr *addr)
 506{
 507        static char line[1000];
 508        int pktlen, len, i;
 509
 510        if (addr) {
 511                char addrbuf[256] = "";
 512                int port = -1;
 513
 514                if (addr->sa_family == AF_INET) {
 515                        struct sockaddr_in *sin_addr = (void *) addr;
 516                        inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
 517                        port = sin_addr->sin_port;
 518#ifndef NO_IPV6
 519                } else if (addr && addr->sa_family == AF_INET6) {
 520                        struct sockaddr_in6 *sin6_addr = (void *) addr;
 521
 522                        char *buf = addrbuf;
 523                        *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
 524                        inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
 525                        strcat(buf, "]");
 526
 527                        port = sin6_addr->sin6_port;
 528#endif
 529                }
 530                loginfo("Connection from %s:%d", addrbuf, port);
 531        }
 532
 533        alarm(init_timeout ? init_timeout : timeout);
 534        pktlen = packet_read_line(0, line, sizeof(line));
 535        alarm(0);
 536
 537        len = strlen(line);
 538        if (pktlen != len)
 539                loginfo("Extended attributes (%d bytes) exist <%.*s>",
 540                        (int) pktlen - len,
 541                        (int) pktlen - len, line + len + 1);
 542        if (len && line[len-1] == '\n')
 543                line[--len] = 0;
 544
 545        if (len != pktlen) {
 546            parse_extra_args(line + len + 1, pktlen - len - 1);
 547            fill_in_extra_table_entries(interp_table);
 548        }
 549
 550        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 551                struct daemon_service *s = &(daemon_service[i]);
 552                int namelen = strlen(s->name);
 553                if (!strncmp("git-", line, 4) &&
 554                    !strncmp(s->name, line + 4, namelen) &&
 555                    line[namelen + 4] == ' ') {
 556                        interp_table[INTERP_SLOT_DIR].value = line+namelen+5;
 557                        return run_service(interp_table, s);
 558                }
 559        }
 560
 561        logerror("Protocol error: '%s'", line);
 562        return -1;
 563}
 564
 565
 566/*
 567 * We count spawned/reaped separately, just to avoid any
 568 * races when updating them from signals. The SIGCHLD handler
 569 * will only update children_reaped, and the fork logic will
 570 * only update children_spawned.
 571 *
 572 * MAX_CHILDREN should be a power-of-two to make the modulus
 573 * operation cheap. It should also be at least twice
 574 * the maximum number of connections we will ever allow.
 575 */
 576#define MAX_CHILDREN 128
 577
 578static int max_connections = 25;
 579
 580/* These are updated by the signal handler */
 581static volatile unsigned int children_reaped;
 582static pid_t dead_child[MAX_CHILDREN];
 583
 584/* These are updated by the main loop */
 585static unsigned int children_spawned;
 586static unsigned int children_deleted;
 587
 588static struct child {
 589        pid_t pid;
 590        int addrlen;
 591        struct sockaddr_storage address;
 592} live_child[MAX_CHILDREN];
 593
 594static void add_child(int idx, pid_t pid, struct sockaddr *addr, int addrlen)
 595{
 596        live_child[idx].pid = pid;
 597        live_child[idx].addrlen = addrlen;
 598        memcpy(&live_child[idx].address, addr, addrlen);
 599}
 600
 601/*
 602 * Walk from "deleted" to "spawned", and remove child "pid".
 603 *
 604 * We move everything up by one, since the new "deleted" will
 605 * be one higher.
 606 */
 607static void remove_child(pid_t pid, unsigned deleted, unsigned spawned)
 608{
 609        struct child n;
 610
 611        deleted %= MAX_CHILDREN;
 612        spawned %= MAX_CHILDREN;
 613        if (live_child[deleted].pid == pid) {
 614                live_child[deleted].pid = -1;
 615                return;
 616        }
 617        n = live_child[deleted];
 618        for (;;) {
 619                struct child m;
 620                deleted = (deleted + 1) % MAX_CHILDREN;
 621                if (deleted == spawned)
 622                        die("could not find dead child %d\n", pid);
 623                m = live_child[deleted];
 624                live_child[deleted] = n;
 625                if (m.pid == pid)
 626                        return;
 627                n = m;
 628        }
 629}
 630
 631/*
 632 * This gets called if the number of connections grows
 633 * past "max_connections".
 634 *
 635 * We _should_ start off by searching for connections
 636 * from the same IP, and if there is some address wth
 637 * multiple connections, we should kill that first.
 638 *
 639 * As it is, we just "randomly" kill 25% of the connections,
 640 * and our pseudo-random generator sucks too. I have no
 641 * shame.
 642 *
 643 * Really, this is just a place-holder for a _real_ algorithm.
 644 */
 645static void kill_some_children(int signo, unsigned start, unsigned stop)
 646{
 647        start %= MAX_CHILDREN;
 648        stop %= MAX_CHILDREN;
 649        while (start != stop) {
 650                if (!(start & 3))
 651                        kill(live_child[start].pid, signo);
 652                start = (start + 1) % MAX_CHILDREN;
 653        }
 654}
 655
 656static void check_max_connections(void)
 657{
 658        for (;;) {
 659                int active;
 660                unsigned spawned, reaped, deleted;
 661
 662                spawned = children_spawned;
 663                reaped = children_reaped;
 664                deleted = children_deleted;
 665
 666                while (deleted < reaped) {
 667                        pid_t pid = dead_child[deleted % MAX_CHILDREN];
 668                        remove_child(pid, deleted, spawned);
 669                        deleted++;
 670                }
 671                children_deleted = deleted;
 672
 673                active = spawned - deleted;
 674                if (active <= max_connections)
 675                        break;
 676
 677                /* Kill some unstarted connections with SIGTERM */
 678                kill_some_children(SIGTERM, deleted, spawned);
 679                if (active <= max_connections << 1)
 680                        break;
 681
 682                /* If the SIGTERM thing isn't helping use SIGKILL */
 683                kill_some_children(SIGKILL, deleted, spawned);
 684                sleep(1);
 685        }
 686}
 687
 688static void handle(int incoming, struct sockaddr *addr, int addrlen)
 689{
 690        pid_t pid = fork();
 691
 692        if (pid) {
 693                unsigned idx;
 694
 695                close(incoming);
 696                if (pid < 0)
 697                        return;
 698
 699                idx = children_spawned % MAX_CHILDREN;
 700                children_spawned++;
 701                add_child(idx, pid, addr, addrlen);
 702
 703                check_max_connections();
 704                return;
 705        }
 706
 707        dup2(incoming, 0);
 708        dup2(incoming, 1);
 709        close(incoming);
 710
 711        exit(execute(addr));
 712}
 713
 714static void child_handler(int signo)
 715{
 716        for (;;) {
 717                int status;
 718                pid_t pid = waitpid(-1, &status, WNOHANG);
 719
 720                if (pid > 0) {
 721                        unsigned reaped = children_reaped;
 722                        dead_child[reaped % MAX_CHILDREN] = pid;
 723                        children_reaped = reaped + 1;
 724                        /* XXX: Custom logging, since we don't wanna getpid() */
 725                        if (verbose) {
 726                                const char *dead = "";
 727                                if (!WIFEXITED(status) || WEXITSTATUS(status) > 0)
 728                                        dead = " (with error)";
 729                                if (log_syslog)
 730                                        syslog(LOG_INFO, "[%d] Disconnected%s", pid, dead);
 731                                else
 732                                        fprintf(stderr, "[%d] Disconnected%s\n", pid, dead);
 733                        }
 734                        continue;
 735                }
 736                break;
 737        }
 738}
 739
 740static int set_reuse_addr(int sockfd)
 741{
 742        int on = 1;
 743
 744        if (!reuseaddr)
 745                return 0;
 746        return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
 747                          &on, sizeof(on));
 748}
 749
 750#ifndef NO_IPV6
 751
 752static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
 753{
 754        int socknum = 0, *socklist = NULL;
 755        int maxfd = -1;
 756        char pbuf[NI_MAXSERV];
 757        struct addrinfo hints, *ai0, *ai;
 758        int gai;
 759
 760        sprintf(pbuf, "%d", listen_port);
 761        memset(&hints, 0, sizeof(hints));
 762        hints.ai_family = AF_UNSPEC;
 763        hints.ai_socktype = SOCK_STREAM;
 764        hints.ai_protocol = IPPROTO_TCP;
 765        hints.ai_flags = AI_PASSIVE;
 766
 767        gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
 768        if (gai)
 769                die("getaddrinfo() failed: %s\n", gai_strerror(gai));
 770
 771        for (ai = ai0; ai; ai = ai->ai_next) {
 772                int sockfd;
 773
 774                sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
 775                if (sockfd < 0)
 776                        continue;
 777                if (sockfd >= FD_SETSIZE) {
 778                        error("too large socket descriptor.");
 779                        close(sockfd);
 780                        continue;
 781                }
 782
 783#ifdef IPV6_V6ONLY
 784                if (ai->ai_family == AF_INET6) {
 785                        int on = 1;
 786                        setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
 787                                   &on, sizeof(on));
 788                        /* Note: error is not fatal */
 789                }
 790#endif
 791
 792                if (set_reuse_addr(sockfd)) {
 793                        close(sockfd);
 794                        continue;
 795                }
 796
 797                if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
 798                        close(sockfd);
 799                        continue;       /* not fatal */
 800                }
 801                if (listen(sockfd, 5) < 0) {
 802                        close(sockfd);
 803                        continue;       /* not fatal */
 804                }
 805
 806                socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
 807                socklist[socknum++] = sockfd;
 808
 809                if (maxfd < sockfd)
 810                        maxfd = sockfd;
 811        }
 812
 813        freeaddrinfo(ai0);
 814
 815        *socklist_p = socklist;
 816        return socknum;
 817}
 818
 819#else /* NO_IPV6 */
 820
 821static int socksetup(char *lisen_addr, int listen_port, int **socklist_p)
 822{
 823        struct sockaddr_in sin;
 824        int sockfd;
 825
 826        memset(&sin, 0, sizeof sin);
 827        sin.sin_family = AF_INET;
 828        sin.sin_port = htons(listen_port);
 829
 830        if (listen_addr) {
 831                /* Well, host better be an IP address here. */
 832                if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
 833                        return 0;
 834        } else {
 835                sin.sin_addr.s_addr = htonl(INADDR_ANY);
 836        }
 837
 838        sockfd = socket(AF_INET, SOCK_STREAM, 0);
 839        if (sockfd < 0)
 840                return 0;
 841
 842        if (set_reuse_addr(sockfd)) {
 843                close(sockfd);
 844                return 0;
 845        }
 846
 847        if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
 848                close(sockfd);
 849                return 0;
 850        }
 851
 852        if (listen(sockfd, 5) < 0) {
 853                close(sockfd);
 854                return 0;
 855        }
 856
 857        *socklist_p = xmalloc(sizeof(int));
 858        **socklist_p = sockfd;
 859        return 1;
 860}
 861
 862#endif
 863
 864static int service_loop(int socknum, int *socklist)
 865{
 866        struct pollfd *pfd;
 867        int i;
 868
 869        pfd = xcalloc(socknum, sizeof(struct pollfd));
 870
 871        for (i = 0; i < socknum; i++) {
 872                pfd[i].fd = socklist[i];
 873                pfd[i].events = POLLIN;
 874        }
 875
 876        signal(SIGCHLD, child_handler);
 877
 878        for (;;) {
 879                int i;
 880
 881                if (poll(pfd, socknum, -1) < 0) {
 882                        if (errno != EINTR) {
 883                                error("poll failed, resuming: %s",
 884                                      strerror(errno));
 885                                sleep(1);
 886                        }
 887                        continue;
 888                }
 889
 890                for (i = 0; i < socknum; i++) {
 891                        if (pfd[i].revents & POLLIN) {
 892                                struct sockaddr_storage ss;
 893                                unsigned int sslen = sizeof(ss);
 894                                int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
 895                                if (incoming < 0) {
 896                                        switch (errno) {
 897                                        case EAGAIN:
 898                                        case EINTR:
 899                                        case ECONNABORTED:
 900                                                continue;
 901                                        default:
 902                                                die("accept returned %s", strerror(errno));
 903                                        }
 904                                }
 905                                handle(incoming, (struct sockaddr *)&ss, sslen);
 906                        }
 907                }
 908        }
 909}
 910
 911/* if any standard file descriptor is missing open it to /dev/null */
 912static void sanitize_stdfds(void)
 913{
 914        int fd = open("/dev/null", O_RDWR, 0);
 915        while (fd != -1 && fd < 2)
 916                fd = dup(fd);
 917        if (fd == -1)
 918                die("open /dev/null or dup failed: %s", strerror(errno));
 919        if (fd > 2)
 920                close(fd);
 921}
 922
 923static void daemonize(void)
 924{
 925        switch (fork()) {
 926                case 0:
 927                        break;
 928                case -1:
 929                        die("fork failed: %s", strerror(errno));
 930                default:
 931                        exit(0);
 932        }
 933        if (setsid() == -1)
 934                die("setsid failed: %s", strerror(errno));
 935        close(0);
 936        close(1);
 937        close(2);
 938        sanitize_stdfds();
 939}
 940
 941static void store_pid(const char *path)
 942{
 943        FILE *f = fopen(path, "w");
 944        if (!f)
 945                die("cannot open pid file %s: %s", path, strerror(errno));
 946        fprintf(f, "%d\n", getpid());
 947        fclose(f);
 948}
 949
 950static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
 951{
 952        int socknum, *socklist;
 953
 954        socknum = socksetup(listen_addr, listen_port, &socklist);
 955        if (socknum == 0)
 956                die("unable to allocate any listen sockets on host %s port %u",
 957                    listen_addr, listen_port);
 958
 959        if (pass && gid &&
 960            (initgroups(pass->pw_name, gid) || setgid (gid) ||
 961             setuid(pass->pw_uid)))
 962                die("cannot drop privileges");
 963
 964        return service_loop(socknum, socklist);
 965}
 966
 967int main(int argc, char **argv)
 968{
 969        int listen_port = 0;
 970        char *listen_addr = NULL;
 971        int inetd_mode = 0;
 972        const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
 973        int detach = 0;
 974        struct passwd *pass = NULL;
 975        struct group *group;
 976        gid_t gid = 0;
 977        int i;
 978
 979        /* Without this we cannot rely on waitpid() to tell
 980         * what happened to our children.
 981         */
 982        signal(SIGCHLD, SIG_DFL);
 983
 984        for (i = 1; i < argc; i++) {
 985                char *arg = argv[i];
 986
 987                if (!strncmp(arg, "--listen=", 9)) {
 988                    char *p = arg + 9;
 989                    char *ph = listen_addr = xmalloc(strlen(arg + 9) + 1);
 990                    while (*p)
 991                        *ph++ = tolower(*p++);
 992                    *ph = 0;
 993                    continue;
 994                }
 995                if (!strncmp(arg, "--port=", 7)) {
 996                        char *end;
 997                        unsigned long n;
 998                        n = strtoul(arg+7, &end, 0);
 999                        if (arg[7] && !*end) {
1000                                listen_port = n;
1001                                continue;
1002                        }
1003                }
1004                if (!strcmp(arg, "--inetd")) {
1005                        inetd_mode = 1;
1006                        log_syslog = 1;
1007                        continue;
1008                }
1009                if (!strcmp(arg, "--verbose")) {
1010                        verbose = 1;
1011                        continue;
1012                }
1013                if (!strcmp(arg, "--syslog")) {
1014                        log_syslog = 1;
1015                        continue;
1016                }
1017                if (!strcmp(arg, "--export-all")) {
1018                        export_all_trees = 1;
1019                        continue;
1020                }
1021                if (!strncmp(arg, "--timeout=", 10)) {
1022                        timeout = atoi(arg+10);
1023                        continue;
1024                }
1025                if (!strncmp(arg, "--init-timeout=", 15)) {
1026                        init_timeout = atoi(arg+15);
1027                        continue;
1028                }
1029                if (!strcmp(arg, "--strict-paths")) {
1030                        strict_paths = 1;
1031                        continue;
1032                }
1033                if (!strncmp(arg, "--base-path=", 12)) {
1034                        base_path = arg+12;
1035                        continue;
1036                }
1037                if (!strncmp(arg, "--interpolated-path=", 20)) {
1038                        interpolated_path = arg+20;
1039                        continue;
1040                }
1041                if (!strcmp(arg, "--reuseaddr")) {
1042                        reuseaddr = 1;
1043                        continue;
1044                }
1045                if (!strcmp(arg, "--user-path")) {
1046                        user_path = "";
1047                        continue;
1048                }
1049                if (!strncmp(arg, "--user-path=", 12)) {
1050                        user_path = arg + 12;
1051                        continue;
1052                }
1053                if (!strncmp(arg, "--pid-file=", 11)) {
1054                        pid_file = arg + 11;
1055                        continue;
1056                }
1057                if (!strcmp(arg, "--detach")) {
1058                        detach = 1;
1059                        log_syslog = 1;
1060                        continue;
1061                }
1062                if (!strncmp(arg, "--user=", 7)) {
1063                        user_name = arg + 7;
1064                        continue;
1065                }
1066                if (!strncmp(arg, "--group=", 8)) {
1067                        group_name = arg + 8;
1068                        continue;
1069                }
1070                if (!strncmp(arg, "--enable=", 9)) {
1071                        enable_service(arg + 9, 1);
1072                        continue;
1073                }
1074                if (!strncmp(arg, "--disable=", 10)) {
1075                        enable_service(arg + 10, 0);
1076                        continue;
1077                }
1078                if (!strncmp(arg, "--allow-override=", 17)) {
1079                        make_service_overridable(arg + 17, 1);
1080                        continue;
1081                }
1082                if (!strncmp(arg, "--forbid-override=", 18)) {
1083                        make_service_overridable(arg + 18, 0);
1084                        continue;
1085                }
1086                if (!strcmp(arg, "--")) {
1087                        ok_paths = &argv[i+1];
1088                        break;
1089                } else if (arg[0] != '-') {
1090                        ok_paths = &argv[i];
1091                        break;
1092                }
1093
1094                usage(daemon_usage);
1095        }
1096
1097        if (inetd_mode && (group_name || user_name))
1098                die("--user and --group are incompatible with --inetd");
1099
1100        if (inetd_mode && (listen_port || listen_addr))
1101                die("--listen= and --port= are incompatible with --inetd");
1102        else if (listen_port == 0)
1103                listen_port = DEFAULT_GIT_PORT;
1104
1105        if (group_name && !user_name)
1106                die("--group supplied without --user");
1107
1108        if (user_name) {
1109                pass = getpwnam(user_name);
1110                if (!pass)
1111                        die("user not found - %s", user_name);
1112
1113                if (!group_name)
1114                        gid = pass->pw_gid;
1115                else {
1116                        group = getgrnam(group_name);
1117                        if (!group)
1118                                die("group not found - %s", group_name);
1119
1120                        gid = group->gr_gid;
1121                }
1122        }
1123
1124        if (log_syslog) {
1125                openlog("git-daemon", 0, LOG_DAEMON);
1126                set_die_routine(daemon_die);
1127        }
1128
1129        if (strict_paths && (!ok_paths || !*ok_paths))
1130                die("option --strict-paths requires a whitelist");
1131
1132        if (inetd_mode) {
1133                struct sockaddr_storage ss;
1134                struct sockaddr *peer = (struct sockaddr *)&ss;
1135                socklen_t slen = sizeof(ss);
1136
1137                freopen("/dev/null", "w", stderr);
1138
1139                if (getpeername(0, peer, &slen))
1140                        peer = NULL;
1141
1142                return execute(peer);
1143        }
1144
1145        if (detach)
1146                daemonize();
1147        else
1148                sanitize_stdfds();
1149
1150        if (pid_file)
1151                store_pid(pid_file);
1152
1153        return serve(listen_addr, listen_port, pass, gid);
1154}