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