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