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