transport-helper: add trailing --
[git/mingw/4msysgit.git] / transport-helper.c
blobf0214d3800cc7bb6b23515d4ed85a85c541e5cd6
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 && starts_with(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 (starts_with(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 (starts_with(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 (starts_with(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 (starts_with(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 if (transport->cloning)
364 set_helper_option(transport, "cloning", "true");
366 if (data->transport_options.update_shallow)
367 set_helper_option(transport, "update-shallow", "true");
369 for (i = 0; i < nr_heads; i++) {
370 const struct ref *posn = to_fetch[i];
371 if (posn->status & REF_STATUS_UPTODATE)
372 continue;
374 strbuf_addf(&buf, "fetch %s %s\n",
375 sha1_to_hex(posn->old_sha1), posn->name);
378 strbuf_addch(&buf, '\n');
379 sendline(data, &buf);
381 while (1) {
382 recvline(data, &buf);
384 if (starts_with(buf.buf, "lock ")) {
385 const char *name = buf.buf + 5;
386 if (transport->pack_lockfile)
387 warning("%s also locked %s", data->name, name);
388 else
389 transport->pack_lockfile = xstrdup(name);
391 else if (data->check_connectivity &&
392 data->transport_options.check_self_contained_and_connected &&
393 !strcmp(buf.buf, "connectivity-ok"))
394 data->transport_options.self_contained_and_connected = 1;
395 else if (!buf.len)
396 break;
397 else
398 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
400 strbuf_release(&buf);
401 return 0;
404 static int get_importer(struct transport *transport, struct child_process *fastimport)
406 struct child_process *helper = get_helper(transport);
407 struct helper_data *data = transport->data;
408 struct argv_array argv = ARGV_ARRAY_INIT;
409 int cat_blob_fd, code;
410 memset(fastimport, 0, sizeof(*fastimport));
411 fastimport->in = helper->out;
412 argv_array_push(&argv, "fast-import");
413 argv_array_push(&argv, debug ? "--stats" : "--quiet");
415 if (data->bidi_import) {
416 cat_blob_fd = xdup(helper->in);
417 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
419 fastimport->argv = argv.argv;
420 fastimport->git_cmd = 1;
422 code = start_command(fastimport);
423 return code;
426 static int get_exporter(struct transport *transport,
427 struct child_process *fastexport,
428 struct string_list *revlist_args)
430 struct helper_data *data = transport->data;
431 struct child_process *helper = get_helper(transport);
432 int argc = 0, i;
433 memset(fastexport, 0, sizeof(*fastexport));
435 /* we need to duplicate helper->in because we want to use it after
436 * fastexport is done with it. */
437 fastexport->out = dup(helper->in);
438 fastexport->argv = xcalloc(7 + revlist_args->nr, sizeof(*fastexport->argv));
439 fastexport->argv[argc++] = "fast-export";
440 fastexport->argv[argc++] = "--use-done-feature";
441 fastexport->argv[argc++] = data->signed_tags ?
442 "--signed-tags=verbatim" : "--signed-tags=warn-strip";
443 if (data->export_marks)
444 fastexport->argv[argc++] = data->export_marks;
445 if (data->import_marks)
446 fastexport->argv[argc++] = data->import_marks;
448 for (i = 0; i < revlist_args->nr; i++)
449 fastexport->argv[argc++] = revlist_args->items[i].string;
451 fastexport->argv[argc++] = "--";
453 fastexport->git_cmd = 1;
454 return start_command(fastexport);
457 static int fetch_with_import(struct transport *transport,
458 int nr_heads, struct ref **to_fetch)
460 struct child_process fastimport;
461 struct helper_data *data = transport->data;
462 int i;
463 struct ref *posn;
464 struct strbuf buf = STRBUF_INIT;
466 get_helper(transport);
468 if (get_importer(transport, &fastimport))
469 die("Couldn't run fast-import");
471 for (i = 0; i < nr_heads; i++) {
472 posn = to_fetch[i];
473 if (posn->status & REF_STATUS_UPTODATE)
474 continue;
476 strbuf_addf(&buf, "import %s\n", posn->name);
477 sendline(data, &buf);
478 strbuf_reset(&buf);
481 write_constant(data->helper->in, "\n");
483 * remote-helpers that advertise the bidi-import capability are required to
484 * buffer the complete batch of import commands until this newline before
485 * sending data to fast-import.
486 * These helpers read back data from fast-import on their stdin, which could
487 * be mixed with import commands, otherwise.
490 if (finish_command(&fastimport))
491 die("Error while running fast-import");
492 argv_array_free_detached(fastimport.argv);
495 * The fast-import stream of a remote helper that advertises
496 * the "refspec" capability writes to the refs named after the
497 * right hand side of the first refspec matching each ref we
498 * were fetching.
500 * (If no "refspec" capability was specified, for historical
501 * reasons we default to the equivalent of *:*.)
503 * Store the result in to_fetch[i].old_sha1. Callers such
504 * as "git fetch" can use the value to write feedback to the
505 * terminal, populate FETCH_HEAD, and determine what new value
506 * should be written to peer_ref if the update is a
507 * fast-forward or this is a forced update.
509 for (i = 0; i < nr_heads; i++) {
510 char *private;
511 posn = to_fetch[i];
512 if (posn->status & REF_STATUS_UPTODATE)
513 continue;
514 if (data->refspecs)
515 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
516 else
517 private = xstrdup(posn->name);
518 if (private) {
519 read_ref(private, posn->old_sha1);
520 free(private);
523 strbuf_release(&buf);
524 return 0;
527 static int process_connect_service(struct transport *transport,
528 const char *name, const char *exec)
530 struct helper_data *data = transport->data;
531 struct strbuf cmdbuf = STRBUF_INIT;
532 struct child_process *helper;
533 int r, duped, ret = 0;
534 FILE *input;
536 helper = get_helper(transport);
539 * Yes, dup the pipe another time, as we need unbuffered version
540 * of input pipe as FILE*. fclose() closes the underlying fd and
541 * stream buffering only can be changed before first I/O operation
542 * on it.
544 duped = dup(helper->out);
545 if (duped < 0)
546 die_errno("Can't dup helper output fd");
547 input = xfdopen(duped, "r");
548 setvbuf(input, NULL, _IONBF, 0);
551 * Handle --upload-pack and friends. This is fire and forget...
552 * just warn if it fails.
554 if (strcmp(name, exec)) {
555 r = set_helper_option(transport, "servpath", exec);
556 if (r > 0)
557 warning("Setting remote service path not supported by protocol.");
558 else if (r < 0)
559 warning("Invalid remote service path.");
562 if (data->connect)
563 strbuf_addf(&cmdbuf, "connect %s\n", name);
564 else
565 goto exit;
567 sendline(data, &cmdbuf);
568 recvline_fh(input, &cmdbuf, name);
569 if (!strcmp(cmdbuf.buf, "")) {
570 data->no_disconnect_req = 1;
571 if (debug)
572 fprintf(stderr, "Debug: Smart transport connection "
573 "ready.\n");
574 ret = 1;
575 } else if (!strcmp(cmdbuf.buf, "fallback")) {
576 if (debug)
577 fprintf(stderr, "Debug: Falling back to dumb "
578 "transport.\n");
579 } else
580 die("Unknown response to connect: %s",
581 cmdbuf.buf);
583 exit:
584 fclose(input);
585 return ret;
588 static int process_connect(struct transport *transport,
589 int for_push)
591 struct helper_data *data = transport->data;
592 const char *name;
593 const char *exec;
595 name = for_push ? "git-receive-pack" : "git-upload-pack";
596 if (for_push)
597 exec = data->transport_options.receivepack;
598 else
599 exec = data->transport_options.uploadpack;
601 return process_connect_service(transport, name, exec);
604 static int connect_helper(struct transport *transport, const char *name,
605 const char *exec, int fd[2])
607 struct helper_data *data = transport->data;
609 /* Get_helper so connect is inited. */
610 get_helper(transport);
611 if (!data->connect)
612 die("Operation not supported by protocol.");
614 if (!process_connect_service(transport, name, exec))
615 die("Can't connect to subservice %s.", name);
617 fd[0] = data->helper->out;
618 fd[1] = data->helper->in;
619 return 0;
622 static int fetch(struct transport *transport,
623 int nr_heads, struct ref **to_fetch)
625 struct helper_data *data = transport->data;
626 int i, count;
628 if (process_connect(transport, 0)) {
629 do_take_over(transport);
630 return transport->fetch(transport, nr_heads, to_fetch);
633 count = 0;
634 for (i = 0; i < nr_heads; i++)
635 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
636 count++;
638 if (!count)
639 return 0;
641 if (data->fetch)
642 return fetch_with_fetch(transport, nr_heads, to_fetch);
644 if (data->import)
645 return fetch_with_import(transport, nr_heads, to_fetch);
647 return -1;
650 static int push_update_ref_status(struct strbuf *buf,
651 struct ref **ref,
652 struct ref *remote_refs)
654 char *refname, *msg;
655 int status;
657 if (starts_with(buf->buf, "ok ")) {
658 status = REF_STATUS_OK;
659 refname = buf->buf + 3;
660 } else if (starts_with(buf->buf, "error ")) {
661 status = REF_STATUS_REMOTE_REJECT;
662 refname = buf->buf + 6;
663 } else
664 die("expected ok/error, helper said '%s'", buf->buf);
666 msg = strchr(refname, ' ');
667 if (msg) {
668 struct strbuf msg_buf = STRBUF_INIT;
669 const char *end;
671 *msg++ = '\0';
672 if (!unquote_c_style(&msg_buf, msg, &end))
673 msg = strbuf_detach(&msg_buf, NULL);
674 else
675 msg = xstrdup(msg);
676 strbuf_release(&msg_buf);
678 if (!strcmp(msg, "no match")) {
679 status = REF_STATUS_NONE;
680 free(msg);
681 msg = NULL;
683 else if (!strcmp(msg, "up to date")) {
684 status = REF_STATUS_UPTODATE;
685 free(msg);
686 msg = NULL;
688 else if (!strcmp(msg, "non-fast forward")) {
689 status = REF_STATUS_REJECT_NONFASTFORWARD;
690 free(msg);
691 msg = NULL;
693 else if (!strcmp(msg, "already exists")) {
694 status = REF_STATUS_REJECT_ALREADY_EXISTS;
695 free(msg);
696 msg = NULL;
698 else if (!strcmp(msg, "fetch first")) {
699 status = REF_STATUS_REJECT_FETCH_FIRST;
700 free(msg);
701 msg = NULL;
703 else if (!strcmp(msg, "needs force")) {
704 status = REF_STATUS_REJECT_NEEDS_FORCE;
705 free(msg);
706 msg = NULL;
708 else if (!strcmp(msg, "stale info")) {
709 status = REF_STATUS_REJECT_STALE;
710 free(msg);
711 msg = NULL;
715 if (*ref)
716 *ref = find_ref_by_name(*ref, refname);
717 if (!*ref)
718 *ref = find_ref_by_name(remote_refs, refname);
719 if (!*ref) {
720 warning("helper reported unexpected status of %s", refname);
721 return 1;
724 if ((*ref)->status != REF_STATUS_NONE) {
726 * Earlier, the ref was marked not to be pushed, so ignore the ref
727 * status reported by the remote helper if the latter is 'no match'.
729 if (status == REF_STATUS_NONE)
730 return 1;
733 (*ref)->status = status;
734 (*ref)->remote_status = msg;
735 return !(status == REF_STATUS_OK);
738 static void push_update_refs_status(struct helper_data *data,
739 struct ref *remote_refs)
741 struct strbuf buf = STRBUF_INIT;
742 struct ref *ref = remote_refs;
743 for (;;) {
744 char *private;
746 recvline(data, &buf);
747 if (!buf.len)
748 break;
750 if (push_update_ref_status(&buf, &ref, remote_refs))
751 continue;
753 if (!data->refspecs || data->no_private_update)
754 continue;
756 /* propagate back the update to the remote namespace */
757 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
758 if (!private)
759 continue;
760 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
761 free(private);
763 strbuf_release(&buf);
766 static int push_refs_with_push(struct transport *transport,
767 struct ref *remote_refs, int flags)
769 int force_all = flags & TRANSPORT_PUSH_FORCE;
770 int mirror = flags & TRANSPORT_PUSH_MIRROR;
771 struct helper_data *data = transport->data;
772 struct strbuf buf = STRBUF_INIT;
773 struct ref *ref;
774 struct string_list cas_options = STRING_LIST_INIT_DUP;
775 struct string_list_item *cas_option;
777 get_helper(transport);
778 if (!data->push)
779 return 1;
781 for (ref = remote_refs; ref; ref = ref->next) {
782 if (!ref->peer_ref && !mirror)
783 continue;
785 /* Check for statuses set by set_ref_status_for_push() */
786 switch (ref->status) {
787 case REF_STATUS_REJECT_NONFASTFORWARD:
788 case REF_STATUS_REJECT_STALE:
789 case REF_STATUS_REJECT_ALREADY_EXISTS:
790 case REF_STATUS_UPTODATE:
791 continue;
792 default:
793 ; /* do nothing */
796 if (force_all)
797 ref->force = 1;
799 strbuf_addstr(&buf, "push ");
800 if (!ref->deletion) {
801 if (ref->force)
802 strbuf_addch(&buf, '+');
803 if (ref->peer_ref)
804 strbuf_addstr(&buf, ref->peer_ref->name);
805 else
806 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
808 strbuf_addch(&buf, ':');
809 strbuf_addstr(&buf, ref->name);
810 strbuf_addch(&buf, '\n');
813 * The "--force-with-lease" options without explicit
814 * values to expect have already been expanded into
815 * the ref->old_sha1_expect[] field; we can ignore
816 * transport->smart_options->cas altogether and instead
817 * can enumerate them from the refs.
819 if (ref->expect_old_sha1) {
820 struct strbuf cas = STRBUF_INIT;
821 strbuf_addf(&cas, "%s:%s",
822 ref->name, sha1_to_hex(ref->old_sha1_expect));
823 string_list_append(&cas_options, strbuf_detach(&cas, NULL));
826 if (buf.len == 0) {
827 string_list_clear(&cas_options, 0);
828 return 0;
831 standard_options(transport);
832 for_each_string_list_item(cas_option, &cas_options)
833 set_helper_option(transport, "cas", cas_option->string);
835 if (flags & TRANSPORT_PUSH_DRY_RUN) {
836 if (set_helper_option(transport, "dry-run", "true") != 0)
837 die("helper %s does not support dry-run", data->name);
840 strbuf_addch(&buf, '\n');
841 sendline(data, &buf);
842 strbuf_release(&buf);
844 push_update_refs_status(data, remote_refs);
845 return 0;
848 static int push_refs_with_export(struct transport *transport,
849 struct ref *remote_refs, int flags)
851 struct ref *ref;
852 struct child_process *helper, exporter;
853 struct helper_data *data = transport->data;
854 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
855 struct strbuf buf = STRBUF_INIT;
857 if (!data->refspecs)
858 die("remote-helper doesn't support push; refspec needed");
860 if (flags & TRANSPORT_PUSH_DRY_RUN) {
861 if (set_helper_option(transport, "dry-run", "true") != 0)
862 die("helper %s does not support dry-run", data->name);
865 helper = get_helper(transport);
867 write_constant(helper->in, "export\n");
869 strbuf_reset(&buf);
871 for (ref = remote_refs; ref; ref = ref->next) {
872 char *private;
873 unsigned char sha1[20];
875 if (ref->deletion)
876 die("remote-helpers do not support ref deletion");
878 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
879 if (private && !get_sha1(private, sha1)) {
880 strbuf_addf(&buf, "^%s", private);
881 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
882 hashcpy(ref->old_sha1, sha1);
884 free(private);
886 if (ref->deletion)
887 die("remote-helpers do not support ref deletion");
889 if (ref->peer_ref) {
890 if (strcmp(ref->peer_ref->name, ref->name))
891 die("remote-helpers do not support old:new syntax");
892 string_list_append(&revlist_args, ref->peer_ref->name);
896 if (get_exporter(transport, &exporter, &revlist_args))
897 die("Couldn't run fast-export");
899 if (finish_command(&exporter))
900 die("Error while running fast-export");
901 push_update_refs_status(data, remote_refs);
902 return 0;
905 static int push_refs(struct transport *transport,
906 struct ref *remote_refs, int flags)
908 struct helper_data *data = transport->data;
910 if (process_connect(transport, 1)) {
911 do_take_over(transport);
912 return transport->push_refs(transport, remote_refs, flags);
915 if (!remote_refs) {
916 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
917 "Perhaps you should specify a branch such as 'master'.\n");
918 return 0;
921 if (data->push)
922 return push_refs_with_push(transport, remote_refs, flags);
924 if (data->export)
925 return push_refs_with_export(transport, remote_refs, flags);
927 return -1;
931 static int has_attribute(const char *attrs, const char *attr) {
932 int len;
933 if (!attrs)
934 return 0;
936 len = strlen(attr);
937 for (;;) {
938 const char *space = strchrnul(attrs, ' ');
939 if (len == space - attrs && !strncmp(attrs, attr, len))
940 return 1;
941 if (!*space)
942 return 0;
943 attrs = space + 1;
947 static struct ref *get_refs_list(struct transport *transport, int for_push)
949 struct helper_data *data = transport->data;
950 struct child_process *helper;
951 struct ref *ret = NULL;
952 struct ref **tail = &ret;
953 struct ref *posn;
954 struct strbuf buf = STRBUF_INIT;
956 helper = get_helper(transport);
958 if (process_connect(transport, for_push)) {
959 do_take_over(transport);
960 return transport->get_refs_list(transport, for_push);
963 if (data->push && for_push)
964 write_str_in_full(helper->in, "list for-push\n");
965 else
966 write_str_in_full(helper->in, "list\n");
968 while (1) {
969 char *eov, *eon;
970 recvline(data, &buf);
972 if (!*buf.buf)
973 break;
975 eov = strchr(buf.buf, ' ');
976 if (!eov)
977 die("Malformed response in ref list: %s", buf.buf);
978 eon = strchr(eov + 1, ' ');
979 *eov = '\0';
980 if (eon)
981 *eon = '\0';
982 *tail = alloc_ref(eov + 1);
983 if (buf.buf[0] == '@')
984 (*tail)->symref = xstrdup(buf.buf + 1);
985 else if (buf.buf[0] != '?')
986 get_sha1_hex(buf.buf, (*tail)->old_sha1);
987 if (eon) {
988 if (has_attribute(eon + 1, "unchanged")) {
989 (*tail)->status |= REF_STATUS_UPTODATE;
990 read_ref((*tail)->name, (*tail)->old_sha1);
993 tail = &((*tail)->next);
995 if (debug)
996 fprintf(stderr, "Debug: Read ref listing.\n");
997 strbuf_release(&buf);
999 for (posn = ret; posn; posn = posn->next)
1000 resolve_remote_symref(posn, ret);
1002 return ret;
1005 int transport_helper_init(struct transport *transport, const char *name)
1007 struct helper_data *data = xcalloc(sizeof(*data), 1);
1008 data->name = name;
1010 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1011 debug = 1;
1013 transport->data = data;
1014 transport->set_option = set_helper_option;
1015 transport->get_refs_list = get_refs_list;
1016 transport->fetch = fetch;
1017 transport->push_refs = push_refs;
1018 transport->disconnect = release_helper;
1019 transport->connect = connect_helper;
1020 transport->smart_options = &(data->transport_options);
1021 return 0;
1025 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1026 * buffer less), so attempt reads and writes with up to that size.
1028 #define BUFFERSIZE 65536
1029 /* This should be enough to hold debugging message. */
1030 #define PBUFFERSIZE 8192
1032 /* Print bidirectional transfer loop debug message. */
1033 __attribute__((format (printf, 1, 2)))
1034 static void transfer_debug(const char *fmt, ...)
1036 va_list args;
1037 char msgbuf[PBUFFERSIZE];
1038 static int debug_enabled = -1;
1040 if (debug_enabled < 0)
1041 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1042 if (!debug_enabled)
1043 return;
1045 va_start(args, fmt);
1046 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1047 va_end(args);
1048 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1051 /* Stream state: More data may be coming in this direction. */
1052 #define SSTATE_TRANSFERING 0
1054 * Stream state: No more data coming in this direction, flushing rest of
1055 * data.
1057 #define SSTATE_FLUSHING 1
1058 /* Stream state: Transfer in this direction finished. */
1059 #define SSTATE_FINISHED 2
1061 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1062 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1063 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1065 /* Unidirectional transfer. */
1066 struct unidirectional_transfer {
1067 /* Source */
1068 int src;
1069 /* Destination */
1070 int dest;
1071 /* Is source socket? */
1072 int src_is_sock;
1073 /* Is destination socket? */
1074 int dest_is_sock;
1075 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1076 int state;
1077 /* Buffer. */
1078 char buf[BUFFERSIZE];
1079 /* Buffer used. */
1080 size_t bufuse;
1081 /* Name of source. */
1082 const char *src_name;
1083 /* Name of destination. */
1084 const char *dest_name;
1087 /* Closes the target (for writing) if transfer has finished. */
1088 static void udt_close_if_finished(struct unidirectional_transfer *t)
1090 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1091 t->state = SSTATE_FINISHED;
1092 if (t->dest_is_sock)
1093 shutdown(t->dest, SHUT_WR);
1094 else
1095 close(t->dest);
1096 transfer_debug("Closed %s.", t->dest_name);
1101 * Tries to read read data from source into buffer. If buffer is full,
1102 * no data is read. Returns 0 on success, -1 on error.
1104 static int udt_do_read(struct unidirectional_transfer *t)
1106 ssize_t bytes;
1108 if (t->bufuse == BUFFERSIZE)
1109 return 0; /* No space for more. */
1111 transfer_debug("%s is readable", t->src_name);
1112 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1113 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1114 errno != EINTR) {
1115 error("read(%s) failed: %s", t->src_name, strerror(errno));
1116 return -1;
1117 } else if (bytes == 0) {
1118 transfer_debug("%s EOF (with %i bytes in buffer)",
1119 t->src_name, (int)t->bufuse);
1120 t->state = SSTATE_FLUSHING;
1121 } else if (bytes > 0) {
1122 t->bufuse += bytes;
1123 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1124 (int)bytes, t->src_name, (int)t->bufuse);
1126 return 0;
1129 /* Tries to write data from buffer into destination. If buffer is empty,
1130 * no data is written. Returns 0 on success, -1 on error.
1132 static int udt_do_write(struct unidirectional_transfer *t)
1134 ssize_t bytes;
1136 if (t->bufuse == 0)
1137 return 0; /* Nothing to write. */
1139 transfer_debug("%s is writable", t->dest_name);
1140 bytes = xwrite(t->dest, t->buf, t->bufuse);
1141 if (bytes < 0 && errno != EWOULDBLOCK) {
1142 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1143 return -1;
1144 } else if (bytes > 0) {
1145 t->bufuse -= bytes;
1146 if (t->bufuse)
1147 memmove(t->buf, t->buf + bytes, t->bufuse);
1148 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1149 (int)bytes, t->dest_name, (int)t->bufuse);
1151 return 0;
1155 /* State of bidirectional transfer loop. */
1156 struct bidirectional_transfer_state {
1157 /* Direction from program to git. */
1158 struct unidirectional_transfer ptg;
1159 /* Direction from git to program. */
1160 struct unidirectional_transfer gtp;
1163 static void *udt_copy_task_routine(void *udt)
1165 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1166 while (t->state != SSTATE_FINISHED) {
1167 if (STATE_NEEDS_READING(t->state))
1168 if (udt_do_read(t))
1169 return NULL;
1170 if (STATE_NEEDS_WRITING(t->state))
1171 if (udt_do_write(t))
1172 return NULL;
1173 if (STATE_NEEDS_CLOSING(t->state))
1174 udt_close_if_finished(t);
1176 return udt; /* Just some non-NULL value. */
1179 #ifndef NO_PTHREADS
1182 * Join thread, with appropriate errors on failure. Name is name for the
1183 * thread (for error messages). Returns 0 on success, 1 on failure.
1185 static int tloop_join(pthread_t thread, const char *name)
1187 int err;
1188 void *tret;
1189 err = pthread_join(thread, &tret);
1190 if (!tret) {
1191 error("%s thread failed", name);
1192 return 1;
1194 if (err) {
1195 error("%s thread failed to join: %s", name, strerror(err));
1196 return 1;
1198 return 0;
1202 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1203 * -1 on failure.
1205 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1207 pthread_t gtp_thread;
1208 pthread_t ptg_thread;
1209 int err;
1210 int ret = 0;
1211 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1212 &s->gtp);
1213 if (err)
1214 die("Can't start thread for copying data: %s", strerror(err));
1215 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1216 &s->ptg);
1217 if (err)
1218 die("Can't start thread for copying data: %s", strerror(err));
1220 ret |= tloop_join(gtp_thread, "Git to program copy");
1221 ret |= tloop_join(ptg_thread, "Program to git copy");
1222 return ret;
1224 #else
1226 /* Close the source and target (for writing) for transfer. */
1227 static void udt_kill_transfer(struct unidirectional_transfer *t)
1229 t->state = SSTATE_FINISHED;
1231 * Socket read end left open isn't a disaster if nobody
1232 * attempts to read from it (mingw compat headers do not
1233 * have SHUT_RD)...
1235 * We can't fully close the socket since otherwise gtp
1236 * task would first close the socket it sends data to
1237 * while closing the ptg file descriptors.
1239 if (!t->src_is_sock)
1240 close(t->src);
1241 if (t->dest_is_sock)
1242 shutdown(t->dest, SHUT_WR);
1243 else
1244 close(t->dest);
1248 * Join process, with appropriate errors on failure. Name is name for the
1249 * process (for error messages). Returns 0 on success, 1 on failure.
1251 static int tloop_join(pid_t pid, const char *name)
1253 int tret;
1254 if (waitpid(pid, &tret, 0) < 0) {
1255 error("%s process failed to wait: %s", name, strerror(errno));
1256 return 1;
1258 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1259 error("%s process failed", name);
1260 return 1;
1262 return 0;
1266 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1267 * -1 on failure.
1269 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1271 pid_t pid1, pid2;
1272 int ret = 0;
1274 /* Fork thread #1: git to program. */
1275 pid1 = fork();
1276 if (pid1 < 0)
1277 die_errno("Can't start thread for copying data");
1278 else if (pid1 == 0) {
1279 udt_kill_transfer(&s->ptg);
1280 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1283 /* Fork thread #2: program to git. */
1284 pid2 = fork();
1285 if (pid2 < 0)
1286 die_errno("Can't start thread for copying data");
1287 else if (pid2 == 0) {
1288 udt_kill_transfer(&s->gtp);
1289 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1293 * Close both streams in parent as to not interfere with
1294 * end of file detection and wait for both tasks to finish.
1296 udt_kill_transfer(&s->gtp);
1297 udt_kill_transfer(&s->ptg);
1298 ret |= tloop_join(pid1, "Git to program copy");
1299 ret |= tloop_join(pid2, "Program to git copy");
1300 return ret;
1302 #endif
1305 * Copies data from stdin to output and from input to stdout simultaneously.
1306 * Additionally filtering through given filter. If filter is NULL, uses
1307 * identity filter.
1309 int bidirectional_transfer_loop(int input, int output)
1311 struct bidirectional_transfer_state state;
1313 /* Fill the state fields. */
1314 state.ptg.src = input;
1315 state.ptg.dest = 1;
1316 state.ptg.src_is_sock = (input == output);
1317 state.ptg.dest_is_sock = 0;
1318 state.ptg.state = SSTATE_TRANSFERING;
1319 state.ptg.bufuse = 0;
1320 state.ptg.src_name = "remote input";
1321 state.ptg.dest_name = "stdout";
1323 state.gtp.src = 0;
1324 state.gtp.dest = output;
1325 state.gtp.src_is_sock = 0;
1326 state.gtp.dest_is_sock = (input == output);
1327 state.gtp.state = SSTATE_TRANSFERING;
1328 state.gtp.bufuse = 0;
1329 state.gtp.src_name = "stdin";
1330 state.gtp.dest_name = "remote output";
1332 return tloop_spawnwait_tasks(&state);