daemon.con commit commit: show interesting ident information in summary (49ff9a7)
   1#include "cache.h"
   2#include "pkt-line.h"
   3#include "exec_cmd.h"
   4#include "run-command.h"
   5#include "strbuf.h"
   6
   7#include <syslog.h>
   8
   9#ifndef HOST_NAME_MAX
  10#define HOST_NAME_MAX 256
  11#endif
  12
  13#ifndef NI_MAXSERV
  14#define NI_MAXSERV 32
  15#endif
  16
  17static int log_syslog;
  18static int verbose;
  19static int reuseaddr;
  20
  21static const char daemon_usage[] =
  22"git daemon [--verbose] [--syslog] [--export-all]\n"
  23"           [--timeout=n] [--init-timeout=n] [--max-connections=n]\n"
  24"           [--strict-paths] [--base-path=path] [--base-path-relaxed]\n"
  25"           [--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;
  43static int base_path_relaxed;
  44
  45/* Flag indicating client sent extra args. */
  46static int saw_extended_args;
  47
  48/* If defined, ~user notation is allowed and the string is inserted
  49 * after ~user/.  E.g. a request to git://host/~alice/frotz would
  50 * go to /home/alice/pub_git/frotz with --user-path=pub_git.
  51 */
  52static const char *user_path;
  53
  54/* Timeout, and initial timeout */
  55static unsigned int timeout;
  56static unsigned int init_timeout;
  57
  58static char *hostname;
  59static char *canon_hostname;
  60static char *ip_address;
  61static char *tcp_port;
  62
  63static void logreport(int priority, const char *err, va_list params)
  64{
  65        if (log_syslog) {
  66                char buf[1024];
  67                vsnprintf(buf, sizeof(buf), err, params);
  68                syslog(priority, "%s", buf);
  69        } else {
  70                /*
  71                 * Since stderr is set to linebuffered mode, the
  72                 * logging of different processes will not overlap
  73                 */
  74                fprintf(stderr, "[%"PRIuMAX"] ", (uintmax_t)getpid());
  75                vfprintf(stderr, err, params);
  76                fputc('\n', stderr);
  77        }
  78}
  79
  80__attribute__((format (printf, 1, 2)))
  81static void logerror(const char *err, ...)
  82{
  83        va_list params;
  84        va_start(params, err);
  85        logreport(LOG_ERR, err, params);
  86        va_end(params);
  87}
  88
  89__attribute__((format (printf, 1, 2)))
  90static void loginfo(const char *err, ...)
  91{
  92        va_list params;
  93        if (!verbose)
  94                return;
  95        va_start(params, err);
  96        logreport(LOG_INFO, err, params);
  97        va_end(params);
  98}
  99
 100static void NORETURN daemon_die(const char *err, va_list params)
 101{
 102        logreport(LOG_ERR, err, params);
 103        exit(1);
 104}
 105
 106static char *path_ok(char *directory)
 107{
 108        static char rpath[PATH_MAX];
 109        static char interp_path[PATH_MAX];
 110        char *path;
 111        char *dir;
 112
 113        dir = directory;
 114
 115        if (daemon_avoid_alias(dir)) {
 116                logerror("'%s': aliased", dir);
 117                return NULL;
 118        }
 119
 120        if (*dir == '~') {
 121                if (!user_path) {
 122                        logerror("'%s': User-path not allowed", dir);
 123                        return NULL;
 124                }
 125                if (*user_path) {
 126                        /* Got either "~alice" or "~alice/foo";
 127                         * rewrite them to "~alice/%s" or
 128                         * "~alice/%s/foo".
 129                         */
 130                        int namlen, restlen = strlen(dir);
 131                        char *slash = strchr(dir, '/');
 132                        if (!slash)
 133                                slash = dir + restlen;
 134                        namlen = slash - dir;
 135                        restlen -= namlen;
 136                        loginfo("userpath <%s>, request <%s>, namlen %d, restlen %d, slash <%s>", user_path, dir, namlen, restlen, slash);
 137                        snprintf(rpath, PATH_MAX, "%.*s/%s%.*s",
 138                                 namlen, dir, user_path, restlen, slash);
 139                        dir = rpath;
 140                }
 141        }
 142        else if (interpolated_path && saw_extended_args) {
 143                struct strbuf expanded_path = STRBUF_INIT;
 144                struct strbuf_expand_dict_entry dict[] = {
 145                        { "H", hostname },
 146                        { "CH", canon_hostname },
 147                        { "IP", ip_address },
 148                        { "P", tcp_port },
 149                        { "D", directory },
 150                        { NULL }
 151                };
 152
 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", timeout_buf, ".", NULL };
 347
 348        snprintf(timeout_buf, sizeof timeout_buf, "--timeout=%u", timeout);
 349        return run_service_command(argv);
 350}
 351
 352static int upload_archive(void)
 353{
 354        static const char *argv[] = { "upload-archive", ".", NULL };
 355        return run_service_command(argv);
 356}
 357
 358static int receive_pack(void)
 359{
 360        static const char *argv[] = { "receive-pack", ".", NULL };
 361        return run_service_command(argv);
 362}
 363
 364static struct daemon_service daemon_service[] = {
 365        { "upload-archive", "uploadarch", upload_archive, 0, 1 },
 366        { "upload-pack", "uploadpack", upload_pack, 1, 1 },
 367        { "receive-pack", "receivepack", receive_pack, 0, 1 },
 368};
 369
 370static void enable_service(const char *name, int ena)
 371{
 372        int i;
 373        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 374                if (!strcmp(daemon_service[i].name, name)) {
 375                        daemon_service[i].enabled = ena;
 376                        return;
 377                }
 378        }
 379        die("No such service %s", name);
 380}
 381
 382static void make_service_overridable(const char *name, int ena)
 383{
 384        int i;
 385        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 386                if (!strcmp(daemon_service[i].name, name)) {
 387                        daemon_service[i].overridable = ena;
 388                        return;
 389                }
 390        }
 391        die("No such service %s", name);
 392}
 393
 394static char *xstrdup_tolower(const char *str)
 395{
 396        char *p, *dup = xstrdup(str);
 397        for (p = dup; *p; p++)
 398                *p = tolower(*p);
 399        return dup;
 400}
 401
 402/*
 403 * Read the host as supplied by the client connection.
 404 */
 405static void parse_host_arg(char *extra_args, int buflen)
 406{
 407        char *val;
 408        int vallen;
 409        char *end = extra_args + buflen;
 410
 411        if (extra_args < end && *extra_args) {
 412                saw_extended_args = 1;
 413                if (strncasecmp("host=", extra_args, 5) == 0) {
 414                        val = extra_args + 5;
 415                        vallen = strlen(val) + 1;
 416                        if (*val) {
 417                                /* Split <host>:<port> at colon. */
 418                                char *host = val;
 419                                char *port = strrchr(host, ':');
 420                                if (port) {
 421                                        *port = 0;
 422                                        port++;
 423                                        free(tcp_port);
 424                                        tcp_port = xstrdup(port);
 425                                }
 426                                free(hostname);
 427                                hostname = xstrdup_tolower(host);
 428                        }
 429
 430                        /* On to the next one */
 431                        extra_args = val + vallen;
 432                }
 433                if (extra_args < end && *extra_args)
 434                        die("Invalid request");
 435        }
 436
 437        /*
 438         * Locate canonical hostname and its IP address.
 439         */
 440        if (hostname) {
 441#ifndef NO_IPV6
 442                struct addrinfo hints;
 443                struct addrinfo *ai;
 444                int gai;
 445                static char addrbuf[HOST_NAME_MAX + 1];
 446
 447                memset(&hints, 0, sizeof(hints));
 448                hints.ai_flags = AI_CANONNAME;
 449
 450                gai = getaddrinfo(hostname, NULL, &hints, &ai);
 451                if (!gai) {
 452                        struct sockaddr_in *sin_addr = (void *)ai->ai_addr;
 453
 454                        inet_ntop(AF_INET, &sin_addr->sin_addr,
 455                                  addrbuf, sizeof(addrbuf));
 456                        free(ip_address);
 457                        ip_address = xstrdup(addrbuf);
 458
 459                        free(canon_hostname);
 460                        canon_hostname = xstrdup(ai->ai_canonname ?
 461                                                 ai->ai_canonname : ip_address);
 462
 463                        freeaddrinfo(ai);
 464                }
 465#else
 466                struct hostent *hent;
 467                struct sockaddr_in sa;
 468                char **ap;
 469                static char addrbuf[HOST_NAME_MAX + 1];
 470
 471                hent = gethostbyname(hostname);
 472
 473                ap = hent->h_addr_list;
 474                memset(&sa, 0, sizeof sa);
 475                sa.sin_family = hent->h_addrtype;
 476                sa.sin_port = htons(0);
 477                memcpy(&sa.sin_addr, *ap, hent->h_length);
 478
 479                inet_ntop(hent->h_addrtype, &sa.sin_addr,
 480                          addrbuf, sizeof(addrbuf));
 481
 482                free(canon_hostname);
 483                canon_hostname = xstrdup(hent->h_name);
 484                free(ip_address);
 485                ip_address = xstrdup(addrbuf);
 486#endif
 487        }
 488}
 489
 490
 491static int execute(struct sockaddr *addr)
 492{
 493        static char line[1000];
 494        int pktlen, len, i;
 495
 496        if (addr) {
 497                char addrbuf[256] = "";
 498                int port = -1;
 499
 500                if (addr->sa_family == AF_INET) {
 501                        struct sockaddr_in *sin_addr = (void *) addr;
 502                        inet_ntop(addr->sa_family, &sin_addr->sin_addr, addrbuf, sizeof(addrbuf));
 503                        port = ntohs(sin_addr->sin_port);
 504#ifndef NO_IPV6
 505                } else if (addr && addr->sa_family == AF_INET6) {
 506                        struct sockaddr_in6 *sin6_addr = (void *) addr;
 507
 508                        char *buf = addrbuf;
 509                        *buf++ = '['; *buf = '\0'; /* stpcpy() is cool */
 510                        inet_ntop(AF_INET6, &sin6_addr->sin6_addr, buf, sizeof(addrbuf) - 1);
 511                        strcat(buf, "]");
 512
 513                        port = ntohs(sin6_addr->sin6_port);
 514#endif
 515                }
 516                loginfo("Connection from %s:%d", addrbuf, port);
 517                setenv("REMOTE_ADDR", addrbuf, 1);
 518        }
 519        else {
 520                unsetenv("REMOTE_ADDR");
 521        }
 522
 523        alarm(init_timeout ? init_timeout : timeout);
 524        pktlen = packet_read_line(0, line, sizeof(line));
 525        alarm(0);
 526
 527        len = strlen(line);
 528        if (pktlen != len)
 529                loginfo("Extended attributes (%d bytes) exist <%.*s>",
 530                        (int) pktlen - len,
 531                        (int) pktlen - len, line + len + 1);
 532        if (len && line[len-1] == '\n') {
 533                line[--len] = 0;
 534                pktlen--;
 535        }
 536
 537        free(hostname);
 538        free(canon_hostname);
 539        free(ip_address);
 540        free(tcp_port);
 541        hostname = canon_hostname = ip_address = tcp_port = NULL;
 542
 543        if (len != pktlen)
 544                parse_host_arg(line + len + 1, pktlen - len - 1);
 545
 546        for (i = 0; i < ARRAY_SIZE(daemon_service); i++) {
 547                struct daemon_service *s = &(daemon_service[i]);
 548                int namelen = strlen(s->name);
 549                if (!prefixcmp(line, "git-") &&
 550                    !strncmp(s->name, line + 4, namelen) &&
 551                    line[namelen + 4] == ' ') {
 552                        /*
 553                         * Note: The directory here is probably context sensitive,
 554                         * and might depend on the actual service being performed.
 555                         */
 556                        return run_service(line + namelen + 5, s);
 557                }
 558        }
 559
 560        logerror("Protocol error: '%s'", line);
 561        return -1;
 562}
 563
 564static int max_connections = 32;
 565
 566static unsigned int live_children;
 567
 568static struct child {
 569        struct child *next;
 570        pid_t pid;
 571        struct sockaddr_storage address;
 572} *firstborn;
 573
 574static void add_child(pid_t pid, struct sockaddr *addr, int addrlen)
 575{
 576        struct child *newborn, **cradle;
 577
 578        /*
 579         * This must be xcalloc() -- we'll compare the whole sockaddr_storage
 580         * but individual address may be shorter.
 581         */
 582        newborn = xcalloc(1, sizeof(*newborn));
 583        live_children++;
 584        newborn->pid = pid;
 585        memcpy(&newborn->address, addr, addrlen);
 586        for (cradle = &firstborn; *cradle; cradle = &(*cradle)->next)
 587                if (!memcmp(&(*cradle)->address, &newborn->address,
 588                            sizeof(newborn->address)))
 589                        break;
 590        newborn->next = *cradle;
 591        *cradle = newborn;
 592}
 593
 594static void remove_child(pid_t pid)
 595{
 596        struct child **cradle, *blanket;
 597
 598        for (cradle = &firstborn; (blanket = *cradle); cradle = &blanket->next)
 599                if (blanket->pid == pid) {
 600                        *cradle = blanket->next;
 601                        live_children--;
 602                        free(blanket);
 603                        break;
 604                }
 605}
 606
 607/*
 608 * This gets called if the number of connections grows
 609 * past "max_connections".
 610 *
 611 * We kill the newest connection from a duplicate IP.
 612 */
 613static void kill_some_child(void)
 614{
 615        const struct child *blanket, *next;
 616
 617        if (!(blanket = firstborn))
 618                return;
 619
 620        for (; (next = blanket->next); blanket = next)
 621                if (!memcmp(&blanket->address, &next->address,
 622                            sizeof(next->address))) {
 623                        kill(blanket->pid, SIGTERM);
 624                        break;
 625                }
 626}
 627
 628static void check_dead_children(void)
 629{
 630        int status;
 631        pid_t pid;
 632
 633        while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
 634                const char *dead = "";
 635                remove_child(pid);
 636                if (!WIFEXITED(status) || (WEXITSTATUS(status) > 0))
 637                        dead = " (with error)";
 638                loginfo("[%"PRIuMAX"] Disconnected%s", (uintmax_t)pid, dead);
 639        }
 640}
 641
 642static void handle(int incoming, struct sockaddr *addr, int addrlen)
 643{
 644        pid_t pid;
 645
 646        if (max_connections && live_children >= max_connections) {
 647                kill_some_child();
 648                sleep(1);  /* give it some time to die */
 649                check_dead_children();
 650                if (live_children >= max_connections) {
 651                        close(incoming);
 652                        logerror("Too many children, dropping connection");
 653                        return;
 654                }
 655        }
 656
 657        if ((pid = fork())) {
 658                close(incoming);
 659                if (pid < 0) {
 660                        logerror("Couldn't fork %s", strerror(errno));
 661                        return;
 662                }
 663
 664                add_child(pid, addr, addrlen);
 665                return;
 666        }
 667
 668        dup2(incoming, 0);
 669        dup2(incoming, 1);
 670        close(incoming);
 671
 672        exit(execute(addr));
 673}
 674
 675static void child_handler(int signo)
 676{
 677        /*
 678         * Otherwise empty handler because systemcalls will get interrupted
 679         * upon signal receipt
 680         * SysV needs the handler to be rearmed
 681         */
 682        signal(SIGCHLD, child_handler);
 683}
 684
 685static int set_reuse_addr(int sockfd)
 686{
 687        int on = 1;
 688
 689        if (!reuseaddr)
 690                return 0;
 691        return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
 692                          &on, sizeof(on));
 693}
 694
 695#ifndef NO_IPV6
 696
 697static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
 698{
 699        int socknum = 0, *socklist = NULL;
 700        int maxfd = -1;
 701        char pbuf[NI_MAXSERV];
 702        struct addrinfo hints, *ai0, *ai;
 703        int gai;
 704        long flags;
 705
 706        sprintf(pbuf, "%d", listen_port);
 707        memset(&hints, 0, sizeof(hints));
 708        hints.ai_family = AF_UNSPEC;
 709        hints.ai_socktype = SOCK_STREAM;
 710        hints.ai_protocol = IPPROTO_TCP;
 711        hints.ai_flags = AI_PASSIVE;
 712
 713        gai = getaddrinfo(listen_addr, pbuf, &hints, &ai0);
 714        if (gai)
 715                die("getaddrinfo() failed: %s", gai_strerror(gai));
 716
 717        for (ai = ai0; ai; ai = ai->ai_next) {
 718                int sockfd;
 719
 720                sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
 721                if (sockfd < 0)
 722                        continue;
 723                if (sockfd >= FD_SETSIZE) {
 724                        logerror("Socket descriptor too large");
 725                        close(sockfd);
 726                        continue;
 727                }
 728
 729#ifdef IPV6_V6ONLY
 730                if (ai->ai_family == AF_INET6) {
 731                        int on = 1;
 732                        setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
 733                                   &on, sizeof(on));
 734                        /* Note: error is not fatal */
 735                }
 736#endif
 737
 738                if (set_reuse_addr(sockfd)) {
 739                        close(sockfd);
 740                        continue;
 741                }
 742
 743                if (bind(sockfd, ai->ai_addr, ai->ai_addrlen) < 0) {
 744                        close(sockfd);
 745                        continue;       /* not fatal */
 746                }
 747                if (listen(sockfd, 5) < 0) {
 748                        close(sockfd);
 749                        continue;       /* not fatal */
 750                }
 751
 752                flags = fcntl(sockfd, F_GETFD, 0);
 753                if (flags >= 0)
 754                        fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
 755
 756                socklist = xrealloc(socklist, sizeof(int) * (socknum + 1));
 757                socklist[socknum++] = sockfd;
 758
 759                if (maxfd < sockfd)
 760                        maxfd = sockfd;
 761        }
 762
 763        freeaddrinfo(ai0);
 764
 765        *socklist_p = socklist;
 766        return socknum;
 767}
 768
 769#else /* NO_IPV6 */
 770
 771static int socksetup(char *listen_addr, int listen_port, int **socklist_p)
 772{
 773        struct sockaddr_in sin;
 774        int sockfd;
 775        long flags;
 776
 777        memset(&sin, 0, sizeof sin);
 778        sin.sin_family = AF_INET;
 779        sin.sin_port = htons(listen_port);
 780
 781        if (listen_addr) {
 782                /* Well, host better be an IP address here. */
 783                if (inet_pton(AF_INET, listen_addr, &sin.sin_addr.s_addr) <= 0)
 784                        return 0;
 785        } else {
 786                sin.sin_addr.s_addr = htonl(INADDR_ANY);
 787        }
 788
 789        sockfd = socket(AF_INET, SOCK_STREAM, 0);
 790        if (sockfd < 0)
 791                return 0;
 792
 793        if (set_reuse_addr(sockfd)) {
 794                close(sockfd);
 795                return 0;
 796        }
 797
 798        if ( bind(sockfd, (struct sockaddr *)&sin, sizeof sin) < 0 ) {
 799                close(sockfd);
 800                return 0;
 801        }
 802
 803        if (listen(sockfd, 5) < 0) {
 804                close(sockfd);
 805                return 0;
 806        }
 807
 808        flags = fcntl(sockfd, F_GETFD, 0);
 809        if (flags >= 0)
 810                fcntl(sockfd, F_SETFD, flags | FD_CLOEXEC);
 811
 812        *socklist_p = xmalloc(sizeof(int));
 813        **socklist_p = sockfd;
 814        return 1;
 815}
 816
 817#endif
 818
 819static int service_loop(int socknum, int *socklist)
 820{
 821        struct pollfd *pfd;
 822        int i;
 823
 824        pfd = xcalloc(socknum, sizeof(struct pollfd));
 825
 826        for (i = 0; i < socknum; i++) {
 827                pfd[i].fd = socklist[i];
 828                pfd[i].events = POLLIN;
 829        }
 830
 831        signal(SIGCHLD, child_handler);
 832
 833        for (;;) {
 834                int i;
 835
 836                check_dead_children();
 837
 838                if (poll(pfd, socknum, -1) < 0) {
 839                        if (errno != EINTR) {
 840                                logerror("Poll failed, resuming: %s",
 841                                      strerror(errno));
 842                                sleep(1);
 843                        }
 844                        continue;
 845                }
 846
 847                for (i = 0; i < socknum; i++) {
 848                        if (pfd[i].revents & POLLIN) {
 849                                struct sockaddr_storage ss;
 850                                unsigned int sslen = sizeof(ss);
 851                                int incoming = accept(pfd[i].fd, (struct sockaddr *)&ss, &sslen);
 852                                if (incoming < 0) {
 853                                        switch (errno) {
 854                                        case EAGAIN:
 855                                        case EINTR:
 856                                        case ECONNABORTED:
 857                                                continue;
 858                                        default:
 859                                                die_errno("accept returned");
 860                                        }
 861                                }
 862                                handle(incoming, (struct sockaddr *)&ss, sslen);
 863                        }
 864                }
 865        }
 866}
 867
 868/* if any standard file descriptor is missing open it to /dev/null */
 869static void sanitize_stdfds(void)
 870{
 871        int fd = open("/dev/null", O_RDWR, 0);
 872        while (fd != -1 && fd < 2)
 873                fd = dup(fd);
 874        if (fd == -1)
 875                die_errno("open /dev/null or dup failed");
 876        if (fd > 2)
 877                close(fd);
 878}
 879
 880static void daemonize(void)
 881{
 882        switch (fork()) {
 883                case 0:
 884                        break;
 885                case -1:
 886                        die_errno("fork failed");
 887                default:
 888                        exit(0);
 889        }
 890        if (setsid() == -1)
 891                die_errno("setsid failed");
 892        close(0);
 893        close(1);
 894        close(2);
 895        sanitize_stdfds();
 896}
 897
 898static void store_pid(const char *path)
 899{
 900        FILE *f = fopen(path, "w");
 901        if (!f)
 902                die_errno("cannot open pid file '%s'", path);
 903        if (fprintf(f, "%"PRIuMAX"\n", (uintmax_t) getpid()) < 0 || fclose(f) != 0)
 904                die_errno("failed to write pid file '%s'", path);
 905}
 906
 907static int serve(char *listen_addr, int listen_port, struct passwd *pass, gid_t gid)
 908{
 909        int socknum, *socklist;
 910
 911        socknum = socksetup(listen_addr, listen_port, &socklist);
 912        if (socknum == 0)
 913                die("unable to allocate any listen sockets on host %s port %u",
 914                    listen_addr, listen_port);
 915
 916        if (pass && gid &&
 917            (initgroups(pass->pw_name, gid) || setgid (gid) ||
 918             setuid(pass->pw_uid)))
 919                die("cannot drop privileges");
 920
 921        return service_loop(socknum, socklist);
 922}
 923
 924int main(int argc, char **argv)
 925{
 926        int listen_port = 0;
 927        char *listen_addr = NULL;
 928        int inetd_mode = 0;
 929        const char *pid_file = NULL, *user_name = NULL, *group_name = NULL;
 930        int detach = 0;
 931        struct passwd *pass = NULL;
 932        struct group *group;
 933        gid_t gid = 0;
 934        int i;
 935
 936        git_extract_argv0_path(argv[0]);
 937
 938        for (i = 1; i < argc; i++) {
 939                char *arg = argv[i];
 940
 941                if (!prefixcmp(arg, "--listen=")) {
 942                        listen_addr = xstrdup_tolower(arg + 9);
 943                        continue;
 944                }
 945                if (!prefixcmp(arg, "--port=")) {
 946                        char *end;
 947                        unsigned long n;
 948                        n = strtoul(arg+7, &end, 0);
 949                        if (arg[7] && !*end) {
 950                                listen_port = n;
 951                                continue;
 952                        }
 953                }
 954                if (!strcmp(arg, "--inetd")) {
 955                        inetd_mode = 1;
 956                        log_syslog = 1;
 957                        continue;
 958                }
 959                if (!strcmp(arg, "--verbose")) {
 960                        verbose = 1;
 961                        continue;
 962                }
 963                if (!strcmp(arg, "--syslog")) {
 964                        log_syslog = 1;
 965                        continue;
 966                }
 967                if (!strcmp(arg, "--export-all")) {
 968                        export_all_trees = 1;
 969                        continue;
 970                }
 971                if (!prefixcmp(arg, "--timeout=")) {
 972                        timeout = atoi(arg+10);
 973                        continue;
 974                }
 975                if (!prefixcmp(arg, "--init-timeout=")) {
 976                        init_timeout = atoi(arg+15);
 977                        continue;
 978                }
 979                if (!prefixcmp(arg, "--max-connections=")) {
 980                        max_connections = atoi(arg+18);
 981                        if (max_connections < 0)
 982                                max_connections = 0;            /* unlimited */
 983                        continue;
 984                }
 985                if (!strcmp(arg, "--strict-paths")) {
 986                        strict_paths = 1;
 987                        continue;
 988                }
 989                if (!prefixcmp(arg, "--base-path=")) {
 990                        base_path = arg+12;
 991                        continue;
 992                }
 993                if (!strcmp(arg, "--base-path-relaxed")) {
 994                        base_path_relaxed = 1;
 995                        continue;
 996                }
 997                if (!prefixcmp(arg, "--interpolated-path=")) {
 998                        interpolated_path = arg+20;
 999                        continue;
1000                }
1001                if (!strcmp(arg, "--reuseaddr")) {
1002                        reuseaddr = 1;
1003                        continue;
1004                }
1005                if (!strcmp(arg, "--user-path")) {
1006                        user_path = "";
1007                        continue;
1008                }
1009                if (!prefixcmp(arg, "--user-path=")) {
1010                        user_path = arg + 12;
1011                        continue;
1012                }
1013                if (!prefixcmp(arg, "--pid-file=")) {
1014                        pid_file = arg + 11;
1015                        continue;
1016                }
1017                if (!strcmp(arg, "--detach")) {
1018                        detach = 1;
1019                        log_syslog = 1;
1020                        continue;
1021                }
1022                if (!prefixcmp(arg, "--user=")) {
1023                        user_name = arg + 7;
1024                        continue;
1025                }
1026                if (!prefixcmp(arg, "--group=")) {
1027                        group_name = arg + 8;
1028                        continue;
1029                }
1030                if (!prefixcmp(arg, "--enable=")) {
1031                        enable_service(arg + 9, 1);
1032                        continue;
1033                }
1034                if (!prefixcmp(arg, "--disable=")) {
1035                        enable_service(arg + 10, 0);
1036                        continue;
1037                }
1038                if (!prefixcmp(arg, "--allow-override=")) {
1039                        make_service_overridable(arg + 17, 1);
1040                        continue;
1041                }
1042                if (!prefixcmp(arg, "--forbid-override=")) {
1043                        make_service_overridable(arg + 18, 0);
1044                        continue;
1045                }
1046                if (!strcmp(arg, "--")) {
1047                        ok_paths = &argv[i+1];
1048                        break;
1049                } else if (arg[0] != '-') {
1050                        ok_paths = &argv[i];
1051                        break;
1052                }
1053
1054                usage(daemon_usage);
1055        }
1056
1057        if (log_syslog) {
1058                openlog("git-daemon", LOG_PID, LOG_DAEMON);
1059                set_die_routine(daemon_die);
1060        } else
1061                /* avoid splitting a message in the middle */
1062                setvbuf(stderr, NULL, _IOLBF, 0);
1063
1064        if (inetd_mode && (group_name || user_name))
1065                die("--user and --group are incompatible with --inetd");
1066
1067        if (inetd_mode && (listen_port || listen_addr))
1068                die("--listen= and --port= are incompatible with --inetd");
1069        else if (listen_port == 0)
1070                listen_port = DEFAULT_GIT_PORT;
1071
1072        if (group_name && !user_name)
1073                die("--group supplied without --user");
1074
1075        if (user_name) {
1076                pass = getpwnam(user_name);
1077                if (!pass)
1078                        die("user not found - %s", user_name);
1079
1080                if (!group_name)
1081                        gid = pass->pw_gid;
1082                else {
1083                        group = getgrnam(group_name);
1084                        if (!group)
1085                                die("group not found - %s", group_name);
1086
1087                        gid = group->gr_gid;
1088                }
1089        }
1090
1091        if (strict_paths && (!ok_paths || !*ok_paths))
1092                die("option --strict-paths requires a whitelist");
1093
1094        if (base_path && !is_directory(base_path))
1095                die("base-path '%s' does not exist or is not a directory",
1096                    base_path);
1097
1098        if (inetd_mode) {
1099                struct sockaddr_storage ss;
1100                struct sockaddr *peer = (struct sockaddr *)&ss;
1101                socklen_t slen = sizeof(ss);
1102
1103                if (!freopen("/dev/null", "w", stderr))
1104                        die_errno("failed to redirect stderr to /dev/null");
1105
1106                if (getpeername(0, peer, &slen))
1107                        peer = NULL;
1108
1109                return execute(peer);
1110        }
1111
1112        if (detach) {
1113                daemonize();
1114                loginfo("Ready to rumble");
1115        }
1116        else
1117                sanitize_stdfds();
1118
1119        if (pid_file)
1120                store_pid(pid_file);
1121
1122        return serve(listen_addr, listen_port, pass, gid);
1123}