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