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