t/helper: fix leaking buffer in "dump-untracked-cache"
[git/gitster.git] / transport-helper.c
blobbc27653cdee211bd68cfc624b0fefd66fa1917fc
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "transport.h"
5 #include "quote.h"
6 #include "run-command.h"
7 #include "commit.h"
8 #include "environment.h"
9 #include "gettext.h"
10 #include "hex.h"
11 #include "object-name.h"
12 #include "repository.h"
13 #include "remote.h"
14 #include "string-list.h"
15 #include "thread-utils.h"
16 #include "sigchain.h"
17 #include "strvec.h"
18 #include "refs.h"
19 #include "refspec.h"
20 #include "transport-internal.h"
21 #include "protocol.h"
22 #include "packfile.h"
24 static int debug;
26 struct helper_data {
27 char *name;
28 struct child_process *helper;
29 FILE *out;
30 unsigned fetch : 1,
31 import : 1,
32 bidi_import : 1,
33 export : 1,
34 option : 1,
35 push : 1,
36 connect : 1,
37 stateless_connect : 1,
38 signed_tags : 1,
39 check_connectivity : 1,
40 no_disconnect_req : 1,
41 no_private_update : 1,
42 object_format : 1;
45 * As an optimization, the transport code may invoke fetch before
46 * get_refs_list. If this happens, and if the transport helper doesn't
47 * support connect or stateless_connect, we need to invoke
48 * get_refs_list ourselves if we haven't already done so. Keep track of
49 * whether we have invoked get_refs_list.
51 unsigned get_refs_list_called : 1;
53 char *export_marks;
54 char *import_marks;
55 /* These go from remote name (as in "list") to private name */
56 struct refspec rs;
57 /* Transport options for fetch-pack/send-pack (should one of
58 * those be invoked).
60 struct git_transport_options transport_options;
63 static void sendline(struct helper_data *helper, struct strbuf *buffer)
65 if (debug)
66 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
67 if (write_in_full(helper->helper->in, buffer->buf, buffer->len) < 0)
68 die_errno(_("full write to remote helper failed"));
71 static int recvline_fh(FILE *helper, struct strbuf *buffer)
73 strbuf_reset(buffer);
74 if (debug)
75 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
76 if (strbuf_getline(buffer, helper) == EOF) {
77 if (debug)
78 fprintf(stderr, "Debug: Remote helper quit.\n");
79 return 1;
82 if (debug)
83 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
84 return 0;
87 static int recvline(struct helper_data *helper, struct strbuf *buffer)
89 return recvline_fh(helper->out, buffer);
92 static int write_constant_gently(int fd, const char *str)
94 if (debug)
95 fprintf(stderr, "Debug: Remote helper: -> %s", str);
96 if (write_in_full(fd, str, strlen(str)) < 0)
97 return -1;
98 return 0;
101 static void write_constant(int fd, const char *str)
103 if (write_constant_gently(fd, str) < 0)
104 die_errno(_("full write to remote helper failed"));
107 static const char *remove_ext_force(const char *url)
109 if (url) {
110 const char *colon = strchr(url, ':');
111 if (colon && colon[1] == ':')
112 return colon + 2;
114 return url;
117 static void do_take_over(struct transport *transport)
119 struct helper_data *data;
120 data = (struct helper_data *)transport->data;
121 transport_take_over(transport, data->helper);
122 fclose(data->out);
123 free(data->name);
124 free(data);
127 static void standard_options(struct transport *t);
129 static struct child_process *get_helper(struct transport *transport)
131 struct helper_data *data = transport->data;
132 struct strbuf buf = STRBUF_INIT;
133 struct child_process *helper;
134 int duped;
135 int code;
137 if (data->helper)
138 return data->helper;
140 helper = xmalloc(sizeof(*helper));
141 child_process_init(helper);
142 helper->in = -1;
143 helper->out = -1;
144 helper->err = 0;
145 strvec_pushf(&helper->args, "remote-%s", data->name);
146 strvec_push(&helper->args, transport->remote->name);
147 strvec_push(&helper->args, remove_ext_force(transport->url));
148 helper->git_cmd = 1;
149 helper->silent_exec_failure = 1;
151 if (have_git_dir())
152 strvec_pushf(&helper->env, "%s=%s",
153 GIT_DIR_ENVIRONMENT, repo_get_git_dir(the_repository));
155 helper->trace2_child_class = helper->args.v[0]; /* "remote-<name>" */
157 code = start_command(helper);
158 if (code < 0 && errno == ENOENT)
159 die(_("unable to find remote helper for '%s'"), data->name);
160 else if (code != 0)
161 exit(code);
163 data->helper = helper;
164 data->no_disconnect_req = 0;
165 refspec_init(&data->rs, REFSPEC_FETCH);
168 * Open the output as FILE* so strbuf_getline_*() family of
169 * functions can be used.
170 * Do this with duped fd because fclose() will close the fd,
171 * and stuff like taking over will require the fd to remain.
173 duped = dup(helper->out);
174 if (duped < 0)
175 die_errno(_("can't dup helper output fd"));
176 data->out = xfdopen(duped, "r");
178 sigchain_push(SIGPIPE, SIG_IGN);
179 if (write_constant_gently(helper->in, "capabilities\n") < 0)
180 die("remote helper '%s' aborted session", data->name);
181 sigchain_pop(SIGPIPE);
183 while (1) {
184 const char *capname, *arg;
185 int mandatory = 0;
186 if (recvline(data, &buf))
187 die("remote helper '%s' aborted session", data->name);
189 if (!*buf.buf)
190 break;
192 if (*buf.buf == '*') {
193 capname = buf.buf + 1;
194 mandatory = 1;
195 } else
196 capname = buf.buf;
198 if (debug)
199 fprintf(stderr, "Debug: Got cap %s\n", capname);
200 if (!strcmp(capname, "fetch"))
201 data->fetch = 1;
202 else if (!strcmp(capname, "option"))
203 data->option = 1;
204 else if (!strcmp(capname, "push"))
205 data->push = 1;
206 else if (!strcmp(capname, "import"))
207 data->import = 1;
208 else if (!strcmp(capname, "bidi-import"))
209 data->bidi_import = 1;
210 else if (!strcmp(capname, "export"))
211 data->export = 1;
212 else if (!strcmp(capname, "check-connectivity"))
213 data->check_connectivity = 1;
214 else if (skip_prefix(capname, "refspec ", &arg)) {
215 refspec_append(&data->rs, arg);
216 } else if (!strcmp(capname, "connect")) {
217 data->connect = 1;
218 } else if (!strcmp(capname, "stateless-connect")) {
219 data->stateless_connect = 1;
220 } else if (!strcmp(capname, "signed-tags")) {
221 data->signed_tags = 1;
222 } else if (skip_prefix(capname, "export-marks ", &arg)) {
223 data->export_marks = xstrdup(arg);
224 } else if (skip_prefix(capname, "import-marks ", &arg)) {
225 data->import_marks = xstrdup(arg);
226 } else if (starts_with(capname, "no-private-update")) {
227 data->no_private_update = 1;
228 } else if (starts_with(capname, "object-format")) {
229 data->object_format = 1;
230 } else if (mandatory) {
231 die(_("unknown mandatory capability %s; this remote "
232 "helper probably needs newer version of Git"),
233 capname);
236 if (!data->rs.nr && (data->import || data->bidi_import || data->export)) {
237 warning(_("this remote helper should implement refspec capability"));
239 strbuf_release(&buf);
240 if (debug)
241 fprintf(stderr, "Debug: Capabilities complete.\n");
242 standard_options(transport);
243 return data->helper;
246 static int disconnect_helper(struct transport *transport)
248 struct helper_data *data = transport->data;
249 int res = 0;
251 if (data->helper) {
252 if (debug)
253 fprintf(stderr, "Debug: Disconnecting.\n");
254 if (!data->no_disconnect_req) {
256 * Ignore write errors; there's nothing we can do,
257 * since we're about to close the pipe anyway. And the
258 * most likely error is EPIPE due to the helper dying
259 * to report an error itself.
261 sigchain_push(SIGPIPE, SIG_IGN);
262 xwrite(data->helper->in, "\n", 1);
263 sigchain_pop(SIGPIPE);
265 close(data->helper->in);
266 close(data->helper->out);
267 fclose(data->out);
268 res = finish_command(data->helper);
269 FREE_AND_NULL(data->name);
270 FREE_AND_NULL(data->helper);
272 return res;
275 static const char *unsupported_options[] = {
276 TRANS_OPT_UPLOADPACK,
277 TRANS_OPT_RECEIVEPACK,
278 TRANS_OPT_THIN,
279 TRANS_OPT_KEEP
282 static const char *boolean_options[] = {
283 TRANS_OPT_THIN,
284 TRANS_OPT_KEEP,
285 TRANS_OPT_FOLLOWTAGS,
286 TRANS_OPT_DEEPEN_RELATIVE
289 static int strbuf_set_helper_option(struct helper_data *data,
290 struct strbuf *buf)
292 int ret;
294 sendline(data, buf);
295 if (recvline(data, buf))
296 exit(128);
298 if (!strcmp(buf->buf, "ok"))
299 ret = 0;
300 else if (starts_with(buf->buf, "error"))
301 ret = -1;
302 else if (!strcmp(buf->buf, "unsupported"))
303 ret = 1;
304 else {
305 warning(_("%s unexpectedly said: '%s'"), data->name, buf->buf);
306 ret = 1;
308 return ret;
311 static int string_list_set_helper_option(struct helper_data *data,
312 const char *name,
313 struct string_list *list)
315 struct strbuf buf = STRBUF_INIT;
316 int i, ret = 0;
318 for (i = 0; i < list->nr; i++) {
319 strbuf_addf(&buf, "option %s ", name);
320 quote_c_style(list->items[i].string, &buf, NULL, 0);
321 strbuf_addch(&buf, '\n');
323 if ((ret = strbuf_set_helper_option(data, &buf)))
324 break;
325 strbuf_reset(&buf);
327 strbuf_release(&buf);
328 return ret;
331 static int set_helper_option(struct transport *transport,
332 const char *name, const char *value)
334 struct helper_data *data = transport->data;
335 struct strbuf buf = STRBUF_INIT;
336 int i, ret, is_bool = 0;
338 get_helper(transport);
340 if (!data->option)
341 return 1;
343 if (!strcmp(name, "deepen-not"))
344 return string_list_set_helper_option(data, name,
345 (struct string_list *)value);
347 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
348 if (!strcmp(name, unsupported_options[i]))
349 return 1;
352 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
353 if (!strcmp(name, boolean_options[i])) {
354 is_bool = 1;
355 break;
359 strbuf_addf(&buf, "option %s ", name);
360 if (is_bool)
361 strbuf_addstr(&buf, value ? "true" : "false");
362 else
363 quote_c_style(value, &buf, NULL, 0);
364 strbuf_addch(&buf, '\n');
366 ret = strbuf_set_helper_option(data, &buf);
367 strbuf_release(&buf);
368 return ret;
371 static void standard_options(struct transport *t)
373 char buf[16];
374 int v = t->verbose;
376 set_helper_option(t, "progress", t->progress ? "true" : "false");
378 xsnprintf(buf, sizeof(buf), "%d", v + 1);
379 set_helper_option(t, "verbosity", buf);
381 switch (t->family) {
382 case TRANSPORT_FAMILY_ALL:
384 * this is already the default,
385 * do not break old remote helpers by setting "all" here
387 break;
388 case TRANSPORT_FAMILY_IPV4:
389 set_helper_option(t, "family", "ipv4");
390 break;
391 case TRANSPORT_FAMILY_IPV6:
392 set_helper_option(t, "family", "ipv6");
393 break;
397 static int release_helper(struct transport *transport)
399 int res = 0;
400 struct helper_data *data = transport->data;
401 refspec_clear(&data->rs);
402 free(data->import_marks);
403 free(data->export_marks);
404 res = disconnect_helper(transport);
405 free(transport->data);
406 return res;
409 static int fetch_with_fetch(struct transport *transport,
410 int nr_heads, struct ref **to_fetch)
412 struct helper_data *data = transport->data;
413 int i;
414 struct strbuf buf = STRBUF_INIT;
416 for (i = 0; i < nr_heads; i++) {
417 const struct ref *posn = to_fetch[i];
418 if (posn->status & REF_STATUS_UPTODATE)
419 continue;
421 strbuf_addf(&buf, "fetch %s %s\n",
422 oid_to_hex(&posn->old_oid),
423 posn->symref ? posn->symref : posn->name);
426 strbuf_addch(&buf, '\n');
427 sendline(data, &buf);
429 while (1) {
430 const char *name;
432 if (recvline(data, &buf))
433 exit(128);
435 if (skip_prefix(buf.buf, "lock ", &name)) {
436 if (transport->pack_lockfiles.nr)
437 warning(_("%s also locked %s"), data->name, name);
438 else
439 string_list_append(&transport->pack_lockfiles,
440 name);
442 else if (data->check_connectivity &&
443 data->transport_options.check_self_contained_and_connected &&
444 !strcmp(buf.buf, "connectivity-ok"))
445 data->transport_options.self_contained_and_connected = 1;
446 else if (!buf.len)
447 break;
448 else
449 warning(_("%s unexpectedly said: '%s'"), data->name, buf.buf);
451 strbuf_release(&buf);
453 reprepare_packed_git(the_repository);
454 return 0;
457 static int get_importer(struct transport *transport, struct child_process *fastimport)
459 struct child_process *helper = get_helper(transport);
460 struct helper_data *data = transport->data;
461 int cat_blob_fd, code;
462 child_process_init(fastimport);
463 fastimport->in = xdup(helper->out);
464 strvec_push(&fastimport->args, "fast-import");
465 strvec_push(&fastimport->args, "--allow-unsafe-features");
466 strvec_push(&fastimport->args, debug ? "--stats" : "--quiet");
468 if (data->bidi_import) {
469 cat_blob_fd = xdup(helper->in);
470 strvec_pushf(&fastimport->args, "--cat-blob-fd=%d", cat_blob_fd);
472 fastimport->git_cmd = 1;
474 code = start_command(fastimport);
475 return code;
478 static int get_exporter(struct transport *transport,
479 struct child_process *fastexport,
480 struct string_list *revlist_args)
482 struct helper_data *data = transport->data;
483 struct child_process *helper = get_helper(transport);
484 int i;
486 child_process_init(fastexport);
488 /* we need to duplicate helper->in because we want to use it after
489 * fastexport is done with it. */
490 fastexport->out = dup(helper->in);
491 strvec_push(&fastexport->args, "fast-export");
492 strvec_push(&fastexport->args, "--use-done-feature");
493 strvec_push(&fastexport->args, data->signed_tags ?
494 "--signed-tags=verbatim" : "--signed-tags=warn-strip");
495 if (data->export_marks)
496 strvec_pushf(&fastexport->args, "--export-marks=%s.tmp", data->export_marks);
497 if (data->import_marks)
498 strvec_pushf(&fastexport->args, "--import-marks=%s", data->import_marks);
500 for (i = 0; i < revlist_args->nr; i++)
501 strvec_push(&fastexport->args, revlist_args->items[i].string);
503 fastexport->git_cmd = 1;
504 return start_command(fastexport);
507 static int fetch_with_import(struct transport *transport,
508 int nr_heads, struct ref **to_fetch)
510 struct child_process fastimport;
511 struct helper_data *data = transport->data;
512 int i;
513 struct ref *posn;
514 struct strbuf buf = STRBUF_INIT;
516 get_helper(transport);
518 if (get_importer(transport, &fastimport))
519 die(_("couldn't run fast-import"));
521 for (i = 0; i < nr_heads; i++) {
522 posn = to_fetch[i];
523 if (posn->status & REF_STATUS_UPTODATE)
524 continue;
526 strbuf_addf(&buf, "import %s\n",
527 posn->symref ? posn->symref : posn->name);
528 sendline(data, &buf);
529 strbuf_reset(&buf);
532 write_constant(data->helper->in, "\n");
534 * remote-helpers that advertise the bidi-import capability are required to
535 * buffer the complete batch of import commands until this newline before
536 * sending data to fast-import.
537 * These helpers read back data from fast-import on their stdin, which could
538 * be mixed with import commands, otherwise.
541 if (finish_command(&fastimport))
542 die(_("error while running fast-import"));
545 * The fast-import stream of a remote helper that advertises
546 * the "refspec" capability writes to the refs named after the
547 * right hand side of the first refspec matching each ref we
548 * were fetching.
550 * (If no "refspec" capability was specified, for historical
551 * reasons we default to the equivalent of *:*.)
553 * Store the result in to_fetch[i].old_sha1. Callers such
554 * as "git fetch" can use the value to write feedback to the
555 * terminal, populate FETCH_HEAD, and determine what new value
556 * should be written to peer_ref if the update is a
557 * fast-forward or this is a forced update.
559 for (i = 0; i < nr_heads; i++) {
560 char *private, *name;
561 posn = to_fetch[i];
562 if (posn->status & REF_STATUS_UPTODATE)
563 continue;
564 name = posn->symref ? posn->symref : posn->name;
565 if (data->rs.nr)
566 private = apply_refspecs(&data->rs, name);
567 else
568 private = xstrdup(name);
569 if (private) {
570 if (refs_read_ref(get_main_ref_store(the_repository), private, &posn->old_oid) < 0)
571 die(_("could not read ref %s"), private);
572 free(private);
575 strbuf_release(&buf);
576 return 0;
579 static int run_connect(struct transport *transport, struct strbuf *cmdbuf)
581 struct helper_data *data = transport->data;
582 int ret = 0;
583 int duped;
584 FILE *input;
585 struct child_process *helper;
587 helper = get_helper(transport);
590 * Yes, dup the pipe another time, as we need unbuffered version
591 * of input pipe as FILE*. fclose() closes the underlying fd and
592 * stream buffering only can be changed before first I/O operation
593 * on it.
595 duped = dup(helper->out);
596 if (duped < 0)
597 die_errno(_("can't dup helper output fd"));
598 input = xfdopen(duped, "r");
599 setvbuf(input, NULL, _IONBF, 0);
601 sendline(data, cmdbuf);
602 if (recvline_fh(input, cmdbuf))
603 exit(128);
605 if (!strcmp(cmdbuf->buf, "")) {
606 data->no_disconnect_req = 1;
607 if (debug)
608 fprintf(stderr, "Debug: Smart transport connection "
609 "ready.\n");
610 ret = 1;
611 } else if (!strcmp(cmdbuf->buf, "fallback")) {
612 if (debug)
613 fprintf(stderr, "Debug: Falling back to dumb "
614 "transport.\n");
615 } else {
616 die(_("unknown response to connect: %s"),
617 cmdbuf->buf);
620 fclose(input);
621 return ret;
624 static int process_connect_service(struct transport *transport,
625 const char *name, const char *exec)
627 struct helper_data *data = transport->data;
628 struct strbuf cmdbuf = STRBUF_INIT;
629 int ret = 0;
632 * Handle --upload-pack and friends. This is fire and forget...
633 * just warn if it fails.
635 if (strcmp(name, exec)) {
636 int r = set_helper_option(transport, "servpath", exec);
637 if (r > 0)
638 warning(_("setting remote service path not supported by protocol"));
639 else if (r < 0)
640 warning(_("invalid remote service path"));
643 if (data->connect) {
644 strbuf_addf(&cmdbuf, "connect %s\n", name);
645 ret = run_connect(transport, &cmdbuf);
646 } else if (data->stateless_connect &&
647 (get_protocol_version_config() == protocol_v2) &&
648 (!strcmp("git-upload-pack", name) ||
649 !strcmp("git-upload-archive", name))) {
650 strbuf_addf(&cmdbuf, "stateless-connect %s\n", name);
651 ret = run_connect(transport, &cmdbuf);
652 if (ret)
653 transport->stateless_rpc = 1;
656 strbuf_release(&cmdbuf);
657 return ret;
660 static int process_connect(struct transport *transport,
661 int for_push)
663 struct helper_data *data = transport->data;
664 const char *name;
665 const char *exec;
666 int ret;
668 name = for_push ? "git-receive-pack" : "git-upload-pack";
669 if (for_push)
670 exec = data->transport_options.receivepack;
671 else
672 exec = data->transport_options.uploadpack;
674 ret = process_connect_service(transport, name, exec);
675 if (ret)
676 do_take_over(transport);
677 return ret;
680 static int connect_helper(struct transport *transport, const char *name,
681 const char *exec, int fd[2])
683 struct helper_data *data = transport->data;
685 /* Get_helper so connect is inited. */
686 get_helper(transport);
688 if (!process_connect_service(transport, name, exec))
689 die(_("can't connect to subservice %s"), name);
691 fd[0] = data->helper->out;
692 fd[1] = data->helper->in;
694 do_take_over(transport);
695 return 0;
698 static struct ref *get_refs_list_using_list(struct transport *transport,
699 int for_push);
701 static int fetch_refs(struct transport *transport,
702 int nr_heads, struct ref **to_fetch)
704 struct helper_data *data = transport->data;
705 int i, count;
707 get_helper(transport);
709 if (process_connect(transport, 0))
710 return transport->vtable->fetch_refs(transport, nr_heads, to_fetch);
713 * If we reach here, then the server, the client, and/or the transport
714 * helper does not support protocol v2. --negotiate-only requires
715 * protocol v2.
717 if (data->transport_options.acked_commits) {
718 warning(_("--negotiate-only requires protocol v2"));
719 return -1;
722 if (!data->get_refs_list_called) {
724 * We do not care about the list of refs returned, but only
725 * that the "list" command was sent.
727 struct ref *dummy = get_refs_list_using_list(transport, 0);
728 free_refs(dummy);
731 count = 0;
732 for (i = 0; i < nr_heads; i++)
733 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
734 count++;
736 if (!count)
737 return 0;
739 if (data->check_connectivity &&
740 data->transport_options.check_self_contained_and_connected)
741 set_helper_option(transport, "check-connectivity", "true");
743 if (transport->cloning)
744 set_helper_option(transport, "cloning", "true");
746 if (data->transport_options.update_shallow)
747 set_helper_option(transport, "update-shallow", "true");
749 if (data->transport_options.refetch)
750 set_helper_option(transport, "refetch", "true");
752 if (data->transport_options.filter_options.choice) {
753 const char *spec = expand_list_objects_filter_spec(
754 &data->transport_options.filter_options);
755 set_helper_option(transport, "filter", spec);
758 if (data->transport_options.negotiation_tips)
759 warning("Ignoring --negotiation-tip because the protocol does not support it.");
761 if (data->fetch)
762 return fetch_with_fetch(transport, nr_heads, to_fetch);
764 if (data->import)
765 return fetch_with_import(transport, nr_heads, to_fetch);
767 return -1;
770 struct push_update_ref_state {
771 struct ref *hint;
772 struct ref_push_report *report;
773 int new_report;
776 static int push_update_ref_status(struct strbuf *buf,
777 struct push_update_ref_state *state,
778 struct ref *remote_refs)
780 char *refname, *msg;
781 int status, forced = 0;
783 if (starts_with(buf->buf, "option ")) {
784 struct object_id old_oid, new_oid;
785 const char *key, *val;
786 char *p;
788 if (!state->hint || !(state->report || state->new_report))
789 die(_("'option' without a matching 'ok/error' directive"));
790 if (state->new_report) {
791 if (!state->hint->report) {
792 CALLOC_ARRAY(state->hint->report, 1);
793 state->report = state->hint->report;
794 } else {
795 state->report = state->hint->report;
796 while (state->report->next)
797 state->report = state->report->next;
798 CALLOC_ARRAY(state->report->next, 1);
799 state->report = state->report->next;
801 state->new_report = 0;
803 key = buf->buf + 7;
804 p = strchr(key, ' ');
805 if (p)
806 *p++ = '\0';
807 val = p;
808 if (!strcmp(key, "refname"))
809 state->report->ref_name = xstrdup_or_null(val);
810 else if (!strcmp(key, "old-oid") && val &&
811 !parse_oid_hex(val, &old_oid, &val))
812 state->report->old_oid = oiddup(&old_oid);
813 else if (!strcmp(key, "new-oid") && val &&
814 !parse_oid_hex(val, &new_oid, &val))
815 state->report->new_oid = oiddup(&new_oid);
816 else if (!strcmp(key, "forced-update"))
817 state->report->forced_update = 1;
818 /* Not update remote namespace again. */
819 return 1;
822 state->report = NULL;
823 state->new_report = 0;
825 if (starts_with(buf->buf, "ok ")) {
826 status = REF_STATUS_OK;
827 refname = buf->buf + 3;
828 } else if (starts_with(buf->buf, "error ")) {
829 status = REF_STATUS_REMOTE_REJECT;
830 refname = buf->buf + 6;
831 } else
832 die(_("expected ok/error, helper said '%s'"), buf->buf);
834 msg = strchr(refname, ' ');
835 if (msg) {
836 struct strbuf msg_buf = STRBUF_INIT;
837 const char *end;
839 *msg++ = '\0';
840 if (!unquote_c_style(&msg_buf, msg, &end))
841 msg = strbuf_detach(&msg_buf, NULL);
842 else
843 msg = xstrdup(msg);
844 strbuf_release(&msg_buf);
846 if (!strcmp(msg, "no match")) {
847 status = REF_STATUS_NONE;
848 FREE_AND_NULL(msg);
850 else if (!strcmp(msg, "up to date")) {
851 status = REF_STATUS_UPTODATE;
852 FREE_AND_NULL(msg);
854 else if (!strcmp(msg, "non-fast forward")) {
855 status = REF_STATUS_REJECT_NONFASTFORWARD;
856 FREE_AND_NULL(msg);
858 else if (!strcmp(msg, "already exists")) {
859 status = REF_STATUS_REJECT_ALREADY_EXISTS;
860 FREE_AND_NULL(msg);
862 else if (!strcmp(msg, "fetch first")) {
863 status = REF_STATUS_REJECT_FETCH_FIRST;
864 FREE_AND_NULL(msg);
866 else if (!strcmp(msg, "needs force")) {
867 status = REF_STATUS_REJECT_NEEDS_FORCE;
868 FREE_AND_NULL(msg);
870 else if (!strcmp(msg, "stale info")) {
871 status = REF_STATUS_REJECT_STALE;
872 FREE_AND_NULL(msg);
874 else if (!strcmp(msg, "remote ref updated since checkout")) {
875 status = REF_STATUS_REJECT_REMOTE_UPDATED;
876 FREE_AND_NULL(msg);
878 else if (!strcmp(msg, "forced update")) {
879 forced = 1;
880 FREE_AND_NULL(msg);
882 else if (!strcmp(msg, "expecting report")) {
883 status = REF_STATUS_EXPECTING_REPORT;
884 FREE_AND_NULL(msg);
888 if (state->hint)
889 state->hint = find_ref_by_name(state->hint, refname);
890 if (!state->hint)
891 state->hint = find_ref_by_name(remote_refs, refname);
892 if (!state->hint) {
893 warning(_("helper reported unexpected status of %s"), refname);
894 return 1;
897 if (state->hint->status != REF_STATUS_NONE) {
899 * Earlier, the ref was marked not to be pushed, so ignore the ref
900 * status reported by the remote helper if the latter is 'no match'.
902 if (status == REF_STATUS_NONE)
903 return 1;
906 if (status == REF_STATUS_OK)
907 state->new_report = 1;
908 state->hint->status = status;
909 state->hint->forced_update |= forced;
910 state->hint->remote_status = msg;
911 return !(status == REF_STATUS_OK);
914 static int push_update_refs_status(struct helper_data *data,
915 struct ref *remote_refs,
916 int flags)
918 struct ref *ref;
919 struct ref_push_report *report;
920 struct strbuf buf = STRBUF_INIT;
921 struct push_update_ref_state state = { remote_refs, NULL, 0 };
923 for (;;) {
924 if (recvline(data, &buf)) {
925 strbuf_release(&buf);
926 return 1;
928 if (!buf.len)
929 break;
930 push_update_ref_status(&buf, &state, remote_refs);
932 strbuf_release(&buf);
934 if (flags & TRANSPORT_PUSH_DRY_RUN || !data->rs.nr || data->no_private_update)
935 return 0;
937 /* propagate back the update to the remote namespace */
938 for (ref = remote_refs; ref; ref = ref->next) {
939 char *private;
941 if (ref->status != REF_STATUS_OK)
942 continue;
944 if (!ref->report) {
945 private = apply_refspecs(&data->rs, ref->name);
946 if (!private)
947 continue;
948 refs_update_ref(get_main_ref_store(the_repository),
949 "update by helper", private,
950 &(ref->new_oid),
951 NULL, 0, 0);
952 free(private);
953 } else {
954 for (report = ref->report; report; report = report->next) {
955 private = apply_refspecs(&data->rs,
956 report->ref_name
957 ? report->ref_name
958 : ref->name);
959 if (!private)
960 continue;
961 refs_update_ref(get_main_ref_store(the_repository),
962 "update by helper", private,
963 report->new_oid
964 ? report->new_oid
965 : &(ref->new_oid),
966 NULL, 0, 0);
967 free(private);
971 return 0;
974 static void set_common_push_options(struct transport *transport,
975 const char *name, int flags)
977 if (flags & TRANSPORT_PUSH_DRY_RUN) {
978 if (set_helper_option(transport, "dry-run", "true") != 0)
979 die(_("helper %s does not support dry-run"), name);
980 } else if (flags & TRANSPORT_PUSH_CERT_ALWAYS) {
981 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "true") != 0)
982 die(_("helper %s does not support --signed"), name);
983 } else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED) {
984 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "if-asked") != 0)
985 die(_("helper %s does not support --signed=if-asked"), name);
988 if (flags & TRANSPORT_PUSH_ATOMIC)
989 if (set_helper_option(transport, TRANS_OPT_ATOMIC, "true") != 0)
990 die(_("helper %s does not support --atomic"), name);
992 if (flags & TRANSPORT_PUSH_FORCE_IF_INCLUDES)
993 if (set_helper_option(transport, TRANS_OPT_FORCE_IF_INCLUDES, "true") != 0)
994 die(_("helper %s does not support --%s"),
995 name, TRANS_OPT_FORCE_IF_INCLUDES);
997 if (flags & TRANSPORT_PUSH_OPTIONS) {
998 struct string_list_item *item;
999 for_each_string_list_item(item, transport->push_options)
1000 if (set_helper_option(transport, "push-option", item->string) != 0)
1001 die(_("helper %s does not support 'push-option'"), name);
1005 static int push_refs_with_push(struct transport *transport,
1006 struct ref *remote_refs, int flags)
1008 int force_all = flags & TRANSPORT_PUSH_FORCE;
1009 int mirror = flags & TRANSPORT_PUSH_MIRROR;
1010 int atomic = flags & TRANSPORT_PUSH_ATOMIC;
1011 struct helper_data *data = transport->data;
1012 struct strbuf buf = STRBUF_INIT;
1013 struct ref *ref;
1014 struct string_list cas_options = STRING_LIST_INIT_DUP;
1015 struct string_list_item *cas_option;
1017 get_helper(transport);
1018 if (!data->push)
1019 return 1;
1021 for (ref = remote_refs; ref; ref = ref->next) {
1022 if (!ref->peer_ref && !mirror)
1023 continue;
1025 /* Check for statuses set by set_ref_status_for_push() */
1026 switch (ref->status) {
1027 case REF_STATUS_REJECT_NONFASTFORWARD:
1028 case REF_STATUS_REJECT_STALE:
1029 case REF_STATUS_REJECT_ALREADY_EXISTS:
1030 case REF_STATUS_REJECT_REMOTE_UPDATED:
1031 if (atomic) {
1032 reject_atomic_push(remote_refs, mirror);
1033 string_list_clear(&cas_options, 0);
1034 strbuf_release(&buf);
1035 return 0;
1036 } else
1037 continue;
1038 case REF_STATUS_UPTODATE:
1039 continue;
1040 default:
1041 ; /* do nothing */
1044 if (force_all)
1045 ref->force = 1;
1047 strbuf_addstr(&buf, "push ");
1048 if (!ref->deletion) {
1049 if (ref->force)
1050 strbuf_addch(&buf, '+');
1051 if (ref->peer_ref)
1052 strbuf_addstr(&buf, ref->peer_ref->name);
1053 else
1054 strbuf_addstr(&buf, oid_to_hex(&ref->new_oid));
1056 strbuf_addch(&buf, ':');
1057 strbuf_addstr(&buf, ref->name);
1058 strbuf_addch(&buf, '\n');
1061 * The "--force-with-lease" options without explicit
1062 * values to expect have already been expanded into
1063 * the ref->old_oid_expect[] field; we can ignore
1064 * transport->smart_options->cas altogether and instead
1065 * can enumerate them from the refs.
1067 if (ref->expect_old_sha1) {
1068 struct strbuf cas = STRBUF_INIT;
1069 strbuf_addf(&cas, "%s:%s",
1070 ref->name, oid_to_hex(&ref->old_oid_expect));
1071 string_list_append_nodup(&cas_options,
1072 strbuf_detach(&cas, NULL));
1075 if (buf.len == 0) {
1076 string_list_clear(&cas_options, 0);
1077 return 0;
1080 for_each_string_list_item(cas_option, &cas_options)
1081 set_helper_option(transport, "cas", cas_option->string);
1082 set_common_push_options(transport, data->name, flags);
1084 strbuf_addch(&buf, '\n');
1085 sendline(data, &buf);
1086 strbuf_release(&buf);
1087 string_list_clear(&cas_options, 0);
1089 return push_update_refs_status(data, remote_refs, flags);
1092 static int push_refs_with_export(struct transport *transport,
1093 struct ref *remote_refs, int flags)
1095 struct ref *ref;
1096 struct child_process *helper, exporter;
1097 struct helper_data *data = transport->data;
1098 struct string_list revlist_args = STRING_LIST_INIT_DUP;
1099 struct strbuf buf = STRBUF_INIT;
1101 if (!data->rs.nr)
1102 die(_("remote-helper doesn't support push; refspec needed"));
1104 set_common_push_options(transport, data->name, flags);
1105 if (flags & TRANSPORT_PUSH_FORCE) {
1106 if (set_helper_option(transport, "force", "true") != 0)
1107 warning(_("helper %s does not support '--force'"), data->name);
1110 helper = get_helper(transport);
1112 write_constant(helper->in, "export\n");
1114 for (ref = remote_refs; ref; ref = ref->next) {
1115 char *private;
1116 struct object_id oid;
1118 private = apply_refspecs(&data->rs, ref->name);
1119 if (private && !repo_get_oid(the_repository, private, &oid)) {
1120 strbuf_addf(&buf, "^%s", private);
1121 string_list_append_nodup(&revlist_args,
1122 strbuf_detach(&buf, NULL));
1123 oidcpy(&ref->old_oid, &oid);
1125 free(private);
1127 if (ref->peer_ref) {
1128 if (strcmp(ref->name, ref->peer_ref->name)) {
1129 if (!ref->deletion) {
1130 const char *name;
1131 int flag;
1133 /* Follow symbolic refs (mainly for HEAD). */
1134 name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1135 ref->peer_ref->name,
1136 RESOLVE_REF_READING,
1137 &oid,
1138 &flag);
1139 if (!name || !(flag & REF_ISSYMREF))
1140 name = ref->peer_ref->name;
1142 strbuf_addf(&buf, "%s:%s", name, ref->name);
1143 } else
1144 strbuf_addf(&buf, ":%s", ref->name);
1146 string_list_append(&revlist_args, "--refspec");
1147 string_list_append(&revlist_args, buf.buf);
1148 strbuf_release(&buf);
1150 if (!ref->deletion)
1151 string_list_append(&revlist_args, ref->peer_ref->name);
1155 if (get_exporter(transport, &exporter, &revlist_args))
1156 die(_("couldn't run fast-export"));
1158 string_list_clear(&revlist_args, 1);
1160 if (finish_command(&exporter))
1161 die(_("error while running fast-export"));
1162 if (push_update_refs_status(data, remote_refs, flags))
1163 return 1;
1165 if (data->export_marks) {
1166 strbuf_addf(&buf, "%s.tmp", data->export_marks);
1167 rename(buf.buf, data->export_marks);
1168 strbuf_release(&buf);
1171 return 0;
1174 static int push_refs(struct transport *transport,
1175 struct ref *remote_refs, int flags)
1177 struct helper_data *data = transport->data;
1179 if (process_connect(transport, 1))
1180 return transport->vtable->push_refs(transport, remote_refs, flags);
1182 if (!remote_refs) {
1183 fprintf(stderr,
1184 _("No refs in common and none specified; doing nothing.\n"
1185 "Perhaps you should specify a branch.\n"));
1186 return 0;
1189 if (data->push)
1190 return push_refs_with_push(transport, remote_refs, flags);
1192 if (data->export)
1193 return push_refs_with_export(transport, remote_refs, flags);
1195 return -1;
1199 static int has_attribute(const char *attrs, const char *attr)
1201 int len;
1202 if (!attrs)
1203 return 0;
1205 len = strlen(attr);
1206 for (;;) {
1207 const char *space = strchrnul(attrs, ' ');
1208 if (len == space - attrs && !strncmp(attrs, attr, len))
1209 return 1;
1210 if (!*space)
1211 return 0;
1212 attrs = space + 1;
1216 static struct ref *get_refs_list(struct transport *transport, int for_push,
1217 struct transport_ls_refs_options *transport_options)
1219 get_helper(transport);
1221 if (process_connect(transport, for_push))
1222 return transport->vtable->get_refs_list(transport, for_push,
1223 transport_options);
1225 return get_refs_list_using_list(transport, for_push);
1228 static struct ref *get_refs_list_using_list(struct transport *transport,
1229 int for_push)
1231 struct helper_data *data = transport->data;
1232 struct child_process *helper;
1233 struct ref *ret = NULL;
1234 struct ref **tail = &ret;
1235 struct ref *posn;
1236 struct strbuf buf = STRBUF_INIT;
1238 data->get_refs_list_called = 1;
1239 helper = get_helper(transport);
1241 if (data->object_format)
1242 set_helper_option(transport, "object-format", "true");
1244 if (data->push && for_push)
1245 write_constant(helper->in, "list for-push\n");
1246 else
1247 write_constant(helper->in, "list\n");
1249 while (1) {
1250 char *eov, *eon;
1251 if (recvline(data, &buf))
1252 exit(128);
1254 if (!*buf.buf)
1255 break;
1256 else if (buf.buf[0] == ':') {
1257 const char *value;
1258 if (skip_prefix(buf.buf, ":object-format ", &value)) {
1259 int algo = hash_algo_by_name(value);
1260 if (algo == GIT_HASH_UNKNOWN)
1261 die(_("unsupported object format '%s'"),
1262 value);
1263 transport->hash_algo = &hash_algos[algo];
1265 continue;
1268 eov = strchr(buf.buf, ' ');
1269 if (!eov)
1270 die(_("malformed response in ref list: %s"), buf.buf);
1271 eon = strchr(eov + 1, ' ');
1272 *eov = '\0';
1273 if (eon)
1274 *eon = '\0';
1275 *tail = alloc_ref(eov + 1);
1276 if (buf.buf[0] == '@')
1277 (*tail)->symref = xstrdup(buf.buf + 1);
1278 else if (buf.buf[0] != '?')
1279 get_oid_hex_algop(buf.buf, &(*tail)->old_oid, transport->hash_algo);
1280 if (eon) {
1281 if (has_attribute(eon + 1, "unchanged")) {
1282 (*tail)->status |= REF_STATUS_UPTODATE;
1283 if (refs_read_ref(get_main_ref_store(the_repository), (*tail)->name, &(*tail)->old_oid) < 0)
1284 die(_("could not read ref %s"),
1285 (*tail)->name);
1288 tail = &((*tail)->next);
1290 if (debug)
1291 fprintf(stderr, "Debug: Read ref listing.\n");
1292 strbuf_release(&buf);
1294 for (posn = ret; posn; posn = posn->next)
1295 resolve_remote_symref(posn, ret);
1297 return ret;
1300 static int get_bundle_uri(struct transport *transport)
1302 get_helper(transport);
1304 if (process_connect(transport, 0))
1305 return transport->vtable->get_bundle_uri(transport);
1307 return -1;
1310 static struct transport_vtable vtable = {
1311 .set_option = set_helper_option,
1312 .get_refs_list = get_refs_list,
1313 .get_bundle_uri = get_bundle_uri,
1314 .fetch_refs = fetch_refs,
1315 .push_refs = push_refs,
1316 .connect = connect_helper,
1317 .disconnect = release_helper
1320 int transport_helper_init(struct transport *transport, const char *name)
1322 struct helper_data *data = xcalloc(1, sizeof(*data));
1323 data->name = xstrdup(name);
1325 transport_check_allowed(name);
1327 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1328 debug = 1;
1330 list_objects_filter_init(&data->transport_options.filter_options);
1332 transport->data = data;
1333 transport->vtable = &vtable;
1334 transport->smart_options = &(data->transport_options);
1335 return 0;
1339 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1340 * buffer less), so attempt reads and writes with up to that size.
1342 #define BUFFERSIZE 65536
1343 /* This should be enough to hold debugging message. */
1344 #define PBUFFERSIZE 8192
1346 /* Print bidirectional transfer loop debug message. */
1347 __attribute__((format (printf, 1, 2)))
1348 static void transfer_debug(const char *fmt, ...)
1351 * NEEDSWORK: This function is sometimes used from multiple threads, and
1352 * we end up using debug_enabled racily. That "should not matter" since
1353 * we always write the same value, but it's still wrong. This function
1354 * is listed in .tsan-suppressions for the time being.
1357 va_list args;
1358 char msgbuf[PBUFFERSIZE];
1359 static int debug_enabled = -1;
1361 if (debug_enabled < 0)
1362 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1363 if (!debug_enabled)
1364 return;
1366 va_start(args, fmt);
1367 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1368 va_end(args);
1369 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1372 /* Stream state: More data may be coming in this direction. */
1373 #define SSTATE_TRANSFERRING 0
1375 * Stream state: No more data coming in this direction, flushing rest of
1376 * data.
1378 #define SSTATE_FLUSHING 1
1379 /* Stream state: Transfer in this direction finished. */
1380 #define SSTATE_FINISHED 2
1382 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERRING)
1383 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1384 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1386 /* Unidirectional transfer. */
1387 struct unidirectional_transfer {
1388 /* Source */
1389 int src;
1390 /* Destination */
1391 int dest;
1392 /* Is source socket? */
1393 int src_is_sock;
1394 /* Is destination socket? */
1395 int dest_is_sock;
1396 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1397 int state;
1398 /* Buffer. */
1399 char buf[BUFFERSIZE];
1400 /* Buffer used. */
1401 size_t bufuse;
1402 /* Name of source. */
1403 const char *src_name;
1404 /* Name of destination. */
1405 const char *dest_name;
1408 /* Closes the target (for writing) if transfer has finished. */
1409 static void udt_close_if_finished(struct unidirectional_transfer *t)
1411 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1412 t->state = SSTATE_FINISHED;
1413 if (t->dest_is_sock)
1414 shutdown(t->dest, SHUT_WR);
1415 else
1416 close(t->dest);
1417 transfer_debug("Closed %s.", t->dest_name);
1422 * Tries to read data from source into buffer. If buffer is full,
1423 * no data is read. Returns 0 on success, -1 on error.
1425 static int udt_do_read(struct unidirectional_transfer *t)
1427 ssize_t bytes;
1429 if (t->bufuse == BUFFERSIZE)
1430 return 0; /* No space for more. */
1432 transfer_debug("%s is readable", t->src_name);
1433 bytes = xread(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1434 if (bytes < 0) {
1435 error_errno(_("read(%s) failed"), t->src_name);
1436 return -1;
1437 } else if (bytes == 0) {
1438 transfer_debug("%s EOF (with %i bytes in buffer)",
1439 t->src_name, (int)t->bufuse);
1440 t->state = SSTATE_FLUSHING;
1441 } else if (bytes > 0) {
1442 t->bufuse += bytes;
1443 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1444 (int)bytes, t->src_name, (int)t->bufuse);
1446 return 0;
1449 /* Tries to write data from buffer into destination. If buffer is empty,
1450 * no data is written. Returns 0 on success, -1 on error.
1452 static int udt_do_write(struct unidirectional_transfer *t)
1454 ssize_t bytes;
1456 if (t->bufuse == 0)
1457 return 0; /* Nothing to write. */
1459 transfer_debug("%s is writable", t->dest_name);
1460 bytes = xwrite(t->dest, t->buf, t->bufuse);
1461 if (bytes < 0) {
1462 error_errno(_("write(%s) failed"), t->dest_name);
1463 return -1;
1464 } else if (bytes > 0) {
1465 t->bufuse -= bytes;
1466 if (t->bufuse)
1467 memmove(t->buf, t->buf + bytes, t->bufuse);
1468 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1469 (int)bytes, t->dest_name, (int)t->bufuse);
1471 return 0;
1475 /* State of bidirectional transfer loop. */
1476 struct bidirectional_transfer_state {
1477 /* Direction from program to git. */
1478 struct unidirectional_transfer ptg;
1479 /* Direction from git to program. */
1480 struct unidirectional_transfer gtp;
1483 static void *udt_copy_task_routine(void *udt)
1485 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1486 while (t->state != SSTATE_FINISHED) {
1487 if (STATE_NEEDS_READING(t->state))
1488 if (udt_do_read(t))
1489 return NULL;
1490 if (STATE_NEEDS_WRITING(t->state))
1491 if (udt_do_write(t))
1492 return NULL;
1493 if (STATE_NEEDS_CLOSING(t->state))
1494 udt_close_if_finished(t);
1496 return udt; /* Just some non-NULL value. */
1499 #ifndef NO_PTHREADS
1502 * Join thread, with appropriate errors on failure. Name is name for the
1503 * thread (for error messages). Returns 0 on success, 1 on failure.
1505 static int tloop_join(pthread_t thread, const char *name)
1507 int err;
1508 void *tret;
1509 err = pthread_join(thread, &tret);
1510 if (!tret) {
1511 error(_("%s thread failed"), name);
1512 return 1;
1514 if (err) {
1515 error(_("%s thread failed to join: %s"), name, strerror(err));
1516 return 1;
1518 return 0;
1522 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1523 * -1 on failure.
1525 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1527 pthread_t gtp_thread;
1528 pthread_t ptg_thread;
1529 int err;
1530 int ret = 0;
1531 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1532 &s->gtp);
1533 if (err)
1534 die(_("can't start thread for copying data: %s"), strerror(err));
1535 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1536 &s->ptg);
1537 if (err)
1538 die(_("can't start thread for copying data: %s"), strerror(err));
1540 ret |= tloop_join(gtp_thread, "Git to program copy");
1541 ret |= tloop_join(ptg_thread, "Program to git copy");
1542 return ret;
1544 #else
1546 /* Close the source and target (for writing) for transfer. */
1547 static void udt_kill_transfer(struct unidirectional_transfer *t)
1549 t->state = SSTATE_FINISHED;
1551 * Socket read end left open isn't a disaster if nobody
1552 * attempts to read from it (mingw compat headers do not
1553 * have SHUT_RD)...
1555 * We can't fully close the socket since otherwise gtp
1556 * task would first close the socket it sends data to
1557 * while closing the ptg file descriptors.
1559 if (!t->src_is_sock)
1560 close(t->src);
1561 if (t->dest_is_sock)
1562 shutdown(t->dest, SHUT_WR);
1563 else
1564 close(t->dest);
1568 * Join process, with appropriate errors on failure. Name is name for the
1569 * process (for error messages). Returns 0 on success, 1 on failure.
1571 static int tloop_join(pid_t pid, const char *name)
1573 int tret;
1574 if (waitpid(pid, &tret, 0) < 0) {
1575 error_errno(_("%s process failed to wait"), name);
1576 return 1;
1578 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1579 error(_("%s process failed"), name);
1580 return 1;
1582 return 0;
1586 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1587 * -1 on failure.
1589 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1591 pid_t pid1, pid2;
1592 int ret = 0;
1594 /* Fork thread #1: git to program. */
1595 pid1 = fork();
1596 if (pid1 < 0)
1597 die_errno(_("can't start thread for copying data"));
1598 else if (pid1 == 0) {
1599 udt_kill_transfer(&s->ptg);
1600 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1603 /* Fork thread #2: program to git. */
1604 pid2 = fork();
1605 if (pid2 < 0)
1606 die_errno(_("can't start thread for copying data"));
1607 else if (pid2 == 0) {
1608 udt_kill_transfer(&s->gtp);
1609 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1613 * Close both streams in parent as to not interfere with
1614 * end of file detection and wait for both tasks to finish.
1616 udt_kill_transfer(&s->gtp);
1617 udt_kill_transfer(&s->ptg);
1618 ret |= tloop_join(pid1, "Git to program copy");
1619 ret |= tloop_join(pid2, "Program to git copy");
1620 return ret;
1622 #endif
1625 * Copies data from stdin to output and from input to stdout simultaneously.
1626 * Additionally filtering through given filter. If filter is NULL, uses
1627 * identity filter.
1629 int bidirectional_transfer_loop(int input, int output)
1631 struct bidirectional_transfer_state state;
1633 /* Fill the state fields. */
1634 state.ptg.src = input;
1635 state.ptg.dest = 1;
1636 state.ptg.src_is_sock = (input == output);
1637 state.ptg.dest_is_sock = 0;
1638 state.ptg.state = SSTATE_TRANSFERRING;
1639 state.ptg.bufuse = 0;
1640 state.ptg.src_name = "remote input";
1641 state.ptg.dest_name = "stdout";
1643 state.gtp.src = 0;
1644 state.gtp.dest = output;
1645 state.gtp.src_is_sock = 0;
1646 state.gtp.dest_is_sock = (input == output);
1647 state.gtp.state = SSTATE_TRANSFERRING;
1648 state.gtp.bufuse = 0;
1649 state.gtp.src_name = "stdin";
1650 state.gtp.dest_name = "remote output";
1652 return tloop_spawnwait_tasks(&state);
1655 void reject_atomic_push(struct ref *remote_refs, int mirror_mode)
1657 struct ref *ref;
1659 /* Mark other refs as failed */
1660 for (ref = remote_refs; ref; ref = ref->next) {
1661 if (!ref->peer_ref && !mirror_mode)
1662 continue;
1664 switch (ref->status) {
1665 case REF_STATUS_NONE:
1666 case REF_STATUS_OK:
1667 case REF_STATUS_EXPECTING_REPORT:
1668 ref->status = REF_STATUS_ATOMIC_PUSH_FAILED;
1669 continue;
1670 default:
1671 break; /* do nothing */
1674 return;