builtin / receive-pack.con commit Merge branch 'jn/parse-config-slot' (b946576)
   1#include "builtin.h"
   2#include "lockfile.h"
   3#include "pack.h"
   4#include "refs.h"
   5#include "pkt-line.h"
   6#include "sideband.h"
   7#include "run-command.h"
   8#include "exec_cmd.h"
   9#include "commit.h"
  10#include "object.h"
  11#include "remote.h"
  12#include "connect.h"
  13#include "transport.h"
  14#include "string-list.h"
  15#include "sha1-array.h"
  16#include "connected.h"
  17#include "argv-array.h"
  18#include "version.h"
  19#include "tag.h"
  20#include "gpg-interface.h"
  21#include "sigchain.h"
  22
  23static const char receive_pack_usage[] = "git receive-pack <git-dir>";
  24
  25enum deny_action {
  26        DENY_UNCONFIGURED,
  27        DENY_IGNORE,
  28        DENY_WARN,
  29        DENY_REFUSE
  30};
  31
  32static int deny_deletes;
  33static int deny_non_fast_forwards;
  34static enum deny_action deny_current_branch = DENY_UNCONFIGURED;
  35static enum deny_action deny_delete_current = DENY_UNCONFIGURED;
  36static int receive_fsck_objects = -1;
  37static int transfer_fsck_objects = -1;
  38static int receive_unpack_limit = -1;
  39static int transfer_unpack_limit = -1;
  40static int unpack_limit = 100;
  41static int report_status;
  42static int use_sideband;
  43static int quiet;
  44static int prefer_ofs_delta = 1;
  45static int auto_update_server_info;
  46static int auto_gc = 1;
  47static int fix_thin = 1;
  48static int stateless_rpc;
  49static const char *service_dir;
  50static const char *head_name;
  51static void *head_name_to_free;
  52static int sent_capabilities;
  53static int shallow_update;
  54static const char *alt_shallow_file;
  55static struct strbuf push_cert = STRBUF_INIT;
  56static unsigned char push_cert_sha1[20];
  57static struct signature_check sigcheck;
  58static const char *push_cert_nonce;
  59static const char *cert_nonce_seed;
  60
  61static const char *NONCE_UNSOLICITED = "UNSOLICITED";
  62static const char *NONCE_BAD = "BAD";
  63static const char *NONCE_MISSING = "MISSING";
  64static const char *NONCE_OK = "OK";
  65static const char *NONCE_SLOP = "SLOP";
  66static const char *nonce_status;
  67static long nonce_stamp_slop;
  68static unsigned long nonce_stamp_slop_limit;
  69
  70static enum deny_action parse_deny_action(const char *var, const char *value)
  71{
  72        if (value) {
  73                if (!strcasecmp(value, "ignore"))
  74                        return DENY_IGNORE;
  75                if (!strcasecmp(value, "warn"))
  76                        return DENY_WARN;
  77                if (!strcasecmp(value, "refuse"))
  78                        return DENY_REFUSE;
  79        }
  80        if (git_config_bool(var, value))
  81                return DENY_REFUSE;
  82        return DENY_IGNORE;
  83}
  84
  85static int receive_pack_config(const char *var, const char *value, void *cb)
  86{
  87        int status = parse_hide_refs_config(var, value, "receive");
  88
  89        if (status)
  90                return status;
  91
  92        if (strcmp(var, "receive.denydeletes") == 0) {
  93                deny_deletes = git_config_bool(var, value);
  94                return 0;
  95        }
  96
  97        if (strcmp(var, "receive.denynonfastforwards") == 0) {
  98                deny_non_fast_forwards = git_config_bool(var, value);
  99                return 0;
 100        }
 101
 102        if (strcmp(var, "receive.unpacklimit") == 0) {
 103                receive_unpack_limit = git_config_int(var, value);
 104                return 0;
 105        }
 106
 107        if (strcmp(var, "transfer.unpacklimit") == 0) {
 108                transfer_unpack_limit = git_config_int(var, value);
 109                return 0;
 110        }
 111
 112        if (strcmp(var, "receive.fsckobjects") == 0) {
 113                receive_fsck_objects = git_config_bool(var, value);
 114                return 0;
 115        }
 116
 117        if (strcmp(var, "transfer.fsckobjects") == 0) {
 118                transfer_fsck_objects = git_config_bool(var, value);
 119                return 0;
 120        }
 121
 122        if (!strcmp(var, "receive.denycurrentbranch")) {
 123                deny_current_branch = parse_deny_action(var, value);
 124                return 0;
 125        }
 126
 127        if (strcmp(var, "receive.denydeletecurrent") == 0) {
 128                deny_delete_current = parse_deny_action(var, value);
 129                return 0;
 130        }
 131
 132        if (strcmp(var, "repack.usedeltabaseoffset") == 0) {
 133                prefer_ofs_delta = git_config_bool(var, value);
 134                return 0;
 135        }
 136
 137        if (strcmp(var, "receive.updateserverinfo") == 0) {
 138                auto_update_server_info = git_config_bool(var, value);
 139                return 0;
 140        }
 141
 142        if (strcmp(var, "receive.autogc") == 0) {
 143                auto_gc = git_config_bool(var, value);
 144                return 0;
 145        }
 146
 147        if (strcmp(var, "receive.shallowupdate") == 0) {
 148                shallow_update = git_config_bool(var, value);
 149                return 0;
 150        }
 151
 152        if (strcmp(var, "receive.certnonceseed") == 0)
 153                return git_config_string(&cert_nonce_seed, var, value);
 154
 155        if (strcmp(var, "receive.certnonceslop") == 0) {
 156                nonce_stamp_slop_limit = git_config_ulong(var, value);
 157                return 0;
 158        }
 159
 160        return git_default_config(var, value, cb);
 161}
 162
 163static void show_ref(const char *path, const unsigned char *sha1)
 164{
 165        if (ref_is_hidden(path))
 166                return;
 167
 168        if (sent_capabilities) {
 169                packet_write(1, "%s %s\n", sha1_to_hex(sha1), path);
 170        } else {
 171                struct strbuf cap = STRBUF_INIT;
 172
 173                strbuf_addstr(&cap,
 174                              "report-status delete-refs side-band-64k quiet");
 175                if (prefer_ofs_delta)
 176                        strbuf_addstr(&cap, " ofs-delta");
 177                if (push_cert_nonce)
 178                        strbuf_addf(&cap, " push-cert=%s", push_cert_nonce);
 179                strbuf_addf(&cap, " agent=%s", git_user_agent_sanitized());
 180                packet_write(1, "%s %s%c%s\n",
 181                             sha1_to_hex(sha1), path, 0, cap.buf);
 182                strbuf_release(&cap);
 183                sent_capabilities = 1;
 184        }
 185}
 186
 187static int show_ref_cb(const char *path, const unsigned char *sha1, int flag, void *unused)
 188{
 189        path = strip_namespace(path);
 190        /*
 191         * Advertise refs outside our current namespace as ".have"
 192         * refs, so that the client can use them to minimize data
 193         * transfer but will otherwise ignore them. This happens to
 194         * cover ".have" that are thrown in by add_one_alternate_ref()
 195         * to mark histories that are complete in our alternates as
 196         * well.
 197         */
 198        if (!path)
 199                path = ".have";
 200        show_ref(path, sha1);
 201        return 0;
 202}
 203
 204static void show_one_alternate_sha1(const unsigned char sha1[20], void *unused)
 205{
 206        show_ref(".have", sha1);
 207}
 208
 209static void collect_one_alternate_ref(const struct ref *ref, void *data)
 210{
 211        struct sha1_array *sa = data;
 212        sha1_array_append(sa, ref->old_sha1);
 213}
 214
 215static void write_head_info(void)
 216{
 217        struct sha1_array sa = SHA1_ARRAY_INIT;
 218        for_each_alternate_ref(collect_one_alternate_ref, &sa);
 219        sha1_array_for_each_unique(&sa, show_one_alternate_sha1, NULL);
 220        sha1_array_clear(&sa);
 221        for_each_ref(show_ref_cb, NULL);
 222        if (!sent_capabilities)
 223                show_ref("capabilities^{}", null_sha1);
 224
 225        advertise_shallow_grafts(1);
 226
 227        /* EOF */
 228        packet_flush(1);
 229}
 230
 231struct command {
 232        struct command *next;
 233        const char *error_string;
 234        unsigned int skip_update:1,
 235                     did_not_exist:1;
 236        int index;
 237        unsigned char old_sha1[20];
 238        unsigned char new_sha1[20];
 239        char ref_name[FLEX_ARRAY]; /* more */
 240};
 241
 242static void rp_error(const char *err, ...) __attribute__((format (printf, 1, 2)));
 243static void rp_warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
 244
 245static void report_message(const char *prefix, const char *err, va_list params)
 246{
 247        int sz = strlen(prefix);
 248        char msg[4096];
 249
 250        strncpy(msg, prefix, sz);
 251        sz += vsnprintf(msg + sz, sizeof(msg) - sz, err, params);
 252        if (sz > (sizeof(msg) - 1))
 253                sz = sizeof(msg) - 1;
 254        msg[sz++] = '\n';
 255
 256        if (use_sideband)
 257                send_sideband(1, 2, msg, sz, use_sideband);
 258        else
 259                xwrite(2, msg, sz);
 260}
 261
 262static void rp_warning(const char *err, ...)
 263{
 264        va_list params;
 265        va_start(params, err);
 266        report_message("warning: ", err, params);
 267        va_end(params);
 268}
 269
 270static void rp_error(const char *err, ...)
 271{
 272        va_list params;
 273        va_start(params, err);
 274        report_message("error: ", err, params);
 275        va_end(params);
 276}
 277
 278static int copy_to_sideband(int in, int out, void *arg)
 279{
 280        char data[128];
 281        while (1) {
 282                ssize_t sz = xread(in, data, sizeof(data));
 283                if (sz <= 0)
 284                        break;
 285                send_sideband(1, 2, data, sz, use_sideband);
 286        }
 287        close(in);
 288        return 0;
 289}
 290
 291#define HMAC_BLOCK_SIZE 64
 292
 293static void hmac_sha1(unsigned char *out,
 294                      const char *key_in, size_t key_len,
 295                      const char *text, size_t text_len)
 296{
 297        unsigned char key[HMAC_BLOCK_SIZE];
 298        unsigned char k_ipad[HMAC_BLOCK_SIZE];
 299        unsigned char k_opad[HMAC_BLOCK_SIZE];
 300        int i;
 301        git_SHA_CTX ctx;
 302
 303        /* RFC 2104 2. (1) */
 304        memset(key, '\0', HMAC_BLOCK_SIZE);
 305        if (HMAC_BLOCK_SIZE < key_len) {
 306                git_SHA1_Init(&ctx);
 307                git_SHA1_Update(&ctx, key_in, key_len);
 308                git_SHA1_Final(key, &ctx);
 309        } else {
 310                memcpy(key, key_in, key_len);
 311        }
 312
 313        /* RFC 2104 2. (2) & (5) */
 314        for (i = 0; i < sizeof(key); i++) {
 315                k_ipad[i] = key[i] ^ 0x36;
 316                k_opad[i] = key[i] ^ 0x5c;
 317        }
 318
 319        /* RFC 2104 2. (3) & (4) */
 320        git_SHA1_Init(&ctx);
 321        git_SHA1_Update(&ctx, k_ipad, sizeof(k_ipad));
 322        git_SHA1_Update(&ctx, text, text_len);
 323        git_SHA1_Final(out, &ctx);
 324
 325        /* RFC 2104 2. (6) & (7) */
 326        git_SHA1_Init(&ctx);
 327        git_SHA1_Update(&ctx, k_opad, sizeof(k_opad));
 328        git_SHA1_Update(&ctx, out, 20);
 329        git_SHA1_Final(out, &ctx);
 330}
 331
 332static char *prepare_push_cert_nonce(const char *path, unsigned long stamp)
 333{
 334        struct strbuf buf = STRBUF_INIT;
 335        unsigned char sha1[20];
 336
 337        strbuf_addf(&buf, "%s:%lu", path, stamp);
 338        hmac_sha1(sha1, buf.buf, buf.len, cert_nonce_seed, strlen(cert_nonce_seed));;
 339        strbuf_release(&buf);
 340
 341        /* RFC 2104 5. HMAC-SHA1-80 */
 342        strbuf_addf(&buf, "%lu-%.*s", stamp, 20, sha1_to_hex(sha1));
 343        return strbuf_detach(&buf, NULL);
 344}
 345
 346/*
 347 * NEEDSWORK: reuse find_commit_header() from jk/commit-author-parsing
 348 * after dropping "_commit" from its name and possibly moving it out
 349 * of commit.c
 350 */
 351static char *find_header(const char *msg, size_t len, const char *key)
 352{
 353        int key_len = strlen(key);
 354        const char *line = msg;
 355
 356        while (line && line < msg + len) {
 357                const char *eol = strchrnul(line, '\n');
 358
 359                if ((msg + len <= eol) || line == eol)
 360                        return NULL;
 361                if (line + key_len < eol &&
 362                    !memcmp(line, key, key_len) && line[key_len] == ' ') {
 363                        int offset = key_len + 1;
 364                        return xmemdupz(line + offset, (eol - line) - offset);
 365                }
 366                line = *eol ? eol + 1 : NULL;
 367        }
 368        return NULL;
 369}
 370
 371static const char *check_nonce(const char *buf, size_t len)
 372{
 373        char *nonce = find_header(buf, len, "nonce");
 374        unsigned long stamp, ostamp;
 375        char *bohmac, *expect = NULL;
 376        const char *retval = NONCE_BAD;
 377
 378        if (!nonce) {
 379                retval = NONCE_MISSING;
 380                goto leave;
 381        } else if (!push_cert_nonce) {
 382                retval = NONCE_UNSOLICITED;
 383                goto leave;
 384        } else if (!strcmp(push_cert_nonce, nonce)) {
 385                retval = NONCE_OK;
 386                goto leave;
 387        }
 388
 389        if (!stateless_rpc) {
 390                /* returned nonce MUST match what we gave out earlier */
 391                retval = NONCE_BAD;
 392                goto leave;
 393        }
 394
 395        /*
 396         * In stateless mode, we may be receiving a nonce issued by
 397         * another instance of the server that serving the same
 398         * repository, and the timestamps may not match, but the
 399         * nonce-seed and dir should match, so we can recompute and
 400         * report the time slop.
 401         *
 402         * In addition, when a nonce issued by another instance has
 403         * timestamp within receive.certnonceslop seconds, we pretend
 404         * as if we issued that nonce when reporting to the hook.
 405         */
 406
 407        /* nonce is concat(<seconds-since-epoch>, "-", <hmac>) */
 408        if (*nonce <= '0' || '9' < *nonce) {
 409                retval = NONCE_BAD;
 410                goto leave;
 411        }
 412        stamp = strtoul(nonce, &bohmac, 10);
 413        if (bohmac == nonce || bohmac[0] != '-') {
 414                retval = NONCE_BAD;
 415                goto leave;
 416        }
 417
 418        expect = prepare_push_cert_nonce(service_dir, stamp);
 419        if (strcmp(expect, nonce)) {
 420                /* Not what we would have signed earlier */
 421                retval = NONCE_BAD;
 422                goto leave;
 423        }
 424
 425        /*
 426         * By how many seconds is this nonce stale?  Negative value
 427         * would mean it was issued by another server with its clock
 428         * skewed in the future.
 429         */
 430        ostamp = strtoul(push_cert_nonce, NULL, 10);
 431        nonce_stamp_slop = (long)ostamp - (long)stamp;
 432
 433        if (nonce_stamp_slop_limit &&
 434            abs(nonce_stamp_slop) <= nonce_stamp_slop_limit) {
 435                /*
 436                 * Pretend as if the received nonce (which passes the
 437                 * HMAC check, so it is not a forged by third-party)
 438                 * is what we issued.
 439                 */
 440                free((void *)push_cert_nonce);
 441                push_cert_nonce = xstrdup(nonce);
 442                retval = NONCE_OK;
 443        } else {
 444                retval = NONCE_SLOP;
 445        }
 446
 447leave:
 448        free(nonce);
 449        free(expect);
 450        return retval;
 451}
 452
 453static void prepare_push_cert_sha1(struct child_process *proc)
 454{
 455        static int already_done;
 456        struct argv_array env = ARGV_ARRAY_INIT;
 457
 458        if (!push_cert.len)
 459                return;
 460
 461        if (!already_done) {
 462                struct strbuf gpg_output = STRBUF_INIT;
 463                struct strbuf gpg_status = STRBUF_INIT;
 464                int bogs /* beginning_of_gpg_sig */;
 465
 466                already_done = 1;
 467                if (write_sha1_file(push_cert.buf, push_cert.len, "blob", push_cert_sha1))
 468                        hashclr(push_cert_sha1);
 469
 470                memset(&sigcheck, '\0', sizeof(sigcheck));
 471                sigcheck.result = 'N';
 472
 473                bogs = parse_signature(push_cert.buf, push_cert.len);
 474                if (verify_signed_buffer(push_cert.buf, bogs,
 475                                         push_cert.buf + bogs, push_cert.len - bogs,
 476                                         &gpg_output, &gpg_status) < 0) {
 477                        ; /* error running gpg */
 478                } else {
 479                        sigcheck.payload = push_cert.buf;
 480                        sigcheck.gpg_output = gpg_output.buf;
 481                        sigcheck.gpg_status = gpg_status.buf;
 482                        parse_gpg_output(&sigcheck);
 483                }
 484
 485                strbuf_release(&gpg_output);
 486                strbuf_release(&gpg_status);
 487                nonce_status = check_nonce(push_cert.buf, bogs);
 488        }
 489        if (!is_null_sha1(push_cert_sha1)) {
 490                argv_array_pushf(&env, "GIT_PUSH_CERT=%s", sha1_to_hex(push_cert_sha1));
 491                argv_array_pushf(&env, "GIT_PUSH_CERT_SIGNER=%s",
 492                                 sigcheck.signer ? sigcheck.signer : "");
 493                argv_array_pushf(&env, "GIT_PUSH_CERT_KEY=%s",
 494                                 sigcheck.key ? sigcheck.key : "");
 495                argv_array_pushf(&env, "GIT_PUSH_CERT_STATUS=%c", sigcheck.result);
 496                if (push_cert_nonce) {
 497                        argv_array_pushf(&env, "GIT_PUSH_CERT_NONCE=%s", push_cert_nonce);
 498                        argv_array_pushf(&env, "GIT_PUSH_CERT_NONCE_STATUS=%s", nonce_status);
 499                        if (nonce_status == NONCE_SLOP)
 500                                argv_array_pushf(&env, "GIT_PUSH_CERT_NONCE_SLOP=%ld",
 501                                                 nonce_stamp_slop);
 502                }
 503                proc->env = env.argv;
 504        }
 505}
 506
 507typedef int (*feed_fn)(void *, const char **, size_t *);
 508static int run_and_feed_hook(const char *hook_name, feed_fn feed, void *feed_state)
 509{
 510        struct child_process proc = CHILD_PROCESS_INIT;
 511        struct async muxer;
 512        const char *argv[2];
 513        int code;
 514
 515        argv[0] = find_hook(hook_name);
 516        if (!argv[0])
 517                return 0;
 518
 519        argv[1] = NULL;
 520
 521        proc.argv = argv;
 522        proc.in = -1;
 523        proc.stdout_to_stderr = 1;
 524
 525        prepare_push_cert_sha1(&proc);
 526
 527        if (use_sideband) {
 528                memset(&muxer, 0, sizeof(muxer));
 529                muxer.proc = copy_to_sideband;
 530                muxer.in = -1;
 531                code = start_async(&muxer);
 532                if (code)
 533                        return code;
 534                proc.err = muxer.in;
 535        }
 536
 537        code = start_command(&proc);
 538        if (code) {
 539                if (use_sideband)
 540                        finish_async(&muxer);
 541                return code;
 542        }
 543
 544        sigchain_push(SIGPIPE, SIG_IGN);
 545
 546        while (1) {
 547                const char *buf;
 548                size_t n;
 549                if (feed(feed_state, &buf, &n))
 550                        break;
 551                if (write_in_full(proc.in, buf, n) != n)
 552                        break;
 553        }
 554        close(proc.in);
 555        if (use_sideband)
 556                finish_async(&muxer);
 557
 558        sigchain_pop(SIGPIPE);
 559
 560        return finish_command(&proc);
 561}
 562
 563struct receive_hook_feed_state {
 564        struct command *cmd;
 565        int skip_broken;
 566        struct strbuf buf;
 567};
 568
 569static int feed_receive_hook(void *state_, const char **bufp, size_t *sizep)
 570{
 571        struct receive_hook_feed_state *state = state_;
 572        struct command *cmd = state->cmd;
 573
 574        while (cmd &&
 575               state->skip_broken && (cmd->error_string || cmd->did_not_exist))
 576                cmd = cmd->next;
 577        if (!cmd)
 578                return -1; /* EOF */
 579        strbuf_reset(&state->buf);
 580        strbuf_addf(&state->buf, "%s %s %s\n",
 581                    sha1_to_hex(cmd->old_sha1), sha1_to_hex(cmd->new_sha1),
 582                    cmd->ref_name);
 583        state->cmd = cmd->next;
 584        if (bufp) {
 585                *bufp = state->buf.buf;
 586                *sizep = state->buf.len;
 587        }
 588        return 0;
 589}
 590
 591static int run_receive_hook(struct command *commands, const char *hook_name,
 592                            int skip_broken)
 593{
 594        struct receive_hook_feed_state state;
 595        int status;
 596
 597        strbuf_init(&state.buf, 0);
 598        state.cmd = commands;
 599        state.skip_broken = skip_broken;
 600        if (feed_receive_hook(&state, NULL, NULL))
 601                return 0;
 602        state.cmd = commands;
 603        status = run_and_feed_hook(hook_name, feed_receive_hook, &state);
 604        strbuf_release(&state.buf);
 605        return status;
 606}
 607
 608static int run_update_hook(struct command *cmd)
 609{
 610        const char *argv[5];
 611        struct child_process proc = CHILD_PROCESS_INIT;
 612        int code;
 613
 614        argv[0] = find_hook("update");
 615        if (!argv[0])
 616                return 0;
 617
 618        argv[1] = cmd->ref_name;
 619        argv[2] = sha1_to_hex(cmd->old_sha1);
 620        argv[3] = sha1_to_hex(cmd->new_sha1);
 621        argv[4] = NULL;
 622
 623        proc.no_stdin = 1;
 624        proc.stdout_to_stderr = 1;
 625        proc.err = use_sideband ? -1 : 0;
 626        proc.argv = argv;
 627
 628        code = start_command(&proc);
 629        if (code)
 630                return code;
 631        if (use_sideband)
 632                copy_to_sideband(proc.err, -1, NULL);
 633        return finish_command(&proc);
 634}
 635
 636static int is_ref_checked_out(const char *ref)
 637{
 638        if (is_bare_repository())
 639                return 0;
 640
 641        if (!head_name)
 642                return 0;
 643        return !strcmp(head_name, ref);
 644}
 645
 646static char *refuse_unconfigured_deny_msg[] = {
 647        "By default, updating the current branch in a non-bare repository",
 648        "is denied, because it will make the index and work tree inconsistent",
 649        "with what you pushed, and will require 'git reset --hard' to match",
 650        "the work tree to HEAD.",
 651        "",
 652        "You can set 'receive.denyCurrentBranch' configuration variable to",
 653        "'ignore' or 'warn' in the remote repository to allow pushing into",
 654        "its current branch; however, this is not recommended unless you",
 655        "arranged to update its work tree to match what you pushed in some",
 656        "other way.",
 657        "",
 658        "To squelch this message and still keep the default behaviour, set",
 659        "'receive.denyCurrentBranch' configuration variable to 'refuse'."
 660};
 661
 662static void refuse_unconfigured_deny(void)
 663{
 664        int i;
 665        for (i = 0; i < ARRAY_SIZE(refuse_unconfigured_deny_msg); i++)
 666                rp_error("%s", refuse_unconfigured_deny_msg[i]);
 667}
 668
 669static char *refuse_unconfigured_deny_delete_current_msg[] = {
 670        "By default, deleting the current branch is denied, because the next",
 671        "'git clone' won't result in any file checked out, causing confusion.",
 672        "",
 673        "You can set 'receive.denyDeleteCurrent' configuration variable to",
 674        "'warn' or 'ignore' in the remote repository to allow deleting the",
 675        "current branch, with or without a warning message.",
 676        "",
 677        "To squelch this message, you can set it to 'refuse'."
 678};
 679
 680static void refuse_unconfigured_deny_delete_current(void)
 681{
 682        int i;
 683        for (i = 0;
 684             i < ARRAY_SIZE(refuse_unconfigured_deny_delete_current_msg);
 685             i++)
 686                rp_error("%s", refuse_unconfigured_deny_delete_current_msg[i]);
 687}
 688
 689static int command_singleton_iterator(void *cb_data, unsigned char sha1[20]);
 690static int update_shallow_ref(struct command *cmd, struct shallow_info *si)
 691{
 692        static struct lock_file shallow_lock;
 693        struct sha1_array extra = SHA1_ARRAY_INIT;
 694        const char *alt_file;
 695        uint32_t mask = 1 << (cmd->index % 32);
 696        int i;
 697
 698        trace_printf_key(&trace_shallow,
 699                         "shallow: update_shallow_ref %s\n", cmd->ref_name);
 700        for (i = 0; i < si->shallow->nr; i++)
 701                if (si->used_shallow[i] &&
 702                    (si->used_shallow[i][cmd->index / 32] & mask) &&
 703                    !delayed_reachability_test(si, i))
 704                        sha1_array_append(&extra, si->shallow->sha1[i]);
 705
 706        setup_alternate_shallow(&shallow_lock, &alt_file, &extra);
 707        if (check_shallow_connected(command_singleton_iterator,
 708                                    0, cmd, alt_file)) {
 709                rollback_lock_file(&shallow_lock);
 710                sha1_array_clear(&extra);
 711                return -1;
 712        }
 713
 714        commit_lock_file(&shallow_lock);
 715
 716        /*
 717         * Make sure setup_alternate_shallow() for the next ref does
 718         * not lose these new roots..
 719         */
 720        for (i = 0; i < extra.nr; i++)
 721                register_shallow(extra.sha1[i]);
 722
 723        si->shallow_ref[cmd->index] = 0;
 724        sha1_array_clear(&extra);
 725        return 0;
 726}
 727
 728static const char *update(struct command *cmd, struct shallow_info *si)
 729{
 730        const char *name = cmd->ref_name;
 731        struct strbuf namespaced_name_buf = STRBUF_INIT;
 732        const char *namespaced_name;
 733        unsigned char *old_sha1 = cmd->old_sha1;
 734        unsigned char *new_sha1 = cmd->new_sha1;
 735
 736        /* only refs/... are allowed */
 737        if (!starts_with(name, "refs/") || check_refname_format(name + 5, 0)) {
 738                rp_error("refusing to create funny ref '%s' remotely", name);
 739                return "funny refname";
 740        }
 741
 742        strbuf_addf(&namespaced_name_buf, "%s%s", get_git_namespace(), name);
 743        namespaced_name = strbuf_detach(&namespaced_name_buf, NULL);
 744
 745        if (is_ref_checked_out(namespaced_name)) {
 746                switch (deny_current_branch) {
 747                case DENY_IGNORE:
 748                        break;
 749                case DENY_WARN:
 750                        rp_warning("updating the current branch");
 751                        break;
 752                case DENY_REFUSE:
 753                case DENY_UNCONFIGURED:
 754                        rp_error("refusing to update checked out branch: %s", name);
 755                        if (deny_current_branch == DENY_UNCONFIGURED)
 756                                refuse_unconfigured_deny();
 757                        return "branch is currently checked out";
 758                }
 759        }
 760
 761        if (!is_null_sha1(new_sha1) && !has_sha1_file(new_sha1)) {
 762                error("unpack should have generated %s, "
 763                      "but I can't find it!", sha1_to_hex(new_sha1));
 764                return "bad pack";
 765        }
 766
 767        if (!is_null_sha1(old_sha1) && is_null_sha1(new_sha1)) {
 768                if (deny_deletes && starts_with(name, "refs/heads/")) {
 769                        rp_error("denying ref deletion for %s", name);
 770                        return "deletion prohibited";
 771                }
 772
 773                if (!strcmp(namespaced_name, head_name)) {
 774                        switch (deny_delete_current) {
 775                        case DENY_IGNORE:
 776                                break;
 777                        case DENY_WARN:
 778                                rp_warning("deleting the current branch");
 779                                break;
 780                        case DENY_REFUSE:
 781                        case DENY_UNCONFIGURED:
 782                                if (deny_delete_current == DENY_UNCONFIGURED)
 783                                        refuse_unconfigured_deny_delete_current();
 784                                rp_error("refusing to delete the current branch: %s", name);
 785                                return "deletion of the current branch prohibited";
 786                        }
 787                }
 788        }
 789
 790        if (deny_non_fast_forwards && !is_null_sha1(new_sha1) &&
 791            !is_null_sha1(old_sha1) &&
 792            starts_with(name, "refs/heads/")) {
 793                struct object *old_object, *new_object;
 794                struct commit *old_commit, *new_commit;
 795
 796                old_object = parse_object(old_sha1);
 797                new_object = parse_object(new_sha1);
 798
 799                if (!old_object || !new_object ||
 800                    old_object->type != OBJ_COMMIT ||
 801                    new_object->type != OBJ_COMMIT) {
 802                        error("bad sha1 objects for %s", name);
 803                        return "bad ref";
 804                }
 805                old_commit = (struct commit *)old_object;
 806                new_commit = (struct commit *)new_object;
 807                if (!in_merge_bases(old_commit, new_commit)) {
 808                        rp_error("denying non-fast-forward %s"
 809                                 " (you should pull first)", name);
 810                        return "non-fast-forward";
 811                }
 812        }
 813        if (run_update_hook(cmd)) {
 814                rp_error("hook declined to update %s", name);
 815                return "hook declined";
 816        }
 817
 818        if (is_null_sha1(new_sha1)) {
 819                if (!parse_object(old_sha1)) {
 820                        old_sha1 = NULL;
 821                        if (ref_exists(name)) {
 822                                rp_warning("Allowing deletion of corrupt ref.");
 823                        } else {
 824                                rp_warning("Deleting a non-existent ref.");
 825                                cmd->did_not_exist = 1;
 826                        }
 827                }
 828                if (delete_ref(namespaced_name, old_sha1, 0)) {
 829                        rp_error("failed to delete %s", name);
 830                        return "failed to delete";
 831                }
 832                return NULL; /* good */
 833        }
 834        else {
 835                struct strbuf err = STRBUF_INIT;
 836                struct ref_transaction *transaction;
 837
 838                if (shallow_update && si->shallow_ref[cmd->index] &&
 839                    update_shallow_ref(cmd, si))
 840                        return "shallow error";
 841
 842                transaction = ref_transaction_begin(&err);
 843                if (!transaction ||
 844                    ref_transaction_update(transaction, namespaced_name,
 845                                           new_sha1, old_sha1, 0, 1, &err) ||
 846                    ref_transaction_commit(transaction, "push", &err)) {
 847                        ref_transaction_free(transaction);
 848
 849                        rp_error("%s", err.buf);
 850                        strbuf_release(&err);
 851                        return "failed to update ref";
 852                }
 853
 854                ref_transaction_free(transaction);
 855                strbuf_release(&err);
 856                return NULL; /* good */
 857        }
 858}
 859
 860static void run_update_post_hook(struct command *commands)
 861{
 862        struct command *cmd;
 863        int argc;
 864        const char **argv;
 865        struct child_process proc = CHILD_PROCESS_INIT;
 866        char *hook;
 867
 868        hook = find_hook("post-update");
 869        for (argc = 0, cmd = commands; cmd; cmd = cmd->next) {
 870                if (cmd->error_string || cmd->did_not_exist)
 871                        continue;
 872                argc++;
 873        }
 874        if (!argc || !hook)
 875                return;
 876
 877        argv = xmalloc(sizeof(*argv) * (2 + argc));
 878        argv[0] = hook;
 879
 880        for (argc = 1, cmd = commands; cmd; cmd = cmd->next) {
 881                if (cmd->error_string || cmd->did_not_exist)
 882                        continue;
 883                argv[argc] = xstrdup(cmd->ref_name);
 884                argc++;
 885        }
 886        argv[argc] = NULL;
 887
 888        proc.no_stdin = 1;
 889        proc.stdout_to_stderr = 1;
 890        proc.err = use_sideband ? -1 : 0;
 891        proc.argv = argv;
 892
 893        if (!start_command(&proc)) {
 894                if (use_sideband)
 895                        copy_to_sideband(proc.err, -1, NULL);
 896                finish_command(&proc);
 897        }
 898}
 899
 900static void check_aliased_update(struct command *cmd, struct string_list *list)
 901{
 902        struct strbuf buf = STRBUF_INIT;
 903        const char *dst_name;
 904        struct string_list_item *item;
 905        struct command *dst_cmd;
 906        unsigned char sha1[20];
 907        char cmd_oldh[41], cmd_newh[41], dst_oldh[41], dst_newh[41];
 908        int flag;
 909
 910        strbuf_addf(&buf, "%s%s", get_git_namespace(), cmd->ref_name);
 911        dst_name = resolve_ref_unsafe(buf.buf, sha1, 0, &flag);
 912        strbuf_release(&buf);
 913
 914        if (!(flag & REF_ISSYMREF))
 915                return;
 916
 917        dst_name = strip_namespace(dst_name);
 918        if (!dst_name) {
 919                rp_error("refusing update to broken symref '%s'", cmd->ref_name);
 920                cmd->skip_update = 1;
 921                cmd->error_string = "broken symref";
 922                return;
 923        }
 924
 925        if ((item = string_list_lookup(list, dst_name)) == NULL)
 926                return;
 927
 928        cmd->skip_update = 1;
 929
 930        dst_cmd = (struct command *) item->util;
 931
 932        if (!hashcmp(cmd->old_sha1, dst_cmd->old_sha1) &&
 933            !hashcmp(cmd->new_sha1, dst_cmd->new_sha1))
 934                return;
 935
 936        dst_cmd->skip_update = 1;
 937
 938        strcpy(cmd_oldh, find_unique_abbrev(cmd->old_sha1, DEFAULT_ABBREV));
 939        strcpy(cmd_newh, find_unique_abbrev(cmd->new_sha1, DEFAULT_ABBREV));
 940        strcpy(dst_oldh, find_unique_abbrev(dst_cmd->old_sha1, DEFAULT_ABBREV));
 941        strcpy(dst_newh, find_unique_abbrev(dst_cmd->new_sha1, DEFAULT_ABBREV));
 942        rp_error("refusing inconsistent update between symref '%s' (%s..%s) and"
 943                 " its target '%s' (%s..%s)",
 944                 cmd->ref_name, cmd_oldh, cmd_newh,
 945                 dst_cmd->ref_name, dst_oldh, dst_newh);
 946
 947        cmd->error_string = dst_cmd->error_string =
 948                "inconsistent aliased update";
 949}
 950
 951static void check_aliased_updates(struct command *commands)
 952{
 953        struct command *cmd;
 954        struct string_list ref_list = STRING_LIST_INIT_NODUP;
 955
 956        for (cmd = commands; cmd; cmd = cmd->next) {
 957                struct string_list_item *item =
 958                        string_list_append(&ref_list, cmd->ref_name);
 959                item->util = (void *)cmd;
 960        }
 961        sort_string_list(&ref_list);
 962
 963        for (cmd = commands; cmd; cmd = cmd->next) {
 964                if (!cmd->error_string)
 965                        check_aliased_update(cmd, &ref_list);
 966        }
 967
 968        string_list_clear(&ref_list, 0);
 969}
 970
 971static int command_singleton_iterator(void *cb_data, unsigned char sha1[20])
 972{
 973        struct command **cmd_list = cb_data;
 974        struct command *cmd = *cmd_list;
 975
 976        if (!cmd || is_null_sha1(cmd->new_sha1))
 977                return -1; /* end of list */
 978        *cmd_list = NULL; /* this returns only one */
 979        hashcpy(sha1, cmd->new_sha1);
 980        return 0;
 981}
 982
 983static void set_connectivity_errors(struct command *commands,
 984                                    struct shallow_info *si)
 985{
 986        struct command *cmd;
 987
 988        for (cmd = commands; cmd; cmd = cmd->next) {
 989                struct command *singleton = cmd;
 990                if (shallow_update && si->shallow_ref[cmd->index])
 991                        /* to be checked in update_shallow_ref() */
 992                        continue;
 993                if (!check_everything_connected(command_singleton_iterator,
 994                                                0, &singleton))
 995                        continue;
 996                cmd->error_string = "missing necessary objects";
 997        }
 998}
 999
1000struct iterate_data {
1001        struct command *cmds;
1002        struct shallow_info *si;
1003};
1004
1005static int iterate_receive_command_list(void *cb_data, unsigned char sha1[20])
1006{
1007        struct iterate_data *data = cb_data;
1008        struct command **cmd_list = &data->cmds;
1009        struct command *cmd = *cmd_list;
1010
1011        for (; cmd; cmd = cmd->next) {
1012                if (shallow_update && data->si->shallow_ref[cmd->index])
1013                        /* to be checked in update_shallow_ref() */
1014                        continue;
1015                if (!is_null_sha1(cmd->new_sha1) && !cmd->skip_update) {
1016                        hashcpy(sha1, cmd->new_sha1);
1017                        *cmd_list = cmd->next;
1018                        return 0;
1019                }
1020        }
1021        *cmd_list = NULL;
1022        return -1; /* end of list */
1023}
1024
1025static void reject_updates_to_hidden(struct command *commands)
1026{
1027        struct command *cmd;
1028
1029        for (cmd = commands; cmd; cmd = cmd->next) {
1030                if (cmd->error_string || !ref_is_hidden(cmd->ref_name))
1031                        continue;
1032                if (is_null_sha1(cmd->new_sha1))
1033                        cmd->error_string = "deny deleting a hidden ref";
1034                else
1035                        cmd->error_string = "deny updating a hidden ref";
1036        }
1037}
1038
1039static void execute_commands(struct command *commands,
1040                             const char *unpacker_error,
1041                             struct shallow_info *si)
1042{
1043        int checked_connectivity;
1044        struct command *cmd;
1045        unsigned char sha1[20];
1046        struct iterate_data data;
1047
1048        if (unpacker_error) {
1049                for (cmd = commands; cmd; cmd = cmd->next)
1050                        cmd->error_string = "unpacker error";
1051                return;
1052        }
1053
1054        data.cmds = commands;
1055        data.si = si;
1056        if (check_everything_connected(iterate_receive_command_list, 0, &data))
1057                set_connectivity_errors(commands, si);
1058
1059        reject_updates_to_hidden(commands);
1060
1061        if (run_receive_hook(commands, "pre-receive", 0)) {
1062                for (cmd = commands; cmd; cmd = cmd->next) {
1063                        if (!cmd->error_string)
1064                                cmd->error_string = "pre-receive hook declined";
1065                }
1066                return;
1067        }
1068
1069        check_aliased_updates(commands);
1070
1071        free(head_name_to_free);
1072        head_name = head_name_to_free = resolve_refdup("HEAD", sha1, 0, NULL);
1073
1074        checked_connectivity = 1;
1075        for (cmd = commands; cmd; cmd = cmd->next) {
1076                if (cmd->error_string)
1077                        continue;
1078
1079                if (cmd->skip_update)
1080                        continue;
1081
1082                cmd->error_string = update(cmd, si);
1083                if (shallow_update && !cmd->error_string &&
1084                    si->shallow_ref[cmd->index]) {
1085                        error("BUG: connectivity check has not been run on ref %s",
1086                              cmd->ref_name);
1087                        checked_connectivity = 0;
1088                }
1089        }
1090
1091        if (shallow_update && !checked_connectivity)
1092                error("BUG: run 'git fsck' for safety.\n"
1093                      "If there are errors, try to remove "
1094                      "the reported refs above");
1095}
1096
1097static struct command **queue_command(struct command **tail,
1098                                      const char *line,
1099                                      int linelen)
1100{
1101        unsigned char old_sha1[20], new_sha1[20];
1102        struct command *cmd;
1103        const char *refname;
1104        int reflen;
1105
1106        if (linelen < 83 ||
1107            line[40] != ' ' ||
1108            line[81] != ' ' ||
1109            get_sha1_hex(line, old_sha1) ||
1110            get_sha1_hex(line + 41, new_sha1))
1111                die("protocol error: expected old/new/ref, got '%s'", line);
1112
1113        refname = line + 82;
1114        reflen = linelen - 82;
1115        cmd = xcalloc(1, sizeof(struct command) + reflen + 1);
1116        hashcpy(cmd->old_sha1, old_sha1);
1117        hashcpy(cmd->new_sha1, new_sha1);
1118        memcpy(cmd->ref_name, refname, reflen);
1119        cmd->ref_name[reflen] = '\0';
1120        *tail = cmd;
1121        return &cmd->next;
1122}
1123
1124static void queue_commands_from_cert(struct command **tail,
1125                                     struct strbuf *push_cert)
1126{
1127        const char *boc, *eoc;
1128
1129        if (*tail)
1130                die("protocol error: got both push certificate and unsigned commands");
1131
1132        boc = strstr(push_cert->buf, "\n\n");
1133        if (!boc)
1134                die("malformed push certificate %.*s", 100, push_cert->buf);
1135        else
1136                boc += 2;
1137        eoc = push_cert->buf + parse_signature(push_cert->buf, push_cert->len);
1138
1139        while (boc < eoc) {
1140                const char *eol = memchr(boc, '\n', eoc - boc);
1141                tail = queue_command(tail, boc, eol ? eol - boc : eoc - eol);
1142                boc = eol ? eol + 1 : eoc;
1143        }
1144}
1145
1146static struct command *read_head_info(struct sha1_array *shallow)
1147{
1148        struct command *commands = NULL;
1149        struct command **p = &commands;
1150        for (;;) {
1151                char *line;
1152                int len, linelen;
1153
1154                line = packet_read_line(0, &len);
1155                if (!line)
1156                        break;
1157
1158                if (len == 48 && starts_with(line, "shallow ")) {
1159                        unsigned char sha1[20];
1160                        if (get_sha1_hex(line + 8, sha1))
1161                                die("protocol error: expected shallow sha, got '%s'",
1162                                    line + 8);
1163                        sha1_array_append(shallow, sha1);
1164                        continue;
1165                }
1166
1167                linelen = strlen(line);
1168                if (linelen < len) {
1169                        const char *feature_list = line + linelen + 1;
1170                        if (parse_feature_request(feature_list, "report-status"))
1171                                report_status = 1;
1172                        if (parse_feature_request(feature_list, "side-band-64k"))
1173                                use_sideband = LARGE_PACKET_MAX;
1174                        if (parse_feature_request(feature_list, "quiet"))
1175                                quiet = 1;
1176                }
1177
1178                if (!strcmp(line, "push-cert")) {
1179                        int true_flush = 0;
1180                        char certbuf[1024];
1181
1182                        for (;;) {
1183                                len = packet_read(0, NULL, NULL,
1184                                                  certbuf, sizeof(certbuf), 0);
1185                                if (!len) {
1186                                        true_flush = 1;
1187                                        break;
1188                                }
1189                                if (!strcmp(certbuf, "push-cert-end\n"))
1190                                        break; /* end of cert */
1191                                strbuf_addstr(&push_cert, certbuf);
1192                        }
1193
1194                        if (true_flush)
1195                                break;
1196                        continue;
1197                }
1198
1199                p = queue_command(p, line, linelen);
1200        }
1201
1202        if (push_cert.len)
1203                queue_commands_from_cert(p, &push_cert);
1204
1205        return commands;
1206}
1207
1208static const char *parse_pack_header(struct pack_header *hdr)
1209{
1210        switch (read_pack_header(0, hdr)) {
1211        case PH_ERROR_EOF:
1212                return "eof before pack header was fully read";
1213
1214        case PH_ERROR_PACK_SIGNATURE:
1215                return "protocol error (pack signature mismatch detected)";
1216
1217        case PH_ERROR_PROTOCOL:
1218                return "protocol error (pack version unsupported)";
1219
1220        default:
1221                return "unknown error in parse_pack_header";
1222
1223        case 0:
1224                return NULL;
1225        }
1226}
1227
1228static const char *pack_lockfile;
1229
1230static const char *unpack(int err_fd, struct shallow_info *si)
1231{
1232        struct pack_header hdr;
1233        const char *hdr_err;
1234        int status;
1235        char hdr_arg[38];
1236        struct child_process child = CHILD_PROCESS_INIT;
1237        int fsck_objects = (receive_fsck_objects >= 0
1238                            ? receive_fsck_objects
1239                            : transfer_fsck_objects >= 0
1240                            ? transfer_fsck_objects
1241                            : 0);
1242
1243        hdr_err = parse_pack_header(&hdr);
1244        if (hdr_err) {
1245                if (err_fd > 0)
1246                        close(err_fd);
1247                return hdr_err;
1248        }
1249        snprintf(hdr_arg, sizeof(hdr_arg),
1250                        "--pack_header=%"PRIu32",%"PRIu32,
1251                        ntohl(hdr.hdr_version), ntohl(hdr.hdr_entries));
1252
1253        if (si->nr_ours || si->nr_theirs) {
1254                alt_shallow_file = setup_temporary_shallow(si->shallow);
1255                argv_array_push(&child.args, "--shallow-file");
1256                argv_array_push(&child.args, alt_shallow_file);
1257        }
1258
1259        if (ntohl(hdr.hdr_entries) < unpack_limit) {
1260                argv_array_pushl(&child.args, "unpack-objects", hdr_arg, NULL);
1261                if (quiet)
1262                        argv_array_push(&child.args, "-q");
1263                if (fsck_objects)
1264                        argv_array_push(&child.args, "--strict");
1265                child.no_stdout = 1;
1266                child.err = err_fd;
1267                child.git_cmd = 1;
1268                status = run_command(&child);
1269                if (status)
1270                        return "unpack-objects abnormal exit";
1271        } else {
1272                int s;
1273                char keep_arg[256];
1274
1275                s = sprintf(keep_arg, "--keep=receive-pack %"PRIuMAX" on ", (uintmax_t) getpid());
1276                if (gethostname(keep_arg + s, sizeof(keep_arg) - s))
1277                        strcpy(keep_arg + s, "localhost");
1278
1279                argv_array_pushl(&child.args, "index-pack",
1280                                 "--stdin", hdr_arg, keep_arg, NULL);
1281                if (fsck_objects)
1282                        argv_array_push(&child.args, "--strict");
1283                if (fix_thin)
1284                        argv_array_push(&child.args, "--fix-thin");
1285                child.out = -1;
1286                child.err = err_fd;
1287                child.git_cmd = 1;
1288                status = start_command(&child);
1289                if (status)
1290                        return "index-pack fork failed";
1291                pack_lockfile = index_pack_lockfile(child.out);
1292                close(child.out);
1293                status = finish_command(&child);
1294                if (status)
1295                        return "index-pack abnormal exit";
1296                reprepare_packed_git();
1297        }
1298        return NULL;
1299}
1300
1301static const char *unpack_with_sideband(struct shallow_info *si)
1302{
1303        struct async muxer;
1304        const char *ret;
1305
1306        if (!use_sideband)
1307                return unpack(0, si);
1308
1309        memset(&muxer, 0, sizeof(muxer));
1310        muxer.proc = copy_to_sideband;
1311        muxer.in = -1;
1312        if (start_async(&muxer))
1313                return NULL;
1314
1315        ret = unpack(muxer.in, si);
1316
1317        finish_async(&muxer);
1318        return ret;
1319}
1320
1321static void prepare_shallow_update(struct command *commands,
1322                                   struct shallow_info *si)
1323{
1324        int i, j, k, bitmap_size = (si->ref->nr + 31) / 32;
1325
1326        si->used_shallow = xmalloc(sizeof(*si->used_shallow) *
1327                                   si->shallow->nr);
1328        assign_shallow_commits_to_refs(si, si->used_shallow, NULL);
1329
1330        si->need_reachability_test =
1331                xcalloc(si->shallow->nr, sizeof(*si->need_reachability_test));
1332        si->reachable =
1333                xcalloc(si->shallow->nr, sizeof(*si->reachable));
1334        si->shallow_ref = xcalloc(si->ref->nr, sizeof(*si->shallow_ref));
1335
1336        for (i = 0; i < si->nr_ours; i++)
1337                si->need_reachability_test[si->ours[i]] = 1;
1338
1339        for (i = 0; i < si->shallow->nr; i++) {
1340                if (!si->used_shallow[i])
1341                        continue;
1342                for (j = 0; j < bitmap_size; j++) {
1343                        if (!si->used_shallow[i][j])
1344                                continue;
1345                        si->need_reachability_test[i]++;
1346                        for (k = 0; k < 32; k++)
1347                                if (si->used_shallow[i][j] & (1 << k))
1348                                        si->shallow_ref[j * 32 + k]++;
1349                }
1350
1351                /*
1352                 * true for those associated with some refs and belong
1353                 * in "ours" list aka "step 7 not done yet"
1354                 */
1355                si->need_reachability_test[i] =
1356                        si->need_reachability_test[i] > 1;
1357        }
1358
1359        /*
1360         * keep hooks happy by forcing a temporary shallow file via
1361         * env variable because we can't add --shallow-file to every
1362         * command. check_everything_connected() will be done with
1363         * true .git/shallow though.
1364         */
1365        setenv(GIT_SHALLOW_FILE_ENVIRONMENT, alt_shallow_file, 1);
1366}
1367
1368static void update_shallow_info(struct command *commands,
1369                                struct shallow_info *si,
1370                                struct sha1_array *ref)
1371{
1372        struct command *cmd;
1373        int *ref_status;
1374        remove_nonexistent_theirs_shallow(si);
1375        if (!si->nr_ours && !si->nr_theirs) {
1376                shallow_update = 0;
1377                return;
1378        }
1379
1380        for (cmd = commands; cmd; cmd = cmd->next) {
1381                if (is_null_sha1(cmd->new_sha1))
1382                        continue;
1383                sha1_array_append(ref, cmd->new_sha1);
1384                cmd->index = ref->nr - 1;
1385        }
1386        si->ref = ref;
1387
1388        if (shallow_update) {
1389                prepare_shallow_update(commands, si);
1390                return;
1391        }
1392
1393        ref_status = xmalloc(sizeof(*ref_status) * ref->nr);
1394        assign_shallow_commits_to_refs(si, NULL, ref_status);
1395        for (cmd = commands; cmd; cmd = cmd->next) {
1396                if (is_null_sha1(cmd->new_sha1))
1397                        continue;
1398                if (ref_status[cmd->index]) {
1399                        cmd->error_string = "shallow update not allowed";
1400                        cmd->skip_update = 1;
1401                }
1402        }
1403        free(ref_status);
1404}
1405
1406static void report(struct command *commands, const char *unpack_status)
1407{
1408        struct command *cmd;
1409        struct strbuf buf = STRBUF_INIT;
1410
1411        packet_buf_write(&buf, "unpack %s\n",
1412                         unpack_status ? unpack_status : "ok");
1413        for (cmd = commands; cmd; cmd = cmd->next) {
1414                if (!cmd->error_string)
1415                        packet_buf_write(&buf, "ok %s\n",
1416                                         cmd->ref_name);
1417                else
1418                        packet_buf_write(&buf, "ng %s %s\n",
1419                                         cmd->ref_name, cmd->error_string);
1420        }
1421        packet_buf_flush(&buf);
1422
1423        if (use_sideband)
1424                send_sideband(1, 1, buf.buf, buf.len, use_sideband);
1425        else
1426                write_or_die(1, buf.buf, buf.len);
1427        strbuf_release(&buf);
1428}
1429
1430static int delete_only(struct command *commands)
1431{
1432        struct command *cmd;
1433        for (cmd = commands; cmd; cmd = cmd->next) {
1434                if (!is_null_sha1(cmd->new_sha1))
1435                        return 0;
1436        }
1437        return 1;
1438}
1439
1440int cmd_receive_pack(int argc, const char **argv, const char *prefix)
1441{
1442        int advertise_refs = 0;
1443        int i;
1444        struct command *commands;
1445        struct sha1_array shallow = SHA1_ARRAY_INIT;
1446        struct sha1_array ref = SHA1_ARRAY_INIT;
1447        struct shallow_info si;
1448
1449        packet_trace_identity("receive-pack");
1450
1451        argv++;
1452        for (i = 1; i < argc; i++) {
1453                const char *arg = *argv++;
1454
1455                if (*arg == '-') {
1456                        if (!strcmp(arg, "--quiet")) {
1457                                quiet = 1;
1458                                continue;
1459                        }
1460
1461                        if (!strcmp(arg, "--advertise-refs")) {
1462                                advertise_refs = 1;
1463                                continue;
1464                        }
1465                        if (!strcmp(arg, "--stateless-rpc")) {
1466                                stateless_rpc = 1;
1467                                continue;
1468                        }
1469                        if (!strcmp(arg, "--reject-thin-pack-for-testing")) {
1470                                fix_thin = 0;
1471                                continue;
1472                        }
1473
1474                        usage(receive_pack_usage);
1475                }
1476                if (service_dir)
1477                        usage(receive_pack_usage);
1478                service_dir = arg;
1479        }
1480        if (!service_dir)
1481                usage(receive_pack_usage);
1482
1483        setup_path();
1484
1485        if (!enter_repo(service_dir, 0))
1486                die("'%s' does not appear to be a git repository", service_dir);
1487
1488        git_config(receive_pack_config, NULL);
1489        if (cert_nonce_seed)
1490                push_cert_nonce = prepare_push_cert_nonce(service_dir, time(NULL));
1491
1492        if (0 <= transfer_unpack_limit)
1493                unpack_limit = transfer_unpack_limit;
1494        else if (0 <= receive_unpack_limit)
1495                unpack_limit = receive_unpack_limit;
1496
1497        if (advertise_refs || !stateless_rpc) {
1498                write_head_info();
1499        }
1500        if (advertise_refs)
1501                return 0;
1502
1503        if ((commands = read_head_info(&shallow)) != NULL) {
1504                const char *unpack_status = NULL;
1505
1506                prepare_shallow_info(&si, &shallow);
1507                if (!si.nr_ours && !si.nr_theirs)
1508                        shallow_update = 0;
1509                if (!delete_only(commands)) {
1510                        unpack_status = unpack_with_sideband(&si);
1511                        update_shallow_info(commands, &si, &ref);
1512                }
1513                execute_commands(commands, unpack_status, &si);
1514                if (pack_lockfile)
1515                        unlink_or_warn(pack_lockfile);
1516                if (report_status)
1517                        report(commands, unpack_status);
1518                run_receive_hook(commands, "post-receive", 1);
1519                run_update_post_hook(commands);
1520                if (auto_gc) {
1521                        const char *argv_gc_auto[] = {
1522                                "gc", "--auto", "--quiet", NULL,
1523                        };
1524                        int opt = RUN_GIT_CMD | RUN_COMMAND_STDOUT_TO_STDERR;
1525                        run_command_v_opt(argv_gc_auto, opt);
1526                }
1527                if (auto_update_server_info)
1528                        update_server_info(0);
1529                clear_shallow_info(&si);
1530        }
1531        if (use_sideband)
1532                packet_flush(1);
1533        sha1_array_clear(&shallow);
1534        sha1_array_clear(&ref);
1535        free((void *)push_cert_nonce);
1536        return 0;
1537}