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