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