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