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