transport-helper.con commit transport-helper: check for 'forced update' message (f9e3c6b)
   1#include "cache.h"
   2#include "transport.h"
   3#include "quote.h"
   4#include "run-command.h"
   5#include "commit.h"
   6#include "diff.h"
   7#include "revision.h"
   8#include "quote.h"
   9#include "remote.h"
  10#include "string-list.h"
  11#include "thread-utils.h"
  12#include "sigchain.h"
  13#include "argv-array.h"
  14#include "refs.h"
  15
  16static int debug;
  17
  18struct helper_data {
  19        const char *name;
  20        struct child_process *helper;
  21        FILE *out;
  22        unsigned fetch : 1,
  23                import : 1,
  24                bidi_import : 1,
  25                export : 1,
  26                option : 1,
  27                push : 1,
  28                connect : 1,
  29                signed_tags : 1,
  30                check_connectivity : 1,
  31                no_disconnect_req : 1,
  32                no_private_update : 1;
  33        char *export_marks;
  34        char *import_marks;
  35        /* These go from remote name (as in "list") to private name */
  36        struct refspec *refspecs;
  37        int refspec_nr;
  38        /* Transport options for fetch-pack/send-pack (should one of
  39         * those be invoked).
  40         */
  41        struct git_transport_options transport_options;
  42};
  43
  44static void sendline(struct helper_data *helper, struct strbuf *buffer)
  45{
  46        if (debug)
  47                fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
  48        if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
  49                != buffer->len)
  50                die_errno("Full write to remote helper failed");
  51}
  52
  53static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
  54{
  55        strbuf_reset(buffer);
  56        if (debug)
  57                fprintf(stderr, "Debug: Remote helper: Waiting...\n");
  58        if (strbuf_getline(buffer, helper, '\n') == EOF) {
  59                if (debug)
  60                        fprintf(stderr, "Debug: Remote helper quit.\n");
  61                exit(128);
  62        }
  63
  64        if (debug)
  65                fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
  66        return 0;
  67}
  68
  69static int recvline(struct helper_data *helper, struct strbuf *buffer)
  70{
  71        return recvline_fh(helper->out, buffer, helper->name);
  72}
  73
  74static void xchgline(struct helper_data *helper, struct strbuf *buffer)
  75{
  76        sendline(helper, buffer);
  77        recvline(helper, buffer);
  78}
  79
  80static void write_constant(int fd, const char *str)
  81{
  82        if (debug)
  83                fprintf(stderr, "Debug: Remote helper: -> %s", str);
  84        if (write_in_full(fd, str, strlen(str)) != strlen(str))
  85                die_errno("Full write to remote helper failed");
  86}
  87
  88static const char *remove_ext_force(const char *url)
  89{
  90        if (url) {
  91                const char *colon = strchr(url, ':');
  92                if (colon && colon[1] == ':')
  93                        return colon + 2;
  94        }
  95        return url;
  96}
  97
  98static void do_take_over(struct transport *transport)
  99{
 100        struct helper_data *data;
 101        data = (struct helper_data *)transport->data;
 102        transport_take_over(transport, data->helper);
 103        fclose(data->out);
 104        free(data);
 105}
 106
 107static struct child_process *get_helper(struct transport *transport)
 108{
 109        struct helper_data *data = transport->data;
 110        struct argv_array argv = ARGV_ARRAY_INIT;
 111        struct strbuf buf = STRBUF_INIT;
 112        struct child_process *helper;
 113        const char **refspecs = NULL;
 114        int refspec_nr = 0;
 115        int refspec_alloc = 0;
 116        int duped;
 117        int code;
 118        char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
 119        const char *helper_env[] = {
 120                git_dir_buf,
 121                NULL
 122        };
 123
 124
 125        if (data->helper)
 126                return data->helper;
 127
 128        helper = xcalloc(1, sizeof(*helper));
 129        helper->in = -1;
 130        helper->out = -1;
 131        helper->err = 0;
 132        argv_array_pushf(&argv, "git-remote-%s", data->name);
 133        argv_array_push(&argv, transport->remote->name);
 134        argv_array_push(&argv, remove_ext_force(transport->url));
 135        helper->argv = argv_array_detach(&argv, NULL);
 136        helper->git_cmd = 0;
 137        helper->silent_exec_failure = 1;
 138
 139        snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
 140        helper->env = helper_env;
 141
 142        code = start_command(helper);
 143        if (code < 0 && errno == ENOENT)
 144                die("Unable to find remote helper for '%s'", data->name);
 145        else if (code != 0)
 146                exit(code);
 147
 148        data->helper = helper;
 149        data->no_disconnect_req = 0;
 150
 151        /*
 152         * Open the output as FILE* so strbuf_getline() can be used.
 153         * Do this with duped fd because fclose() will close the fd,
 154         * and stuff like taking over will require the fd to remain.
 155         */
 156        duped = dup(helper->out);
 157        if (duped < 0)
 158                die_errno("Can't dup helper output fd");
 159        data->out = xfdopen(duped, "r");
 160
 161        write_constant(helper->in, "capabilities\n");
 162
 163        while (1) {
 164                const char *capname;
 165                int mandatory = 0;
 166                recvline(data, &buf);
 167
 168                if (!*buf.buf)
 169                        break;
 170
 171                if (*buf.buf == '*') {
 172                        capname = buf.buf + 1;
 173                        mandatory = 1;
 174                } else
 175                        capname = buf.buf;
 176
 177                if (debug)
 178                        fprintf(stderr, "Debug: Got cap %s\n", capname);
 179                if (!strcmp(capname, "fetch"))
 180                        data->fetch = 1;
 181                else if (!strcmp(capname, "option"))
 182                        data->option = 1;
 183                else if (!strcmp(capname, "push"))
 184                        data->push = 1;
 185                else if (!strcmp(capname, "import"))
 186                        data->import = 1;
 187                else if (!strcmp(capname, "bidi-import"))
 188                        data->bidi_import = 1;
 189                else if (!strcmp(capname, "export"))
 190                        data->export = 1;
 191                else if (!strcmp(capname, "check-connectivity"))
 192                        data->check_connectivity = 1;
 193                else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
 194                        ALLOC_GROW(refspecs,
 195                                   refspec_nr + 1,
 196                                   refspec_alloc);
 197                        refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
 198                } else if (!strcmp(capname, "connect")) {
 199                        data->connect = 1;
 200                } else if (!strcmp(capname, "signed-tags")) {
 201                        data->signed_tags = 1;
 202                } else if (!prefixcmp(capname, "export-marks ")) {
 203                        struct strbuf arg = STRBUF_INIT;
 204                        strbuf_addstr(&arg, "--export-marks=");
 205                        strbuf_addstr(&arg, capname + strlen("export-marks "));
 206                        data->export_marks = strbuf_detach(&arg, NULL);
 207                } else if (!prefixcmp(capname, "import-marks")) {
 208                        struct strbuf arg = STRBUF_INIT;
 209                        strbuf_addstr(&arg, "--import-marks=");
 210                        strbuf_addstr(&arg, capname + strlen("import-marks "));
 211                        data->import_marks = strbuf_detach(&arg, NULL);
 212                } else if (!prefixcmp(capname, "no-private-update")) {
 213                        data->no_private_update = 1;
 214                } else if (mandatory) {
 215                        die("Unknown mandatory capability %s. This remote "
 216                            "helper probably needs newer version of Git.",
 217                            capname);
 218                }
 219        }
 220        if (refspecs) {
 221                int i;
 222                data->refspec_nr = refspec_nr;
 223                data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
 224                for (i = 0; i < refspec_nr; i++)
 225                        free((char *)refspecs[i]);
 226                free(refspecs);
 227        } else if (data->import || data->bidi_import || data->export) {
 228                warning("This remote helper should implement refspec capability.");
 229        }
 230        strbuf_release(&buf);
 231        if (debug)
 232                fprintf(stderr, "Debug: Capabilities complete.\n");
 233        return data->helper;
 234}
 235
 236static int disconnect_helper(struct transport *transport)
 237{
 238        struct helper_data *data = transport->data;
 239        int res = 0;
 240
 241        if (data->helper) {
 242                if (debug)
 243                        fprintf(stderr, "Debug: Disconnecting.\n");
 244                if (!data->no_disconnect_req) {
 245                        /*
 246                         * Ignore write errors; there's nothing we can do,
 247                         * since we're about to close the pipe anyway. And the
 248                         * most likely error is EPIPE due to the helper dying
 249                         * to report an error itself.
 250                         */
 251                        sigchain_push(SIGPIPE, SIG_IGN);
 252                        xwrite(data->helper->in, "\n", 1);
 253                        sigchain_pop(SIGPIPE);
 254                }
 255                close(data->helper->in);
 256                close(data->helper->out);
 257                fclose(data->out);
 258                res = finish_command(data->helper);
 259                argv_array_free_detached(data->helper->argv);
 260                free(data->helper);
 261                data->helper = NULL;
 262        }
 263        return res;
 264}
 265
 266static const char *unsupported_options[] = {
 267        TRANS_OPT_UPLOADPACK,
 268        TRANS_OPT_RECEIVEPACK,
 269        TRANS_OPT_THIN,
 270        TRANS_OPT_KEEP
 271        };
 272static const char *boolean_options[] = {
 273        TRANS_OPT_THIN,
 274        TRANS_OPT_KEEP,
 275        TRANS_OPT_FOLLOWTAGS
 276        };
 277
 278static int set_helper_option(struct transport *transport,
 279                          const char *name, const char *value)
 280{
 281        struct helper_data *data = transport->data;
 282        struct strbuf buf = STRBUF_INIT;
 283        int i, ret, is_bool = 0;
 284
 285        get_helper(transport);
 286
 287        if (!data->option)
 288                return 1;
 289
 290        for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
 291                if (!strcmp(name, unsupported_options[i]))
 292                        return 1;
 293        }
 294
 295        for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
 296                if (!strcmp(name, boolean_options[i])) {
 297                        is_bool = 1;
 298                        break;
 299                }
 300        }
 301
 302        strbuf_addf(&buf, "option %s ", name);
 303        if (is_bool)
 304                strbuf_addstr(&buf, value ? "true" : "false");
 305        else
 306                quote_c_style(value, &buf, NULL, 0);
 307        strbuf_addch(&buf, '\n');
 308
 309        xchgline(data, &buf);
 310
 311        if (!strcmp(buf.buf, "ok"))
 312                ret = 0;
 313        else if (!prefixcmp(buf.buf, "error")) {
 314                ret = -1;
 315        } else if (!strcmp(buf.buf, "unsupported"))
 316                ret = 1;
 317        else {
 318                warning("%s unexpectedly said: '%s'", data->name, buf.buf);
 319                ret = 1;
 320        }
 321        strbuf_release(&buf);
 322        return ret;
 323}
 324
 325static void standard_options(struct transport *t)
 326{
 327        char buf[16];
 328        int n;
 329        int v = t->verbose;
 330
 331        set_helper_option(t, "progress", t->progress ? "true" : "false");
 332
 333        n = snprintf(buf, sizeof(buf), "%d", v + 1);
 334        if (n >= sizeof(buf))
 335                die("impossibly large verbosity value");
 336        set_helper_option(t, "verbosity", buf);
 337}
 338
 339static int release_helper(struct transport *transport)
 340{
 341        int res = 0;
 342        struct helper_data *data = transport->data;
 343        free_refspec(data->refspec_nr, data->refspecs);
 344        data->refspecs = NULL;
 345        res = disconnect_helper(transport);
 346        free(transport->data);
 347        return res;
 348}
 349
 350static int fetch_with_fetch(struct transport *transport,
 351                            int nr_heads, struct ref **to_fetch)
 352{
 353        struct helper_data *data = transport->data;
 354        int i;
 355        struct strbuf buf = STRBUF_INIT;
 356
 357        standard_options(transport);
 358        if (data->check_connectivity &&
 359            data->transport_options.check_self_contained_and_connected)
 360                set_helper_option(transport, "check-connectivity", "true");
 361
 362        for (i = 0; i < nr_heads; i++) {
 363                const struct ref *posn = to_fetch[i];
 364                if (posn->status & REF_STATUS_UPTODATE)
 365                        continue;
 366
 367                strbuf_addf(&buf, "fetch %s %s\n",
 368                            sha1_to_hex(posn->old_sha1), posn->name);
 369        }
 370
 371        strbuf_addch(&buf, '\n');
 372        sendline(data, &buf);
 373
 374        while (1) {
 375                recvline(data, &buf);
 376
 377                if (!prefixcmp(buf.buf, "lock ")) {
 378                        const char *name = buf.buf + 5;
 379                        if (transport->pack_lockfile)
 380                                warning("%s also locked %s", data->name, name);
 381                        else
 382                                transport->pack_lockfile = xstrdup(name);
 383                }
 384                else if (data->check_connectivity &&
 385                         data->transport_options.check_self_contained_and_connected &&
 386                         !strcmp(buf.buf, "connectivity-ok"))
 387                        data->transport_options.self_contained_and_connected = 1;
 388                else if (!buf.len)
 389                        break;
 390                else
 391                        warning("%s unexpectedly said: '%s'", data->name, buf.buf);
 392        }
 393        strbuf_release(&buf);
 394        return 0;
 395}
 396
 397static int get_importer(struct transport *transport, struct child_process *fastimport)
 398{
 399        struct child_process *helper = get_helper(transport);
 400        struct helper_data *data = transport->data;
 401        struct argv_array argv = ARGV_ARRAY_INIT;
 402        int cat_blob_fd, code;
 403        memset(fastimport, 0, sizeof(*fastimport));
 404        fastimport->in = helper->out;
 405        argv_array_push(&argv, "fast-import");
 406        argv_array_push(&argv, debug ? "--stats" : "--quiet");
 407
 408        if (data->bidi_import) {
 409                cat_blob_fd = xdup(helper->in);
 410                argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
 411        }
 412        fastimport->argv = argv.argv;
 413        fastimport->git_cmd = 1;
 414
 415        code = start_command(fastimport);
 416        return code;
 417}
 418
 419static int get_exporter(struct transport *transport,
 420                        struct child_process *fastexport,
 421                        struct string_list *revlist_args)
 422{
 423        struct helper_data *data = transport->data;
 424        struct child_process *helper = get_helper(transport);
 425        int argc = 0, i;
 426        memset(fastexport, 0, sizeof(*fastexport));
 427
 428        /* we need to duplicate helper->in because we want to use it after
 429         * fastexport is done with it. */
 430        fastexport->out = dup(helper->in);
 431        fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
 432        fastexport->argv[argc++] = "fast-export";
 433        fastexport->argv[argc++] = "--use-done-feature";
 434        fastexport->argv[argc++] = data->signed_tags ?
 435                "--signed-tags=verbatim" : "--signed-tags=warn-strip";
 436        if (data->export_marks)
 437                fastexport->argv[argc++] = data->export_marks;
 438        if (data->import_marks)
 439                fastexport->argv[argc++] = data->import_marks;
 440
 441        for (i = 0; i < revlist_args->nr; i++)
 442                fastexport->argv[argc++] = revlist_args->items[i].string;
 443
 444        fastexport->git_cmd = 1;
 445        return start_command(fastexport);
 446}
 447
 448static int fetch_with_import(struct transport *transport,
 449                             int nr_heads, struct ref **to_fetch)
 450{
 451        struct child_process fastimport;
 452        struct helper_data *data = transport->data;
 453        int i;
 454        struct ref *posn;
 455        struct strbuf buf = STRBUF_INIT;
 456
 457        get_helper(transport);
 458
 459        if (get_importer(transport, &fastimport))
 460                die("Couldn't run fast-import");
 461
 462        for (i = 0; i < nr_heads; i++) {
 463                posn = to_fetch[i];
 464                if (posn->status & REF_STATUS_UPTODATE)
 465                        continue;
 466
 467                strbuf_addf(&buf, "import %s\n", posn->name);
 468                sendline(data, &buf);
 469                strbuf_reset(&buf);
 470        }
 471
 472        write_constant(data->helper->in, "\n");
 473        /*
 474         * remote-helpers that advertise the bidi-import capability are required to
 475         * buffer the complete batch of import commands until this newline before
 476         * sending data to fast-import.
 477         * These helpers read back data from fast-import on their stdin, which could
 478         * be mixed with import commands, otherwise.
 479         */
 480
 481        if (finish_command(&fastimport))
 482                die("Error while running fast-import");
 483        argv_array_free_detached(fastimport.argv);
 484
 485        /*
 486         * The fast-import stream of a remote helper that advertises
 487         * the "refspec" capability writes to the refs named after the
 488         * right hand side of the first refspec matching each ref we
 489         * were fetching.
 490         *
 491         * (If no "refspec" capability was specified, for historical
 492         * reasons we default to the equivalent of *:*.)
 493         *
 494         * Store the result in to_fetch[i].old_sha1.  Callers such
 495         * as "git fetch" can use the value to write feedback to the
 496         * terminal, populate FETCH_HEAD, and determine what new value
 497         * should be written to peer_ref if the update is a
 498         * fast-forward or this is a forced update.
 499         */
 500        for (i = 0; i < nr_heads; i++) {
 501                char *private;
 502                posn = to_fetch[i];
 503                if (posn->status & REF_STATUS_UPTODATE)
 504                        continue;
 505                if (data->refspecs)
 506                        private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
 507                else
 508                        private = xstrdup(posn->name);
 509                if (private) {
 510                        read_ref(private, posn->old_sha1);
 511                        free(private);
 512                }
 513        }
 514        strbuf_release(&buf);
 515        return 0;
 516}
 517
 518static int process_connect_service(struct transport *transport,
 519                                   const char *name, const char *exec)
 520{
 521        struct helper_data *data = transport->data;
 522        struct strbuf cmdbuf = STRBUF_INIT;
 523        struct child_process *helper;
 524        int r, duped, ret = 0;
 525        FILE *input;
 526
 527        helper = get_helper(transport);
 528
 529        /*
 530         * Yes, dup the pipe another time, as we need unbuffered version
 531         * of input pipe as FILE*. fclose() closes the underlying fd and
 532         * stream buffering only can be changed before first I/O operation
 533         * on it.
 534         */
 535        duped = dup(helper->out);
 536        if (duped < 0)
 537                die_errno("Can't dup helper output fd");
 538        input = xfdopen(duped, "r");
 539        setvbuf(input, NULL, _IONBF, 0);
 540
 541        /*
 542         * Handle --upload-pack and friends. This is fire and forget...
 543         * just warn if it fails.
 544         */
 545        if (strcmp(name, exec)) {
 546                r = set_helper_option(transport, "servpath", exec);
 547                if (r > 0)
 548                        warning("Setting remote service path not supported by protocol.");
 549                else if (r < 0)
 550                        warning("Invalid remote service path.");
 551        }
 552
 553        if (data->connect)
 554                strbuf_addf(&cmdbuf, "connect %s\n", name);
 555        else
 556                goto exit;
 557
 558        sendline(data, &cmdbuf);
 559        recvline_fh(input, &cmdbuf, name);
 560        if (!strcmp(cmdbuf.buf, "")) {
 561                data->no_disconnect_req = 1;
 562                if (debug)
 563                        fprintf(stderr, "Debug: Smart transport connection "
 564                                "ready.\n");
 565                ret = 1;
 566        } else if (!strcmp(cmdbuf.buf, "fallback")) {
 567                if (debug)
 568                        fprintf(stderr, "Debug: Falling back to dumb "
 569                                "transport.\n");
 570        } else
 571                die("Unknown response to connect: %s",
 572                        cmdbuf.buf);
 573
 574exit:
 575        fclose(input);
 576        return ret;
 577}
 578
 579static int process_connect(struct transport *transport,
 580                                     int for_push)
 581{
 582        struct helper_data *data = transport->data;
 583        const char *name;
 584        const char *exec;
 585
 586        name = for_push ? "git-receive-pack" : "git-upload-pack";
 587        if (for_push)
 588                exec = data->transport_options.receivepack;
 589        else
 590                exec = data->transport_options.uploadpack;
 591
 592        return process_connect_service(transport, name, exec);
 593}
 594
 595static int connect_helper(struct transport *transport, const char *name,
 596                   const char *exec, int fd[2])
 597{
 598        struct helper_data *data = transport->data;
 599
 600        /* Get_helper so connect is inited. */
 601        get_helper(transport);
 602        if (!data->connect)
 603                die("Operation not supported by protocol.");
 604
 605        if (!process_connect_service(transport, name, exec))
 606                die("Can't connect to subservice %s.", name);
 607
 608        fd[0] = data->helper->out;
 609        fd[1] = data->helper->in;
 610        return 0;
 611}
 612
 613static int fetch(struct transport *transport,
 614                 int nr_heads, struct ref **to_fetch)
 615{
 616        struct helper_data *data = transport->data;
 617        int i, count;
 618
 619        if (process_connect(transport, 0)) {
 620                do_take_over(transport);
 621                return transport->fetch(transport, nr_heads, to_fetch);
 622        }
 623
 624        count = 0;
 625        for (i = 0; i < nr_heads; i++)
 626                if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
 627                        count++;
 628
 629        if (!count)
 630                return 0;
 631
 632        if (data->fetch)
 633                return fetch_with_fetch(transport, nr_heads, to_fetch);
 634
 635        if (data->import)
 636                return fetch_with_import(transport, nr_heads, to_fetch);
 637
 638        return -1;
 639}
 640
 641static int push_update_ref_status(struct strbuf *buf,
 642                                   struct ref **ref,
 643                                   struct ref *remote_refs)
 644{
 645        char *refname, *msg;
 646        int status, forced = 0;
 647
 648        if (!prefixcmp(buf->buf, "ok ")) {
 649                status = REF_STATUS_OK;
 650                refname = buf->buf + 3;
 651        } else if (!prefixcmp(buf->buf, "error ")) {
 652                status = REF_STATUS_REMOTE_REJECT;
 653                refname = buf->buf + 6;
 654        } else
 655                die("expected ok/error, helper said '%s'", buf->buf);
 656
 657        msg = strchr(refname, ' ');
 658        if (msg) {
 659                struct strbuf msg_buf = STRBUF_INIT;
 660                const char *end;
 661
 662                *msg++ = '\0';
 663                if (!unquote_c_style(&msg_buf, msg, &end))
 664                        msg = strbuf_detach(&msg_buf, NULL);
 665                else
 666                        msg = xstrdup(msg);
 667                strbuf_release(&msg_buf);
 668
 669                if (!strcmp(msg, "no match")) {
 670                        status = REF_STATUS_NONE;
 671                        free(msg);
 672                        msg = NULL;
 673                }
 674                else if (!strcmp(msg, "up to date")) {
 675                        status = REF_STATUS_UPTODATE;
 676                        free(msg);
 677                        msg = NULL;
 678                }
 679                else if (!strcmp(msg, "non-fast forward")) {
 680                        status = REF_STATUS_REJECT_NONFASTFORWARD;
 681                        free(msg);
 682                        msg = NULL;
 683                }
 684                else if (!strcmp(msg, "already exists")) {
 685                        status = REF_STATUS_REJECT_ALREADY_EXISTS;
 686                        free(msg);
 687                        msg = NULL;
 688                }
 689                else if (!strcmp(msg, "fetch first")) {
 690                        status = REF_STATUS_REJECT_FETCH_FIRST;
 691                        free(msg);
 692                        msg = NULL;
 693                }
 694                else if (!strcmp(msg, "needs force")) {
 695                        status = REF_STATUS_REJECT_NEEDS_FORCE;
 696                        free(msg);
 697                        msg = NULL;
 698                }
 699                else if (!strcmp(msg, "stale info")) {
 700                        status = REF_STATUS_REJECT_STALE;
 701                        free(msg);
 702                        msg = NULL;
 703                }
 704                else if (!strcmp(msg, "forced update")) {
 705                        forced = 1;
 706                        free(msg);
 707                        msg = NULL;
 708                }
 709        }
 710
 711        if (*ref)
 712                *ref = find_ref_by_name(*ref, refname);
 713        if (!*ref)
 714                *ref = find_ref_by_name(remote_refs, refname);
 715        if (!*ref) {
 716                warning("helper reported unexpected status of %s", refname);
 717                return 1;
 718        }
 719
 720        if ((*ref)->status != REF_STATUS_NONE) {
 721                /*
 722                 * Earlier, the ref was marked not to be pushed, so ignore the ref
 723                 * status reported by the remote helper if the latter is 'no match'.
 724                 */
 725                if (status == REF_STATUS_NONE)
 726                        return 1;
 727        }
 728
 729        (*ref)->status = status;
 730        (*ref)->forced_update = forced;
 731        (*ref)->remote_status = msg;
 732        return !(status == REF_STATUS_OK);
 733}
 734
 735static void push_update_refs_status(struct helper_data *data,
 736                                    struct ref *remote_refs,
 737                                    int flags)
 738{
 739        struct strbuf buf = STRBUF_INIT;
 740        struct ref *ref = remote_refs;
 741        for (;;) {
 742                char *private;
 743
 744                recvline(data, &buf);
 745                if (!buf.len)
 746                        break;
 747
 748                if (push_update_ref_status(&buf, &ref, remote_refs))
 749                        continue;
 750
 751                if (flags & TRANSPORT_PUSH_DRY_RUN || !data->refspecs || data->no_private_update)
 752                        continue;
 753
 754                /* propagate back the update to the remote namespace */
 755                private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
 756                if (!private)
 757                        continue;
 758                update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
 759                free(private);
 760        }
 761        strbuf_release(&buf);
 762}
 763
 764static int push_refs_with_push(struct transport *transport,
 765                               struct ref *remote_refs, int flags)
 766{
 767        int force_all = flags & TRANSPORT_PUSH_FORCE;
 768        int mirror = flags & TRANSPORT_PUSH_MIRROR;
 769        struct helper_data *data = transport->data;
 770        struct strbuf buf = STRBUF_INIT;
 771        struct ref *ref;
 772        struct string_list cas_options = STRING_LIST_INIT_DUP;
 773        struct string_list_item *cas_option;
 774
 775        get_helper(transport);
 776        if (!data->push)
 777                return 1;
 778
 779        for (ref = remote_refs; ref; ref = ref->next) {
 780                if (!ref->peer_ref && !mirror)
 781                        continue;
 782
 783                /* Check for statuses set by set_ref_status_for_push() */
 784                switch (ref->status) {
 785                case REF_STATUS_REJECT_NONFASTFORWARD:
 786                case REF_STATUS_REJECT_STALE:
 787                case REF_STATUS_REJECT_ALREADY_EXISTS:
 788                case REF_STATUS_UPTODATE:
 789                        continue;
 790                default:
 791                        ; /* do nothing */
 792                }
 793
 794                if (force_all)
 795                        ref->force = 1;
 796
 797                strbuf_addstr(&buf, "push ");
 798                if (!ref->deletion) {
 799                        if (ref->force)
 800                                strbuf_addch(&buf, '+');
 801                        if (ref->peer_ref)
 802                                strbuf_addstr(&buf, ref->peer_ref->name);
 803                        else
 804                                strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
 805                }
 806                strbuf_addch(&buf, ':');
 807                strbuf_addstr(&buf, ref->name);
 808                strbuf_addch(&buf, '\n');
 809
 810                /*
 811                 * The "--force-with-lease" options without explicit
 812                 * values to expect have already been expanded into
 813                 * the ref->old_sha1_expect[] field; we can ignore
 814                 * transport->smart_options->cas altogether and instead
 815                 * can enumerate them from the refs.
 816                 */
 817                if (ref->expect_old_sha1) {
 818                        struct strbuf cas = STRBUF_INIT;
 819                        strbuf_addf(&cas, "%s:%s",
 820                                    ref->name, sha1_to_hex(ref->old_sha1_expect));
 821                        string_list_append(&cas_options, strbuf_detach(&cas, NULL));
 822                }
 823        }
 824        if (buf.len == 0) {
 825                string_list_clear(&cas_options, 0);
 826                return 0;
 827        }
 828
 829        standard_options(transport);
 830        for_each_string_list_item(cas_option, &cas_options)
 831                set_helper_option(transport, "cas", cas_option->string);
 832
 833        if (flags & TRANSPORT_PUSH_DRY_RUN) {
 834                if (set_helper_option(transport, "dry-run", "true") != 0)
 835                        die("helper %s does not support dry-run", data->name);
 836        }
 837
 838        strbuf_addch(&buf, '\n');
 839        sendline(data, &buf);
 840        strbuf_release(&buf);
 841
 842        push_update_refs_status(data, remote_refs, flags);
 843        return 0;
 844}
 845
 846static int push_refs_with_export(struct transport *transport,
 847                struct ref *remote_refs, int flags)
 848{
 849        struct ref *ref;
 850        struct child_process *helper, exporter;
 851        struct helper_data *data = transport->data;
 852        struct string_list revlist_args = STRING_LIST_INIT_NODUP;
 853        struct strbuf buf = STRBUF_INIT;
 854
 855        if (!data->refspecs)
 856                die("remote-helper doesn't support push; refspec needed");
 857
 858        if (flags & TRANSPORT_PUSH_DRY_RUN) {
 859                if (set_helper_option(transport, "dry-run", "true") != 0)
 860                        die("helper %s does not support dry-run", data->name);
 861        }
 862
 863        if (flags & TRANSPORT_PUSH_FORCE) {
 864                if (set_helper_option(transport, "force", "true") != 0)
 865                        warning("helper %s does not support 'force'", data->name);
 866        }
 867
 868        helper = get_helper(transport);
 869
 870        write_constant(helper->in, "export\n");
 871
 872        strbuf_reset(&buf);
 873
 874        for (ref = remote_refs; ref; ref = ref->next) {
 875                char *private;
 876                unsigned char sha1[20];
 877
 878                if (ref->deletion)
 879                        die("remote-helpers do not support ref deletion");
 880
 881                private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
 882                if (private && !get_sha1(private, sha1)) {
 883                        strbuf_addf(&buf, "^%s", private);
 884                        string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
 885                        hashcpy(ref->old_sha1, sha1);
 886                }
 887                free(private);
 888
 889                if (ref->peer_ref) {
 890                        if (strcmp(ref->peer_ref->name, ref->name))
 891                                die("remote-helpers do not support old:new syntax");
 892                        string_list_append(&revlist_args, ref->peer_ref->name);
 893                }
 894        }
 895
 896        if (get_exporter(transport, &exporter, &revlist_args))
 897                die("Couldn't run fast-export");
 898
 899        if (finish_command(&exporter))
 900                die("Error while running fast-export");
 901        push_update_refs_status(data, remote_refs, flags);
 902        return 0;
 903}
 904
 905static int push_refs(struct transport *transport,
 906                struct ref *remote_refs, int flags)
 907{
 908        struct helper_data *data = transport->data;
 909
 910        if (process_connect(transport, 1)) {
 911                do_take_over(transport);
 912                return transport->push_refs(transport, remote_refs, flags);
 913        }
 914
 915        if (!remote_refs) {
 916                fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
 917                        "Perhaps you should specify a branch such as 'master'.\n");
 918                return 0;
 919        }
 920
 921        if (data->push)
 922                return push_refs_with_push(transport, remote_refs, flags);
 923
 924        if (data->export)
 925                return push_refs_with_export(transport, remote_refs, flags);
 926
 927        return -1;
 928}
 929
 930
 931static int has_attribute(const char *attrs, const char *attr) {
 932        int len;
 933        if (!attrs)
 934                return 0;
 935
 936        len = strlen(attr);
 937        for (;;) {
 938                const char *space = strchrnul(attrs, ' ');
 939                if (len == space - attrs && !strncmp(attrs, attr, len))
 940                        return 1;
 941                if (!*space)
 942                        return 0;
 943                attrs = space + 1;
 944        }
 945}
 946
 947static struct ref *get_refs_list(struct transport *transport, int for_push)
 948{
 949        struct helper_data *data = transport->data;
 950        struct child_process *helper;
 951        struct ref *ret = NULL;
 952        struct ref **tail = &ret;
 953        struct ref *posn;
 954        struct strbuf buf = STRBUF_INIT;
 955
 956        helper = get_helper(transport);
 957
 958        if (process_connect(transport, for_push)) {
 959                do_take_over(transport);
 960                return transport->get_refs_list(transport, for_push);
 961        }
 962
 963        if (data->push && for_push)
 964                write_str_in_full(helper->in, "list for-push\n");
 965        else
 966                write_str_in_full(helper->in, "list\n");
 967
 968        while (1) {
 969                char *eov, *eon;
 970                recvline(data, &buf);
 971
 972                if (!*buf.buf)
 973                        break;
 974
 975                eov = strchr(buf.buf, ' ');
 976                if (!eov)
 977                        die("Malformed response in ref list: %s", buf.buf);
 978                eon = strchr(eov + 1, ' ');
 979                *eov = '\0';
 980                if (eon)
 981                        *eon = '\0';
 982                *tail = alloc_ref(eov + 1);
 983                if (buf.buf[0] == '@')
 984                        (*tail)->symref = xstrdup(buf.buf + 1);
 985                else if (buf.buf[0] != '?')
 986                        get_sha1_hex(buf.buf, (*tail)->old_sha1);
 987                if (eon) {
 988                        if (has_attribute(eon + 1, "unchanged")) {
 989                                (*tail)->status |= REF_STATUS_UPTODATE;
 990                                read_ref((*tail)->name, (*tail)->old_sha1);
 991                        }
 992                }
 993                tail = &((*tail)->next);
 994        }
 995        if (debug)
 996                fprintf(stderr, "Debug: Read ref listing.\n");
 997        strbuf_release(&buf);
 998
 999        for (posn = ret; posn; posn = posn->next)
1000                resolve_remote_symref(posn, ret);
1001
1002        return ret;
1003}
1004
1005int transport_helper_init(struct transport *transport, const char *name)
1006{
1007        struct helper_data *data = xcalloc(sizeof(*data), 1);
1008        data->name = name;
1009
1010        if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1011                debug = 1;
1012
1013        transport->data = data;
1014        transport->set_option = set_helper_option;
1015        transport->get_refs_list = get_refs_list;
1016        transport->fetch = fetch;
1017        transport->push_refs = push_refs;
1018        transport->disconnect = release_helper;
1019        transport->connect = connect_helper;
1020        transport->smart_options = &(data->transport_options);
1021        return 0;
1022}
1023
1024/*
1025 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1026 * buffer less), so attempt reads and writes with up to that size.
1027 */
1028#define BUFFERSIZE 65536
1029/* This should be enough to hold debugging message. */
1030#define PBUFFERSIZE 8192
1031
1032/* Print bidirectional transfer loop debug message. */
1033__attribute__((format (printf, 1, 2)))
1034static void transfer_debug(const char *fmt, ...)
1035{
1036        va_list args;
1037        char msgbuf[PBUFFERSIZE];
1038        static int debug_enabled = -1;
1039
1040        if (debug_enabled < 0)
1041                debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1042        if (!debug_enabled)
1043                return;
1044
1045        va_start(args, fmt);
1046        vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1047        va_end(args);
1048        fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1049}
1050
1051/* Stream state: More data may be coming in this direction. */
1052#define SSTATE_TRANSFERING 0
1053/*
1054 * Stream state: No more data coming in this direction, flushing rest of
1055 * data.
1056 */
1057#define SSTATE_FLUSHING 1
1058/* Stream state: Transfer in this direction finished. */
1059#define SSTATE_FINISHED 2
1060
1061#define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1062#define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1063#define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1064
1065/* Unidirectional transfer. */
1066struct unidirectional_transfer {
1067        /* Source */
1068        int src;
1069        /* Destination */
1070        int dest;
1071        /* Is source socket? */
1072        int src_is_sock;
1073        /* Is destination socket? */
1074        int dest_is_sock;
1075        /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1076        int state;
1077        /* Buffer. */
1078        char buf[BUFFERSIZE];
1079        /* Buffer used. */
1080        size_t bufuse;
1081        /* Name of source. */
1082        const char *src_name;
1083        /* Name of destination. */
1084        const char *dest_name;
1085};
1086
1087/* Closes the target (for writing) if transfer has finished. */
1088static void udt_close_if_finished(struct unidirectional_transfer *t)
1089{
1090        if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1091                t->state = SSTATE_FINISHED;
1092                if (t->dest_is_sock)
1093                        shutdown(t->dest, SHUT_WR);
1094                else
1095                        close(t->dest);
1096                transfer_debug("Closed %s.", t->dest_name);
1097        }
1098}
1099
1100/*
1101 * Tries to read read data from source into buffer. If buffer is full,
1102 * no data is read. Returns 0 on success, -1 on error.
1103 */
1104static int udt_do_read(struct unidirectional_transfer *t)
1105{
1106        ssize_t bytes;
1107
1108        if (t->bufuse == BUFFERSIZE)
1109                return 0;       /* No space for more. */
1110
1111        transfer_debug("%s is readable", t->src_name);
1112        bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1113        if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1114                errno != EINTR) {
1115                error("read(%s) failed: %s", t->src_name, strerror(errno));
1116                return -1;
1117        } else if (bytes == 0) {
1118                transfer_debug("%s EOF (with %i bytes in buffer)",
1119                        t->src_name, (int)t->bufuse);
1120                t->state = SSTATE_FLUSHING;
1121        } else if (bytes > 0) {
1122                t->bufuse += bytes;
1123                transfer_debug("Read %i bytes from %s (buffer now at %i)",
1124                        (int)bytes, t->src_name, (int)t->bufuse);
1125        }
1126        return 0;
1127}
1128
1129/* Tries to write data from buffer into destination. If buffer is empty,
1130 * no data is written. Returns 0 on success, -1 on error.
1131 */
1132static int udt_do_write(struct unidirectional_transfer *t)
1133{
1134        ssize_t bytes;
1135
1136        if (t->bufuse == 0)
1137                return 0;       /* Nothing to write. */
1138
1139        transfer_debug("%s is writable", t->dest_name);
1140        bytes = write(t->dest, t->buf, t->bufuse);
1141        if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1142                errno != EINTR) {
1143                error("write(%s) failed: %s", t->dest_name, strerror(errno));
1144                return -1;
1145        } else if (bytes > 0) {
1146                t->bufuse -= bytes;
1147                if (t->bufuse)
1148                        memmove(t->buf, t->buf + bytes, t->bufuse);
1149                transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1150                        (int)bytes, t->dest_name, (int)t->bufuse);
1151        }
1152        return 0;
1153}
1154
1155
1156/* State of bidirectional transfer loop. */
1157struct bidirectional_transfer_state {
1158        /* Direction from program to git. */
1159        struct unidirectional_transfer ptg;
1160        /* Direction from git to program. */
1161        struct unidirectional_transfer gtp;
1162};
1163
1164static void *udt_copy_task_routine(void *udt)
1165{
1166        struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1167        while (t->state != SSTATE_FINISHED) {
1168                if (STATE_NEEDS_READING(t->state))
1169                        if (udt_do_read(t))
1170                                return NULL;
1171                if (STATE_NEEDS_WRITING(t->state))
1172                        if (udt_do_write(t))
1173                                return NULL;
1174                if (STATE_NEEDS_CLOSING(t->state))
1175                        udt_close_if_finished(t);
1176        }
1177        return udt;     /* Just some non-NULL value. */
1178}
1179
1180#ifndef NO_PTHREADS
1181
1182/*
1183 * Join thread, with appropriate errors on failure. Name is name for the
1184 * thread (for error messages). Returns 0 on success, 1 on failure.
1185 */
1186static int tloop_join(pthread_t thread, const char *name)
1187{
1188        int err;
1189        void *tret;
1190        err = pthread_join(thread, &tret);
1191        if (!tret) {
1192                error("%s thread failed", name);
1193                return 1;
1194        }
1195        if (err) {
1196                error("%s thread failed to join: %s", name, strerror(err));
1197                return 1;
1198        }
1199        return 0;
1200}
1201
1202/*
1203 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1204 * -1 on failure.
1205 */
1206static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1207{
1208        pthread_t gtp_thread;
1209        pthread_t ptg_thread;
1210        int err;
1211        int ret = 0;
1212        err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1213                &s->gtp);
1214        if (err)
1215                die("Can't start thread for copying data: %s", strerror(err));
1216        err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1217                &s->ptg);
1218        if (err)
1219                die("Can't start thread for copying data: %s", strerror(err));
1220
1221        ret |= tloop_join(gtp_thread, "Git to program copy");
1222        ret |= tloop_join(ptg_thread, "Program to git copy");
1223        return ret;
1224}
1225#else
1226
1227/* Close the source and target (for writing) for transfer. */
1228static void udt_kill_transfer(struct unidirectional_transfer *t)
1229{
1230        t->state = SSTATE_FINISHED;
1231        /*
1232         * Socket read end left open isn't a disaster if nobody
1233         * attempts to read from it (mingw compat headers do not
1234         * have SHUT_RD)...
1235         *
1236         * We can't fully close the socket since otherwise gtp
1237         * task would first close the socket it sends data to
1238         * while closing the ptg file descriptors.
1239         */
1240        if (!t->src_is_sock)
1241                close(t->src);
1242        if (t->dest_is_sock)
1243                shutdown(t->dest, SHUT_WR);
1244        else
1245                close(t->dest);
1246}
1247
1248/*
1249 * Join process, with appropriate errors on failure. Name is name for the
1250 * process (for error messages). Returns 0 on success, 1 on failure.
1251 */
1252static int tloop_join(pid_t pid, const char *name)
1253{
1254        int tret;
1255        if (waitpid(pid, &tret, 0) < 0) {
1256                error("%s process failed to wait: %s", name, strerror(errno));
1257                return 1;
1258        }
1259        if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1260                error("%s process failed", name);
1261                return 1;
1262        }
1263        return 0;
1264}
1265
1266/*
1267 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1268 * -1 on failure.
1269 */
1270static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1271{
1272        pid_t pid1, pid2;
1273        int ret = 0;
1274
1275        /* Fork thread #1: git to program. */
1276        pid1 = fork();
1277        if (pid1 < 0)
1278                die_errno("Can't start thread for copying data");
1279        else if (pid1 == 0) {
1280                udt_kill_transfer(&s->ptg);
1281                exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1282        }
1283
1284        /* Fork thread #2: program to git. */
1285        pid2 = fork();
1286        if (pid2 < 0)
1287                die_errno("Can't start thread for copying data");
1288        else if (pid2 == 0) {
1289                udt_kill_transfer(&s->gtp);
1290                exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1291        }
1292
1293        /*
1294         * Close both streams in parent as to not interfere with
1295         * end of file detection and wait for both tasks to finish.
1296         */
1297        udt_kill_transfer(&s->gtp);
1298        udt_kill_transfer(&s->ptg);
1299        ret |= tloop_join(pid1, "Git to program copy");
1300        ret |= tloop_join(pid2, "Program to git copy");
1301        return ret;
1302}
1303#endif
1304
1305/*
1306 * Copies data from stdin to output and from input to stdout simultaneously.
1307 * Additionally filtering through given filter. If filter is NULL, uses
1308 * identity filter.
1309 */
1310int bidirectional_transfer_loop(int input, int output)
1311{
1312        struct bidirectional_transfer_state state;
1313
1314        /* Fill the state fields. */
1315        state.ptg.src = input;
1316        state.ptg.dest = 1;
1317        state.ptg.src_is_sock = (input == output);
1318        state.ptg.dest_is_sock = 0;
1319        state.ptg.state = SSTATE_TRANSFERING;
1320        state.ptg.bufuse = 0;
1321        state.ptg.src_name = "remote input";
1322        state.ptg.dest_name = "stdout";
1323
1324        state.gtp.src = 0;
1325        state.gtp.dest = output;
1326        state.gtp.src_is_sock = 0;
1327        state.gtp.dest_is_sock = (input == output);
1328        state.gtp.state = SSTATE_TRANSFERING;
1329        state.gtp.bufuse = 0;
1330        state.gtp.src_name = "stdin";
1331        state.gtp.dest_name = "remote output";
1332
1333        return tloop_spawnwait_tasks(&state);
1334}