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