1821ad5fa62ddcce41b16416fb63e77cb35a3b47
   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#include "fsck.h"
  23#include "tmp-objdir.h"
  24#include "oidset.h"
  25
  26static const char * const receive_pack_usage[] = {
  27        N_("git receive-pack <git-dir>"),
  28        NULL
  29};
  30
  31enum deny_action {
  32        DENY_UNCONFIGURED,
  33        DENY_IGNORE,
  34        DENY_WARN,
  35        DENY_REFUSE,
  36        DENY_UPDATE_INSTEAD
  37};
  38
  39static int deny_deletes;
  40static int deny_non_fast_forwards;
  41static enum deny_action deny_current_branch = DENY_UNCONFIGURED;
  42static enum deny_action deny_delete_current = DENY_UNCONFIGURED;
  43static int receive_fsck_objects = -1;
  44static int transfer_fsck_objects = -1;
  45static struct strbuf fsck_msg_types = STRBUF_INIT;
  46static int receive_unpack_limit = -1;
  47static int transfer_unpack_limit = -1;
  48static int advertise_atomic_push = 1;
  49static int advertise_push_options;
  50static int unpack_limit = 100;
  51static off_t max_input_size;
  52static int report_status;
  53static int use_sideband;
  54static int use_atomic;
  55static int use_push_options;
  56static int quiet;
  57static int prefer_ofs_delta = 1;
  58static int auto_update_server_info;
  59static int auto_gc = 1;
  60static int reject_thin;
  61static int stateless_rpc;
  62static const char *service_dir;
  63static const char *head_name;
  64static void *head_name_to_free;
  65static int sent_capabilities;
  66static int shallow_update;
  67static const char *alt_shallow_file;
  68static struct strbuf push_cert = STRBUF_INIT;
  69static unsigned char push_cert_sha1[20];
  70static struct signature_check sigcheck;
  71static const char *push_cert_nonce;
  72static const char *cert_nonce_seed;
  73
  74static const char *NONCE_UNSOLICITED = "UNSOLICITED";
  75static const char *NONCE_BAD = "BAD";
  76static const char *NONCE_MISSING = "MISSING";
  77static const char *NONCE_OK = "OK";
  78static const char *NONCE_SLOP = "SLOP";
  79static const char *nonce_status;
  80static long nonce_stamp_slop;
  81static unsigned long nonce_stamp_slop_limit;
  82static struct ref_transaction *transaction;
  83
  84static enum {
  85        KEEPALIVE_NEVER = 0,
  86        KEEPALIVE_AFTER_NUL,
  87        KEEPALIVE_ALWAYS
  88} use_keepalive;
  89static int keepalive_in_sec = 5;
  90
  91static struct tmp_objdir *tmp_objdir;
  92
  93static enum deny_action parse_deny_action(const char *var, const char *value)
  94{
  95        if (value) {
  96                if (!strcasecmp(value, "ignore"))
  97                        return DENY_IGNORE;
  98                if (!strcasecmp(value, "warn"))
  99                        return DENY_WARN;
 100                if (!strcasecmp(value, "refuse"))
 101                        return DENY_REFUSE;
 102                if (!strcasecmp(value, "updateinstead"))
 103                        return DENY_UPDATE_INSTEAD;
 104        }
 105        if (git_config_bool(var, value))
 106                return DENY_REFUSE;
 107        return DENY_IGNORE;
 108}
 109
 110static int receive_pack_config(const char *var, const char *value, void *cb)
 111{
 112        int status = parse_hide_refs_config(var, value, "receive");
 113
 114        if (status)
 115                return status;
 116
 117        if (strcmp(var, "receive.denydeletes") == 0) {
 118                deny_deletes = git_config_bool(var, value);
 119                return 0;
 120        }
 121
 122        if (strcmp(var, "receive.denynonfastforwards") == 0) {
 123                deny_non_fast_forwards = git_config_bool(var, value);
 124                return 0;
 125        }
 126
 127        if (strcmp(var, "receive.unpacklimit") == 0) {
 128                receive_unpack_limit = git_config_int(var, value);
 129                return 0;
 130        }
 131
 132        if (strcmp(var, "transfer.unpacklimit") == 0) {
 133                transfer_unpack_limit = git_config_int(var, value);
 134                return 0;
 135        }
 136
 137        if (strcmp(var, "receive.fsck.skiplist") == 0) {
 138                const char *path;
 139
 140                if (git_config_pathname(&path, var, value))
 141                        return 1;
 142                strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
 143                        fsck_msg_types.len ? ',' : '=', path);
 144                free((char *)path);
 145                return 0;
 146        }
 147
 148        if (skip_prefix(var, "receive.fsck.", &var)) {
 149                if (is_valid_msg_type(var, value))
 150                        strbuf_addf(&fsck_msg_types, "%c%s=%s",
 151                                fsck_msg_types.len ? ',' : '=', var, value);
 152                else
 153                        warning("Skipping unknown msg id '%s'", var);
 154                return 0;
 155        }
 156
 157        if (strcmp(var, "receive.fsckobjects") == 0) {
 158                receive_fsck_objects = git_config_bool(var, value);
 159                return 0;
 160        }
 161
 162        if (strcmp(var, "transfer.fsckobjects") == 0) {
 163                transfer_fsck_objects = git_config_bool(var, value);
 164                return 0;
 165        }
 166
 167        if (!strcmp(var, "receive.denycurrentbranch")) {
 168                deny_current_branch = parse_deny_action(var, value);
 169                return 0;
 170        }
 171
 172        if (strcmp(var, "receive.denydeletecurrent") == 0) {
 173                deny_delete_current = parse_deny_action(var, value);
 174                return 0;
 175        }
 176
 177        if (strcmp(var, "repack.usedeltabaseoffset") == 0) {
 178                prefer_ofs_delta = git_config_bool(var, value);
 179                return 0;
 180        }
 181
 182        if (strcmp(var, "receive.updateserverinfo") == 0) {
 183                auto_update_server_info = git_config_bool(var, value);
 184                return 0;
 185        }
 186
 187        if (strcmp(var, "receive.autogc") == 0) {
 188                auto_gc = git_config_bool(var, value);
 189                return 0;
 190        }
 191
 192        if (strcmp(var, "receive.shallowupdate") == 0) {
 193                shallow_update = git_config_bool(var, value);
 194                return 0;
 195        }
 196
 197        if (strcmp(var, "receive.certnonceseed") == 0)
 198                return git_config_string(&cert_nonce_seed, var, value);
 199
 200        if (strcmp(var, "receive.certnonceslop") == 0) {
 201                nonce_stamp_slop_limit = git_config_ulong(var, value);
 202                return 0;
 203        }
 204
 205        if (strcmp(var, "receive.advertiseatomic") == 0) {
 206                advertise_atomic_push = git_config_bool(var, value);
 207                return 0;
 208        }
 209
 210        if (strcmp(var, "receive.advertisepushoptions") == 0) {
 211                advertise_push_options = git_config_bool(var, value);
 212                return 0;
 213        }
 214
 215        if (strcmp(var, "receive.keepalive") == 0) {
 216                keepalive_in_sec = git_config_int(var, value);
 217                return 0;
 218        }
 219
 220        if (strcmp(var, "receive.maxinputsize") == 0) {
 221                max_input_size = git_config_int64(var, value);
 222                return 0;
 223        }
 224
 225        return git_default_config(var, value, cb);
 226}
 227
 228static void show_ref(const char *path, const unsigned char *sha1)
 229{
 230        if (sent_capabilities) {
 231                packet_write_fmt(1, "%s %s\n", sha1_to_hex(sha1), path);
 232        } else {
 233                struct strbuf cap = STRBUF_INIT;
 234
 235                strbuf_addstr(&cap,
 236                              "report-status delete-refs side-band-64k quiet");
 237                if (advertise_atomic_push)
 238                        strbuf_addstr(&cap, " atomic");
 239                if (prefer_ofs_delta)
 240                        strbuf_addstr(&cap, " ofs-delta");
 241                if (push_cert_nonce)
 242                        strbuf_addf(&cap, " push-cert=%s", push_cert_nonce);
 243                if (advertise_push_options)
 244                        strbuf_addstr(&cap, " push-options");
 245                strbuf_addf(&cap, " agent=%s", git_user_agent_sanitized());
 246                packet_write_fmt(1, "%s %s%c%s\n",
 247                             sha1_to_hex(sha1), path, 0, cap.buf);
 248                strbuf_release(&cap);
 249                sent_capabilities = 1;
 250        }
 251}
 252
 253static int show_ref_cb(const char *path_full, const struct object_id *oid,
 254                       int flag, void *unused)
 255{
 256        const char *path = strip_namespace(path_full);
 257
 258        if (ref_is_hidden(path, path_full))
 259                return 0;
 260
 261        /*
 262         * Advertise refs outside our current namespace as ".have"
 263         * refs, so that the client can use them to minimize data
 264         * transfer but will otherwise ignore them.
 265         */
 266        if (!path)
 267                path = ".have";
 268        show_ref(path, oid->hash);
 269        return 0;
 270}
 271
 272static void show_one_alternate_ref(const char *refname,
 273                                   const struct object_id *oid,
 274                                   void *data)
 275{
 276        struct oidset *seen = data;
 277
 278        if (oidset_insert(seen, oid))
 279                return;
 280
 281        show_ref(".have", oid->hash);
 282}
 283
 284static void write_head_info(void)
 285{
 286        static struct oidset seen = OIDSET_INIT;
 287
 288        for_each_alternate_ref(show_one_alternate_ref, &seen);
 289        oidset_clear(&seen);
 290        for_each_ref(show_ref_cb, NULL);
 291        if (!sent_capabilities)
 292                show_ref("capabilities^{}", null_sha1);
 293
 294        advertise_shallow_grafts(1);
 295
 296        /* EOF */
 297        packet_flush(1);
 298}
 299
 300struct command {
 301        struct command *next;
 302        const char *error_string;
 303        unsigned int skip_update:1,
 304                     did_not_exist:1;
 305        int index;
 306        unsigned char old_sha1[20];
 307        unsigned char new_sha1[20];
 308        char ref_name[FLEX_ARRAY]; /* more */
 309};
 310
 311static void rp_error(const char *err, ...) __attribute__((format (printf, 1, 2)));
 312static void rp_warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
 313
 314static void report_message(const char *prefix, const char *err, va_list params)
 315{
 316        int sz;
 317        char msg[4096];
 318
 319        sz = xsnprintf(msg, sizeof(msg), "%s", prefix);
 320        sz += vsnprintf(msg + sz, sizeof(msg) - sz, err, params);
 321        if (sz > (sizeof(msg) - 1))
 322                sz = sizeof(msg) - 1;
 323        msg[sz++] = '\n';
 324
 325        if (use_sideband)
 326                send_sideband(1, 2, msg, sz, use_sideband);
 327        else
 328                xwrite(2, msg, sz);
 329}
 330
 331static void rp_warning(const char *err, ...)
 332{
 333        va_list params;
 334        va_start(params, err);
 335        report_message("warning: ", err, params);
 336        va_end(params);
 337}
 338
 339static void rp_error(const char *err, ...)
 340{
 341        va_list params;
 342        va_start(params, err);
 343        report_message("error: ", err, params);
 344        va_end(params);
 345}
 346
 347static int copy_to_sideband(int in, int out, void *arg)
 348{
 349        char data[128];
 350        int keepalive_active = 0;
 351
 352        if (keepalive_in_sec <= 0)
 353                use_keepalive = KEEPALIVE_NEVER;
 354        if (use_keepalive == KEEPALIVE_ALWAYS)
 355                keepalive_active = 1;
 356
 357        while (1) {
 358                ssize_t sz;
 359
 360                if (keepalive_active) {
 361                        struct pollfd pfd;
 362                        int ret;
 363
 364                        pfd.fd = in;
 365                        pfd.events = POLLIN;
 366                        ret = poll(&pfd, 1, 1000 * keepalive_in_sec);
 367
 368                        if (ret < 0) {
 369                                if (errno == EINTR)
 370                                        continue;
 371                                else
 372                                        break;
 373                        } else if (ret == 0) {
 374                                /* no data; send a keepalive packet */
 375                                static const char buf[] = "0005\1";
 376                                write_or_die(1, buf, sizeof(buf) - 1);
 377                                continue;
 378                        } /* else there is actual data to read */
 379                }
 380
 381                sz = xread(in, data, sizeof(data));
 382                if (sz <= 0)
 383                        break;
 384
 385                if (use_keepalive == KEEPALIVE_AFTER_NUL && !keepalive_active) {
 386                        const char *p = memchr(data, '\0', sz);
 387                        if (p) {
 388                                /*
 389                                 * The NUL tells us to start sending keepalives. Make
 390                                 * sure we send any other data we read along
 391                                 * with it.
 392                                 */
 393                                keepalive_active = 1;
 394                                send_sideband(1, 2, data, p - data, use_sideband);
 395                                send_sideband(1, 2, p + 1, sz - (p - data + 1), use_sideband);
 396                                continue;
 397                        }
 398                }
 399
 400                /*
 401                 * Either we're not looking for a NUL signal, or we didn't see
 402                 * it yet; just pass along the data.
 403                 */
 404                send_sideband(1, 2, data, sz, use_sideband);
 405        }
 406        close(in);
 407        return 0;
 408}
 409
 410#define HMAC_BLOCK_SIZE 64
 411
 412static void hmac_sha1(unsigned char *out,
 413                      const char *key_in, size_t key_len,
 414                      const char *text, size_t text_len)
 415{
 416        unsigned char key[HMAC_BLOCK_SIZE];
 417        unsigned char k_ipad[HMAC_BLOCK_SIZE];
 418        unsigned char k_opad[HMAC_BLOCK_SIZE];
 419        int i;
 420        git_SHA_CTX ctx;
 421
 422        /* RFC 2104 2. (1) */
 423        memset(key, '\0', HMAC_BLOCK_SIZE);
 424        if (HMAC_BLOCK_SIZE < key_len) {
 425                git_SHA1_Init(&ctx);
 426                git_SHA1_Update(&ctx, key_in, key_len);
 427                git_SHA1_Final(key, &ctx);
 428        } else {
 429                memcpy(key, key_in, key_len);
 430        }
 431
 432        /* RFC 2104 2. (2) & (5) */
 433        for (i = 0; i < sizeof(key); i++) {
 434                k_ipad[i] = key[i] ^ 0x36;
 435                k_opad[i] = key[i] ^ 0x5c;
 436        }
 437
 438        /* RFC 2104 2. (3) & (4) */
 439        git_SHA1_Init(&ctx);
 440        git_SHA1_Update(&ctx, k_ipad, sizeof(k_ipad));
 441        git_SHA1_Update(&ctx, text, text_len);
 442        git_SHA1_Final(out, &ctx);
 443
 444        /* RFC 2104 2. (6) & (7) */
 445        git_SHA1_Init(&ctx);
 446        git_SHA1_Update(&ctx, k_opad, sizeof(k_opad));
 447        git_SHA1_Update(&ctx, out, 20);
 448        git_SHA1_Final(out, &ctx);
 449}
 450
 451static char *prepare_push_cert_nonce(const char *path, unsigned long stamp)
 452{
 453        struct strbuf buf = STRBUF_INIT;
 454        unsigned char sha1[20];
 455
 456        strbuf_addf(&buf, "%s:%lu", path, stamp);
 457        hmac_sha1(sha1, buf.buf, buf.len, cert_nonce_seed, strlen(cert_nonce_seed));;
 458        strbuf_release(&buf);
 459
 460        /* RFC 2104 5. HMAC-SHA1-80 */
 461        strbuf_addf(&buf, "%lu-%.*s", stamp, 20, sha1_to_hex(sha1));
 462        return strbuf_detach(&buf, NULL);
 463}
 464
 465/*
 466 * NEEDSWORK: reuse find_commit_header() from jk/commit-author-parsing
 467 * after dropping "_commit" from its name and possibly moving it out
 468 * of commit.c
 469 */
 470static char *find_header(const char *msg, size_t len, const char *key)
 471{
 472        int key_len = strlen(key);
 473        const char *line = msg;
 474
 475        while (line && line < msg + len) {
 476                const char *eol = strchrnul(line, '\n');
 477
 478                if ((msg + len <= eol) || line == eol)
 479                        return NULL;
 480                if (line + key_len < eol &&
 481                    !memcmp(line, key, key_len) && line[key_len] == ' ') {
 482                        int offset = key_len + 1;
 483                        return xmemdupz(line + offset, (eol - line) - offset);
 484                }
 485                line = *eol ? eol + 1 : NULL;
 486        }
 487        return NULL;
 488}
 489
 490static const char *check_nonce(const char *buf, size_t len)
 491{
 492        char *nonce = find_header(buf, len, "nonce");
 493        unsigned long stamp, ostamp;
 494        char *bohmac, *expect = NULL;
 495        const char *retval = NONCE_BAD;
 496
 497        if (!nonce) {
 498                retval = NONCE_MISSING;
 499                goto leave;
 500        } else if (!push_cert_nonce) {
 501                retval = NONCE_UNSOLICITED;
 502                goto leave;
 503        } else if (!strcmp(push_cert_nonce, nonce)) {
 504                retval = NONCE_OK;
 505                goto leave;
 506        }
 507
 508        if (!stateless_rpc) {
 509                /* returned nonce MUST match what we gave out earlier */
 510                retval = NONCE_BAD;
 511                goto leave;
 512        }
 513
 514        /*
 515         * In stateless mode, we may be receiving a nonce issued by
 516         * another instance of the server that serving the same
 517         * repository, and the timestamps may not match, but the
 518         * nonce-seed and dir should match, so we can recompute and
 519         * report the time slop.
 520         *
 521         * In addition, when a nonce issued by another instance has
 522         * timestamp within receive.certnonceslop seconds, we pretend
 523         * as if we issued that nonce when reporting to the hook.
 524         */
 525
 526        /* nonce is concat(<seconds-since-epoch>, "-", <hmac>) */
 527        if (*nonce <= '0' || '9' < *nonce) {
 528                retval = NONCE_BAD;
 529                goto leave;
 530        }
 531        stamp = strtoul(nonce, &bohmac, 10);
 532        if (bohmac == nonce || bohmac[0] != '-') {
 533                retval = NONCE_BAD;
 534                goto leave;
 535        }
 536
 537        expect = prepare_push_cert_nonce(service_dir, stamp);
 538        if (strcmp(expect, nonce)) {
 539                /* Not what we would have signed earlier */
 540                retval = NONCE_BAD;
 541                goto leave;
 542        }
 543
 544        /*
 545         * By how many seconds is this nonce stale?  Negative value
 546         * would mean it was issued by another server with its clock
 547         * skewed in the future.
 548         */
 549        ostamp = strtoul(push_cert_nonce, NULL, 10);
 550        nonce_stamp_slop = (long)ostamp - (long)stamp;
 551
 552        if (nonce_stamp_slop_limit &&
 553            labs(nonce_stamp_slop) <= nonce_stamp_slop_limit) {
 554                /*
 555                 * Pretend as if the received nonce (which passes the
 556                 * HMAC check, so it is not a forged by third-party)
 557                 * is what we issued.
 558                 */
 559                free((void *)push_cert_nonce);
 560                push_cert_nonce = xstrdup(nonce);
 561                retval = NONCE_OK;
 562        } else {
 563                retval = NONCE_SLOP;
 564        }
 565
 566leave:
 567        free(nonce);
 568        free(expect);
 569        return retval;
 570}
 571
 572static void prepare_push_cert_sha1(struct child_process *proc)
 573{
 574        static int already_done;
 575
 576        if (!push_cert.len)
 577                return;
 578
 579        if (!already_done) {
 580                struct strbuf gpg_output = STRBUF_INIT;
 581                struct strbuf gpg_status = STRBUF_INIT;
 582                int bogs /* beginning_of_gpg_sig */;
 583
 584                already_done = 1;
 585                if (write_sha1_file(push_cert.buf, push_cert.len, "blob", push_cert_sha1))
 586                        hashclr(push_cert_sha1);
 587
 588                memset(&sigcheck, '\0', sizeof(sigcheck));
 589                sigcheck.result = 'N';
 590
 591                bogs = parse_signature(push_cert.buf, push_cert.len);
 592                if (verify_signed_buffer(push_cert.buf, bogs,
 593                                         push_cert.buf + bogs, push_cert.len - bogs,
 594                                         &gpg_output, &gpg_status) < 0) {
 595                        ; /* error running gpg */
 596                } else {
 597                        sigcheck.payload = push_cert.buf;
 598                        sigcheck.gpg_output = gpg_output.buf;
 599                        sigcheck.gpg_status = gpg_status.buf;
 600                        parse_gpg_output(&sigcheck);
 601                }
 602
 603                strbuf_release(&gpg_output);
 604                strbuf_release(&gpg_status);
 605                nonce_status = check_nonce(push_cert.buf, bogs);
 606        }
 607        if (!is_null_sha1(push_cert_sha1)) {
 608                argv_array_pushf(&proc->env_array, "GIT_PUSH_CERT=%s",
 609                                 sha1_to_hex(push_cert_sha1));
 610                argv_array_pushf(&proc->env_array, "GIT_PUSH_CERT_SIGNER=%s",
 611                                 sigcheck.signer ? sigcheck.signer : "");
 612                argv_array_pushf(&proc->env_array, "GIT_PUSH_CERT_KEY=%s",
 613                                 sigcheck.key ? sigcheck.key : "");
 614                argv_array_pushf(&proc->env_array, "GIT_PUSH_CERT_STATUS=%c",
 615                                 sigcheck.result);
 616                if (push_cert_nonce) {
 617                        argv_array_pushf(&proc->env_array,
 618                                         "GIT_PUSH_CERT_NONCE=%s",
 619                                         push_cert_nonce);
 620                        argv_array_pushf(&proc->env_array,
 621                                         "GIT_PUSH_CERT_NONCE_STATUS=%s",
 622                                         nonce_status);
 623                        if (nonce_status == NONCE_SLOP)
 624                                argv_array_pushf(&proc->env_array,
 625                                                 "GIT_PUSH_CERT_NONCE_SLOP=%ld",
 626                                                 nonce_stamp_slop);
 627                }
 628        }
 629}
 630
 631struct receive_hook_feed_state {
 632        struct command *cmd;
 633        int skip_broken;
 634        struct strbuf buf;
 635        const struct string_list *push_options;
 636};
 637
 638typedef int (*feed_fn)(void *, const char **, size_t *);
 639static int run_and_feed_hook(const char *hook_name, feed_fn feed,
 640                             struct receive_hook_feed_state *feed_state)
 641{
 642        struct child_process proc = CHILD_PROCESS_INIT;
 643        struct async muxer;
 644        const char *argv[2];
 645        int code;
 646
 647        argv[0] = find_hook(hook_name);
 648        if (!argv[0])
 649                return 0;
 650
 651        argv[1] = NULL;
 652
 653        proc.argv = argv;
 654        proc.in = -1;
 655        proc.stdout_to_stderr = 1;
 656        if (feed_state->push_options) {
 657                int i;
 658                for (i = 0; i < feed_state->push_options->nr; i++)
 659                        argv_array_pushf(&proc.env_array,
 660                                "GIT_PUSH_OPTION_%d=%s", i,
 661                                feed_state->push_options->items[i].string);
 662                argv_array_pushf(&proc.env_array, "GIT_PUSH_OPTION_COUNT=%d",
 663                                 feed_state->push_options->nr);
 664        } else
 665                argv_array_pushf(&proc.env_array, "GIT_PUSH_OPTION_COUNT");
 666
 667        if (tmp_objdir)
 668                argv_array_pushv(&proc.env_array, tmp_objdir_env(tmp_objdir));
 669
 670        if (use_sideband) {
 671                memset(&muxer, 0, sizeof(muxer));
 672                muxer.proc = copy_to_sideband;
 673                muxer.in = -1;
 674                code = start_async(&muxer);
 675                if (code)
 676                        return code;
 677                proc.err = muxer.in;
 678        }
 679
 680        prepare_push_cert_sha1(&proc);
 681
 682        code = start_command(&proc);
 683        if (code) {
 684                if (use_sideband)
 685                        finish_async(&muxer);
 686                return code;
 687        }
 688
 689        sigchain_push(SIGPIPE, SIG_IGN);
 690
 691        while (1) {
 692                const char *buf;
 693                size_t n;
 694                if (feed(feed_state, &buf, &n))
 695                        break;
 696                if (write_in_full(proc.in, buf, n) != n)
 697                        break;
 698        }
 699        close(proc.in);
 700        if (use_sideband)
 701                finish_async(&muxer);
 702
 703        sigchain_pop(SIGPIPE);
 704
 705        return finish_command(&proc);
 706}
 707
 708static int feed_receive_hook(void *state_, const char **bufp, size_t *sizep)
 709{
 710        struct receive_hook_feed_state *state = state_;
 711        struct command *cmd = state->cmd;
 712
 713        while (cmd &&
 714               state->skip_broken && (cmd->error_string || cmd->did_not_exist))
 715                cmd = cmd->next;
 716        if (!cmd)
 717                return -1; /* EOF */
 718        strbuf_reset(&state->buf);
 719        strbuf_addf(&state->buf, "%s %s %s\n",
 720                    sha1_to_hex(cmd->old_sha1), sha1_to_hex(cmd->new_sha1),
 721                    cmd->ref_name);
 722        state->cmd = cmd->next;
 723        if (bufp) {
 724                *bufp = state->buf.buf;
 725                *sizep = state->buf.len;
 726        }
 727        return 0;
 728}
 729
 730static int run_receive_hook(struct command *commands,
 731                            const char *hook_name,
 732                            int skip_broken,
 733                            const struct string_list *push_options)
 734{
 735        struct receive_hook_feed_state state;
 736        int status;
 737
 738        strbuf_init(&state.buf, 0);
 739        state.cmd = commands;
 740        state.skip_broken = skip_broken;
 741        if (feed_receive_hook(&state, NULL, NULL))
 742                return 0;
 743        state.cmd = commands;
 744        state.push_options = push_options;
 745        status = run_and_feed_hook(hook_name, feed_receive_hook, &state);
 746        strbuf_release(&state.buf);
 747        return status;
 748}
 749
 750static int run_update_hook(struct command *cmd)
 751{
 752        const char *argv[5];
 753        struct child_process proc = CHILD_PROCESS_INIT;
 754        int code;
 755
 756        argv[0] = find_hook("update");
 757        if (!argv[0])
 758                return 0;
 759
 760        argv[1] = cmd->ref_name;
 761        argv[2] = sha1_to_hex(cmd->old_sha1);
 762        argv[3] = sha1_to_hex(cmd->new_sha1);
 763        argv[4] = NULL;
 764
 765        proc.no_stdin = 1;
 766        proc.stdout_to_stderr = 1;
 767        proc.err = use_sideband ? -1 : 0;
 768        proc.argv = argv;
 769        proc.env = tmp_objdir_env(tmp_objdir);
 770
 771        code = start_command(&proc);
 772        if (code)
 773                return code;
 774        if (use_sideband)
 775                copy_to_sideband(proc.err, -1, NULL);
 776        return finish_command(&proc);
 777}
 778
 779static int is_ref_checked_out(const char *ref)
 780{
 781        if (is_bare_repository())
 782                return 0;
 783
 784        if (!head_name)
 785                return 0;
 786        return !strcmp(head_name, ref);
 787}
 788
 789static char *refuse_unconfigured_deny_msg =
 790        N_("By default, updating the current branch in a non-bare repository\n"
 791           "is denied, because it will make the index and work tree inconsistent\n"
 792           "with what you pushed, and will require 'git reset --hard' to match\n"
 793           "the work tree to HEAD.\n"
 794           "\n"
 795           "You can set the 'receive.denyCurrentBranch' configuration variable\n"
 796           "to 'ignore' or 'warn' in the remote repository to allow pushing into\n"
 797           "its current branch; however, this is not recommended unless you\n"
 798           "arranged to update its work tree to match what you pushed in some\n"
 799           "other way.\n"
 800           "\n"
 801           "To squelch this message and still keep the default behaviour, set\n"
 802           "'receive.denyCurrentBranch' configuration variable to 'refuse'.");
 803
 804static void refuse_unconfigured_deny(void)
 805{
 806        rp_error("%s", _(refuse_unconfigured_deny_msg));
 807}
 808
 809static char *refuse_unconfigured_deny_delete_current_msg =
 810        N_("By default, deleting the current branch is denied, because the next\n"
 811           "'git clone' won't result in any file checked out, causing confusion.\n"
 812           "\n"
 813           "You can set 'receive.denyDeleteCurrent' configuration variable to\n"
 814           "'warn' or 'ignore' in the remote repository to allow deleting the\n"
 815           "current branch, with or without a warning message.\n"
 816           "\n"
 817           "To squelch this message, you can set it to 'refuse'.");
 818
 819static void refuse_unconfigured_deny_delete_current(void)
 820{
 821        rp_error("%s", _(refuse_unconfigured_deny_delete_current_msg));
 822}
 823
 824static int command_singleton_iterator(void *cb_data, unsigned char sha1[20]);
 825static int update_shallow_ref(struct command *cmd, struct shallow_info *si)
 826{
 827        static struct lock_file shallow_lock;
 828        struct sha1_array extra = SHA1_ARRAY_INIT;
 829        struct check_connected_options opt = CHECK_CONNECTED_INIT;
 830        uint32_t mask = 1 << (cmd->index % 32);
 831        int i;
 832
 833        trace_printf_key(&trace_shallow,
 834                         "shallow: update_shallow_ref %s\n", cmd->ref_name);
 835        for (i = 0; i < si->shallow->nr; i++)
 836                if (si->used_shallow[i] &&
 837                    (si->used_shallow[i][cmd->index / 32] & mask) &&
 838                    !delayed_reachability_test(si, i))
 839                        sha1_array_append(&extra, si->shallow->sha1[i]);
 840
 841        opt.env = tmp_objdir_env(tmp_objdir);
 842        setup_alternate_shallow(&shallow_lock, &opt.shallow_file, &extra);
 843        if (check_connected(command_singleton_iterator, cmd, &opt)) {
 844                rollback_lock_file(&shallow_lock);
 845                sha1_array_clear(&extra);
 846                return -1;
 847        }
 848
 849        commit_lock_file(&shallow_lock);
 850
 851        /*
 852         * Make sure setup_alternate_shallow() for the next ref does
 853         * not lose these new roots..
 854         */
 855        for (i = 0; i < extra.nr; i++)
 856                register_shallow(extra.sha1[i]);
 857
 858        si->shallow_ref[cmd->index] = 0;
 859        sha1_array_clear(&extra);
 860        return 0;
 861}
 862
 863/*
 864 * NEEDSWORK: we should consolidate various implementions of "are we
 865 * on an unborn branch?" test into one, and make the unified one more
 866 * robust. !get_sha1() based check used here and elsewhere would not
 867 * allow us to tell an unborn branch from corrupt ref, for example.
 868 * For the purpose of fixing "deploy-to-update does not work when
 869 * pushing into an empty repository" issue, this should suffice for
 870 * now.
 871 */
 872static int head_has_history(void)
 873{
 874        unsigned char sha1[20];
 875
 876        return !get_sha1("HEAD", sha1);
 877}
 878
 879static const char *push_to_deploy(unsigned char *sha1,
 880                                  struct argv_array *env,
 881                                  const char *work_tree)
 882{
 883        const char *update_refresh[] = {
 884                "update-index", "-q", "--ignore-submodules", "--refresh", NULL
 885        };
 886        const char *diff_files[] = {
 887                "diff-files", "--quiet", "--ignore-submodules", "--", NULL
 888        };
 889        const char *diff_index[] = {
 890                "diff-index", "--quiet", "--cached", "--ignore-submodules",
 891                NULL, "--", NULL
 892        };
 893        const char *read_tree[] = {
 894                "read-tree", "-u", "-m", NULL, NULL
 895        };
 896        struct child_process child = CHILD_PROCESS_INIT;
 897
 898        child.argv = update_refresh;
 899        child.env = env->argv;
 900        child.dir = work_tree;
 901        child.no_stdin = 1;
 902        child.stdout_to_stderr = 1;
 903        child.git_cmd = 1;
 904        if (run_command(&child))
 905                return "Up-to-date check failed";
 906
 907        /* run_command() does not clean up completely; reinitialize */
 908        child_process_init(&child);
 909        child.argv = diff_files;
 910        child.env = env->argv;
 911        child.dir = work_tree;
 912        child.no_stdin = 1;
 913        child.stdout_to_stderr = 1;
 914        child.git_cmd = 1;
 915        if (run_command(&child))
 916                return "Working directory has unstaged changes";
 917
 918        /* diff-index with either HEAD or an empty tree */
 919        diff_index[4] = head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX;
 920
 921        child_process_init(&child);
 922        child.argv = diff_index;
 923        child.env = env->argv;
 924        child.no_stdin = 1;
 925        child.no_stdout = 1;
 926        child.stdout_to_stderr = 0;
 927        child.git_cmd = 1;
 928        if (run_command(&child))
 929                return "Working directory has staged changes";
 930
 931        read_tree[3] = sha1_to_hex(sha1);
 932        child_process_init(&child);
 933        child.argv = read_tree;
 934        child.env = env->argv;
 935        child.dir = work_tree;
 936        child.no_stdin = 1;
 937        child.no_stdout = 1;
 938        child.stdout_to_stderr = 0;
 939        child.git_cmd = 1;
 940        if (run_command(&child))
 941                return "Could not update working tree to new HEAD";
 942
 943        return NULL;
 944}
 945
 946static const char *push_to_checkout_hook = "push-to-checkout";
 947
 948static const char *push_to_checkout(unsigned char *sha1,
 949                                    struct argv_array *env,
 950                                    const char *work_tree)
 951{
 952        argv_array_pushf(env, "GIT_WORK_TREE=%s", absolute_path(work_tree));
 953        if (run_hook_le(env->argv, push_to_checkout_hook,
 954                        sha1_to_hex(sha1), NULL))
 955                return "push-to-checkout hook declined";
 956        else
 957                return NULL;
 958}
 959
 960static const char *update_worktree(unsigned char *sha1)
 961{
 962        const char *retval;
 963        const char *work_tree = git_work_tree_cfg ? git_work_tree_cfg : "..";
 964        struct argv_array env = ARGV_ARRAY_INIT;
 965
 966        if (is_bare_repository())
 967                return "denyCurrentBranch = updateInstead needs a worktree";
 968
 969        argv_array_pushf(&env, "GIT_DIR=%s", absolute_path(get_git_dir()));
 970
 971        if (!find_hook(push_to_checkout_hook))
 972                retval = push_to_deploy(sha1, &env, work_tree);
 973        else
 974                retval = push_to_checkout(sha1, &env, work_tree);
 975
 976        argv_array_clear(&env);
 977        return retval;
 978}
 979
 980static const char *update(struct command *cmd, struct shallow_info *si)
 981{
 982        const char *name = cmd->ref_name;
 983        struct strbuf namespaced_name_buf = STRBUF_INIT;
 984        const char *namespaced_name, *ret;
 985        unsigned char *old_sha1 = cmd->old_sha1;
 986        unsigned char *new_sha1 = cmd->new_sha1;
 987
 988        /* only refs/... are allowed */
 989        if (!starts_with(name, "refs/") || check_refname_format(name + 5, 0)) {
 990                rp_error("refusing to create funny ref '%s' remotely", name);
 991                return "funny refname";
 992        }
 993
 994        strbuf_addf(&namespaced_name_buf, "%s%s", get_git_namespace(), name);
 995        namespaced_name = strbuf_detach(&namespaced_name_buf, NULL);
 996
 997        if (is_ref_checked_out(namespaced_name)) {
 998                switch (deny_current_branch) {
 999                case DENY_IGNORE:
1000                        break;
1001                case DENY_WARN:
1002                        rp_warning("updating the current branch");
1003                        break;
1004                case DENY_REFUSE:
1005                case DENY_UNCONFIGURED:
1006                        rp_error("refusing to update checked out branch: %s", name);
1007                        if (deny_current_branch == DENY_UNCONFIGURED)
1008                                refuse_unconfigured_deny();
1009                        return "branch is currently checked out";
1010                case DENY_UPDATE_INSTEAD:
1011                        ret = update_worktree(new_sha1);
1012                        if (ret)
1013                                return ret;
1014                        break;
1015                }
1016        }
1017
1018        if (!is_null_sha1(new_sha1) && !has_sha1_file(new_sha1)) {
1019                error("unpack should have generated %s, "
1020                      "but I can't find it!", sha1_to_hex(new_sha1));
1021                return "bad pack";
1022        }
1023
1024        if (!is_null_sha1(old_sha1) && is_null_sha1(new_sha1)) {
1025                if (deny_deletes && starts_with(name, "refs/heads/")) {
1026                        rp_error("denying ref deletion for %s", name);
1027                        return "deletion prohibited";
1028                }
1029
1030                if (head_name && !strcmp(namespaced_name, head_name)) {
1031                        switch (deny_delete_current) {
1032                        case DENY_IGNORE:
1033                                break;
1034                        case DENY_WARN:
1035                                rp_warning("deleting the current branch");
1036                                break;
1037                        case DENY_REFUSE:
1038                        case DENY_UNCONFIGURED:
1039                        case DENY_UPDATE_INSTEAD:
1040                                if (deny_delete_current == DENY_UNCONFIGURED)
1041                                        refuse_unconfigured_deny_delete_current();
1042                                rp_error("refusing to delete the current branch: %s", name);
1043                                return "deletion of the current branch prohibited";
1044                        default:
1045                                return "Invalid denyDeleteCurrent setting";
1046                        }
1047                }
1048        }
1049
1050        if (deny_non_fast_forwards && !is_null_sha1(new_sha1) &&
1051            !is_null_sha1(old_sha1) &&
1052            starts_with(name, "refs/heads/")) {
1053                struct object *old_object, *new_object;
1054                struct commit *old_commit, *new_commit;
1055
1056                old_object = parse_object(old_sha1);
1057                new_object = parse_object(new_sha1);
1058
1059                if (!old_object || !new_object ||
1060                    old_object->type != OBJ_COMMIT ||
1061                    new_object->type != OBJ_COMMIT) {
1062                        error("bad sha1 objects for %s", name);
1063                        return "bad ref";
1064                }
1065                old_commit = (struct commit *)old_object;
1066                new_commit = (struct commit *)new_object;
1067                if (!in_merge_bases(old_commit, new_commit)) {
1068                        rp_error("denying non-fast-forward %s"
1069                                 " (you should pull first)", name);
1070                        return "non-fast-forward";
1071                }
1072        }
1073        if (run_update_hook(cmd)) {
1074                rp_error("hook declined to update %s", name);
1075                return "hook declined";
1076        }
1077
1078        if (is_null_sha1(new_sha1)) {
1079                struct strbuf err = STRBUF_INIT;
1080                if (!parse_object(old_sha1)) {
1081                        old_sha1 = NULL;
1082                        if (ref_exists(name)) {
1083                                rp_warning("Allowing deletion of corrupt ref.");
1084                        } else {
1085                                rp_warning("Deleting a non-existent ref.");
1086                                cmd->did_not_exist = 1;
1087                        }
1088                }
1089                if (ref_transaction_delete(transaction,
1090                                           namespaced_name,
1091                                           old_sha1,
1092                                           0, "push", &err)) {
1093                        rp_error("%s", err.buf);
1094                        strbuf_release(&err);
1095                        return "failed to delete";
1096                }
1097                strbuf_release(&err);
1098                return NULL; /* good */
1099        }
1100        else {
1101                struct strbuf err = STRBUF_INIT;
1102                if (shallow_update && si->shallow_ref[cmd->index] &&
1103                    update_shallow_ref(cmd, si))
1104                        return "shallow error";
1105
1106                if (ref_transaction_update(transaction,
1107                                           namespaced_name,
1108                                           new_sha1, old_sha1,
1109                                           0, "push",
1110                                           &err)) {
1111                        rp_error("%s", err.buf);
1112                        strbuf_release(&err);
1113
1114                        return "failed to update ref";
1115                }
1116                strbuf_release(&err);
1117
1118                return NULL; /* good */
1119        }
1120}
1121
1122static void run_update_post_hook(struct command *commands)
1123{
1124        struct command *cmd;
1125        int argc;
1126        struct child_process proc = CHILD_PROCESS_INIT;
1127        const char *hook;
1128
1129        hook = find_hook("post-update");
1130        for (argc = 0, cmd = commands; cmd; cmd = cmd->next) {
1131                if (cmd->error_string || cmd->did_not_exist)
1132                        continue;
1133                argc++;
1134        }
1135        if (!argc || !hook)
1136                return;
1137
1138        argv_array_push(&proc.args, hook);
1139        for (cmd = commands; cmd; cmd = cmd->next) {
1140                if (cmd->error_string || cmd->did_not_exist)
1141                        continue;
1142                argv_array_push(&proc.args, cmd->ref_name);
1143        }
1144
1145        proc.no_stdin = 1;
1146        proc.stdout_to_stderr = 1;
1147        proc.err = use_sideband ? -1 : 0;
1148
1149        if (!start_command(&proc)) {
1150                if (use_sideband)
1151                        copy_to_sideband(proc.err, -1, NULL);
1152                finish_command(&proc);
1153        }
1154}
1155
1156static void check_aliased_update(struct command *cmd, struct string_list *list)
1157{
1158        struct strbuf buf = STRBUF_INIT;
1159        const char *dst_name;
1160        struct string_list_item *item;
1161        struct command *dst_cmd;
1162        unsigned char sha1[GIT_SHA1_RAWSZ];
1163        int flag;
1164
1165        strbuf_addf(&buf, "%s%s", get_git_namespace(), cmd->ref_name);
1166        dst_name = resolve_ref_unsafe(buf.buf, 0, sha1, &flag);
1167        strbuf_release(&buf);
1168
1169        if (!(flag & REF_ISSYMREF))
1170                return;
1171
1172        if (!dst_name) {
1173                rp_error("refusing update to broken symref '%s'", cmd->ref_name);
1174                cmd->skip_update = 1;
1175                cmd->error_string = "broken symref";
1176                return;
1177        }
1178        dst_name = strip_namespace(dst_name);
1179
1180        if ((item = string_list_lookup(list, dst_name)) == NULL)
1181                return;
1182
1183        cmd->skip_update = 1;
1184
1185        dst_cmd = (struct command *) item->util;
1186
1187        if (!hashcmp(cmd->old_sha1, dst_cmd->old_sha1) &&
1188            !hashcmp(cmd->new_sha1, dst_cmd->new_sha1))
1189                return;
1190
1191        dst_cmd->skip_update = 1;
1192
1193        rp_error("refusing inconsistent update between symref '%s' (%s..%s) and"
1194                 " its target '%s' (%s..%s)",
1195                 cmd->ref_name,
1196                 find_unique_abbrev(cmd->old_sha1, DEFAULT_ABBREV),
1197                 find_unique_abbrev(cmd->new_sha1, DEFAULT_ABBREV),
1198                 dst_cmd->ref_name,
1199                 find_unique_abbrev(dst_cmd->old_sha1, DEFAULT_ABBREV),
1200                 find_unique_abbrev(dst_cmd->new_sha1, DEFAULT_ABBREV));
1201
1202        cmd->error_string = dst_cmd->error_string =
1203                "inconsistent aliased update";
1204}
1205
1206static void check_aliased_updates(struct command *commands)
1207{
1208        struct command *cmd;
1209        struct string_list ref_list = STRING_LIST_INIT_NODUP;
1210
1211        for (cmd = commands; cmd; cmd = cmd->next) {
1212                struct string_list_item *item =
1213                        string_list_append(&ref_list, cmd->ref_name);
1214                item->util = (void *)cmd;
1215        }
1216        string_list_sort(&ref_list);
1217
1218        for (cmd = commands; cmd; cmd = cmd->next) {
1219                if (!cmd->error_string)
1220                        check_aliased_update(cmd, &ref_list);
1221        }
1222
1223        string_list_clear(&ref_list, 0);
1224}
1225
1226static int command_singleton_iterator(void *cb_data, unsigned char sha1[20])
1227{
1228        struct command **cmd_list = cb_data;
1229        struct command *cmd = *cmd_list;
1230
1231        if (!cmd || is_null_sha1(cmd->new_sha1))
1232                return -1; /* end of list */
1233        *cmd_list = NULL; /* this returns only one */
1234        hashcpy(sha1, cmd->new_sha1);
1235        return 0;
1236}
1237
1238static void set_connectivity_errors(struct command *commands,
1239                                    struct shallow_info *si)
1240{
1241        struct command *cmd;
1242
1243        for (cmd = commands; cmd; cmd = cmd->next) {
1244                struct command *singleton = cmd;
1245                struct check_connected_options opt = CHECK_CONNECTED_INIT;
1246
1247                if (shallow_update && si->shallow_ref[cmd->index])
1248                        /* to be checked in update_shallow_ref() */
1249                        continue;
1250
1251                opt.env = tmp_objdir_env(tmp_objdir);
1252                if (!check_connected(command_singleton_iterator, &singleton,
1253                                     &opt))
1254                        continue;
1255
1256                cmd->error_string = "missing necessary objects";
1257        }
1258}
1259
1260struct iterate_data {
1261        struct command *cmds;
1262        struct shallow_info *si;
1263};
1264
1265static int iterate_receive_command_list(void *cb_data, unsigned char sha1[20])
1266{
1267        struct iterate_data *data = cb_data;
1268        struct command **cmd_list = &data->cmds;
1269        struct command *cmd = *cmd_list;
1270
1271        for (; cmd; cmd = cmd->next) {
1272                if (shallow_update && data->si->shallow_ref[cmd->index])
1273                        /* to be checked in update_shallow_ref() */
1274                        continue;
1275                if (!is_null_sha1(cmd->new_sha1) && !cmd->skip_update) {
1276                        hashcpy(sha1, cmd->new_sha1);
1277                        *cmd_list = cmd->next;
1278                        return 0;
1279                }
1280        }
1281        *cmd_list = NULL;
1282        return -1; /* end of list */
1283}
1284
1285static void reject_updates_to_hidden(struct command *commands)
1286{
1287        struct strbuf refname_full = STRBUF_INIT;
1288        size_t prefix_len;
1289        struct command *cmd;
1290
1291        strbuf_addstr(&refname_full, get_git_namespace());
1292        prefix_len = refname_full.len;
1293
1294        for (cmd = commands; cmd; cmd = cmd->next) {
1295                if (cmd->error_string)
1296                        continue;
1297
1298                strbuf_setlen(&refname_full, prefix_len);
1299                strbuf_addstr(&refname_full, cmd->ref_name);
1300
1301                if (!ref_is_hidden(cmd->ref_name, refname_full.buf))
1302                        continue;
1303                if (is_null_sha1(cmd->new_sha1))
1304                        cmd->error_string = "deny deleting a hidden ref";
1305                else
1306                        cmd->error_string = "deny updating a hidden ref";
1307        }
1308
1309        strbuf_release(&refname_full);
1310}
1311
1312static int should_process_cmd(struct command *cmd)
1313{
1314        return !cmd->error_string && !cmd->skip_update;
1315}
1316
1317static void warn_if_skipped_connectivity_check(struct command *commands,
1318                                               struct shallow_info *si)
1319{
1320        struct command *cmd;
1321        int checked_connectivity = 1;
1322
1323        for (cmd = commands; cmd; cmd = cmd->next) {
1324                if (should_process_cmd(cmd) && si->shallow_ref[cmd->index]) {
1325                        error("BUG: connectivity check has not been run on ref %s",
1326                              cmd->ref_name);
1327                        checked_connectivity = 0;
1328                }
1329        }
1330        if (!checked_connectivity)
1331                die("BUG: connectivity check skipped???");
1332}
1333
1334static void execute_commands_non_atomic(struct command *commands,
1335                                        struct shallow_info *si)
1336{
1337        struct command *cmd;
1338        struct strbuf err = STRBUF_INIT;
1339
1340        for (cmd = commands; cmd; cmd = cmd->next) {
1341                if (!should_process_cmd(cmd))
1342                        continue;
1343
1344                transaction = ref_transaction_begin(&err);
1345                if (!transaction) {
1346                        rp_error("%s", err.buf);
1347                        strbuf_reset(&err);
1348                        cmd->error_string = "transaction failed to start";
1349                        continue;
1350                }
1351
1352                cmd->error_string = update(cmd, si);
1353
1354                if (!cmd->error_string
1355                    && ref_transaction_commit(transaction, &err)) {
1356                        rp_error("%s", err.buf);
1357                        strbuf_reset(&err);
1358                        cmd->error_string = "failed to update ref";
1359                }
1360                ref_transaction_free(transaction);
1361        }
1362        strbuf_release(&err);
1363}
1364
1365static void execute_commands_atomic(struct command *commands,
1366                                        struct shallow_info *si)
1367{
1368        struct command *cmd;
1369        struct strbuf err = STRBUF_INIT;
1370        const char *reported_error = "atomic push failure";
1371
1372        transaction = ref_transaction_begin(&err);
1373        if (!transaction) {
1374                rp_error("%s", err.buf);
1375                strbuf_reset(&err);
1376                reported_error = "transaction failed to start";
1377                goto failure;
1378        }
1379
1380        for (cmd = commands; cmd; cmd = cmd->next) {
1381                if (!should_process_cmd(cmd))
1382                        continue;
1383
1384                cmd->error_string = update(cmd, si);
1385
1386                if (cmd->error_string)
1387                        goto failure;
1388        }
1389
1390        if (ref_transaction_commit(transaction, &err)) {
1391                rp_error("%s", err.buf);
1392                reported_error = "atomic transaction failed";
1393                goto failure;
1394        }
1395        goto cleanup;
1396
1397failure:
1398        for (cmd = commands; cmd; cmd = cmd->next)
1399                if (!cmd->error_string)
1400                        cmd->error_string = reported_error;
1401
1402cleanup:
1403        ref_transaction_free(transaction);
1404        strbuf_release(&err);
1405}
1406
1407static void execute_commands(struct command *commands,
1408                             const char *unpacker_error,
1409                             struct shallow_info *si,
1410                             const struct string_list *push_options)
1411{
1412        struct check_connected_options opt = CHECK_CONNECTED_INIT;
1413        struct command *cmd;
1414        unsigned char sha1[20];
1415        struct iterate_data data;
1416        struct async muxer;
1417        int err_fd = 0;
1418
1419        if (unpacker_error) {
1420                for (cmd = commands; cmd; cmd = cmd->next)
1421                        cmd->error_string = "unpacker error";
1422                return;
1423        }
1424
1425        if (use_sideband) {
1426                memset(&muxer, 0, sizeof(muxer));
1427                muxer.proc = copy_to_sideband;
1428                muxer.in = -1;
1429                if (!start_async(&muxer))
1430                        err_fd = muxer.in;
1431                /* ...else, continue without relaying sideband */
1432        }
1433
1434        data.cmds = commands;
1435        data.si = si;
1436        opt.err_fd = err_fd;
1437        opt.progress = err_fd && !quiet;
1438        opt.env = tmp_objdir_env(tmp_objdir);
1439        if (check_connected(iterate_receive_command_list, &data, &opt))
1440                set_connectivity_errors(commands, si);
1441
1442        if (use_sideband)
1443                finish_async(&muxer);
1444
1445        reject_updates_to_hidden(commands);
1446
1447        if (run_receive_hook(commands, "pre-receive", 0, push_options)) {
1448                for (cmd = commands; cmd; cmd = cmd->next) {
1449                        if (!cmd->error_string)
1450                                cmd->error_string = "pre-receive hook declined";
1451                }
1452                return;
1453        }
1454
1455        /*
1456         * Now we'll start writing out refs, which means the objects need
1457         * to be in their final positions so that other processes can see them.
1458         */
1459        if (tmp_objdir_migrate(tmp_objdir) < 0) {
1460                for (cmd = commands; cmd; cmd = cmd->next) {
1461                        if (!cmd->error_string)
1462                                cmd->error_string = "unable to migrate objects to permanent storage";
1463                }
1464                return;
1465        }
1466        tmp_objdir = NULL;
1467
1468        check_aliased_updates(commands);
1469
1470        free(head_name_to_free);
1471        head_name = head_name_to_free = resolve_refdup("HEAD", 0, sha1, NULL);
1472
1473        if (use_atomic)
1474                execute_commands_atomic(commands, si);
1475        else
1476                execute_commands_non_atomic(commands, si);
1477
1478        if (shallow_update)
1479                warn_if_skipped_connectivity_check(commands, si);
1480}
1481
1482static struct command **queue_command(struct command **tail,
1483                                      const char *line,
1484                                      int linelen)
1485{
1486        unsigned char old_sha1[20], new_sha1[20];
1487        struct command *cmd;
1488        const char *refname;
1489        int reflen;
1490
1491        if (linelen < 83 ||
1492            line[40] != ' ' ||
1493            line[81] != ' ' ||
1494            get_sha1_hex(line, old_sha1) ||
1495            get_sha1_hex(line + 41, new_sha1))
1496                die("protocol error: expected old/new/ref, got '%s'", line);
1497
1498        refname = line + 82;
1499        reflen = linelen - 82;
1500        FLEX_ALLOC_MEM(cmd, ref_name, refname, reflen);
1501        hashcpy(cmd->old_sha1, old_sha1);
1502        hashcpy(cmd->new_sha1, new_sha1);
1503        *tail = cmd;
1504        return &cmd->next;
1505}
1506
1507static void queue_commands_from_cert(struct command **tail,
1508                                     struct strbuf *push_cert)
1509{
1510        const char *boc, *eoc;
1511
1512        if (*tail)
1513                die("protocol error: got both push certificate and unsigned commands");
1514
1515        boc = strstr(push_cert->buf, "\n\n");
1516        if (!boc)
1517                die("malformed push certificate %.*s", 100, push_cert->buf);
1518        else
1519                boc += 2;
1520        eoc = push_cert->buf + parse_signature(push_cert->buf, push_cert->len);
1521
1522        while (boc < eoc) {
1523                const char *eol = memchr(boc, '\n', eoc - boc);
1524                tail = queue_command(tail, boc, eol ? eol - boc : eoc - eol);
1525                boc = eol ? eol + 1 : eoc;
1526        }
1527}
1528
1529static struct command *read_head_info(struct sha1_array *shallow)
1530{
1531        struct command *commands = NULL;
1532        struct command **p = &commands;
1533        for (;;) {
1534                char *line;
1535                int len, linelen;
1536
1537                line = packet_read_line(0, &len);
1538                if (!line)
1539                        break;
1540
1541                if (len == 48 && starts_with(line, "shallow ")) {
1542                        unsigned char sha1[20];
1543                        if (get_sha1_hex(line + 8, sha1))
1544                                die("protocol error: expected shallow sha, got '%s'",
1545                                    line + 8);
1546                        sha1_array_append(shallow, sha1);
1547                        continue;
1548                }
1549
1550                linelen = strlen(line);
1551                if (linelen < len) {
1552                        const char *feature_list = line + linelen + 1;
1553                        if (parse_feature_request(feature_list, "report-status"))
1554                                report_status = 1;
1555                        if (parse_feature_request(feature_list, "side-band-64k"))
1556                                use_sideband = LARGE_PACKET_MAX;
1557                        if (parse_feature_request(feature_list, "quiet"))
1558                                quiet = 1;
1559                        if (advertise_atomic_push
1560                            && parse_feature_request(feature_list, "atomic"))
1561                                use_atomic = 1;
1562                        if (advertise_push_options
1563                            && parse_feature_request(feature_list, "push-options"))
1564                                use_push_options = 1;
1565                }
1566
1567                if (!strcmp(line, "push-cert")) {
1568                        int true_flush = 0;
1569                        char certbuf[1024];
1570
1571                        for (;;) {
1572                                len = packet_read(0, NULL, NULL,
1573                                                  certbuf, sizeof(certbuf), 0);
1574                                if (!len) {
1575                                        true_flush = 1;
1576                                        break;
1577                                }
1578                                if (!strcmp(certbuf, "push-cert-end\n"))
1579                                        break; /* end of cert */
1580                                strbuf_addstr(&push_cert, certbuf);
1581                        }
1582
1583                        if (true_flush)
1584                                break;
1585                        continue;
1586                }
1587
1588                p = queue_command(p, line, linelen);
1589        }
1590
1591        if (push_cert.len)
1592                queue_commands_from_cert(p, &push_cert);
1593
1594        return commands;
1595}
1596
1597static void read_push_options(struct string_list *options)
1598{
1599        while (1) {
1600                char *line;
1601                int len;
1602
1603                line = packet_read_line(0, &len);
1604
1605                if (!line)
1606                        break;
1607
1608                string_list_append(options, line);
1609        }
1610}
1611
1612static const char *parse_pack_header(struct pack_header *hdr)
1613{
1614        switch (read_pack_header(0, hdr)) {
1615        case PH_ERROR_EOF:
1616                return "eof before pack header was fully read";
1617
1618        case PH_ERROR_PACK_SIGNATURE:
1619                return "protocol error (pack signature mismatch detected)";
1620
1621        case PH_ERROR_PROTOCOL:
1622                return "protocol error (pack version unsupported)";
1623
1624        default:
1625                return "unknown error in parse_pack_header";
1626
1627        case 0:
1628                return NULL;
1629        }
1630}
1631
1632static const char *pack_lockfile;
1633
1634static const char *unpack(int err_fd, struct shallow_info *si)
1635{
1636        struct pack_header hdr;
1637        const char *hdr_err;
1638        int status;
1639        char hdr_arg[38];
1640        struct child_process child = CHILD_PROCESS_INIT;
1641        int fsck_objects = (receive_fsck_objects >= 0
1642                            ? receive_fsck_objects
1643                            : transfer_fsck_objects >= 0
1644                            ? transfer_fsck_objects
1645                            : 0);
1646
1647        hdr_err = parse_pack_header(&hdr);
1648        if (hdr_err) {
1649                if (err_fd > 0)
1650                        close(err_fd);
1651                return hdr_err;
1652        }
1653        snprintf(hdr_arg, sizeof(hdr_arg),
1654                        "--pack_header=%"PRIu32",%"PRIu32,
1655                        ntohl(hdr.hdr_version), ntohl(hdr.hdr_entries));
1656
1657        if (si->nr_ours || si->nr_theirs) {
1658                alt_shallow_file = setup_temporary_shallow(si->shallow);
1659                argv_array_push(&child.args, "--shallow-file");
1660                argv_array_push(&child.args, alt_shallow_file);
1661        }
1662
1663        tmp_objdir = tmp_objdir_create();
1664        if (!tmp_objdir)
1665                return "unable to create temporary object directory";
1666        child.env = tmp_objdir_env(tmp_objdir);
1667
1668        /*
1669         * Normally we just pass the tmp_objdir environment to the child
1670         * processes that do the heavy lifting, but we may need to see these
1671         * objects ourselves to set up shallow information.
1672         */
1673        tmp_objdir_add_as_alternate(tmp_objdir);
1674
1675        if (ntohl(hdr.hdr_entries) < unpack_limit) {
1676                argv_array_pushl(&child.args, "unpack-objects", hdr_arg, NULL);
1677                if (quiet)
1678                        argv_array_push(&child.args, "-q");
1679                if (fsck_objects)
1680                        argv_array_pushf(&child.args, "--strict%s",
1681                                fsck_msg_types.buf);
1682                if (max_input_size)
1683                        argv_array_pushf(&child.args, "--max-input-size=%"PRIuMAX,
1684                                (uintmax_t)max_input_size);
1685                child.no_stdout = 1;
1686                child.err = err_fd;
1687                child.git_cmd = 1;
1688                status = run_command(&child);
1689                if (status)
1690                        return "unpack-objects abnormal exit";
1691        } else {
1692                char hostname[256];
1693
1694                argv_array_pushl(&child.args, "index-pack",
1695                                 "--stdin", hdr_arg, NULL);
1696
1697                if (gethostname(hostname, sizeof(hostname)))
1698                        xsnprintf(hostname, sizeof(hostname), "localhost");
1699                argv_array_pushf(&child.args,
1700                                 "--keep=receive-pack %"PRIuMAX" on %s",
1701                                 (uintmax_t)getpid(),
1702                                 hostname);
1703
1704                if (!quiet && err_fd)
1705                        argv_array_push(&child.args, "--show-resolving-progress");
1706                if (use_sideband)
1707                        argv_array_push(&child.args, "--report-end-of-input");
1708                if (fsck_objects)
1709                        argv_array_pushf(&child.args, "--strict%s",
1710                                fsck_msg_types.buf);
1711                if (!reject_thin)
1712                        argv_array_push(&child.args, "--fix-thin");
1713                if (max_input_size)
1714                        argv_array_pushf(&child.args, "--max-input-size=%"PRIuMAX,
1715                                (uintmax_t)max_input_size);
1716                child.out = -1;
1717                child.err = err_fd;
1718                child.git_cmd = 1;
1719                status = start_command(&child);
1720                if (status)
1721                        return "index-pack fork failed";
1722                pack_lockfile = index_pack_lockfile(child.out);
1723                close(child.out);
1724                status = finish_command(&child);
1725                if (status)
1726                        return "index-pack abnormal exit";
1727                reprepare_packed_git();
1728        }
1729        return NULL;
1730}
1731
1732static const char *unpack_with_sideband(struct shallow_info *si)
1733{
1734        struct async muxer;
1735        const char *ret;
1736
1737        if (!use_sideband)
1738                return unpack(0, si);
1739
1740        use_keepalive = KEEPALIVE_AFTER_NUL;
1741        memset(&muxer, 0, sizeof(muxer));
1742        muxer.proc = copy_to_sideband;
1743        muxer.in = -1;
1744        if (start_async(&muxer))
1745                return NULL;
1746
1747        ret = unpack(muxer.in, si);
1748
1749        finish_async(&muxer);
1750        return ret;
1751}
1752
1753static void prepare_shallow_update(struct command *commands,
1754                                   struct shallow_info *si)
1755{
1756        int i, j, k, bitmap_size = (si->ref->nr + 31) / 32;
1757
1758        ALLOC_ARRAY(si->used_shallow, si->shallow->nr);
1759        assign_shallow_commits_to_refs(si, si->used_shallow, NULL);
1760
1761        si->need_reachability_test =
1762                xcalloc(si->shallow->nr, sizeof(*si->need_reachability_test));
1763        si->reachable =
1764                xcalloc(si->shallow->nr, sizeof(*si->reachable));
1765        si->shallow_ref = xcalloc(si->ref->nr, sizeof(*si->shallow_ref));
1766
1767        for (i = 0; i < si->nr_ours; i++)
1768                si->need_reachability_test[si->ours[i]] = 1;
1769
1770        for (i = 0; i < si->shallow->nr; i++) {
1771                if (!si->used_shallow[i])
1772                        continue;
1773                for (j = 0; j < bitmap_size; j++) {
1774                        if (!si->used_shallow[i][j])
1775                                continue;
1776                        si->need_reachability_test[i]++;
1777                        for (k = 0; k < 32; k++)
1778                                if (si->used_shallow[i][j] & (1U << k))
1779                                        si->shallow_ref[j * 32 + k]++;
1780                }
1781
1782                /*
1783                 * true for those associated with some refs and belong
1784                 * in "ours" list aka "step 7 not done yet"
1785                 */
1786                si->need_reachability_test[i] =
1787                        si->need_reachability_test[i] > 1;
1788        }
1789
1790        /*
1791         * keep hooks happy by forcing a temporary shallow file via
1792         * env variable because we can't add --shallow-file to every
1793         * command. check_everything_connected() will be done with
1794         * true .git/shallow though.
1795         */
1796        setenv(GIT_SHALLOW_FILE_ENVIRONMENT, alt_shallow_file, 1);
1797}
1798
1799static void update_shallow_info(struct command *commands,
1800                                struct shallow_info *si,
1801                                struct sha1_array *ref)
1802{
1803        struct command *cmd;
1804        int *ref_status;
1805        remove_nonexistent_theirs_shallow(si);
1806        if (!si->nr_ours && !si->nr_theirs) {
1807                shallow_update = 0;
1808                return;
1809        }
1810
1811        for (cmd = commands; cmd; cmd = cmd->next) {
1812                if (is_null_sha1(cmd->new_sha1))
1813                        continue;
1814                sha1_array_append(ref, cmd->new_sha1);
1815                cmd->index = ref->nr - 1;
1816        }
1817        si->ref = ref;
1818
1819        if (shallow_update) {
1820                prepare_shallow_update(commands, si);
1821                return;
1822        }
1823
1824        ALLOC_ARRAY(ref_status, ref->nr);
1825        assign_shallow_commits_to_refs(si, NULL, ref_status);
1826        for (cmd = commands; cmd; cmd = cmd->next) {
1827                if (is_null_sha1(cmd->new_sha1))
1828                        continue;
1829                if (ref_status[cmd->index]) {
1830                        cmd->error_string = "shallow update not allowed";
1831                        cmd->skip_update = 1;
1832                }
1833        }
1834        free(ref_status);
1835}
1836
1837static void report(struct command *commands, const char *unpack_status)
1838{
1839        struct command *cmd;
1840        struct strbuf buf = STRBUF_INIT;
1841
1842        packet_buf_write(&buf, "unpack %s\n",
1843                         unpack_status ? unpack_status : "ok");
1844        for (cmd = commands; cmd; cmd = cmd->next) {
1845                if (!cmd->error_string)
1846                        packet_buf_write(&buf, "ok %s\n",
1847                                         cmd->ref_name);
1848                else
1849                        packet_buf_write(&buf, "ng %s %s\n",
1850                                         cmd->ref_name, cmd->error_string);
1851        }
1852        packet_buf_flush(&buf);
1853
1854        if (use_sideband)
1855                send_sideband(1, 1, buf.buf, buf.len, use_sideband);
1856        else
1857                write_or_die(1, buf.buf, buf.len);
1858        strbuf_release(&buf);
1859}
1860
1861static int delete_only(struct command *commands)
1862{
1863        struct command *cmd;
1864        for (cmd = commands; cmd; cmd = cmd->next) {
1865                if (!is_null_sha1(cmd->new_sha1))
1866                        return 0;
1867        }
1868        return 1;
1869}
1870
1871int cmd_receive_pack(int argc, const char **argv, const char *prefix)
1872{
1873        int advertise_refs = 0;
1874        struct command *commands;
1875        struct sha1_array shallow = SHA1_ARRAY_INIT;
1876        struct sha1_array ref = SHA1_ARRAY_INIT;
1877        struct shallow_info si;
1878
1879        struct option options[] = {
1880                OPT__QUIET(&quiet, N_("quiet")),
1881                OPT_HIDDEN_BOOL(0, "stateless-rpc", &stateless_rpc, NULL),
1882                OPT_HIDDEN_BOOL(0, "advertise-refs", &advertise_refs, NULL),
1883                OPT_HIDDEN_BOOL(0, "reject-thin-pack-for-testing", &reject_thin, NULL),
1884                OPT_END()
1885        };
1886
1887        packet_trace_identity("receive-pack");
1888
1889        argc = parse_options(argc, argv, prefix, options, receive_pack_usage, 0);
1890
1891        if (argc > 1)
1892                usage_msg_opt(_("Too many arguments."), receive_pack_usage, options);
1893        if (argc == 0)
1894                usage_msg_opt(_("You must specify a directory."), receive_pack_usage, options);
1895
1896        service_dir = argv[0];
1897
1898        setup_path();
1899
1900        if (!enter_repo(service_dir, 0))
1901                die("'%s' does not appear to be a git repository", service_dir);
1902
1903        git_config(receive_pack_config, NULL);
1904        if (cert_nonce_seed)
1905                push_cert_nonce = prepare_push_cert_nonce(service_dir, time(NULL));
1906
1907        if (0 <= transfer_unpack_limit)
1908                unpack_limit = transfer_unpack_limit;
1909        else if (0 <= receive_unpack_limit)
1910                unpack_limit = receive_unpack_limit;
1911
1912        if (advertise_refs || !stateless_rpc) {
1913                write_head_info();
1914        }
1915        if (advertise_refs)
1916                return 0;
1917
1918        if ((commands = read_head_info(&shallow)) != NULL) {
1919                const char *unpack_status = NULL;
1920                struct string_list push_options = STRING_LIST_INIT_DUP;
1921
1922                if (use_push_options)
1923                        read_push_options(&push_options);
1924
1925                prepare_shallow_info(&si, &shallow);
1926                if (!si.nr_ours && !si.nr_theirs)
1927                        shallow_update = 0;
1928                if (!delete_only(commands)) {
1929                        unpack_status = unpack_with_sideband(&si);
1930                        update_shallow_info(commands, &si, &ref);
1931                }
1932                use_keepalive = KEEPALIVE_ALWAYS;
1933                execute_commands(commands, unpack_status, &si,
1934                                 &push_options);
1935                if (pack_lockfile)
1936                        unlink_or_warn(pack_lockfile);
1937                if (report_status)
1938                        report(commands, unpack_status);
1939                run_receive_hook(commands, "post-receive", 1,
1940                                 &push_options);
1941                run_update_post_hook(commands);
1942                string_list_clear(&push_options, 0);
1943                if (auto_gc) {
1944                        const char *argv_gc_auto[] = {
1945                                "gc", "--auto", "--quiet", NULL,
1946                        };
1947                        struct child_process proc = CHILD_PROCESS_INIT;
1948
1949                        proc.no_stdin = 1;
1950                        proc.stdout_to_stderr = 1;
1951                        proc.err = use_sideband ? -1 : 0;
1952                        proc.git_cmd = 1;
1953                        proc.argv = argv_gc_auto;
1954
1955                        close_all_packs();
1956                        if (!start_command(&proc)) {
1957                                if (use_sideband)
1958                                        copy_to_sideband(proc.err, -1, NULL);
1959                                finish_command(&proc);
1960                        }
1961                }
1962                if (auto_update_server_info)
1963                        update_server_info(0);
1964                clear_shallow_info(&si);
1965        }
1966        if (use_sideband)
1967                packet_flush(1);
1968        sha1_array_clear(&shallow);
1969        sha1_array_clear(&ref);
1970        free((void *)push_cert_nonce);
1971        return 0;
1972}