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