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