upload-pack.con commit Merge branch 'kw/write-index-reduce-alloc' (d085f97)
   1#include "cache.h"
   2#include "config.h"
   3#include "refs.h"
   4#include "pkt-line.h"
   5#include "sideband.h"
   6#include "tag.h"
   7#include "object.h"
   8#include "commit.h"
   9#include "exec_cmd.h"
  10#include "diff.h"
  11#include "revision.h"
  12#include "list-objects.h"
  13#include "run-command.h"
  14#include "connect.h"
  15#include "sigchain.h"
  16#include "version.h"
  17#include "string-list.h"
  18#include "parse-options.h"
  19#include "argv-array.h"
  20#include "prio-queue.h"
  21
  22static const char * const upload_pack_usage[] = {
  23        N_("git upload-pack [<options>] <dir>"),
  24        NULL
  25};
  26
  27/* Remember to update object flag allocation in object.h */
  28#define THEY_HAVE       (1u << 11)
  29#define OUR_REF         (1u << 12)
  30#define WANTED          (1u << 13)
  31#define COMMON_KNOWN    (1u << 14)
  32#define REACHABLE       (1u << 15)
  33
  34#define SHALLOW         (1u << 16)
  35#define NOT_SHALLOW     (1u << 17)
  36#define CLIENT_SHALLOW  (1u << 18)
  37#define HIDDEN_REF      (1u << 19)
  38
  39static timestamp_t oldest_have;
  40
  41static int deepen_relative;
  42static int multi_ack;
  43static int no_done;
  44static int use_thin_pack, use_ofs_delta, use_include_tag;
  45static int no_progress, daemon_mode;
  46/* Allow specifying sha1 if it is a ref tip. */
  47#define ALLOW_TIP_SHA1  01
  48/* Allow request of a sha1 if it is reachable from a ref (possibly hidden ref). */
  49#define ALLOW_REACHABLE_SHA1    02
  50/* Allow request of any sha1. Implies ALLOW_TIP_SHA1 and ALLOW_REACHABLE_SHA1. */
  51#define ALLOW_ANY_SHA1  07
  52static unsigned int allow_unadvertised_object_request;
  53static int shallow_nr;
  54static struct object_array have_obj;
  55static struct object_array want_obj;
  56static struct object_array extra_edge_obj;
  57static unsigned int timeout;
  58static int keepalive = 5;
  59/* 0 for no sideband,
  60 * otherwise maximum packet size (up to 65520 bytes).
  61 */
  62static int use_sideband;
  63static int advertise_refs;
  64static int stateless_rpc;
  65static const char *pack_objects_hook;
  66
  67static void reset_timeout(void)
  68{
  69        alarm(timeout);
  70}
  71
  72static void send_client_data(int fd, const char *data, ssize_t sz)
  73{
  74        if (use_sideband) {
  75                send_sideband(1, fd, data, sz, use_sideband);
  76                return;
  77        }
  78        if (fd == 3)
  79                /* emergency quit */
  80                fd = 2;
  81        if (fd == 2) {
  82                /* XXX: are we happy to lose stuff here? */
  83                xwrite(fd, data, sz);
  84                return;
  85        }
  86        write_or_die(fd, data, sz);
  87}
  88
  89static int write_one_shallow(const struct commit_graft *graft, void *cb_data)
  90{
  91        FILE *fp = cb_data;
  92        if (graft->nr_parent == -1)
  93                fprintf(fp, "--shallow %s\n", oid_to_hex(&graft->oid));
  94        return 0;
  95}
  96
  97static void create_pack_file(void)
  98{
  99        struct child_process pack_objects = CHILD_PROCESS_INIT;
 100        char data[8193], progress[128];
 101        char abort_msg[] = "aborting due to possible repository "
 102                "corruption on the remote side.";
 103        int buffered = -1;
 104        ssize_t sz;
 105        int i;
 106        FILE *pipe_fd;
 107
 108        if (!pack_objects_hook)
 109                pack_objects.git_cmd = 1;
 110        else {
 111                argv_array_push(&pack_objects.args, pack_objects_hook);
 112                argv_array_push(&pack_objects.args, "git");
 113                pack_objects.use_shell = 1;
 114        }
 115
 116        if (shallow_nr) {
 117                argv_array_push(&pack_objects.args, "--shallow-file");
 118                argv_array_push(&pack_objects.args, "");
 119        }
 120        argv_array_push(&pack_objects.args, "pack-objects");
 121        argv_array_push(&pack_objects.args, "--revs");
 122        if (use_thin_pack)
 123                argv_array_push(&pack_objects.args, "--thin");
 124
 125        argv_array_push(&pack_objects.args, "--stdout");
 126        if (shallow_nr)
 127                argv_array_push(&pack_objects.args, "--shallow");
 128        if (!no_progress)
 129                argv_array_push(&pack_objects.args, "--progress");
 130        if (use_ofs_delta)
 131                argv_array_push(&pack_objects.args, "--delta-base-offset");
 132        if (use_include_tag)
 133                argv_array_push(&pack_objects.args, "--include-tag");
 134
 135        pack_objects.in = -1;
 136        pack_objects.out = -1;
 137        pack_objects.err = -1;
 138
 139        if (start_command(&pack_objects))
 140                die("git upload-pack: unable to fork git-pack-objects");
 141
 142        pipe_fd = xfdopen(pack_objects.in, "w");
 143
 144        if (shallow_nr)
 145                for_each_commit_graft(write_one_shallow, pipe_fd);
 146
 147        for (i = 0; i < want_obj.nr; i++)
 148                fprintf(pipe_fd, "%s\n",
 149                        oid_to_hex(&want_obj.objects[i].item->oid));
 150        fprintf(pipe_fd, "--not\n");
 151        for (i = 0; i < have_obj.nr; i++)
 152                fprintf(pipe_fd, "%s\n",
 153                        oid_to_hex(&have_obj.objects[i].item->oid));
 154        for (i = 0; i < extra_edge_obj.nr; i++)
 155                fprintf(pipe_fd, "%s\n",
 156                        oid_to_hex(&extra_edge_obj.objects[i].item->oid));
 157        fprintf(pipe_fd, "\n");
 158        fflush(pipe_fd);
 159        fclose(pipe_fd);
 160
 161        /* We read from pack_objects.err to capture stderr output for
 162         * progress bar, and pack_objects.out to capture the pack data.
 163         */
 164
 165        while (1) {
 166                struct pollfd pfd[2];
 167                int pe, pu, pollsize;
 168                int ret;
 169
 170                reset_timeout();
 171
 172                pollsize = 0;
 173                pe = pu = -1;
 174
 175                if (0 <= pack_objects.out) {
 176                        pfd[pollsize].fd = pack_objects.out;
 177                        pfd[pollsize].events = POLLIN;
 178                        pu = pollsize;
 179                        pollsize++;
 180                }
 181                if (0 <= pack_objects.err) {
 182                        pfd[pollsize].fd = pack_objects.err;
 183                        pfd[pollsize].events = POLLIN;
 184                        pe = pollsize;
 185                        pollsize++;
 186                }
 187
 188                if (!pollsize)
 189                        break;
 190
 191                ret = poll(pfd, pollsize,
 192                        keepalive < 0 ? -1 : 1000 * keepalive);
 193
 194                if (ret < 0) {
 195                        if (errno != EINTR) {
 196                                error_errno("poll failed, resuming");
 197                                sleep(1);
 198                        }
 199                        continue;
 200                }
 201                if (0 <= pe && (pfd[pe].revents & (POLLIN|POLLHUP))) {
 202                        /* Status ready; we ship that in the side-band
 203                         * or dump to the standard error.
 204                         */
 205                        sz = xread(pack_objects.err, progress,
 206                                  sizeof(progress));
 207                        if (0 < sz)
 208                                send_client_data(2, progress, sz);
 209                        else if (sz == 0) {
 210                                close(pack_objects.err);
 211                                pack_objects.err = -1;
 212                        }
 213                        else
 214                                goto fail;
 215                        /* give priority to status messages */
 216                        continue;
 217                }
 218                if (0 <= pu && (pfd[pu].revents & (POLLIN|POLLHUP))) {
 219                        /* Data ready; we keep the last byte to ourselves
 220                         * in case we detect broken rev-list, so that we
 221                         * can leave the stream corrupted.  This is
 222                         * unfortunate -- unpack-objects would happily
 223                         * accept a valid packdata with trailing garbage,
 224                         * so appending garbage after we pass all the
 225                         * pack data is not good enough to signal
 226                         * breakage to downstream.
 227                         */
 228                        char *cp = data;
 229                        ssize_t outsz = 0;
 230                        if (0 <= buffered) {
 231                                *cp++ = buffered;
 232                                outsz++;
 233                        }
 234                        sz = xread(pack_objects.out, cp,
 235                                  sizeof(data) - outsz);
 236                        if (0 < sz)
 237                                ;
 238                        else if (sz == 0) {
 239                                close(pack_objects.out);
 240                                pack_objects.out = -1;
 241                        }
 242                        else
 243                                goto fail;
 244                        sz += outsz;
 245                        if (1 < sz) {
 246                                buffered = data[sz-1] & 0xFF;
 247                                sz--;
 248                        }
 249                        else
 250                                buffered = -1;
 251                        send_client_data(1, data, sz);
 252                }
 253
 254                /*
 255                 * We hit the keepalive timeout without saying anything; send
 256                 * an empty message on the data sideband just to let the other
 257                 * side know we're still working on it, but don't have any data
 258                 * yet.
 259                 *
 260                 * If we don't have a sideband channel, there's no room in the
 261                 * protocol to say anything, so those clients are just out of
 262                 * luck.
 263                 */
 264                if (!ret && use_sideband) {
 265                        static const char buf[] = "0005\1";
 266                        write_or_die(1, buf, 5);
 267                }
 268        }
 269
 270        if (finish_command(&pack_objects)) {
 271                error("git upload-pack: git-pack-objects died with error.");
 272                goto fail;
 273        }
 274
 275        /* flush the data */
 276        if (0 <= buffered) {
 277                data[0] = buffered;
 278                send_client_data(1, data, 1);
 279                fprintf(stderr, "flushed.\n");
 280        }
 281        if (use_sideband)
 282                packet_flush(1);
 283        return;
 284
 285 fail:
 286        send_client_data(3, abort_msg, sizeof(abort_msg));
 287        die("git upload-pack: %s", abort_msg);
 288}
 289
 290static int got_oid(const char *hex, struct object_id *oid)
 291{
 292        struct object *o;
 293        int we_knew_they_have = 0;
 294
 295        if (get_oid_hex(hex, oid))
 296                die("git upload-pack: expected SHA1 object, got '%s'", hex);
 297        if (!has_object_file(oid))
 298                return -1;
 299
 300        o = parse_object(oid);
 301        if (!o)
 302                die("oops (%s)", oid_to_hex(oid));
 303        if (o->type == OBJ_COMMIT) {
 304                struct commit_list *parents;
 305                struct commit *commit = (struct commit *)o;
 306                if (o->flags & THEY_HAVE)
 307                        we_knew_they_have = 1;
 308                else
 309                        o->flags |= THEY_HAVE;
 310                if (!oldest_have || (commit->date < oldest_have))
 311                        oldest_have = commit->date;
 312                for (parents = commit->parents;
 313                     parents;
 314                     parents = parents->next)
 315                        parents->item->object.flags |= THEY_HAVE;
 316        }
 317        if (!we_knew_they_have) {
 318                add_object_array(o, NULL, &have_obj);
 319                return 1;
 320        }
 321        return 0;
 322}
 323
 324static int reachable(struct commit *want)
 325{
 326        struct prio_queue work = { compare_commits_by_commit_date };
 327
 328        prio_queue_put(&work, want);
 329        while (work.nr) {
 330                struct commit_list *list;
 331                struct commit *commit = prio_queue_get(&work);
 332
 333                if (commit->object.flags & THEY_HAVE) {
 334                        want->object.flags |= COMMON_KNOWN;
 335                        break;
 336                }
 337                if (!commit->object.parsed)
 338                        parse_object(&commit->object.oid);
 339                if (commit->object.flags & REACHABLE)
 340                        continue;
 341                commit->object.flags |= REACHABLE;
 342                if (commit->date < oldest_have)
 343                        continue;
 344                for (list = commit->parents; list; list = list->next) {
 345                        struct commit *parent = list->item;
 346                        if (!(parent->object.flags & REACHABLE))
 347                                prio_queue_put(&work, parent);
 348                }
 349        }
 350        want->object.flags |= REACHABLE;
 351        clear_commit_marks(want, REACHABLE);
 352        clear_prio_queue(&work);
 353        return (want->object.flags & COMMON_KNOWN);
 354}
 355
 356static int ok_to_give_up(void)
 357{
 358        int i;
 359
 360        if (!have_obj.nr)
 361                return 0;
 362
 363        for (i = 0; i < want_obj.nr; i++) {
 364                struct object *want = want_obj.objects[i].item;
 365
 366                if (want->flags & COMMON_KNOWN)
 367                        continue;
 368                want = deref_tag(want, "a want line", 0);
 369                if (!want || want->type != OBJ_COMMIT) {
 370                        /* no way to tell if this is reachable by
 371                         * looking at the ancestry chain alone, so
 372                         * leave a note to ourselves not to worry about
 373                         * this object anymore.
 374                         */
 375                        want_obj.objects[i].item->flags |= COMMON_KNOWN;
 376                        continue;
 377                }
 378                if (!reachable((struct commit *)want))
 379                        return 0;
 380        }
 381        return 1;
 382}
 383
 384static int get_common_commits(void)
 385{
 386        struct object_id oid;
 387        char last_hex[GIT_MAX_HEXSZ + 1];
 388        int got_common = 0;
 389        int got_other = 0;
 390        int sent_ready = 0;
 391
 392        save_commit_buffer = 0;
 393
 394        for (;;) {
 395                char *line = packet_read_line(0, NULL);
 396                const char *arg;
 397
 398                reset_timeout();
 399
 400                if (!line) {
 401                        if (multi_ack == 2 && got_common
 402                            && !got_other && ok_to_give_up()) {
 403                                sent_ready = 1;
 404                                packet_write_fmt(1, "ACK %s ready\n", last_hex);
 405                        }
 406                        if (have_obj.nr == 0 || multi_ack)
 407                                packet_write_fmt(1, "NAK\n");
 408
 409                        if (no_done && sent_ready) {
 410                                packet_write_fmt(1, "ACK %s\n", last_hex);
 411                                return 0;
 412                        }
 413                        if (stateless_rpc)
 414                                exit(0);
 415                        got_common = 0;
 416                        got_other = 0;
 417                        continue;
 418                }
 419                if (skip_prefix(line, "have ", &arg)) {
 420                        switch (got_oid(arg, &oid)) {
 421                        case -1: /* they have what we do not */
 422                                got_other = 1;
 423                                if (multi_ack && ok_to_give_up()) {
 424                                        const char *hex = oid_to_hex(&oid);
 425                                        if (multi_ack == 2) {
 426                                                sent_ready = 1;
 427                                                packet_write_fmt(1, "ACK %s ready\n", hex);
 428                                        } else
 429                                                packet_write_fmt(1, "ACK %s continue\n", hex);
 430                                }
 431                                break;
 432                        default:
 433                                got_common = 1;
 434                                memcpy(last_hex, oid_to_hex(&oid), 41);
 435                                if (multi_ack == 2)
 436                                        packet_write_fmt(1, "ACK %s common\n", last_hex);
 437                                else if (multi_ack)
 438                                        packet_write_fmt(1, "ACK %s continue\n", last_hex);
 439                                else if (have_obj.nr == 1)
 440                                        packet_write_fmt(1, "ACK %s\n", last_hex);
 441                                break;
 442                        }
 443                        continue;
 444                }
 445                if (!strcmp(line, "done")) {
 446                        if (have_obj.nr > 0) {
 447                                if (multi_ack)
 448                                        packet_write_fmt(1, "ACK %s\n", last_hex);
 449                                return 0;
 450                        }
 451                        packet_write_fmt(1, "NAK\n");
 452                        return -1;
 453                }
 454                die("git upload-pack: expected SHA1 list, got '%s'", line);
 455        }
 456}
 457
 458static int is_our_ref(struct object *o)
 459{
 460        int allow_hidden_ref = (allow_unadvertised_object_request &
 461                        (ALLOW_TIP_SHA1 | ALLOW_REACHABLE_SHA1));
 462        return o->flags & ((allow_hidden_ref ? HIDDEN_REF : 0) | OUR_REF);
 463}
 464
 465/*
 466 * on successful case, it's up to the caller to close cmd->out
 467 */
 468static int do_reachable_revlist(struct child_process *cmd,
 469                                struct object_array *src,
 470                                struct object_array *reachable)
 471{
 472        static const char *argv[] = {
 473                "rev-list", "--stdin", NULL,
 474        };
 475        struct object *o;
 476        char namebuf[42]; /* ^ + SHA-1 + LF */
 477        int i;
 478
 479        cmd->argv = argv;
 480        cmd->git_cmd = 1;
 481        cmd->no_stderr = 1;
 482        cmd->in = -1;
 483        cmd->out = -1;
 484
 485        /*
 486         * If the next rev-list --stdin encounters an unknown commit,
 487         * it terminates, which will cause SIGPIPE in the write loop
 488         * below.
 489         */
 490        sigchain_push(SIGPIPE, SIG_IGN);
 491
 492        if (start_command(cmd))
 493                goto error;
 494
 495        namebuf[0] = '^';
 496        namebuf[GIT_SHA1_HEXSZ + 1] = '\n';
 497        for (i = get_max_object_index(); 0 < i; ) {
 498                o = get_indexed_object(--i);
 499                if (!o)
 500                        continue;
 501                if (reachable && o->type == OBJ_COMMIT)
 502                        o->flags &= ~TMP_MARK;
 503                if (!is_our_ref(o))
 504                        continue;
 505                memcpy(namebuf + 1, oid_to_hex(&o->oid), GIT_SHA1_HEXSZ);
 506                if (write_in_full(cmd->in, namebuf, GIT_SHA1_HEXSZ + 2) < 0)
 507                        goto error;
 508        }
 509        namebuf[GIT_SHA1_HEXSZ] = '\n';
 510        for (i = 0; i < src->nr; i++) {
 511                o = src->objects[i].item;
 512                if (is_our_ref(o)) {
 513                        if (reachable)
 514                                add_object_array(o, NULL, reachable);
 515                        continue;
 516                }
 517                if (reachable && o->type == OBJ_COMMIT)
 518                        o->flags |= TMP_MARK;
 519                memcpy(namebuf, oid_to_hex(&o->oid), GIT_SHA1_HEXSZ);
 520                if (write_in_full(cmd->in, namebuf, GIT_SHA1_HEXSZ + 1) < 0)
 521                        goto error;
 522        }
 523        close(cmd->in);
 524        cmd->in = -1;
 525        sigchain_pop(SIGPIPE);
 526
 527        return 0;
 528
 529error:
 530        sigchain_pop(SIGPIPE);
 531
 532        if (cmd->in >= 0)
 533                close(cmd->in);
 534        if (cmd->out >= 0)
 535                close(cmd->out);
 536        return -1;
 537}
 538
 539static int get_reachable_list(struct object_array *src,
 540                              struct object_array *reachable)
 541{
 542        struct child_process cmd = CHILD_PROCESS_INIT;
 543        int i;
 544        struct object *o;
 545        char namebuf[42]; /* ^ + SHA-1 + LF */
 546
 547        if (do_reachable_revlist(&cmd, src, reachable) < 0)
 548                return -1;
 549
 550        while ((i = read_in_full(cmd.out, namebuf, 41)) == 41) {
 551                struct object_id sha1;
 552
 553                if (namebuf[40] != '\n' || get_oid_hex(namebuf, &sha1))
 554                        break;
 555
 556                o = lookup_object(sha1.hash);
 557                if (o && o->type == OBJ_COMMIT) {
 558                        o->flags &= ~TMP_MARK;
 559                }
 560        }
 561        for (i = get_max_object_index(); 0 < i; i--) {
 562                o = get_indexed_object(i - 1);
 563                if (o && o->type == OBJ_COMMIT &&
 564                    (o->flags & TMP_MARK)) {
 565                        add_object_array(o, NULL, reachable);
 566                                o->flags &= ~TMP_MARK;
 567                }
 568        }
 569        close(cmd.out);
 570
 571        if (finish_command(&cmd))
 572                return -1;
 573
 574        return 0;
 575}
 576
 577static int has_unreachable(struct object_array *src)
 578{
 579        struct child_process cmd = CHILD_PROCESS_INIT;
 580        char buf[1];
 581        int i;
 582
 583        if (do_reachable_revlist(&cmd, src, NULL) < 0)
 584                return 1;
 585
 586        /*
 587         * The commits out of the rev-list are not ancestors of
 588         * our ref.
 589         */
 590        i = read_in_full(cmd.out, buf, 1);
 591        if (i)
 592                goto error;
 593        close(cmd.out);
 594        cmd.out = -1;
 595
 596        /*
 597         * rev-list may have died by encountering a bad commit
 598         * in the history, in which case we do want to bail out
 599         * even when it showed no commit.
 600         */
 601        if (finish_command(&cmd))
 602                goto error;
 603
 604        /* All the non-tip ones are ancestors of what we advertised */
 605        return 0;
 606
 607error:
 608        sigchain_pop(SIGPIPE);
 609        if (cmd.out >= 0)
 610                close(cmd.out);
 611        return 1;
 612}
 613
 614static void check_non_tip(void)
 615{
 616        int i;
 617
 618        /*
 619         * In the normal in-process case without
 620         * uploadpack.allowReachableSHA1InWant,
 621         * non-tip requests can never happen.
 622         */
 623        if (!stateless_rpc && !(allow_unadvertised_object_request & ALLOW_REACHABLE_SHA1))
 624                goto error;
 625        if (!has_unreachable(&want_obj))
 626                /* All the non-tip ones are ancestors of what we advertised */
 627                return;
 628
 629error:
 630        /* Pick one of them (we know there at least is one) */
 631        for (i = 0; i < want_obj.nr; i++) {
 632                struct object *o = want_obj.objects[i].item;
 633                if (!is_our_ref(o))
 634                        die("git upload-pack: not our ref %s",
 635                            oid_to_hex(&o->oid));
 636        }
 637}
 638
 639static void send_shallow(struct commit_list *result)
 640{
 641        while (result) {
 642                struct object *object = &result->item->object;
 643                if (!(object->flags & (CLIENT_SHALLOW|NOT_SHALLOW))) {
 644                        packet_write_fmt(1, "shallow %s",
 645                                         oid_to_hex(&object->oid));
 646                        register_shallow(&object->oid);
 647                        shallow_nr++;
 648                }
 649                result = result->next;
 650        }
 651}
 652
 653static void send_unshallow(const struct object_array *shallows)
 654{
 655        int i;
 656
 657        for (i = 0; i < shallows->nr; i++) {
 658                struct object *object = shallows->objects[i].item;
 659                if (object->flags & NOT_SHALLOW) {
 660                        struct commit_list *parents;
 661                        packet_write_fmt(1, "unshallow %s",
 662                                         oid_to_hex(&object->oid));
 663                        object->flags &= ~CLIENT_SHALLOW;
 664                        /*
 665                         * We want to _register_ "object" as shallow, but we
 666                         * also need to traverse object's parents to deepen a
 667                         * shallow clone. Unregister it for now so we can
 668                         * parse and add the parents to the want list, then
 669                         * re-register it.
 670                         */
 671                        unregister_shallow(&object->oid);
 672                        object->parsed = 0;
 673                        parse_commit_or_die((struct commit *)object);
 674                        parents = ((struct commit *)object)->parents;
 675                        while (parents) {
 676                                add_object_array(&parents->item->object,
 677                                                 NULL, &want_obj);
 678                                parents = parents->next;
 679                        }
 680                        add_object_array(object, NULL, &extra_edge_obj);
 681                }
 682                /* make sure commit traversal conforms to client */
 683                register_shallow(&object->oid);
 684        }
 685}
 686
 687static void deepen(int depth, int deepen_relative,
 688                   struct object_array *shallows)
 689{
 690        if (depth == INFINITE_DEPTH && !is_repository_shallow()) {
 691                int i;
 692
 693                for (i = 0; i < shallows->nr; i++) {
 694                        struct object *object = shallows->objects[i].item;
 695                        object->flags |= NOT_SHALLOW;
 696                }
 697        } else if (deepen_relative) {
 698                struct object_array reachable_shallows = OBJECT_ARRAY_INIT;
 699                struct commit_list *result;
 700
 701                get_reachable_list(shallows, &reachable_shallows);
 702                result = get_shallow_commits(&reachable_shallows,
 703                                             depth + 1,
 704                                             SHALLOW, NOT_SHALLOW);
 705                send_shallow(result);
 706                free_commit_list(result);
 707                object_array_clear(&reachable_shallows);
 708        } else {
 709                struct commit_list *result;
 710
 711                result = get_shallow_commits(&want_obj, depth,
 712                                             SHALLOW, NOT_SHALLOW);
 713                send_shallow(result);
 714                free_commit_list(result);
 715        }
 716
 717        send_unshallow(shallows);
 718        packet_flush(1);
 719}
 720
 721static void deepen_by_rev_list(int ac, const char **av,
 722                               struct object_array *shallows)
 723{
 724        struct commit_list *result;
 725
 726        result = get_shallow_commits_by_rev_list(ac, av, SHALLOW, NOT_SHALLOW);
 727        send_shallow(result);
 728        free_commit_list(result);
 729        send_unshallow(shallows);
 730        packet_flush(1);
 731}
 732
 733static void receive_needs(void)
 734{
 735        struct object_array shallows = OBJECT_ARRAY_INIT;
 736        struct string_list deepen_not = STRING_LIST_INIT_DUP;
 737        int depth = 0;
 738        int has_non_tip = 0;
 739        timestamp_t deepen_since = 0;
 740        int deepen_rev_list = 0;
 741
 742        shallow_nr = 0;
 743        for (;;) {
 744                struct object *o;
 745                const char *features;
 746                struct object_id oid_buf;
 747                char *line = packet_read_line(0, NULL);
 748                const char *arg;
 749
 750                reset_timeout();
 751                if (!line)
 752                        break;
 753
 754                if (skip_prefix(line, "shallow ", &arg)) {
 755                        struct object_id oid;
 756                        struct object *object;
 757                        if (get_oid_hex(arg, &oid))
 758                                die("invalid shallow line: %s", line);
 759                        object = parse_object(&oid);
 760                        if (!object)
 761                                continue;
 762                        if (object->type != OBJ_COMMIT)
 763                                die("invalid shallow object %s", oid_to_hex(&oid));
 764                        if (!(object->flags & CLIENT_SHALLOW)) {
 765                                object->flags |= CLIENT_SHALLOW;
 766                                add_object_array(object, NULL, &shallows);
 767                        }
 768                        continue;
 769                }
 770                if (skip_prefix(line, "deepen ", &arg)) {
 771                        char *end = NULL;
 772                        depth = strtol(arg, &end, 0);
 773                        if (!end || *end || depth <= 0)
 774                                die("Invalid deepen: %s", line);
 775                        continue;
 776                }
 777                if (skip_prefix(line, "deepen-since ", &arg)) {
 778                        char *end = NULL;
 779                        deepen_since = parse_timestamp(arg, &end, 0);
 780                        if (!end || *end || !deepen_since ||
 781                            /* revisions.c's max_age -1 is special */
 782                            deepen_since == -1)
 783                                die("Invalid deepen-since: %s", line);
 784                        deepen_rev_list = 1;
 785                        continue;
 786                }
 787                if (skip_prefix(line, "deepen-not ", &arg)) {
 788                        char *ref = NULL;
 789                        struct object_id oid;
 790                        if (expand_ref(arg, strlen(arg), oid.hash, &ref) != 1)
 791                                die("git upload-pack: ambiguous deepen-not: %s", line);
 792                        string_list_append(&deepen_not, ref);
 793                        free(ref);
 794                        deepen_rev_list = 1;
 795                        continue;
 796                }
 797                if (!skip_prefix(line, "want ", &arg) ||
 798                    get_oid_hex(arg, &oid_buf))
 799                        die("git upload-pack: protocol error, "
 800                            "expected to get sha, not '%s'", line);
 801
 802                features = arg + 40;
 803
 804                if (parse_feature_request(features, "deepen-relative"))
 805                        deepen_relative = 1;
 806                if (parse_feature_request(features, "multi_ack_detailed"))
 807                        multi_ack = 2;
 808                else if (parse_feature_request(features, "multi_ack"))
 809                        multi_ack = 1;
 810                if (parse_feature_request(features, "no-done"))
 811                        no_done = 1;
 812                if (parse_feature_request(features, "thin-pack"))
 813                        use_thin_pack = 1;
 814                if (parse_feature_request(features, "ofs-delta"))
 815                        use_ofs_delta = 1;
 816                if (parse_feature_request(features, "side-band-64k"))
 817                        use_sideband = LARGE_PACKET_MAX;
 818                else if (parse_feature_request(features, "side-band"))
 819                        use_sideband = DEFAULT_PACKET_MAX;
 820                if (parse_feature_request(features, "no-progress"))
 821                        no_progress = 1;
 822                if (parse_feature_request(features, "include-tag"))
 823                        use_include_tag = 1;
 824
 825                o = parse_object(&oid_buf);
 826                if (!o) {
 827                        packet_write_fmt(1,
 828                                         "ERR upload-pack: not our ref %s",
 829                                         oid_to_hex(&oid_buf));
 830                        die("git upload-pack: not our ref %s",
 831                            oid_to_hex(&oid_buf));
 832                }
 833                if (!(o->flags & WANTED)) {
 834                        o->flags |= WANTED;
 835                        if (!((allow_unadvertised_object_request & ALLOW_ANY_SHA1) == ALLOW_ANY_SHA1
 836                              || is_our_ref(o)))
 837                                has_non_tip = 1;
 838                        add_object_array(o, NULL, &want_obj);
 839                }
 840        }
 841
 842        /*
 843         * We have sent all our refs already, and the other end
 844         * should have chosen out of them. When we are operating
 845         * in the stateless RPC mode, however, their choice may
 846         * have been based on the set of older refs advertised
 847         * by another process that handled the initial request.
 848         */
 849        if (has_non_tip)
 850                check_non_tip();
 851
 852        if (!use_sideband && daemon_mode)
 853                no_progress = 1;
 854
 855        if (depth == 0 && !deepen_rev_list && shallows.nr == 0)
 856                return;
 857        if (depth > 0 && deepen_rev_list)
 858                die("git upload-pack: deepen and deepen-since (or deepen-not) cannot be used together");
 859        if (depth > 0)
 860                deepen(depth, deepen_relative, &shallows);
 861        else if (deepen_rev_list) {
 862                struct argv_array av = ARGV_ARRAY_INIT;
 863                int i;
 864
 865                argv_array_push(&av, "rev-list");
 866                if (deepen_since)
 867                        argv_array_pushf(&av, "--max-age=%"PRItime, deepen_since);
 868                if (deepen_not.nr) {
 869                        argv_array_push(&av, "--not");
 870                        for (i = 0; i < deepen_not.nr; i++) {
 871                                struct string_list_item *s = deepen_not.items + i;
 872                                argv_array_push(&av, s->string);
 873                        }
 874                        argv_array_push(&av, "--not");
 875                }
 876                for (i = 0; i < want_obj.nr; i++) {
 877                        struct object *o = want_obj.objects[i].item;
 878                        argv_array_push(&av, oid_to_hex(&o->oid));
 879                }
 880                deepen_by_rev_list(av.argc, av.argv, &shallows);
 881                argv_array_clear(&av);
 882        }
 883        else
 884                if (shallows.nr > 0) {
 885                        int i;
 886                        for (i = 0; i < shallows.nr; i++)
 887                                register_shallow(&shallows.objects[i].item->oid);
 888                }
 889
 890        shallow_nr += shallows.nr;
 891        free(shallows.objects);
 892}
 893
 894/* return non-zero if the ref is hidden, otherwise 0 */
 895static int mark_our_ref(const char *refname, const char *refname_full,
 896                        const struct object_id *oid)
 897{
 898        struct object *o = lookup_unknown_object(oid->hash);
 899
 900        if (ref_is_hidden(refname, refname_full)) {
 901                o->flags |= HIDDEN_REF;
 902                return 1;
 903        }
 904        o->flags |= OUR_REF;
 905        return 0;
 906}
 907
 908static int check_ref(const char *refname_full, const struct object_id *oid,
 909                     int flag, void *cb_data)
 910{
 911        const char *refname = strip_namespace(refname_full);
 912
 913        mark_our_ref(refname, refname_full, oid);
 914        return 0;
 915}
 916
 917static void format_symref_info(struct strbuf *buf, struct string_list *symref)
 918{
 919        struct string_list_item *item;
 920
 921        if (!symref->nr)
 922                return;
 923        for_each_string_list_item(item, symref)
 924                strbuf_addf(buf, " symref=%s:%s", item->string, (char *)item->util);
 925}
 926
 927static int send_ref(const char *refname, const struct object_id *oid,
 928                    int flag, void *cb_data)
 929{
 930        static const char *capabilities = "multi_ack thin-pack side-band"
 931                " side-band-64k ofs-delta shallow deepen-since deepen-not"
 932                " deepen-relative no-progress include-tag multi_ack_detailed";
 933        const char *refname_nons = strip_namespace(refname);
 934        struct object_id peeled;
 935
 936        if (mark_our_ref(refname_nons, refname, oid))
 937                return 0;
 938
 939        if (capabilities) {
 940                struct strbuf symref_info = STRBUF_INIT;
 941
 942                format_symref_info(&symref_info, cb_data);
 943                packet_write_fmt(1, "%s %s%c%s%s%s%s%s agent=%s\n",
 944                             oid_to_hex(oid), refname_nons,
 945                             0, capabilities,
 946                             (allow_unadvertised_object_request & ALLOW_TIP_SHA1) ?
 947                                     " allow-tip-sha1-in-want" : "",
 948                             (allow_unadvertised_object_request & ALLOW_REACHABLE_SHA1) ?
 949                                     " allow-reachable-sha1-in-want" : "",
 950                             stateless_rpc ? " no-done" : "",
 951                             symref_info.buf,
 952                             git_user_agent_sanitized());
 953                strbuf_release(&symref_info);
 954        } else {
 955                packet_write_fmt(1, "%s %s\n", oid_to_hex(oid), refname_nons);
 956        }
 957        capabilities = NULL;
 958        if (!peel_ref(refname, peeled.hash))
 959                packet_write_fmt(1, "%s %s^{}\n", oid_to_hex(&peeled), refname_nons);
 960        return 0;
 961}
 962
 963static int find_symref(const char *refname, const struct object_id *oid,
 964                       int flag, void *cb_data)
 965{
 966        const char *symref_target;
 967        struct string_list_item *item;
 968        struct object_id unused;
 969
 970        if ((flag & REF_ISSYMREF) == 0)
 971                return 0;
 972        symref_target = resolve_ref_unsafe(refname, 0, unused.hash, &flag);
 973        if (!symref_target || (flag & REF_ISSYMREF) == 0)
 974                die("'%s' is a symref but it is not?", refname);
 975        item = string_list_append(cb_data, refname);
 976        item->util = xstrdup(symref_target);
 977        return 0;
 978}
 979
 980static void upload_pack(void)
 981{
 982        struct string_list symref = STRING_LIST_INIT_DUP;
 983
 984        head_ref_namespaced(find_symref, &symref);
 985
 986        if (advertise_refs || !stateless_rpc) {
 987                reset_timeout();
 988                head_ref_namespaced(send_ref, &symref);
 989                for_each_namespaced_ref(send_ref, &symref);
 990                advertise_shallow_grafts(1);
 991                packet_flush(1);
 992        } else {
 993                head_ref_namespaced(check_ref, NULL);
 994                for_each_namespaced_ref(check_ref, NULL);
 995        }
 996        string_list_clear(&symref, 1);
 997        if (advertise_refs)
 998                return;
 999
1000        receive_needs();
1001        if (want_obj.nr) {
1002                get_common_commits();
1003                create_pack_file();
1004        }
1005}
1006
1007static int upload_pack_config(const char *var, const char *value, void *unused)
1008{
1009        if (!strcmp("uploadpack.allowtipsha1inwant", var)) {
1010                if (git_config_bool(var, value))
1011                        allow_unadvertised_object_request |= ALLOW_TIP_SHA1;
1012                else
1013                        allow_unadvertised_object_request &= ~ALLOW_TIP_SHA1;
1014        } else if (!strcmp("uploadpack.allowreachablesha1inwant", var)) {
1015                if (git_config_bool(var, value))
1016                        allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1017                else
1018                        allow_unadvertised_object_request &= ~ALLOW_REACHABLE_SHA1;
1019        } else if (!strcmp("uploadpack.allowanysha1inwant", var)) {
1020                if (git_config_bool(var, value))
1021                        allow_unadvertised_object_request |= ALLOW_ANY_SHA1;
1022                else
1023                        allow_unadvertised_object_request &= ~ALLOW_ANY_SHA1;
1024        } else if (!strcmp("uploadpack.keepalive", var)) {
1025                keepalive = git_config_int(var, value);
1026                if (!keepalive)
1027                        keepalive = -1;
1028        } else if (current_config_scope() != CONFIG_SCOPE_REPO) {
1029                if (!strcmp("uploadpack.packobjectshook", var))
1030                        return git_config_string(&pack_objects_hook, var, value);
1031        }
1032        return parse_hide_refs_config(var, value, "uploadpack");
1033}
1034
1035int cmd_main(int argc, const char **argv)
1036{
1037        const char *dir;
1038        int strict = 0;
1039        struct option options[] = {
1040                OPT_BOOL(0, "stateless-rpc", &stateless_rpc,
1041                         N_("quit after a single request/response exchange")),
1042                OPT_BOOL(0, "advertise-refs", &advertise_refs,
1043                         N_("exit immediately after initial ref advertisement")),
1044                OPT_BOOL(0, "strict", &strict,
1045                         N_("do not try <directory>/.git/ if <directory> is no Git directory")),
1046                OPT_INTEGER(0, "timeout", &timeout,
1047                            N_("interrupt transfer after <n> seconds of inactivity")),
1048                OPT_END()
1049        };
1050
1051        packet_trace_identity("upload-pack");
1052        check_replace_refs = 0;
1053
1054        argc = parse_options(argc, argv, NULL, options, upload_pack_usage, 0);
1055
1056        if (argc != 1)
1057                usage_with_options(upload_pack_usage, options);
1058
1059        if (timeout)
1060                daemon_mode = 1;
1061
1062        setup_path();
1063
1064        dir = argv[0];
1065
1066        if (!enter_repo(dir, strict))
1067                die("'%s' does not appear to be a git repository", dir);
1068
1069        git_config(upload_pack_config, NULL);
1070        upload_pack();
1071        return 0;
1072}