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