transport-helper.con commit transport-helper: add no-private-update capability (597b831)
   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                no_disconnect_req : 1,
  31                no_private_update : 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 (!data->refspecs && !prefixcmp(capname, "refspec ")) {
 191                        ALLOC_GROW(refspecs,
 192                                   refspec_nr + 1,
 193                                   refspec_alloc);
 194                        refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
 195                } else if (!strcmp(capname, "connect")) {
 196                        data->connect = 1;
 197                } else if (!strcmp(capname, "signed-tags")) {
 198                        data->signed_tags = 1;
 199                } else if (!prefixcmp(capname, "export-marks ")) {
 200                        struct strbuf arg = STRBUF_INIT;
 201                        strbuf_addstr(&arg, "--export-marks=");
 202                        strbuf_addstr(&arg, capname + strlen("export-marks "));
 203                        data->export_marks = strbuf_detach(&arg, NULL);
 204                } else if (!prefixcmp(capname, "import-marks")) {
 205                        struct strbuf arg = STRBUF_INIT;
 206                        strbuf_addstr(&arg, "--import-marks=");
 207                        strbuf_addstr(&arg, capname + strlen("import-marks "));
 208                        data->import_marks = strbuf_detach(&arg, NULL);
 209                } else if (!prefixcmp(capname, "no-private-update")) {
 210                        data->no_private_update = 1;
 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
 356        for (i = 0; i < nr_heads; i++) {
 357                const struct ref *posn = to_fetch[i];
 358                if (posn->status & REF_STATUS_UPTODATE)
 359                        continue;
 360
 361                strbuf_addf(&buf, "fetch %s %s\n",
 362                            sha1_to_hex(posn->old_sha1), posn->name);
 363        }
 364
 365        strbuf_addch(&buf, '\n');
 366        sendline(data, &buf);
 367
 368        while (1) {
 369                recvline(data, &buf);
 370
 371                if (!prefixcmp(buf.buf, "lock ")) {
 372                        const char *name = buf.buf + 5;
 373                        if (transport->pack_lockfile)
 374                                warning("%s also locked %s", data->name, name);
 375                        else
 376                                transport->pack_lockfile = xstrdup(name);
 377                }
 378                else if (!buf.len)
 379                        break;
 380                else
 381                        warning("%s unexpectedly said: '%s'", data->name, buf.buf);
 382        }
 383        strbuf_release(&buf);
 384        return 0;
 385}
 386
 387static int get_importer(struct transport *transport, struct child_process *fastimport)
 388{
 389        struct child_process *helper = get_helper(transport);
 390        struct helper_data *data = transport->data;
 391        struct argv_array argv = ARGV_ARRAY_INIT;
 392        int cat_blob_fd, code;
 393        memset(fastimport, 0, sizeof(*fastimport));
 394        fastimport->in = helper->out;
 395        argv_array_push(&argv, "fast-import");
 396        argv_array_push(&argv, debug ? "--stats" : "--quiet");
 397
 398        if (data->bidi_import) {
 399                cat_blob_fd = xdup(helper->in);
 400                argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
 401        }
 402        fastimport->argv = argv.argv;
 403        fastimport->git_cmd = 1;
 404
 405        code = start_command(fastimport);
 406        return code;
 407}
 408
 409static int get_exporter(struct transport *transport,
 410                        struct child_process *fastexport,
 411                        struct string_list *revlist_args)
 412{
 413        struct helper_data *data = transport->data;
 414        struct child_process *helper = get_helper(transport);
 415        int argc = 0, i;
 416        memset(fastexport, 0, sizeof(*fastexport));
 417
 418        /* we need to duplicate helper->in because we want to use it after
 419         * fastexport is done with it. */
 420        fastexport->out = dup(helper->in);
 421        fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
 422        fastexport->argv[argc++] = "fast-export";
 423        fastexport->argv[argc++] = "--use-done-feature";
 424        fastexport->argv[argc++] = data->signed_tags ?
 425                "--signed-tags=verbatim" : "--signed-tags=warn-strip";
 426        if (data->export_marks)
 427                fastexport->argv[argc++] = data->export_marks;
 428        if (data->import_marks)
 429                fastexport->argv[argc++] = data->import_marks;
 430
 431        for (i = 0; i < revlist_args->nr; i++)
 432                fastexport->argv[argc++] = revlist_args->items[i].string;
 433
 434        fastexport->git_cmd = 1;
 435        return start_command(fastexport);
 436}
 437
 438static int fetch_with_import(struct transport *transport,
 439                             int nr_heads, struct ref **to_fetch)
 440{
 441        struct child_process fastimport;
 442        struct helper_data *data = transport->data;
 443        int i;
 444        struct ref *posn;
 445        struct strbuf buf = STRBUF_INIT;
 446
 447        get_helper(transport);
 448
 449        if (get_importer(transport, &fastimport))
 450                die("Couldn't run fast-import");
 451
 452        for (i = 0; i < nr_heads; i++) {
 453                posn = to_fetch[i];
 454                if (posn->status & REF_STATUS_UPTODATE)
 455                        continue;
 456
 457                strbuf_addf(&buf, "import %s\n", posn->name);
 458                sendline(data, &buf);
 459                strbuf_reset(&buf);
 460        }
 461
 462        write_constant(data->helper->in, "\n");
 463        /*
 464         * remote-helpers that advertise the bidi-import capability are required to
 465         * buffer the complete batch of import commands until this newline before
 466         * sending data to fast-import.
 467         * These helpers read back data from fast-import on their stdin, which could
 468         * be mixed with import commands, otherwise.
 469         */
 470
 471        if (finish_command(&fastimport))
 472                die("Error while running fast-import");
 473        argv_array_free_detached(fastimport.argv);
 474
 475        /*
 476         * The fast-import stream of a remote helper that advertises
 477         * the "refspec" capability writes to the refs named after the
 478         * right hand side of the first refspec matching each ref we
 479         * were fetching.
 480         *
 481         * (If no "refspec" capability was specified, for historical
 482         * reasons we default to the equivalent of *:*.)
 483         *
 484         * Store the result in to_fetch[i].old_sha1.  Callers such
 485         * as "git fetch" can use the value to write feedback to the
 486         * terminal, populate FETCH_HEAD, and determine what new value
 487         * should be written to peer_ref if the update is a
 488         * fast-forward or this is a forced update.
 489         */
 490        for (i = 0; i < nr_heads; i++) {
 491                char *private;
 492                posn = to_fetch[i];
 493                if (posn->status & REF_STATUS_UPTODATE)
 494                        continue;
 495                if (data->refspecs)
 496                        private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
 497                else
 498                        private = xstrdup(posn->name);
 499                if (private) {
 500                        read_ref(private, posn->old_sha1);
 501                        free(private);
 502                }
 503        }
 504        strbuf_release(&buf);
 505        return 0;
 506}
 507
 508static int process_connect_service(struct transport *transport,
 509                                   const char *name, const char *exec)
 510{
 511        struct helper_data *data = transport->data;
 512        struct strbuf cmdbuf = STRBUF_INIT;
 513        struct child_process *helper;
 514        int r, duped, ret = 0;
 515        FILE *input;
 516
 517        helper = get_helper(transport);
 518
 519        /*
 520         * Yes, dup the pipe another time, as we need unbuffered version
 521         * of input pipe as FILE*. fclose() closes the underlying fd and
 522         * stream buffering only can be changed before first I/O operation
 523         * on it.
 524         */
 525        duped = dup(helper->out);
 526        if (duped < 0)
 527                die_errno("Can't dup helper output fd");
 528        input = xfdopen(duped, "r");
 529        setvbuf(input, NULL, _IONBF, 0);
 530
 531        /*
 532         * Handle --upload-pack and friends. This is fire and forget...
 533         * just warn if it fails.
 534         */
 535        if (strcmp(name, exec)) {
 536                r = set_helper_option(transport, "servpath", exec);
 537                if (r > 0)
 538                        warning("Setting remote service path not supported by protocol.");
 539                else if (r < 0)
 540                        warning("Invalid remote service path.");
 541        }
 542
 543        if (data->connect)
 544                strbuf_addf(&cmdbuf, "connect %s\n", name);
 545        else
 546                goto exit;
 547
 548        sendline(data, &cmdbuf);
 549        recvline_fh(input, &cmdbuf, name);
 550        if (!strcmp(cmdbuf.buf, "")) {
 551                data->no_disconnect_req = 1;
 552                if (debug)
 553                        fprintf(stderr, "Debug: Smart transport connection "
 554                                "ready.\n");
 555                ret = 1;
 556        } else if (!strcmp(cmdbuf.buf, "fallback")) {
 557                if (debug)
 558                        fprintf(stderr, "Debug: Falling back to dumb "
 559                                "transport.\n");
 560        } else
 561                die("Unknown response to connect: %s",
 562                        cmdbuf.buf);
 563
 564exit:
 565        fclose(input);
 566        return ret;
 567}
 568
 569static int process_connect(struct transport *transport,
 570                                     int for_push)
 571{
 572        struct helper_data *data = transport->data;
 573        const char *name;
 574        const char *exec;
 575
 576        name = for_push ? "git-receive-pack" : "git-upload-pack";
 577        if (for_push)
 578                exec = data->transport_options.receivepack;
 579        else
 580                exec = data->transport_options.uploadpack;
 581
 582        return process_connect_service(transport, name, exec);
 583}
 584
 585static int connect_helper(struct transport *transport, const char *name,
 586                   const char *exec, int fd[2])
 587{
 588        struct helper_data *data = transport->data;
 589
 590        /* Get_helper so connect is inited. */
 591        get_helper(transport);
 592        if (!data->connect)
 593                die("Operation not supported by protocol.");
 594
 595        if (!process_connect_service(transport, name, exec))
 596                die("Can't connect to subservice %s.", name);
 597
 598        fd[0] = data->helper->out;
 599        fd[1] = data->helper->in;
 600        return 0;
 601}
 602
 603static int fetch(struct transport *transport,
 604                 int nr_heads, struct ref **to_fetch)
 605{
 606        struct helper_data *data = transport->data;
 607        int i, count;
 608
 609        if (process_connect(transport, 0)) {
 610                do_take_over(transport);
 611                return transport->fetch(transport, nr_heads, to_fetch);
 612        }
 613
 614        count = 0;
 615        for (i = 0; i < nr_heads; i++)
 616                if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
 617                        count++;
 618
 619        if (!count)
 620                return 0;
 621
 622        if (data->fetch)
 623                return fetch_with_fetch(transport, nr_heads, to_fetch);
 624
 625        if (data->import)
 626                return fetch_with_import(transport, nr_heads, to_fetch);
 627
 628        return -1;
 629}
 630
 631static int push_update_ref_status(struct strbuf *buf,
 632                                   struct ref **ref,
 633                                   struct ref *remote_refs)
 634{
 635        char *refname, *msg;
 636        int status;
 637
 638        if (!prefixcmp(buf->buf, "ok ")) {
 639                status = REF_STATUS_OK;
 640                refname = buf->buf + 3;
 641        } else if (!prefixcmp(buf->buf, "error ")) {
 642                status = REF_STATUS_REMOTE_REJECT;
 643                refname = buf->buf + 6;
 644        } else
 645                die("expected ok/error, helper said '%s'", buf->buf);
 646
 647        msg = strchr(refname, ' ');
 648        if (msg) {
 649                struct strbuf msg_buf = STRBUF_INIT;
 650                const char *end;
 651
 652                *msg++ = '\0';
 653                if (!unquote_c_style(&msg_buf, msg, &end))
 654                        msg = strbuf_detach(&msg_buf, NULL);
 655                else
 656                        msg = xstrdup(msg);
 657                strbuf_release(&msg_buf);
 658
 659                if (!strcmp(msg, "no match")) {
 660                        status = REF_STATUS_NONE;
 661                        free(msg);
 662                        msg = NULL;
 663                }
 664                else if (!strcmp(msg, "up to date")) {
 665                        status = REF_STATUS_UPTODATE;
 666                        free(msg);
 667                        msg = NULL;
 668                }
 669                else if (!strcmp(msg, "non-fast forward")) {
 670                        status = REF_STATUS_REJECT_NONFASTFORWARD;
 671                        free(msg);
 672                        msg = NULL;
 673                }
 674                else if (!strcmp(msg, "already exists")) {
 675                        status = REF_STATUS_REJECT_ALREADY_EXISTS;
 676                        free(msg);
 677                        msg = NULL;
 678                }
 679                else if (!strcmp(msg, "fetch first")) {
 680                        status = REF_STATUS_REJECT_FETCH_FIRST;
 681                        free(msg);
 682                        msg = NULL;
 683                }
 684                else if (!strcmp(msg, "needs force")) {
 685                        status = REF_STATUS_REJECT_NEEDS_FORCE;
 686                        free(msg);
 687                        msg = NULL;
 688                }
 689        }
 690
 691        if (*ref)
 692                *ref = find_ref_by_name(*ref, refname);
 693        if (!*ref)
 694                *ref = find_ref_by_name(remote_refs, refname);
 695        if (!*ref) {
 696                warning("helper reported unexpected status of %s", refname);
 697                return 1;
 698        }
 699
 700        if ((*ref)->status != REF_STATUS_NONE) {
 701                /*
 702                 * Earlier, the ref was marked not to be pushed, so ignore the ref
 703                 * status reported by the remote helper if the latter is 'no match'.
 704                 */
 705                if (status == REF_STATUS_NONE)
 706                        return 1;
 707        }
 708
 709        (*ref)->status = status;
 710        (*ref)->remote_status = msg;
 711        return !(status == REF_STATUS_OK);
 712}
 713
 714static void push_update_refs_status(struct helper_data *data,
 715                                    struct ref *remote_refs)
 716{
 717        struct strbuf buf = STRBUF_INIT;
 718        struct ref *ref = remote_refs;
 719        for (;;) {
 720                char *private;
 721
 722                recvline(data, &buf);
 723                if (!buf.len)
 724                        break;
 725
 726                if (push_update_ref_status(&buf, &ref, remote_refs))
 727                        continue;
 728
 729                if (!data->refspecs || data->no_private_update)
 730                        continue;
 731
 732                /* propagate back the update to the remote namespace */
 733                private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
 734                if (!private)
 735                        continue;
 736                update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
 737                free(private);
 738        }
 739        strbuf_release(&buf);
 740}
 741
 742static int push_refs_with_push(struct transport *transport,
 743                struct ref *remote_refs, int flags)
 744{
 745        int force_all = flags & TRANSPORT_PUSH_FORCE;
 746        int mirror = flags & TRANSPORT_PUSH_MIRROR;
 747        struct helper_data *data = transport->data;
 748        struct strbuf buf = STRBUF_INIT;
 749        struct ref *ref;
 750
 751        get_helper(transport);
 752        if (!data->push)
 753                return 1;
 754
 755        for (ref = remote_refs; ref; ref = ref->next) {
 756                if (!ref->peer_ref && !mirror)
 757                        continue;
 758
 759                /* Check for statuses set by set_ref_status_for_push() */
 760                switch (ref->status) {
 761                case REF_STATUS_REJECT_NONFASTFORWARD:
 762                case REF_STATUS_REJECT_ALREADY_EXISTS:
 763                case REF_STATUS_UPTODATE:
 764                        continue;
 765                default:
 766                        ; /* do nothing */
 767                }
 768
 769                if (force_all)
 770                        ref->force = 1;
 771
 772                strbuf_addstr(&buf, "push ");
 773                if (!ref->deletion) {
 774                        if (ref->force)
 775                                strbuf_addch(&buf, '+');
 776                        if (ref->peer_ref)
 777                                strbuf_addstr(&buf, ref->peer_ref->name);
 778                        else
 779                                strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
 780                }
 781                strbuf_addch(&buf, ':');
 782                strbuf_addstr(&buf, ref->name);
 783                strbuf_addch(&buf, '\n');
 784        }
 785        if (buf.len == 0)
 786                return 0;
 787
 788        standard_options(transport);
 789
 790        if (flags & TRANSPORT_PUSH_DRY_RUN) {
 791                if (set_helper_option(transport, "dry-run", "true") != 0)
 792                        die("helper %s does not support dry-run", data->name);
 793        }
 794
 795        strbuf_addch(&buf, '\n');
 796        sendline(data, &buf);
 797        strbuf_release(&buf);
 798
 799        push_update_refs_status(data, remote_refs);
 800        return 0;
 801}
 802
 803static int push_refs_with_export(struct transport *transport,
 804                struct ref *remote_refs, int flags)
 805{
 806        struct ref *ref;
 807        struct child_process *helper, exporter;
 808        struct helper_data *data = transport->data;
 809        struct string_list revlist_args = STRING_LIST_INIT_NODUP;
 810        struct strbuf buf = STRBUF_INIT;
 811
 812        if (!data->refspecs)
 813                die("remote-helper doesn't support push; refspec needed");
 814
 815        if (flags & TRANSPORT_PUSH_DRY_RUN) {
 816                if (set_helper_option(transport, "dry-run", "true") != 0)
 817                        die("helper %s does not support dry-run", data->name);
 818        }
 819
 820        helper = get_helper(transport);
 821
 822        write_constant(helper->in, "export\n");
 823
 824        strbuf_reset(&buf);
 825
 826        for (ref = remote_refs; ref; ref = ref->next) {
 827                char *private;
 828                unsigned char sha1[20];
 829
 830                if (ref->deletion)
 831                        die("remote-helpers do not support ref deletion");
 832
 833                private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
 834                if (private && !get_sha1(private, sha1)) {
 835                        strbuf_addf(&buf, "^%s", private);
 836                        string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
 837                        hashcpy(ref->old_sha1, sha1);
 838                }
 839                free(private);
 840
 841                if (ref->deletion)
 842                        die("remote-helpers do not support ref deletion");
 843
 844                if (ref->peer_ref) {
 845                        if (strcmp(ref->peer_ref->name, ref->name))
 846                                die("remote-helpers do not support old:new syntax");
 847                        string_list_append(&revlist_args, ref->peer_ref->name);
 848                }
 849        }
 850
 851        if (get_exporter(transport, &exporter, &revlist_args))
 852                die("Couldn't run fast-export");
 853
 854        if (finish_command(&exporter))
 855                die("Error while running fast-export");
 856        push_update_refs_status(data, remote_refs);
 857        return 0;
 858}
 859
 860static int push_refs(struct transport *transport,
 861                struct ref *remote_refs, int flags)
 862{
 863        struct helper_data *data = transport->data;
 864
 865        if (process_connect(transport, 1)) {
 866                do_take_over(transport);
 867                return transport->push_refs(transport, remote_refs, flags);
 868        }
 869
 870        if (!remote_refs) {
 871                fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
 872                        "Perhaps you should specify a branch such as 'master'.\n");
 873                return 0;
 874        }
 875
 876        if (data->push)
 877                return push_refs_with_push(transport, remote_refs, flags);
 878
 879        if (data->export)
 880                return push_refs_with_export(transport, remote_refs, flags);
 881
 882        return -1;
 883}
 884
 885
 886static int has_attribute(const char *attrs, const char *attr) {
 887        int len;
 888        if (!attrs)
 889                return 0;
 890
 891        len = strlen(attr);
 892        for (;;) {
 893                const char *space = strchrnul(attrs, ' ');
 894                if (len == space - attrs && !strncmp(attrs, attr, len))
 895                        return 1;
 896                if (!*space)
 897                        return 0;
 898                attrs = space + 1;
 899        }
 900}
 901
 902static struct ref *get_refs_list(struct transport *transport, int for_push)
 903{
 904        struct helper_data *data = transport->data;
 905        struct child_process *helper;
 906        struct ref *ret = NULL;
 907        struct ref **tail = &ret;
 908        struct ref *posn;
 909        struct strbuf buf = STRBUF_INIT;
 910
 911        helper = get_helper(transport);
 912
 913        if (process_connect(transport, for_push)) {
 914                do_take_over(transport);
 915                return transport->get_refs_list(transport, for_push);
 916        }
 917
 918        if (data->push && for_push)
 919                write_str_in_full(helper->in, "list for-push\n");
 920        else
 921                write_str_in_full(helper->in, "list\n");
 922
 923        while (1) {
 924                char *eov, *eon;
 925                recvline(data, &buf);
 926
 927                if (!*buf.buf)
 928                        break;
 929
 930                eov = strchr(buf.buf, ' ');
 931                if (!eov)
 932                        die("Malformed response in ref list: %s", buf.buf);
 933                eon = strchr(eov + 1, ' ');
 934                *eov = '\0';
 935                if (eon)
 936                        *eon = '\0';
 937                *tail = alloc_ref(eov + 1);
 938                if (buf.buf[0] == '@')
 939                        (*tail)->symref = xstrdup(buf.buf + 1);
 940                else if (buf.buf[0] != '?')
 941                        get_sha1_hex(buf.buf, (*tail)->old_sha1);
 942                if (eon) {
 943                        if (has_attribute(eon + 1, "unchanged")) {
 944                                (*tail)->status |= REF_STATUS_UPTODATE;
 945                                read_ref((*tail)->name, (*tail)->old_sha1);
 946                        }
 947                }
 948                tail = &((*tail)->next);
 949        }
 950        if (debug)
 951                fprintf(stderr, "Debug: Read ref listing.\n");
 952        strbuf_release(&buf);
 953
 954        for (posn = ret; posn; posn = posn->next)
 955                resolve_remote_symref(posn, ret);
 956
 957        return ret;
 958}
 959
 960int transport_helper_init(struct transport *transport, const char *name)
 961{
 962        struct helper_data *data = xcalloc(sizeof(*data), 1);
 963        data->name = name;
 964
 965        if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
 966                debug = 1;
 967
 968        transport->data = data;
 969        transport->set_option = set_helper_option;
 970        transport->get_refs_list = get_refs_list;
 971        transport->fetch = fetch;
 972        transport->push_refs = push_refs;
 973        transport->disconnect = release_helper;
 974        transport->connect = connect_helper;
 975        transport->smart_options = &(data->transport_options);
 976        return 0;
 977}
 978
 979/*
 980 * Linux pipes can buffer 65536 bytes at once (and most platforms can
 981 * buffer less), so attempt reads and writes with up to that size.
 982 */
 983#define BUFFERSIZE 65536
 984/* This should be enough to hold debugging message. */
 985#define PBUFFERSIZE 8192
 986
 987/* Print bidirectional transfer loop debug message. */
 988__attribute__((format (printf, 1, 2)))
 989static void transfer_debug(const char *fmt, ...)
 990{
 991        va_list args;
 992        char msgbuf[PBUFFERSIZE];
 993        static int debug_enabled = -1;
 994
 995        if (debug_enabled < 0)
 996                debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
 997        if (!debug_enabled)
 998                return;
 999
1000        va_start(args, fmt);
1001        vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1002        va_end(args);
1003        fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1004}
1005
1006/* Stream state: More data may be coming in this direction. */
1007#define SSTATE_TRANSFERING 0
1008/*
1009 * Stream state: No more data coming in this direction, flushing rest of
1010 * data.
1011 */
1012#define SSTATE_FLUSHING 1
1013/* Stream state: Transfer in this direction finished. */
1014#define SSTATE_FINISHED 2
1015
1016#define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1017#define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1018#define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1019
1020/* Unidirectional transfer. */
1021struct unidirectional_transfer {
1022        /* Source */
1023        int src;
1024        /* Destination */
1025        int dest;
1026        /* Is source socket? */
1027        int src_is_sock;
1028        /* Is destination socket? */
1029        int dest_is_sock;
1030        /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1031        int state;
1032        /* Buffer. */
1033        char buf[BUFFERSIZE];
1034        /* Buffer used. */
1035        size_t bufuse;
1036        /* Name of source. */
1037        const char *src_name;
1038        /* Name of destination. */
1039        const char *dest_name;
1040};
1041
1042/* Closes the target (for writing) if transfer has finished. */
1043static void udt_close_if_finished(struct unidirectional_transfer *t)
1044{
1045        if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1046                t->state = SSTATE_FINISHED;
1047                if (t->dest_is_sock)
1048                        shutdown(t->dest, SHUT_WR);
1049                else
1050                        close(t->dest);
1051                transfer_debug("Closed %s.", t->dest_name);
1052        }
1053}
1054
1055/*
1056 * Tries to read read data from source into buffer. If buffer is full,
1057 * no data is read. Returns 0 on success, -1 on error.
1058 */
1059static int udt_do_read(struct unidirectional_transfer *t)
1060{
1061        ssize_t bytes;
1062
1063        if (t->bufuse == BUFFERSIZE)
1064                return 0;       /* No space for more. */
1065
1066        transfer_debug("%s is readable", t->src_name);
1067        bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1068        if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1069                errno != EINTR) {
1070                error("read(%s) failed: %s", t->src_name, strerror(errno));
1071                return -1;
1072        } else if (bytes == 0) {
1073                transfer_debug("%s EOF (with %i bytes in buffer)",
1074                        t->src_name, (int)t->bufuse);
1075                t->state = SSTATE_FLUSHING;
1076        } else if (bytes > 0) {
1077                t->bufuse += bytes;
1078                transfer_debug("Read %i bytes from %s (buffer now at %i)",
1079                        (int)bytes, t->src_name, (int)t->bufuse);
1080        }
1081        return 0;
1082}
1083
1084/* Tries to write data from buffer into destination. If buffer is empty,
1085 * no data is written. Returns 0 on success, -1 on error.
1086 */
1087static int udt_do_write(struct unidirectional_transfer *t)
1088{
1089        ssize_t bytes;
1090
1091        if (t->bufuse == 0)
1092                return 0;       /* Nothing to write. */
1093
1094        transfer_debug("%s is writable", t->dest_name);
1095        bytes = write(t->dest, t->buf, t->bufuse);
1096        if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1097                errno != EINTR) {
1098                error("write(%s) failed: %s", t->dest_name, strerror(errno));
1099                return -1;
1100        } else if (bytes > 0) {
1101                t->bufuse -= bytes;
1102                if (t->bufuse)
1103                        memmove(t->buf, t->buf + bytes, t->bufuse);
1104                transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1105                        (int)bytes, t->dest_name, (int)t->bufuse);
1106        }
1107        return 0;
1108}
1109
1110
1111/* State of bidirectional transfer loop. */
1112struct bidirectional_transfer_state {
1113        /* Direction from program to git. */
1114        struct unidirectional_transfer ptg;
1115        /* Direction from git to program. */
1116        struct unidirectional_transfer gtp;
1117};
1118
1119static void *udt_copy_task_routine(void *udt)
1120{
1121        struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1122        while (t->state != SSTATE_FINISHED) {
1123                if (STATE_NEEDS_READING(t->state))
1124                        if (udt_do_read(t))
1125                                return NULL;
1126                if (STATE_NEEDS_WRITING(t->state))
1127                        if (udt_do_write(t))
1128                                return NULL;
1129                if (STATE_NEEDS_CLOSING(t->state))
1130                        udt_close_if_finished(t);
1131        }
1132        return udt;     /* Just some non-NULL value. */
1133}
1134
1135#ifndef NO_PTHREADS
1136
1137/*
1138 * Join thread, with appropriate errors on failure. Name is name for the
1139 * thread (for error messages). Returns 0 on success, 1 on failure.
1140 */
1141static int tloop_join(pthread_t thread, const char *name)
1142{
1143        int err;
1144        void *tret;
1145        err = pthread_join(thread, &tret);
1146        if (!tret) {
1147                error("%s thread failed", name);
1148                return 1;
1149        }
1150        if (err) {
1151                error("%s thread failed to join: %s", name, strerror(err));
1152                return 1;
1153        }
1154        return 0;
1155}
1156
1157/*
1158 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1159 * -1 on failure.
1160 */
1161static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1162{
1163        pthread_t gtp_thread;
1164        pthread_t ptg_thread;
1165        int err;
1166        int ret = 0;
1167        err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1168                &s->gtp);
1169        if (err)
1170                die("Can't start thread for copying data: %s", strerror(err));
1171        err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1172                &s->ptg);
1173        if (err)
1174                die("Can't start thread for copying data: %s", strerror(err));
1175
1176        ret |= tloop_join(gtp_thread, "Git to program copy");
1177        ret |= tloop_join(ptg_thread, "Program to git copy");
1178        return ret;
1179}
1180#else
1181
1182/* Close the source and target (for writing) for transfer. */
1183static void udt_kill_transfer(struct unidirectional_transfer *t)
1184{
1185        t->state = SSTATE_FINISHED;
1186        /*
1187         * Socket read end left open isn't a disaster if nobody
1188         * attempts to read from it (mingw compat headers do not
1189         * have SHUT_RD)...
1190         *
1191         * We can't fully close the socket since otherwise gtp
1192         * task would first close the socket it sends data to
1193         * while closing the ptg file descriptors.
1194         */
1195        if (!t->src_is_sock)
1196                close(t->src);
1197        if (t->dest_is_sock)
1198                shutdown(t->dest, SHUT_WR);
1199        else
1200                close(t->dest);
1201}
1202
1203/*
1204 * Join process, with appropriate errors on failure. Name is name for the
1205 * process (for error messages). Returns 0 on success, 1 on failure.
1206 */
1207static int tloop_join(pid_t pid, const char *name)
1208{
1209        int tret;
1210        if (waitpid(pid, &tret, 0) < 0) {
1211                error("%s process failed to wait: %s", name, strerror(errno));
1212                return 1;
1213        }
1214        if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1215                error("%s process failed", name);
1216                return 1;
1217        }
1218        return 0;
1219}
1220
1221/*
1222 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1223 * -1 on failure.
1224 */
1225static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1226{
1227        pid_t pid1, pid2;
1228        int ret = 0;
1229
1230        /* Fork thread #1: git to program. */
1231        pid1 = fork();
1232        if (pid1 < 0)
1233                die_errno("Can't start thread for copying data");
1234        else if (pid1 == 0) {
1235                udt_kill_transfer(&s->ptg);
1236                exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1237        }
1238
1239        /* Fork thread #2: program to git. */
1240        pid2 = fork();
1241        if (pid2 < 0)
1242                die_errno("Can't start thread for copying data");
1243        else if (pid2 == 0) {
1244                udt_kill_transfer(&s->gtp);
1245                exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1246        }
1247
1248        /*
1249         * Close both streams in parent as to not interfere with
1250         * end of file detection and wait for both tasks to finish.
1251         */
1252        udt_kill_transfer(&s->gtp);
1253        udt_kill_transfer(&s->ptg);
1254        ret |= tloop_join(pid1, "Git to program copy");
1255        ret |= tloop_join(pid2, "Program to git copy");
1256        return ret;
1257}
1258#endif
1259
1260/*
1261 * Copies data from stdin to output and from input to stdout simultaneously.
1262 * Additionally filtering through given filter. If filter is NULL, uses
1263 * identity filter.
1264 */
1265int bidirectional_transfer_loop(int input, int output)
1266{
1267        struct bidirectional_transfer_state state;
1268
1269        /* Fill the state fields. */
1270        state.ptg.src = input;
1271        state.ptg.dest = 1;
1272        state.ptg.src_is_sock = (input == output);
1273        state.ptg.dest_is_sock = 0;
1274        state.ptg.state = SSTATE_TRANSFERING;
1275        state.ptg.bufuse = 0;
1276        state.ptg.src_name = "remote input";
1277        state.ptg.dest_name = "stdout";
1278
1279        state.gtp.src = 0;
1280        state.gtp.dest = output;
1281        state.gtp.src_is_sock = 0;
1282        state.gtp.dest_is_sock = (input == output);
1283        state.gtp.state = SSTATE_TRANSFERING;
1284        state.gtp.bufuse = 0;
1285        state.gtp.src_name = "stdin";
1286        state.gtp.dest_name = "remote output";
1287
1288        return tloop_spawnwait_tasks(&state);
1289}