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