remote-helper: check helper status after import/export
[git/mingw/4msysgit.git] / transport-helper.c
blob76bba32006e3b0f3ab49b61a72e514a0520a4bf0
1 #include "cache.h"
2 #include "transport.h"
3 #include "quote.h"
4 #include "run-command.h"
5 #include "commit.h"
6 #include "diff.h"
7 #include "revision.h"
8 #include "quote.h"
9 #include "remote.h"
10 #include "string-list.h"
11 #include "thread-utils.h"
12 #include "sigchain.h"
13 #include "argv-array.h"
14 #include "refs.h"
16 static int debug;
18 struct helper_data {
19 const char *name;
20 struct child_process *helper;
21 FILE *out;
22 unsigned fetch : 1,
23 import : 1,
24 bidi_import : 1,
25 export : 1,
26 option : 1,
27 push : 1,
28 connect : 1,
29 signed_tags : 1,
30 check_connectivity : 1,
31 no_disconnect_req : 1,
32 no_private_update : 1;
33 char *export_marks;
34 char *import_marks;
35 /* These go from remote name (as in "list") to private name */
36 struct refspec *refspecs;
37 int refspec_nr;
38 /* Transport options for fetch-pack/send-pack (should one of
39 * those be invoked).
41 struct git_transport_options transport_options;
44 static void sendline(struct helper_data *helper, struct strbuf *buffer)
46 if (debug)
47 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
48 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
49 != buffer->len)
50 die_errno("Full write to remote helper failed");
53 static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
55 strbuf_reset(buffer);
56 if (debug)
57 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
58 if (strbuf_getline(buffer, helper, '\n') == EOF) {
59 if (debug)
60 fprintf(stderr, "Debug: Remote helper quit.\n");
61 exit(128);
64 if (debug)
65 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
66 return 0;
69 static int recvline(struct helper_data *helper, struct strbuf *buffer)
71 return recvline_fh(helper->out, buffer, helper->name);
74 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
76 sendline(helper, buffer);
77 recvline(helper, buffer);
80 static void write_constant(int fd, const char *str)
82 if (debug)
83 fprintf(stderr, "Debug: Remote helper: -> %s", str);
84 if (write_in_full(fd, str, strlen(str)) != strlen(str))
85 die_errno("Full write to remote helper failed");
88 static const char *remove_ext_force(const char *url)
90 if (url) {
91 const char *colon = strchr(url, ':');
92 if (colon && colon[1] == ':')
93 return colon + 2;
95 return url;
98 static void do_take_over(struct transport *transport)
100 struct helper_data *data;
101 data = (struct helper_data *)transport->data;
102 transport_take_over(transport, data->helper);
103 fclose(data->out);
104 free(data);
107 static struct child_process *get_helper(struct transport *transport)
109 struct helper_data *data = transport->data;
110 struct argv_array argv = ARGV_ARRAY_INIT;
111 struct strbuf buf = STRBUF_INIT;
112 struct child_process *helper;
113 const char **refspecs = NULL;
114 int refspec_nr = 0;
115 int refspec_alloc = 0;
116 int duped;
117 int code;
118 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
119 const char *helper_env[] = {
120 git_dir_buf,
121 NULL
125 if (data->helper)
126 return data->helper;
128 helper = xcalloc(1, sizeof(*helper));
129 helper->in = -1;
130 helper->out = -1;
131 helper->err = 0;
132 argv_array_pushf(&argv, "git-remote-%s", data->name);
133 argv_array_push(&argv, transport->remote->name);
134 argv_array_push(&argv, remove_ext_force(transport->url));
135 helper->argv = argv_array_detach(&argv, NULL);
136 helper->git_cmd = 0;
137 helper->silent_exec_failure = 1;
139 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
140 helper->env = helper_env;
142 code = start_command(helper);
143 if (code < 0 && errno == ENOENT)
144 die("Unable to find remote helper for '%s'", data->name);
145 else if (code != 0)
146 exit(code);
148 data->helper = helper;
149 data->no_disconnect_req = 0;
152 * Open the output as FILE* so strbuf_getline() can be used.
153 * Do this with duped fd because fclose() will close the fd,
154 * and stuff like taking over will require the fd to remain.
156 duped = dup(helper->out);
157 if (duped < 0)
158 die_errno("Can't dup helper output fd");
159 data->out = xfdopen(duped, "r");
161 write_constant(helper->in, "capabilities\n");
163 while (1) {
164 const char *capname;
165 int mandatory = 0;
166 recvline(data, &buf);
168 if (!*buf.buf)
169 break;
171 if (*buf.buf == '*') {
172 capname = buf.buf + 1;
173 mandatory = 1;
174 } else
175 capname = buf.buf;
177 if (debug)
178 fprintf(stderr, "Debug: Got cap %s\n", capname);
179 if (!strcmp(capname, "fetch"))
180 data->fetch = 1;
181 else if (!strcmp(capname, "option"))
182 data->option = 1;
183 else if (!strcmp(capname, "push"))
184 data->push = 1;
185 else if (!strcmp(capname, "import"))
186 data->import = 1;
187 else if (!strcmp(capname, "bidi-import"))
188 data->bidi_import = 1;
189 else if (!strcmp(capname, "export"))
190 data->export = 1;
191 else if (!strcmp(capname, "check-connectivity"))
192 data->check_connectivity = 1;
193 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
194 ALLOC_GROW(refspecs,
195 refspec_nr + 1,
196 refspec_alloc);
197 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
198 } else if (!strcmp(capname, "connect")) {
199 data->connect = 1;
200 } else if (!strcmp(capname, "signed-tags")) {
201 data->signed_tags = 1;
202 } else if (!prefixcmp(capname, "export-marks ")) {
203 struct strbuf arg = STRBUF_INIT;
204 strbuf_addstr(&arg, "--export-marks=");
205 strbuf_addstr(&arg, capname + strlen("export-marks "));
206 data->export_marks = strbuf_detach(&arg, NULL);
207 } else if (!prefixcmp(capname, "import-marks")) {
208 struct strbuf arg = STRBUF_INIT;
209 strbuf_addstr(&arg, "--import-marks=");
210 strbuf_addstr(&arg, capname + strlen("import-marks "));
211 data->import_marks = strbuf_detach(&arg, NULL);
212 } else if (!prefixcmp(capname, "no-private-update")) {
213 data->no_private_update = 1;
214 } else if (mandatory) {
215 die("Unknown mandatory capability %s. This remote "
216 "helper probably needs newer version of Git.",
217 capname);
220 if (refspecs) {
221 int i;
222 data->refspec_nr = refspec_nr;
223 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
224 for (i = 0; i < refspec_nr; i++)
225 free((char *)refspecs[i]);
226 free(refspecs);
227 } else if (data->import || data->bidi_import || data->export) {
228 warning("This remote helper should implement refspec capability.");
230 strbuf_release(&buf);
231 if (debug)
232 fprintf(stderr, "Debug: Capabilities complete.\n");
233 return data->helper;
236 static int disconnect_helper(struct transport *transport)
238 struct helper_data *data = transport->data;
239 int res = 0;
241 if (data->helper) {
242 if (debug)
243 fprintf(stderr, "Debug: Disconnecting.\n");
244 if (!data->no_disconnect_req) {
246 * Ignore write errors; there's nothing we can do,
247 * since we're about to close the pipe anyway. And the
248 * most likely error is EPIPE due to the helper dying
249 * to report an error itself.
251 sigchain_push(SIGPIPE, SIG_IGN);
252 xwrite(data->helper->in, "\n", 1);
253 sigchain_pop(SIGPIPE);
255 close(data->helper->in);
256 close(data->helper->out);
257 fclose(data->out);
258 res = finish_command(data->helper);
259 argv_array_free_detached(data->helper->argv);
260 free(data->helper);
261 data->helper = NULL;
263 return res;
266 static const char *unsupported_options[] = {
267 TRANS_OPT_UPLOADPACK,
268 TRANS_OPT_RECEIVEPACK,
269 TRANS_OPT_THIN,
270 TRANS_OPT_KEEP
273 static const char *boolean_options[] = {
274 TRANS_OPT_THIN,
275 TRANS_OPT_KEEP,
276 TRANS_OPT_FOLLOWTAGS
279 static int set_helper_option(struct transport *transport,
280 const char *name, const char *value)
282 struct helper_data *data = transport->data;
283 struct strbuf buf = STRBUF_INIT;
284 int i, ret, is_bool = 0;
286 get_helper(transport);
288 if (!data->option)
289 return 1;
291 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
292 if (!strcmp(name, unsupported_options[i]))
293 return 1;
296 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
297 if (!strcmp(name, boolean_options[i])) {
298 is_bool = 1;
299 break;
303 strbuf_addf(&buf, "option %s ", name);
304 if (is_bool)
305 strbuf_addstr(&buf, value ? "true" : "false");
306 else
307 quote_c_style(value, &buf, NULL, 0);
308 strbuf_addch(&buf, '\n');
310 xchgline(data, &buf);
312 if (!strcmp(buf.buf, "ok"))
313 ret = 0;
314 else if (!prefixcmp(buf.buf, "error")) {
315 ret = -1;
316 } else if (!strcmp(buf.buf, "unsupported"))
317 ret = 1;
318 else {
319 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
320 ret = 1;
322 strbuf_release(&buf);
323 return ret;
326 static void standard_options(struct transport *t)
328 char buf[16];
329 int n;
330 int v = t->verbose;
332 set_helper_option(t, "progress", t->progress ? "true" : "false");
334 n = snprintf(buf, sizeof(buf), "%d", v + 1);
335 if (n >= sizeof(buf))
336 die("impossibly large verbosity value");
337 set_helper_option(t, "verbosity", buf);
340 static int release_helper(struct transport *transport)
342 int res = 0;
343 struct helper_data *data = transport->data;
344 free_refspec(data->refspec_nr, data->refspecs);
345 data->refspecs = NULL;
346 res = disconnect_helper(transport);
347 free(transport->data);
348 return res;
351 static int fetch_with_fetch(struct transport *transport,
352 int nr_heads, struct ref **to_fetch)
354 struct helper_data *data = transport->data;
355 int i;
356 struct strbuf buf = STRBUF_INIT;
358 standard_options(transport);
359 if (data->check_connectivity &&
360 data->transport_options.check_self_contained_and_connected)
361 set_helper_option(transport, "check-connectivity", "true");
363 for (i = 0; i < nr_heads; i++) {
364 const struct ref *posn = to_fetch[i];
365 if (posn->status & REF_STATUS_UPTODATE)
366 continue;
368 strbuf_addf(&buf, "fetch %s %s\n",
369 sha1_to_hex(posn->old_sha1), posn->name);
372 strbuf_addch(&buf, '\n');
373 sendline(data, &buf);
375 while (1) {
376 recvline(data, &buf);
378 if (!prefixcmp(buf.buf, "lock ")) {
379 const char *name = buf.buf + 5;
380 if (transport->pack_lockfile)
381 warning("%s also locked %s", data->name, name);
382 else
383 transport->pack_lockfile = xstrdup(name);
385 else if (data->check_connectivity &&
386 data->transport_options.check_self_contained_and_connected &&
387 !strcmp(buf.buf, "connectivity-ok"))
388 data->transport_options.self_contained_and_connected = 1;
389 else if (!buf.len)
390 break;
391 else
392 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
394 strbuf_release(&buf);
395 return 0;
398 static int get_importer(struct transport *transport, struct child_process *fastimport)
400 struct child_process *helper = get_helper(transport);
401 struct helper_data *data = transport->data;
402 struct argv_array argv = ARGV_ARRAY_INIT;
403 int cat_blob_fd, code;
404 memset(fastimport, 0, sizeof(*fastimport));
405 fastimport->in = helper->out;
406 argv_array_push(&argv, "fast-import");
407 argv_array_push(&argv, debug ? "--stats" : "--quiet");
409 if (data->bidi_import) {
410 cat_blob_fd = xdup(helper->in);
411 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
413 fastimport->argv = argv.argv;
414 fastimport->git_cmd = 1;
416 code = start_command(fastimport);
417 return code;
420 static int get_exporter(struct transport *transport,
421 struct child_process *fastexport,
422 struct string_list *revlist_args)
424 struct helper_data *data = transport->data;
425 struct child_process *helper = get_helper(transport);
426 int argc = 0, i;
427 memset(fastexport, 0, sizeof(*fastexport));
429 /* we need to duplicate helper->in because we want to use it after
430 * fastexport is done with it. */
431 fastexport->out = dup(helper->in);
432 fastexport->argv = xcalloc(7 + revlist_args->nr, sizeof(*fastexport->argv));
433 fastexport->argv[argc++] = "fast-export";
434 fastexport->argv[argc++] = "--use-done-feature";
435 fastexport->argv[argc++] = data->signed_tags ?
436 "--signed-tags=verbatim" : "--signed-tags=warn-strip";
437 if (data->export_marks)
438 fastexport->argv[argc++] = data->export_marks;
439 if (data->import_marks)
440 fastexport->argv[argc++] = data->import_marks;
442 for (i = 0; i < revlist_args->nr; i++)
443 fastexport->argv[argc++] = revlist_args->items[i].string;
445 fastexport->argv[argc++] = "--";
447 fastexport->git_cmd = 1;
448 return start_command(fastexport);
451 static void check_helper_status(struct helper_data *data)
453 int pid, status;
455 pid = waitpid(data->helper->pid, &status, WNOHANG);
456 if (pid < 0)
457 die("Could not retrieve status of remote helper '%s'",
458 data->name);
459 if (pid > 0 && WIFEXITED(status))
460 die("Remote helper '%s' died with %d",
461 data->name, WEXITSTATUS(status));
464 static int fetch_with_import(struct transport *transport,
465 int nr_heads, struct ref **to_fetch)
467 struct child_process fastimport;
468 struct helper_data *data = transport->data;
469 int i;
470 struct ref *posn;
471 struct strbuf buf = STRBUF_INIT;
473 get_helper(transport);
475 if (get_importer(transport, &fastimport))
476 die("Couldn't run fast-import");
478 for (i = 0; i < nr_heads; i++) {
479 posn = to_fetch[i];
480 if (posn->status & REF_STATUS_UPTODATE)
481 continue;
483 strbuf_addf(&buf, "import %s\n", posn->name);
484 sendline(data, &buf);
485 strbuf_reset(&buf);
488 write_constant(data->helper->in, "\n");
490 * remote-helpers that advertise the bidi-import capability are required to
491 * buffer the complete batch of import commands until this newline before
492 * sending data to fast-import.
493 * These helpers read back data from fast-import on their stdin, which could
494 * be mixed with import commands, otherwise.
497 if (finish_command(&fastimport))
498 die("Error while running fast-import");
499 argv_array_free_detached(fastimport.argv);
500 check_helper_status(data);
503 * The fast-import stream of a remote helper that advertises
504 * the "refspec" capability writes to the refs named after the
505 * right hand side of the first refspec matching each ref we
506 * were fetching.
508 * (If no "refspec" capability was specified, for historical
509 * reasons we default to the equivalent of *:*.)
511 * Store the result in to_fetch[i].old_sha1. Callers such
512 * as "git fetch" can use the value to write feedback to the
513 * terminal, populate FETCH_HEAD, and determine what new value
514 * should be written to peer_ref if the update is a
515 * fast-forward or this is a forced update.
517 for (i = 0; i < nr_heads; i++) {
518 char *private;
519 posn = to_fetch[i];
520 if (posn->status & REF_STATUS_UPTODATE)
521 continue;
522 if (data->refspecs)
523 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
524 else
525 private = xstrdup(posn->name);
526 if (private) {
527 read_ref(private, posn->old_sha1);
528 free(private);
531 strbuf_release(&buf);
532 return 0;
535 static int process_connect_service(struct transport *transport,
536 const char *name, const char *exec)
538 struct helper_data *data = transport->data;
539 struct strbuf cmdbuf = STRBUF_INIT;
540 struct child_process *helper;
541 int r, duped, ret = 0;
542 FILE *input;
544 helper = get_helper(transport);
547 * Yes, dup the pipe another time, as we need unbuffered version
548 * of input pipe as FILE*. fclose() closes the underlying fd and
549 * stream buffering only can be changed before first I/O operation
550 * on it.
552 duped = dup(helper->out);
553 if (duped < 0)
554 die_errno("Can't dup helper output fd");
555 input = xfdopen(duped, "r");
556 setvbuf(input, NULL, _IONBF, 0);
559 * Handle --upload-pack and friends. This is fire and forget...
560 * just warn if it fails.
562 if (strcmp(name, exec)) {
563 r = set_helper_option(transport, "servpath", exec);
564 if (r > 0)
565 warning("Setting remote service path not supported by protocol.");
566 else if (r < 0)
567 warning("Invalid remote service path.");
570 if (data->connect)
571 strbuf_addf(&cmdbuf, "connect %s\n", name);
572 else
573 goto exit;
575 sendline(data, &cmdbuf);
576 recvline_fh(input, &cmdbuf, name);
577 if (!strcmp(cmdbuf.buf, "")) {
578 data->no_disconnect_req = 1;
579 if (debug)
580 fprintf(stderr, "Debug: Smart transport connection "
581 "ready.\n");
582 ret = 1;
583 } else if (!strcmp(cmdbuf.buf, "fallback")) {
584 if (debug)
585 fprintf(stderr, "Debug: Falling back to dumb "
586 "transport.\n");
587 } else
588 die("Unknown response to connect: %s",
589 cmdbuf.buf);
591 exit:
592 fclose(input);
593 return ret;
596 static int process_connect(struct transport *transport,
597 int for_push)
599 struct helper_data *data = transport->data;
600 const char *name;
601 const char *exec;
603 name = for_push ? "git-receive-pack" : "git-upload-pack";
604 if (for_push)
605 exec = data->transport_options.receivepack;
606 else
607 exec = data->transport_options.uploadpack;
609 return process_connect_service(transport, name, exec);
612 static int connect_helper(struct transport *transport, const char *name,
613 const char *exec, int fd[2])
615 struct helper_data *data = transport->data;
617 /* Get_helper so connect is inited. */
618 get_helper(transport);
619 if (!data->connect)
620 die("Operation not supported by protocol.");
622 if (!process_connect_service(transport, name, exec))
623 die("Can't connect to subservice %s.", name);
625 fd[0] = data->helper->out;
626 fd[1] = data->helper->in;
627 return 0;
630 static int fetch(struct transport *transport,
631 int nr_heads, struct ref **to_fetch)
633 struct helper_data *data = transport->data;
634 int i, count;
636 if (process_connect(transport, 0)) {
637 do_take_over(transport);
638 return transport->fetch(transport, nr_heads, to_fetch);
641 count = 0;
642 for (i = 0; i < nr_heads; i++)
643 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
644 count++;
646 if (!count)
647 return 0;
649 if (data->fetch)
650 return fetch_with_fetch(transport, nr_heads, to_fetch);
652 if (data->import)
653 return fetch_with_import(transport, nr_heads, to_fetch);
655 return -1;
658 static int push_update_ref_status(struct strbuf *buf,
659 struct ref **ref,
660 struct ref *remote_refs)
662 char *refname, *msg;
663 int status;
665 if (!prefixcmp(buf->buf, "ok ")) {
666 status = REF_STATUS_OK;
667 refname = buf->buf + 3;
668 } else if (!prefixcmp(buf->buf, "error ")) {
669 status = REF_STATUS_REMOTE_REJECT;
670 refname = buf->buf + 6;
671 } else
672 die("expected ok/error, helper said '%s'", buf->buf);
674 msg = strchr(refname, ' ');
675 if (msg) {
676 struct strbuf msg_buf = STRBUF_INIT;
677 const char *end;
679 *msg++ = '\0';
680 if (!unquote_c_style(&msg_buf, msg, &end))
681 msg = strbuf_detach(&msg_buf, NULL);
682 else
683 msg = xstrdup(msg);
684 strbuf_release(&msg_buf);
686 if (!strcmp(msg, "no match")) {
687 status = REF_STATUS_NONE;
688 free(msg);
689 msg = NULL;
691 else if (!strcmp(msg, "up to date")) {
692 status = REF_STATUS_UPTODATE;
693 free(msg);
694 msg = NULL;
696 else if (!strcmp(msg, "non-fast forward")) {
697 status = REF_STATUS_REJECT_NONFASTFORWARD;
698 free(msg);
699 msg = NULL;
701 else if (!strcmp(msg, "already exists")) {
702 status = REF_STATUS_REJECT_ALREADY_EXISTS;
703 free(msg);
704 msg = NULL;
706 else if (!strcmp(msg, "fetch first")) {
707 status = REF_STATUS_REJECT_FETCH_FIRST;
708 free(msg);
709 msg = NULL;
711 else if (!strcmp(msg, "needs force")) {
712 status = REF_STATUS_REJECT_NEEDS_FORCE;
713 free(msg);
714 msg = NULL;
716 else if (!strcmp(msg, "stale info")) {
717 status = REF_STATUS_REJECT_STALE;
718 free(msg);
719 msg = NULL;
723 if (*ref)
724 *ref = find_ref_by_name(*ref, refname);
725 if (!*ref)
726 *ref = find_ref_by_name(remote_refs, refname);
727 if (!*ref) {
728 warning("helper reported unexpected status of %s", refname);
729 return 1;
732 if ((*ref)->status != REF_STATUS_NONE) {
734 * Earlier, the ref was marked not to be pushed, so ignore the ref
735 * status reported by the remote helper if the latter is 'no match'.
737 if (status == REF_STATUS_NONE)
738 return 1;
741 (*ref)->status = status;
742 (*ref)->remote_status = msg;
743 return !(status == REF_STATUS_OK);
746 static void push_update_refs_status(struct helper_data *data,
747 struct ref *remote_refs)
749 struct strbuf buf = STRBUF_INIT;
750 struct ref *ref = remote_refs;
751 for (;;) {
752 char *private;
754 recvline(data, &buf);
755 if (!buf.len)
756 break;
758 if (push_update_ref_status(&buf, &ref, remote_refs))
759 continue;
761 if (!data->refspecs || data->no_private_update)
762 continue;
764 /* propagate back the update to the remote namespace */
765 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
766 if (!private)
767 continue;
768 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
769 free(private);
771 strbuf_release(&buf);
774 static int push_refs_with_push(struct transport *transport,
775 struct ref *remote_refs, int flags)
777 int force_all = flags & TRANSPORT_PUSH_FORCE;
778 int mirror = flags & TRANSPORT_PUSH_MIRROR;
779 struct helper_data *data = transport->data;
780 struct strbuf buf = STRBUF_INIT;
781 struct ref *ref;
782 struct string_list cas_options = STRING_LIST_INIT_DUP;
783 struct string_list_item *cas_option;
785 get_helper(transport);
786 if (!data->push)
787 return 1;
789 for (ref = remote_refs; ref; ref = ref->next) {
790 if (!ref->peer_ref && !mirror)
791 continue;
793 /* Check for statuses set by set_ref_status_for_push() */
794 switch (ref->status) {
795 case REF_STATUS_REJECT_NONFASTFORWARD:
796 case REF_STATUS_REJECT_STALE:
797 case REF_STATUS_REJECT_ALREADY_EXISTS:
798 case REF_STATUS_UPTODATE:
799 continue;
800 default:
801 ; /* do nothing */
804 if (force_all)
805 ref->force = 1;
807 strbuf_addstr(&buf, "push ");
808 if (!ref->deletion) {
809 if (ref->force)
810 strbuf_addch(&buf, '+');
811 if (ref->peer_ref)
812 strbuf_addstr(&buf, ref->peer_ref->name);
813 else
814 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
816 strbuf_addch(&buf, ':');
817 strbuf_addstr(&buf, ref->name);
818 strbuf_addch(&buf, '\n');
821 * The "--force-with-lease" options without explicit
822 * values to expect have already been expanded into
823 * the ref->old_sha1_expect[] field; we can ignore
824 * transport->smart_options->cas altogether and instead
825 * can enumerate them from the refs.
827 if (ref->expect_old_sha1) {
828 struct strbuf cas = STRBUF_INIT;
829 strbuf_addf(&cas, "%s:%s",
830 ref->name, sha1_to_hex(ref->old_sha1_expect));
831 string_list_append(&cas_options, strbuf_detach(&cas, NULL));
834 if (buf.len == 0) {
835 string_list_clear(&cas_options, 0);
836 return 0;
839 standard_options(transport);
840 for_each_string_list_item(cas_option, &cas_options)
841 set_helper_option(transport, "cas", cas_option->string);
843 if (flags & TRANSPORT_PUSH_DRY_RUN) {
844 if (set_helper_option(transport, "dry-run", "true") != 0)
845 die("helper %s does not support dry-run", data->name);
848 strbuf_addch(&buf, '\n');
849 sendline(data, &buf);
850 strbuf_release(&buf);
852 push_update_refs_status(data, remote_refs);
853 return 0;
856 static int push_refs_with_export(struct transport *transport,
857 struct ref *remote_refs, int flags)
859 struct ref *ref;
860 struct child_process *helper, exporter;
861 struct helper_data *data = transport->data;
862 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
863 struct strbuf buf = STRBUF_INIT;
865 if (!data->refspecs)
866 die("remote-helper doesn't support push; refspec needed");
868 if (flags & TRANSPORT_PUSH_DRY_RUN) {
869 if (set_helper_option(transport, "dry-run", "true") != 0)
870 die("helper %s does not support dry-run", data->name);
873 helper = get_helper(transport);
875 write_constant(helper->in, "export\n");
877 strbuf_reset(&buf);
879 for (ref = remote_refs; ref; ref = ref->next) {
880 char *private;
881 unsigned char sha1[20];
883 if (ref->deletion)
884 die("remote-helpers do not support ref deletion");
886 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
887 if (private && !get_sha1(private, sha1)) {
888 strbuf_addf(&buf, "^%s", private);
889 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
890 hashcpy(ref->old_sha1, sha1);
892 free(private);
894 if (ref->deletion)
895 die("remote-helpers do not support ref deletion");
897 if (ref->peer_ref) {
898 if (strcmp(ref->peer_ref->name, ref->name))
899 die("remote-helpers do not support old:new syntax");
900 string_list_append(&revlist_args, ref->peer_ref->name);
904 if (get_exporter(transport, &exporter, &revlist_args))
905 die("Couldn't run fast-export");
907 if (finish_command(&exporter))
908 die("Error while running fast-export");
909 check_helper_status(data);
910 push_update_refs_status(data, remote_refs);
911 return 0;
914 static int push_refs(struct transport *transport,
915 struct ref *remote_refs, int flags)
917 struct helper_data *data = transport->data;
919 if (process_connect(transport, 1)) {
920 do_take_over(transport);
921 return transport->push_refs(transport, remote_refs, flags);
924 if (!remote_refs) {
925 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
926 "Perhaps you should specify a branch such as 'master'.\n");
927 return 0;
930 if (data->push)
931 return push_refs_with_push(transport, remote_refs, flags);
933 if (data->export)
934 return push_refs_with_export(transport, remote_refs, flags);
936 return -1;
940 static int has_attribute(const char *attrs, const char *attr) {
941 int len;
942 if (!attrs)
943 return 0;
945 len = strlen(attr);
946 for (;;) {
947 const char *space = strchrnul(attrs, ' ');
948 if (len == space - attrs && !strncmp(attrs, attr, len))
949 return 1;
950 if (!*space)
951 return 0;
952 attrs = space + 1;
956 static struct ref *get_refs_list(struct transport *transport, int for_push)
958 struct helper_data *data = transport->data;
959 struct child_process *helper;
960 struct ref *ret = NULL;
961 struct ref **tail = &ret;
962 struct ref *posn;
963 struct strbuf buf = STRBUF_INIT;
965 helper = get_helper(transport);
967 if (process_connect(transport, for_push)) {
968 do_take_over(transport);
969 return transport->get_refs_list(transport, for_push);
972 if (data->push && for_push)
973 write_str_in_full(helper->in, "list for-push\n");
974 else
975 write_str_in_full(helper->in, "list\n");
977 while (1) {
978 char *eov, *eon;
979 recvline(data, &buf);
981 if (!*buf.buf)
982 break;
984 eov = strchr(buf.buf, ' ');
985 if (!eov)
986 die("Malformed response in ref list: %s", buf.buf);
987 eon = strchr(eov + 1, ' ');
988 *eov = '\0';
989 if (eon)
990 *eon = '\0';
991 *tail = alloc_ref(eov + 1);
992 if (buf.buf[0] == '@')
993 (*tail)->symref = xstrdup(buf.buf + 1);
994 else if (buf.buf[0] != '?')
995 get_sha1_hex(buf.buf, (*tail)->old_sha1);
996 if (eon) {
997 if (has_attribute(eon + 1, "unchanged")) {
998 (*tail)->status |= REF_STATUS_UPTODATE;
999 read_ref((*tail)->name, (*tail)->old_sha1);
1002 tail = &((*tail)->next);
1004 if (debug)
1005 fprintf(stderr, "Debug: Read ref listing.\n");
1006 strbuf_release(&buf);
1008 for (posn = ret; posn; posn = posn->next)
1009 resolve_remote_symref(posn, ret);
1011 return ret;
1014 int transport_helper_init(struct transport *transport, const char *name)
1016 struct helper_data *data = xcalloc(sizeof(*data), 1);
1017 data->name = name;
1019 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1020 debug = 1;
1022 transport->data = data;
1023 transport->set_option = set_helper_option;
1024 transport->get_refs_list = get_refs_list;
1025 transport->fetch = fetch;
1026 transport->push_refs = push_refs;
1027 transport->disconnect = release_helper;
1028 transport->connect = connect_helper;
1029 transport->smart_options = &(data->transport_options);
1030 return 0;
1034 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1035 * buffer less), so attempt reads and writes with up to that size.
1037 #define BUFFERSIZE 65536
1038 /* This should be enough to hold debugging message. */
1039 #define PBUFFERSIZE 8192
1041 /* Print bidirectional transfer loop debug message. */
1042 __attribute__((format (printf, 1, 2)))
1043 static void transfer_debug(const char *fmt, ...)
1045 va_list args;
1046 char msgbuf[PBUFFERSIZE];
1047 static int debug_enabled = -1;
1049 if (debug_enabled < 0)
1050 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1051 if (!debug_enabled)
1052 return;
1054 va_start(args, fmt);
1055 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1056 va_end(args);
1057 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1060 /* Stream state: More data may be coming in this direction. */
1061 #define SSTATE_TRANSFERING 0
1063 * Stream state: No more data coming in this direction, flushing rest of
1064 * data.
1066 #define SSTATE_FLUSHING 1
1067 /* Stream state: Transfer in this direction finished. */
1068 #define SSTATE_FINISHED 2
1070 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1071 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1072 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1074 /* Unidirectional transfer. */
1075 struct unidirectional_transfer {
1076 /* Source */
1077 int src;
1078 /* Destination */
1079 int dest;
1080 /* Is source socket? */
1081 int src_is_sock;
1082 /* Is destination socket? */
1083 int dest_is_sock;
1084 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1085 int state;
1086 /* Buffer. */
1087 char buf[BUFFERSIZE];
1088 /* Buffer used. */
1089 size_t bufuse;
1090 /* Name of source. */
1091 const char *src_name;
1092 /* Name of destination. */
1093 const char *dest_name;
1096 /* Closes the target (for writing) if transfer has finished. */
1097 static void udt_close_if_finished(struct unidirectional_transfer *t)
1099 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1100 t->state = SSTATE_FINISHED;
1101 if (t->dest_is_sock)
1102 shutdown(t->dest, SHUT_WR);
1103 else
1104 close(t->dest);
1105 transfer_debug("Closed %s.", t->dest_name);
1110 * Tries to read read data from source into buffer. If buffer is full,
1111 * no data is read. Returns 0 on success, -1 on error.
1113 static int udt_do_read(struct unidirectional_transfer *t)
1115 ssize_t bytes;
1117 if (t->bufuse == BUFFERSIZE)
1118 return 0; /* No space for more. */
1120 transfer_debug("%s is readable", t->src_name);
1121 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1122 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1123 errno != EINTR) {
1124 error("read(%s) failed: %s", t->src_name, strerror(errno));
1125 return -1;
1126 } else if (bytes == 0) {
1127 transfer_debug("%s EOF (with %i bytes in buffer)",
1128 t->src_name, (int)t->bufuse);
1129 t->state = SSTATE_FLUSHING;
1130 } else if (bytes > 0) {
1131 t->bufuse += bytes;
1132 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1133 (int)bytes, t->src_name, (int)t->bufuse);
1135 return 0;
1138 /* Tries to write data from buffer into destination. If buffer is empty,
1139 * no data is written. Returns 0 on success, -1 on error.
1141 static int udt_do_write(struct unidirectional_transfer *t)
1143 ssize_t bytes;
1145 if (t->bufuse == 0)
1146 return 0; /* Nothing to write. */
1148 transfer_debug("%s is writable", t->dest_name);
1149 bytes = write(t->dest, t->buf, t->bufuse);
1150 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1151 errno != EINTR) {
1152 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1153 return -1;
1154 } else if (bytes > 0) {
1155 t->bufuse -= bytes;
1156 if (t->bufuse)
1157 memmove(t->buf, t->buf + bytes, t->bufuse);
1158 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1159 (int)bytes, t->dest_name, (int)t->bufuse);
1161 return 0;
1165 /* State of bidirectional transfer loop. */
1166 struct bidirectional_transfer_state {
1167 /* Direction from program to git. */
1168 struct unidirectional_transfer ptg;
1169 /* Direction from git to program. */
1170 struct unidirectional_transfer gtp;
1173 static void *udt_copy_task_routine(void *udt)
1175 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1176 while (t->state != SSTATE_FINISHED) {
1177 if (STATE_NEEDS_READING(t->state))
1178 if (udt_do_read(t))
1179 return NULL;
1180 if (STATE_NEEDS_WRITING(t->state))
1181 if (udt_do_write(t))
1182 return NULL;
1183 if (STATE_NEEDS_CLOSING(t->state))
1184 udt_close_if_finished(t);
1186 return udt; /* Just some non-NULL value. */
1189 #ifndef NO_PTHREADS
1192 * Join thread, with appropriate errors on failure. Name is name for the
1193 * thread (for error messages). Returns 0 on success, 1 on failure.
1195 static int tloop_join(pthread_t thread, const char *name)
1197 int err;
1198 void *tret;
1199 err = pthread_join(thread, &tret);
1200 if (!tret) {
1201 error("%s thread failed", name);
1202 return 1;
1204 if (err) {
1205 error("%s thread failed to join: %s", name, strerror(err));
1206 return 1;
1208 return 0;
1212 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1213 * -1 on failure.
1215 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1217 pthread_t gtp_thread;
1218 pthread_t ptg_thread;
1219 int err;
1220 int ret = 0;
1221 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1222 &s->gtp);
1223 if (err)
1224 die("Can't start thread for copying data: %s", strerror(err));
1225 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1226 &s->ptg);
1227 if (err)
1228 die("Can't start thread for copying data: %s", strerror(err));
1230 ret |= tloop_join(gtp_thread, "Git to program copy");
1231 ret |= tloop_join(ptg_thread, "Program to git copy");
1232 return ret;
1234 #else
1236 /* Close the source and target (for writing) for transfer. */
1237 static void udt_kill_transfer(struct unidirectional_transfer *t)
1239 t->state = SSTATE_FINISHED;
1241 * Socket read end left open isn't a disaster if nobody
1242 * attempts to read from it (mingw compat headers do not
1243 * have SHUT_RD)...
1245 * We can't fully close the socket since otherwise gtp
1246 * task would first close the socket it sends data to
1247 * while closing the ptg file descriptors.
1249 if (!t->src_is_sock)
1250 close(t->src);
1251 if (t->dest_is_sock)
1252 shutdown(t->dest, SHUT_WR);
1253 else
1254 close(t->dest);
1258 * Join process, with appropriate errors on failure. Name is name for the
1259 * process (for error messages). Returns 0 on success, 1 on failure.
1261 static int tloop_join(pid_t pid, const char *name)
1263 int tret;
1264 if (waitpid(pid, &tret, 0) < 0) {
1265 error("%s process failed to wait: %s", name, strerror(errno));
1266 return 1;
1268 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1269 error("%s process failed", name);
1270 return 1;
1272 return 0;
1276 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1277 * -1 on failure.
1279 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1281 pid_t pid1, pid2;
1282 int ret = 0;
1284 /* Fork thread #1: git to program. */
1285 pid1 = fork();
1286 if (pid1 < 0)
1287 die_errno("Can't start thread for copying data");
1288 else if (pid1 == 0) {
1289 udt_kill_transfer(&s->ptg);
1290 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1293 /* Fork thread #2: program to git. */
1294 pid2 = fork();
1295 if (pid2 < 0)
1296 die_errno("Can't start thread for copying data");
1297 else if (pid2 == 0) {
1298 udt_kill_transfer(&s->gtp);
1299 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1303 * Close both streams in parent as to not interfere with
1304 * end of file detection and wait for both tasks to finish.
1306 udt_kill_transfer(&s->gtp);
1307 udt_kill_transfer(&s->ptg);
1308 ret |= tloop_join(pid1, "Git to program copy");
1309 ret |= tloop_join(pid2, "Program to git copy");
1310 return ret;
1312 #endif
1315 * Copies data from stdin to output and from input to stdout simultaneously.
1316 * Additionally filtering through given filter. If filter is NULL, uses
1317 * identity filter.
1319 int bidirectional_transfer_loop(int input, int output)
1321 struct bidirectional_transfer_state state;
1323 /* Fill the state fields. */
1324 state.ptg.src = input;
1325 state.ptg.dest = 1;
1326 state.ptg.src_is_sock = (input == output);
1327 state.ptg.dest_is_sock = 0;
1328 state.ptg.state = SSTATE_TRANSFERING;
1329 state.ptg.bufuse = 0;
1330 state.ptg.src_name = "remote input";
1331 state.ptg.dest_name = "stdout";
1333 state.gtp.src = 0;
1334 state.gtp.dest = output;
1335 state.gtp.src_is_sock = 0;
1336 state.gtp.dest_is_sock = (input == output);
1337 state.gtp.state = SSTATE_TRANSFERING;
1338 state.gtp.bufuse = 0;
1339 state.gtp.src_name = "stdin";
1340 state.gtp.dest_name = "remote output";
1342 return tloop_spawnwait_tasks(&state);