Merge branch 'jk/fetch-pack' into maint
[git.git] / transport-helper.c
blob7dc4a443aee0c6220dc0581d4bcfdd1d65da1d8a
1 #include "cache.h"
2 #include "transport.h"
3 #include "quote.h"
4 #include "run-command.h"
5 #include "commit.h"
6 #include "diff.h"
7 #include "revision.h"
8 #include "remote.h"
9 #include "string-list.h"
10 #include "thread-utils.h"
11 #include "sigchain.h"
12 #include "argv-array.h"
13 #include "refs.h"
15 static int debug;
17 struct helper_data {
18 const char *name;
19 struct child_process *helper;
20 FILE *out;
21 unsigned fetch : 1,
22 import : 1,
23 bidi_import : 1,
24 export : 1,
25 option : 1,
26 push : 1,
27 connect : 1,
28 signed_tags : 1,
29 check_connectivity : 1,
30 no_disconnect_req : 1,
31 no_private_update : 1;
32 char *export_marks;
33 char *import_marks;
34 /* These go from remote name (as in "list") to private name */
35 struct refspec *refspecs;
36 int refspec_nr;
37 /* Transport options for fetch-pack/send-pack (should one of
38 * those be invoked).
40 struct git_transport_options transport_options;
43 static void sendline(struct helper_data *helper, struct strbuf *buffer)
45 if (debug)
46 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
47 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
48 != buffer->len)
49 die_errno("Full write to remote helper failed");
52 static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
54 strbuf_reset(buffer);
55 if (debug)
56 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
57 if (strbuf_getline(buffer, helper, '\n') == EOF) {
58 if (debug)
59 fprintf(stderr, "Debug: Remote helper quit.\n");
60 return 1;
63 if (debug)
64 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
65 return 0;
68 static int recvline(struct helper_data *helper, struct strbuf *buffer)
70 return recvline_fh(helper->out, buffer, helper->name);
73 static void write_constant(int fd, const char *str)
75 if (debug)
76 fprintf(stderr, "Debug: Remote helper: -> %s", str);
77 if (write_in_full(fd, str, strlen(str)) != strlen(str))
78 die_errno("Full write to remote helper failed");
81 static const char *remove_ext_force(const char *url)
83 if (url) {
84 const char *colon = strchr(url, ':');
85 if (colon && colon[1] == ':')
86 return colon + 2;
88 return url;
91 static void do_take_over(struct transport *transport)
93 struct helper_data *data;
94 data = (struct helper_data *)transport->data;
95 transport_take_over(transport, data->helper);
96 fclose(data->out);
97 free(data);
100 static struct child_process *get_helper(struct transport *transport)
102 struct helper_data *data = transport->data;
103 struct strbuf buf = STRBUF_INIT;
104 struct child_process *helper;
105 const char **refspecs = NULL;
106 int refspec_nr = 0;
107 int refspec_alloc = 0;
108 int duped;
109 int code;
111 if (data->helper)
112 return data->helper;
114 helper = xmalloc(sizeof(*helper));
115 child_process_init(helper);
116 helper->in = -1;
117 helper->out = -1;
118 helper->err = 0;
119 argv_array_pushf(&helper->args, "git-remote-%s", data->name);
120 argv_array_push(&helper->args, transport->remote->name);
121 argv_array_push(&helper->args, remove_ext_force(transport->url));
122 helper->git_cmd = 0;
123 helper->silent_exec_failure = 1;
125 argv_array_pushf(&helper->env_array, "%s=%s", GIT_DIR_ENVIRONMENT,
126 get_git_dir());
128 code = start_command(helper);
129 if (code < 0 && errno == ENOENT)
130 die("Unable to find remote helper for '%s'", data->name);
131 else if (code != 0)
132 exit(code);
134 data->helper = helper;
135 data->no_disconnect_req = 0;
138 * Open the output as FILE* so strbuf_getline() can be used.
139 * Do this with duped fd because fclose() will close the fd,
140 * and stuff like taking over will require the fd to remain.
142 duped = dup(helper->out);
143 if (duped < 0)
144 die_errno("Can't dup helper output fd");
145 data->out = xfdopen(duped, "r");
147 write_constant(helper->in, "capabilities\n");
149 while (1) {
150 const char *capname, *arg;
151 int mandatory = 0;
152 if (recvline(data, &buf))
153 exit(128);
155 if (!*buf.buf)
156 break;
158 if (*buf.buf == '*') {
159 capname = buf.buf + 1;
160 mandatory = 1;
161 } else
162 capname = buf.buf;
164 if (debug)
165 fprintf(stderr, "Debug: Got cap %s\n", capname);
166 if (!strcmp(capname, "fetch"))
167 data->fetch = 1;
168 else if (!strcmp(capname, "option"))
169 data->option = 1;
170 else if (!strcmp(capname, "push"))
171 data->push = 1;
172 else if (!strcmp(capname, "import"))
173 data->import = 1;
174 else if (!strcmp(capname, "bidi-import"))
175 data->bidi_import = 1;
176 else if (!strcmp(capname, "export"))
177 data->export = 1;
178 else if (!strcmp(capname, "check-connectivity"))
179 data->check_connectivity = 1;
180 else if (!data->refspecs && skip_prefix(capname, "refspec ", &arg)) {
181 ALLOC_GROW(refspecs,
182 refspec_nr + 1,
183 refspec_alloc);
184 refspecs[refspec_nr++] = xstrdup(arg);
185 } else if (!strcmp(capname, "connect")) {
186 data->connect = 1;
187 } else if (!strcmp(capname, "signed-tags")) {
188 data->signed_tags = 1;
189 } else if (skip_prefix(capname, "export-marks ", &arg)) {
190 data->export_marks = xstrdup(arg);
191 } else if (skip_prefix(capname, "import-marks ", &arg)) {
192 data->import_marks = xstrdup(arg);
193 } else if (starts_with(capname, "no-private-update")) {
194 data->no_private_update = 1;
195 } else if (mandatory) {
196 die("Unknown mandatory capability %s. This remote "
197 "helper probably needs newer version of Git.",
198 capname);
201 if (refspecs) {
202 int i;
203 data->refspec_nr = refspec_nr;
204 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
205 for (i = 0; i < refspec_nr; i++)
206 free((char *)refspecs[i]);
207 free(refspecs);
208 } else if (data->import || data->bidi_import || data->export) {
209 warning("This remote helper should implement refspec capability.");
211 strbuf_release(&buf);
212 if (debug)
213 fprintf(stderr, "Debug: Capabilities complete.\n");
214 return data->helper;
217 static int disconnect_helper(struct transport *transport)
219 struct helper_data *data = transport->data;
220 int res = 0;
222 if (data->helper) {
223 if (debug)
224 fprintf(stderr, "Debug: Disconnecting.\n");
225 if (!data->no_disconnect_req) {
227 * Ignore write errors; there's nothing we can do,
228 * since we're about to close the pipe anyway. And the
229 * most likely error is EPIPE due to the helper dying
230 * to report an error itself.
232 sigchain_push(SIGPIPE, SIG_IGN);
233 xwrite(data->helper->in, "\n", 1);
234 sigchain_pop(SIGPIPE);
236 close(data->helper->in);
237 close(data->helper->out);
238 fclose(data->out);
239 res = finish_command(data->helper);
240 free(data->helper);
241 data->helper = NULL;
243 return res;
246 static const char *unsupported_options[] = {
247 TRANS_OPT_UPLOADPACK,
248 TRANS_OPT_RECEIVEPACK,
249 TRANS_OPT_THIN,
250 TRANS_OPT_KEEP
253 static const char *boolean_options[] = {
254 TRANS_OPT_THIN,
255 TRANS_OPT_KEEP,
256 TRANS_OPT_FOLLOWTAGS,
257 TRANS_OPT_PUSH_CERT
260 static int set_helper_option(struct transport *transport,
261 const char *name, const char *value)
263 struct helper_data *data = transport->data;
264 struct strbuf buf = STRBUF_INIT;
265 int i, ret, is_bool = 0;
267 get_helper(transport);
269 if (!data->option)
270 return 1;
272 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
273 if (!strcmp(name, unsupported_options[i]))
274 return 1;
277 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
278 if (!strcmp(name, boolean_options[i])) {
279 is_bool = 1;
280 break;
284 strbuf_addf(&buf, "option %s ", name);
285 if (is_bool)
286 strbuf_addstr(&buf, value ? "true" : "false");
287 else
288 quote_c_style(value, &buf, NULL, 0);
289 strbuf_addch(&buf, '\n');
291 sendline(data, &buf);
292 if (recvline(data, &buf))
293 exit(128);
295 if (!strcmp(buf.buf, "ok"))
296 ret = 0;
297 else if (starts_with(buf.buf, "error")) {
298 ret = -1;
299 } else if (!strcmp(buf.buf, "unsupported"))
300 ret = 1;
301 else {
302 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
303 ret = 1;
305 strbuf_release(&buf);
306 return ret;
309 static void standard_options(struct transport *t)
311 char buf[16];
312 int n;
313 int v = t->verbose;
315 set_helper_option(t, "progress", t->progress ? "true" : "false");
317 n = snprintf(buf, sizeof(buf), "%d", v + 1);
318 if (n >= sizeof(buf))
319 die("impossibly large verbosity value");
320 set_helper_option(t, "verbosity", buf);
323 static int release_helper(struct transport *transport)
325 int res = 0;
326 struct helper_data *data = transport->data;
327 free_refspec(data->refspec_nr, data->refspecs);
328 data->refspecs = NULL;
329 res = disconnect_helper(transport);
330 free(transport->data);
331 return res;
334 static int fetch_with_fetch(struct transport *transport,
335 int nr_heads, struct ref **to_fetch)
337 struct helper_data *data = transport->data;
338 int i;
339 struct strbuf buf = STRBUF_INIT;
341 standard_options(transport);
342 if (data->check_connectivity &&
343 data->transport_options.check_self_contained_and_connected)
344 set_helper_option(transport, "check-connectivity", "true");
346 if (transport->cloning)
347 set_helper_option(transport, "cloning", "true");
349 if (data->transport_options.update_shallow)
350 set_helper_option(transport, "update-shallow", "true");
352 for (i = 0; i < nr_heads; i++) {
353 const struct ref *posn = to_fetch[i];
354 if (posn->status & REF_STATUS_UPTODATE)
355 continue;
357 strbuf_addf(&buf, "fetch %s %s\n",
358 sha1_to_hex(posn->old_sha1),
359 posn->symref ? posn->symref : posn->name);
362 strbuf_addch(&buf, '\n');
363 sendline(data, &buf);
365 while (1) {
366 if (recvline(data, &buf))
367 exit(128);
369 if (starts_with(buf.buf, "lock ")) {
370 const char *name = buf.buf + 5;
371 if (transport->pack_lockfile)
372 warning("%s also locked %s", data->name, name);
373 else
374 transport->pack_lockfile = xstrdup(name);
376 else if (data->check_connectivity &&
377 data->transport_options.check_self_contained_and_connected &&
378 !strcmp(buf.buf, "connectivity-ok"))
379 data->transport_options.self_contained_and_connected = 1;
380 else if (!buf.len)
381 break;
382 else
383 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
385 strbuf_release(&buf);
386 return 0;
389 static int get_importer(struct transport *transport, struct child_process *fastimport)
391 struct child_process *helper = get_helper(transport);
392 struct helper_data *data = transport->data;
393 int cat_blob_fd, code;
394 child_process_init(fastimport);
395 fastimport->in = helper->out;
396 argv_array_push(&fastimport->args, "fast-import");
397 argv_array_push(&fastimport->args, debug ? "--stats" : "--quiet");
399 if (data->bidi_import) {
400 cat_blob_fd = xdup(helper->in);
401 argv_array_pushf(&fastimport->args, "--cat-blob-fd=%d", cat_blob_fd);
403 fastimport->git_cmd = 1;
405 code = start_command(fastimport);
406 return code;
409 static int get_exporter(struct transport *transport,
410 struct child_process *fastexport,
411 struct string_list *revlist_args)
413 struct helper_data *data = transport->data;
414 struct child_process *helper = get_helper(transport);
415 int i;
417 child_process_init(fastexport);
419 /* we need to duplicate helper->in because we want to use it after
420 * fastexport is done with it. */
421 fastexport->out = dup(helper->in);
422 argv_array_push(&fastexport->args, "fast-export");
423 argv_array_push(&fastexport->args, "--use-done-feature");
424 argv_array_push(&fastexport->args, data->signed_tags ?
425 "--signed-tags=verbatim" : "--signed-tags=warn-strip");
426 if (data->export_marks)
427 argv_array_pushf(&fastexport->args, "--export-marks=%s.tmp", data->export_marks);
428 if (data->import_marks)
429 argv_array_pushf(&fastexport->args, "--import-marks=%s", data->import_marks);
431 for (i = 0; i < revlist_args->nr; i++)
432 argv_array_push(&fastexport->args, revlist_args->items[i].string);
434 fastexport->git_cmd = 1;
435 return start_command(fastexport);
438 static int fetch_with_import(struct transport *transport,
439 int nr_heads, struct ref **to_fetch)
441 struct child_process fastimport;
442 struct helper_data *data = transport->data;
443 int i;
444 struct ref *posn;
445 struct strbuf buf = STRBUF_INIT;
447 get_helper(transport);
449 if (get_importer(transport, &fastimport))
450 die("Couldn't run fast-import");
452 for (i = 0; i < nr_heads; i++) {
453 posn = to_fetch[i];
454 if (posn->status & REF_STATUS_UPTODATE)
455 continue;
457 strbuf_addf(&buf, "import %s\n",
458 posn->symref ? posn->symref : posn->name);
459 sendline(data, &buf);
460 strbuf_reset(&buf);
463 write_constant(data->helper->in, "\n");
465 * remote-helpers that advertise the bidi-import capability are required to
466 * buffer the complete batch of import commands until this newline before
467 * sending data to fast-import.
468 * These helpers read back data from fast-import on their stdin, which could
469 * be mixed with import commands, otherwise.
472 if (finish_command(&fastimport))
473 die("Error while running fast-import");
476 * The fast-import stream of a remote helper that advertises
477 * the "refspec" capability writes to the refs named after the
478 * right hand side of the first refspec matching each ref we
479 * were fetching.
481 * (If no "refspec" capability was specified, for historical
482 * reasons we default to the equivalent of *:*.)
484 * Store the result in to_fetch[i].old_sha1. Callers such
485 * as "git fetch" can use the value to write feedback to the
486 * terminal, populate FETCH_HEAD, and determine what new value
487 * should be written to peer_ref if the update is a
488 * fast-forward or this is a forced update.
490 for (i = 0; i < nr_heads; i++) {
491 char *private, *name;
492 posn = to_fetch[i];
493 if (posn->status & REF_STATUS_UPTODATE)
494 continue;
495 name = posn->symref ? posn->symref : posn->name;
496 if (data->refspecs)
497 private = apply_refspecs(data->refspecs, data->refspec_nr, name);
498 else
499 private = xstrdup(name);
500 if (private) {
501 read_ref(private, posn->old_sha1);
502 free(private);
505 strbuf_release(&buf);
506 return 0;
509 static int process_connect_service(struct transport *transport,
510 const char *name, const char *exec)
512 struct helper_data *data = transport->data;
513 struct strbuf cmdbuf = STRBUF_INIT;
514 struct child_process *helper;
515 int r, duped, ret = 0;
516 FILE *input;
518 helper = get_helper(transport);
521 * Yes, dup the pipe another time, as we need unbuffered version
522 * of input pipe as FILE*. fclose() closes the underlying fd and
523 * stream buffering only can be changed before first I/O operation
524 * on it.
526 duped = dup(helper->out);
527 if (duped < 0)
528 die_errno("Can't dup helper output fd");
529 input = xfdopen(duped, "r");
530 setvbuf(input, NULL, _IONBF, 0);
533 * Handle --upload-pack and friends. This is fire and forget...
534 * just warn if it fails.
536 if (strcmp(name, exec)) {
537 r = set_helper_option(transport, "servpath", exec);
538 if (r > 0)
539 warning("Setting remote service path not supported by protocol.");
540 else if (r < 0)
541 warning("Invalid remote service path.");
544 if (data->connect)
545 strbuf_addf(&cmdbuf, "connect %s\n", name);
546 else
547 goto exit;
549 sendline(data, &cmdbuf);
550 if (recvline_fh(input, &cmdbuf, name))
551 exit(128);
553 if (!strcmp(cmdbuf.buf, "")) {
554 data->no_disconnect_req = 1;
555 if (debug)
556 fprintf(stderr, "Debug: Smart transport connection "
557 "ready.\n");
558 ret = 1;
559 } else if (!strcmp(cmdbuf.buf, "fallback")) {
560 if (debug)
561 fprintf(stderr, "Debug: Falling back to dumb "
562 "transport.\n");
563 } else
564 die("Unknown response to connect: %s",
565 cmdbuf.buf);
567 exit:
568 fclose(input);
569 return ret;
572 static int process_connect(struct transport *transport,
573 int for_push)
575 struct helper_data *data = transport->data;
576 const char *name;
577 const char *exec;
579 name = for_push ? "git-receive-pack" : "git-upload-pack";
580 if (for_push)
581 exec = data->transport_options.receivepack;
582 else
583 exec = data->transport_options.uploadpack;
585 return process_connect_service(transport, name, exec);
588 static int connect_helper(struct transport *transport, const char *name,
589 const char *exec, int fd[2])
591 struct helper_data *data = transport->data;
593 /* Get_helper so connect is inited. */
594 get_helper(transport);
595 if (!data->connect)
596 die("Operation not supported by protocol.");
598 if (!process_connect_service(transport, name, exec))
599 die("Can't connect to subservice %s.", name);
601 fd[0] = data->helper->out;
602 fd[1] = data->helper->in;
603 return 0;
606 static int fetch(struct transport *transport,
607 int nr_heads, struct ref **to_fetch)
609 struct helper_data *data = transport->data;
610 int i, count;
612 if (process_connect(transport, 0)) {
613 do_take_over(transport);
614 return transport->fetch(transport, nr_heads, to_fetch);
617 count = 0;
618 for (i = 0; i < nr_heads; i++)
619 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
620 count++;
622 if (!count)
623 return 0;
625 if (data->fetch)
626 return fetch_with_fetch(transport, nr_heads, to_fetch);
628 if (data->import)
629 return fetch_with_import(transport, nr_heads, to_fetch);
631 return -1;
634 static int push_update_ref_status(struct strbuf *buf,
635 struct ref **ref,
636 struct ref *remote_refs)
638 char *refname, *msg;
639 int status, forced = 0;
641 if (starts_with(buf->buf, "ok ")) {
642 status = REF_STATUS_OK;
643 refname = buf->buf + 3;
644 } else if (starts_with(buf->buf, "error ")) {
645 status = REF_STATUS_REMOTE_REJECT;
646 refname = buf->buf + 6;
647 } else
648 die("expected ok/error, helper said '%s'", buf->buf);
650 msg = strchr(refname, ' ');
651 if (msg) {
652 struct strbuf msg_buf = STRBUF_INIT;
653 const char *end;
655 *msg++ = '\0';
656 if (!unquote_c_style(&msg_buf, msg, &end))
657 msg = strbuf_detach(&msg_buf, NULL);
658 else
659 msg = xstrdup(msg);
660 strbuf_release(&msg_buf);
662 if (!strcmp(msg, "no match")) {
663 status = REF_STATUS_NONE;
664 free(msg);
665 msg = NULL;
667 else if (!strcmp(msg, "up to date")) {
668 status = REF_STATUS_UPTODATE;
669 free(msg);
670 msg = NULL;
672 else if (!strcmp(msg, "non-fast forward")) {
673 status = REF_STATUS_REJECT_NONFASTFORWARD;
674 free(msg);
675 msg = NULL;
677 else if (!strcmp(msg, "already exists")) {
678 status = REF_STATUS_REJECT_ALREADY_EXISTS;
679 free(msg);
680 msg = NULL;
682 else if (!strcmp(msg, "fetch first")) {
683 status = REF_STATUS_REJECT_FETCH_FIRST;
684 free(msg);
685 msg = NULL;
687 else if (!strcmp(msg, "needs force")) {
688 status = REF_STATUS_REJECT_NEEDS_FORCE;
689 free(msg);
690 msg = NULL;
692 else if (!strcmp(msg, "stale info")) {
693 status = REF_STATUS_REJECT_STALE;
694 free(msg);
695 msg = NULL;
697 else if (!strcmp(msg, "forced update")) {
698 forced = 1;
699 free(msg);
700 msg = NULL;
704 if (*ref)
705 *ref = find_ref_by_name(*ref, refname);
706 if (!*ref)
707 *ref = find_ref_by_name(remote_refs, refname);
708 if (!*ref) {
709 warning("helper reported unexpected status of %s", refname);
710 return 1;
713 if ((*ref)->status != REF_STATUS_NONE) {
715 * Earlier, the ref was marked not to be pushed, so ignore the ref
716 * status reported by the remote helper if the latter is 'no match'.
718 if (status == REF_STATUS_NONE)
719 return 1;
722 (*ref)->status = status;
723 (*ref)->forced_update |= forced;
724 (*ref)->remote_status = msg;
725 return !(status == REF_STATUS_OK);
728 static int push_update_refs_status(struct helper_data *data,
729 struct ref *remote_refs,
730 int flags)
732 struct strbuf buf = STRBUF_INIT;
733 struct ref *ref = remote_refs;
734 int ret = 0;
736 for (;;) {
737 char *private;
739 if (recvline(data, &buf)) {
740 ret = 1;
741 break;
744 if (!buf.len)
745 break;
747 if (push_update_ref_status(&buf, &ref, remote_refs))
748 continue;
750 if (flags & TRANSPORT_PUSH_DRY_RUN || !data->refspecs || data->no_private_update)
751 continue;
753 /* propagate back the update to the remote namespace */
754 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
755 if (!private)
756 continue;
757 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
758 free(private);
760 strbuf_release(&buf);
761 return ret;
764 static int push_refs_with_push(struct transport *transport,
765 struct ref *remote_refs, int flags)
767 int force_all = flags & TRANSPORT_PUSH_FORCE;
768 int mirror = flags & TRANSPORT_PUSH_MIRROR;
769 struct helper_data *data = transport->data;
770 struct strbuf buf = STRBUF_INIT;
771 struct ref *ref;
772 struct string_list cas_options = STRING_LIST_INIT_DUP;
773 struct string_list_item *cas_option;
775 get_helper(transport);
776 if (!data->push)
777 return 1;
779 for (ref = remote_refs; ref; ref = ref->next) {
780 if (!ref->peer_ref && !mirror)
781 continue;
783 /* Check for statuses set by set_ref_status_for_push() */
784 switch (ref->status) {
785 case REF_STATUS_REJECT_NONFASTFORWARD:
786 case REF_STATUS_REJECT_STALE:
787 case REF_STATUS_REJECT_ALREADY_EXISTS:
788 case REF_STATUS_UPTODATE:
789 continue;
790 default:
791 ; /* do nothing */
794 if (force_all)
795 ref->force = 1;
797 strbuf_addstr(&buf, "push ");
798 if (!ref->deletion) {
799 if (ref->force)
800 strbuf_addch(&buf, '+');
801 if (ref->peer_ref)
802 strbuf_addstr(&buf, ref->peer_ref->name);
803 else
804 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
806 strbuf_addch(&buf, ':');
807 strbuf_addstr(&buf, ref->name);
808 strbuf_addch(&buf, '\n');
811 * The "--force-with-lease" options without explicit
812 * values to expect have already been expanded into
813 * the ref->old_sha1_expect[] field; we can ignore
814 * transport->smart_options->cas altogether and instead
815 * can enumerate them from the refs.
817 if (ref->expect_old_sha1) {
818 struct strbuf cas = STRBUF_INIT;
819 strbuf_addf(&cas, "%s:%s",
820 ref->name, sha1_to_hex(ref->old_sha1_expect));
821 string_list_append(&cas_options, strbuf_detach(&cas, NULL));
824 if (buf.len == 0) {
825 string_list_clear(&cas_options, 0);
826 return 0;
829 standard_options(transport);
830 for_each_string_list_item(cas_option, &cas_options)
831 set_helper_option(transport, "cas", cas_option->string);
833 if (flags & TRANSPORT_PUSH_DRY_RUN) {
834 if (set_helper_option(transport, "dry-run", "true") != 0)
835 die("helper %s does not support dry-run", data->name);
836 } else if (flags & TRANSPORT_PUSH_CERT) {
837 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "true") != 0)
838 die("helper %s does not support --signed", data->name);
841 strbuf_addch(&buf, '\n');
842 sendline(data, &buf);
843 strbuf_release(&buf);
845 return push_update_refs_status(data, remote_refs, flags);
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_DUP;
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);
863 } else if (flags & TRANSPORT_PUSH_CERT) {
864 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "true") != 0)
865 die("helper %s does not support --signed", data->name);
868 if (flags & TRANSPORT_PUSH_FORCE) {
869 if (set_helper_option(transport, "force", "true") != 0)
870 warning("helper %s does not support 'force'", data->name);
873 helper = get_helper(transport);
875 write_constant(helper->in, "export\n");
877 for (ref = remote_refs; ref; ref = ref->next) {
878 char *private;
879 unsigned char sha1[20];
881 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
882 if (private && !get_sha1(private, sha1)) {
883 strbuf_addf(&buf, "^%s", private);
884 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
885 hashcpy(ref->old_sha1, sha1);
887 free(private);
889 if (ref->peer_ref) {
890 if (strcmp(ref->name, ref->peer_ref->name)) {
891 if (!ref->deletion) {
892 const char *name;
893 int flag;
895 /* Follow symbolic refs (mainly for HEAD). */
896 name = resolve_ref_unsafe(
897 ref->peer_ref->name,
898 RESOLVE_REF_READING,
899 sha1, &flag);
900 if (!name || !(flag & REF_ISSYMREF))
901 name = ref->peer_ref->name;
903 strbuf_addf(&buf, "%s:%s", name, ref->name);
904 } else
905 strbuf_addf(&buf, ":%s", ref->name);
907 string_list_append(&revlist_args, "--refspec");
908 string_list_append(&revlist_args, buf.buf);
909 strbuf_release(&buf);
911 if (!ref->deletion)
912 string_list_append(&revlist_args, ref->peer_ref->name);
916 if (get_exporter(transport, &exporter, &revlist_args))
917 die("Couldn't run fast-export");
919 string_list_clear(&revlist_args, 1);
921 if (finish_command(&exporter))
922 die("Error while running fast-export");
923 if (push_update_refs_status(data, remote_refs, flags))
924 return 1;
926 if (data->export_marks) {
927 strbuf_addf(&buf, "%s.tmp", data->export_marks);
928 rename(buf.buf, data->export_marks);
929 strbuf_release(&buf);
932 return 0;
935 static int push_refs(struct transport *transport,
936 struct ref *remote_refs, int flags)
938 struct helper_data *data = transport->data;
940 if (process_connect(transport, 1)) {
941 do_take_over(transport);
942 return transport->push_refs(transport, remote_refs, flags);
945 if (!remote_refs) {
946 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
947 "Perhaps you should specify a branch such as 'master'.\n");
948 return 0;
951 if (data->push)
952 return push_refs_with_push(transport, remote_refs, flags);
954 if (data->export)
955 return push_refs_with_export(transport, remote_refs, flags);
957 return -1;
961 static int has_attribute(const char *attrs, const char *attr) {
962 int len;
963 if (!attrs)
964 return 0;
966 len = strlen(attr);
967 for (;;) {
968 const char *space = strchrnul(attrs, ' ');
969 if (len == space - attrs && !strncmp(attrs, attr, len))
970 return 1;
971 if (!*space)
972 return 0;
973 attrs = space + 1;
977 static struct ref *get_refs_list(struct transport *transport, int for_push)
979 struct helper_data *data = transport->data;
980 struct child_process *helper;
981 struct ref *ret = NULL;
982 struct ref **tail = &ret;
983 struct ref *posn;
984 struct strbuf buf = STRBUF_INIT;
986 helper = get_helper(transport);
988 if (process_connect(transport, for_push)) {
989 do_take_over(transport);
990 return transport->get_refs_list(transport, for_push);
993 if (data->push && for_push)
994 write_str_in_full(helper->in, "list for-push\n");
995 else
996 write_str_in_full(helper->in, "list\n");
998 while (1) {
999 char *eov, *eon;
1000 if (recvline(data, &buf))
1001 exit(128);
1003 if (!*buf.buf)
1004 break;
1006 eov = strchr(buf.buf, ' ');
1007 if (!eov)
1008 die("Malformed response in ref list: %s", buf.buf);
1009 eon = strchr(eov + 1, ' ');
1010 *eov = '\0';
1011 if (eon)
1012 *eon = '\0';
1013 *tail = alloc_ref(eov + 1);
1014 if (buf.buf[0] == '@')
1015 (*tail)->symref = xstrdup(buf.buf + 1);
1016 else if (buf.buf[0] != '?')
1017 get_sha1_hex(buf.buf, (*tail)->old_sha1);
1018 if (eon) {
1019 if (has_attribute(eon + 1, "unchanged")) {
1020 (*tail)->status |= REF_STATUS_UPTODATE;
1021 read_ref((*tail)->name, (*tail)->old_sha1);
1024 tail = &((*tail)->next);
1026 if (debug)
1027 fprintf(stderr, "Debug: Read ref listing.\n");
1028 strbuf_release(&buf);
1030 for (posn = ret; posn; posn = posn->next)
1031 resolve_remote_symref(posn, ret);
1033 return ret;
1036 int transport_helper_init(struct transport *transport, const char *name)
1038 struct helper_data *data = xcalloc(1, sizeof(*data));
1039 data->name = name;
1041 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1042 debug = 1;
1044 transport->data = data;
1045 transport->set_option = set_helper_option;
1046 transport->get_refs_list = get_refs_list;
1047 transport->fetch = fetch;
1048 transport->push_refs = push_refs;
1049 transport->disconnect = release_helper;
1050 transport->connect = connect_helper;
1051 transport->smart_options = &(data->transport_options);
1052 return 0;
1056 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1057 * buffer less), so attempt reads and writes with up to that size.
1059 #define BUFFERSIZE 65536
1060 /* This should be enough to hold debugging message. */
1061 #define PBUFFERSIZE 8192
1063 /* Print bidirectional transfer loop debug message. */
1064 __attribute__((format (printf, 1, 2)))
1065 static void transfer_debug(const char *fmt, ...)
1067 va_list args;
1068 char msgbuf[PBUFFERSIZE];
1069 static int debug_enabled = -1;
1071 if (debug_enabled < 0)
1072 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1073 if (!debug_enabled)
1074 return;
1076 va_start(args, fmt);
1077 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1078 va_end(args);
1079 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1082 /* Stream state: More data may be coming in this direction. */
1083 #define SSTATE_TRANSFERING 0
1085 * Stream state: No more data coming in this direction, flushing rest of
1086 * data.
1088 #define SSTATE_FLUSHING 1
1089 /* Stream state: Transfer in this direction finished. */
1090 #define SSTATE_FINISHED 2
1092 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1093 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1094 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1096 /* Unidirectional transfer. */
1097 struct unidirectional_transfer {
1098 /* Source */
1099 int src;
1100 /* Destination */
1101 int dest;
1102 /* Is source socket? */
1103 int src_is_sock;
1104 /* Is destination socket? */
1105 int dest_is_sock;
1106 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1107 int state;
1108 /* Buffer. */
1109 char buf[BUFFERSIZE];
1110 /* Buffer used. */
1111 size_t bufuse;
1112 /* Name of source. */
1113 const char *src_name;
1114 /* Name of destination. */
1115 const char *dest_name;
1118 /* Closes the target (for writing) if transfer has finished. */
1119 static void udt_close_if_finished(struct unidirectional_transfer *t)
1121 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1122 t->state = SSTATE_FINISHED;
1123 if (t->dest_is_sock)
1124 shutdown(t->dest, SHUT_WR);
1125 else
1126 close(t->dest);
1127 transfer_debug("Closed %s.", t->dest_name);
1132 * Tries to read read data from source into buffer. If buffer is full,
1133 * no data is read. Returns 0 on success, -1 on error.
1135 static int udt_do_read(struct unidirectional_transfer *t)
1137 ssize_t bytes;
1139 if (t->bufuse == BUFFERSIZE)
1140 return 0; /* No space for more. */
1142 transfer_debug("%s is readable", t->src_name);
1143 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1144 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1145 errno != EINTR) {
1146 error("read(%s) failed: %s", t->src_name, strerror(errno));
1147 return -1;
1148 } else if (bytes == 0) {
1149 transfer_debug("%s EOF (with %i bytes in buffer)",
1150 t->src_name, (int)t->bufuse);
1151 t->state = SSTATE_FLUSHING;
1152 } else if (bytes > 0) {
1153 t->bufuse += bytes;
1154 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1155 (int)bytes, t->src_name, (int)t->bufuse);
1157 return 0;
1160 /* Tries to write data from buffer into destination. If buffer is empty,
1161 * no data is written. Returns 0 on success, -1 on error.
1163 static int udt_do_write(struct unidirectional_transfer *t)
1165 ssize_t bytes;
1167 if (t->bufuse == 0)
1168 return 0; /* Nothing to write. */
1170 transfer_debug("%s is writable", t->dest_name);
1171 bytes = xwrite(t->dest, t->buf, t->bufuse);
1172 if (bytes < 0 && errno != EWOULDBLOCK) {
1173 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1174 return -1;
1175 } else if (bytes > 0) {
1176 t->bufuse -= bytes;
1177 if (t->bufuse)
1178 memmove(t->buf, t->buf + bytes, t->bufuse);
1179 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1180 (int)bytes, t->dest_name, (int)t->bufuse);
1182 return 0;
1186 /* State of bidirectional transfer loop. */
1187 struct bidirectional_transfer_state {
1188 /* Direction from program to git. */
1189 struct unidirectional_transfer ptg;
1190 /* Direction from git to program. */
1191 struct unidirectional_transfer gtp;
1194 static void *udt_copy_task_routine(void *udt)
1196 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1197 while (t->state != SSTATE_FINISHED) {
1198 if (STATE_NEEDS_READING(t->state))
1199 if (udt_do_read(t))
1200 return NULL;
1201 if (STATE_NEEDS_WRITING(t->state))
1202 if (udt_do_write(t))
1203 return NULL;
1204 if (STATE_NEEDS_CLOSING(t->state))
1205 udt_close_if_finished(t);
1207 return udt; /* Just some non-NULL value. */
1210 #ifndef NO_PTHREADS
1213 * Join thread, with appropriate errors on failure. Name is name for the
1214 * thread (for error messages). Returns 0 on success, 1 on failure.
1216 static int tloop_join(pthread_t thread, const char *name)
1218 int err;
1219 void *tret;
1220 err = pthread_join(thread, &tret);
1221 if (!tret) {
1222 error("%s thread failed", name);
1223 return 1;
1225 if (err) {
1226 error("%s thread failed to join: %s", name, strerror(err));
1227 return 1;
1229 return 0;
1233 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1234 * -1 on failure.
1236 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1238 pthread_t gtp_thread;
1239 pthread_t ptg_thread;
1240 int err;
1241 int ret = 0;
1242 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1243 &s->gtp);
1244 if (err)
1245 die("Can't start thread for copying data: %s", strerror(err));
1246 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1247 &s->ptg);
1248 if (err)
1249 die("Can't start thread for copying data: %s", strerror(err));
1251 ret |= tloop_join(gtp_thread, "Git to program copy");
1252 ret |= tloop_join(ptg_thread, "Program to git copy");
1253 return ret;
1255 #else
1257 /* Close the source and target (for writing) for transfer. */
1258 static void udt_kill_transfer(struct unidirectional_transfer *t)
1260 t->state = SSTATE_FINISHED;
1262 * Socket read end left open isn't a disaster if nobody
1263 * attempts to read from it (mingw compat headers do not
1264 * have SHUT_RD)...
1266 * We can't fully close the socket since otherwise gtp
1267 * task would first close the socket it sends data to
1268 * while closing the ptg file descriptors.
1270 if (!t->src_is_sock)
1271 close(t->src);
1272 if (t->dest_is_sock)
1273 shutdown(t->dest, SHUT_WR);
1274 else
1275 close(t->dest);
1279 * Join process, with appropriate errors on failure. Name is name for the
1280 * process (for error messages). Returns 0 on success, 1 on failure.
1282 static int tloop_join(pid_t pid, const char *name)
1284 int tret;
1285 if (waitpid(pid, &tret, 0) < 0) {
1286 error("%s process failed to wait: %s", name, strerror(errno));
1287 return 1;
1289 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1290 error("%s process failed", name);
1291 return 1;
1293 return 0;
1297 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1298 * -1 on failure.
1300 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1302 pid_t pid1, pid2;
1303 int ret = 0;
1305 /* Fork thread #1: git to program. */
1306 pid1 = fork();
1307 if (pid1 < 0)
1308 die_errno("Can't start thread for copying data");
1309 else if (pid1 == 0) {
1310 udt_kill_transfer(&s->ptg);
1311 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1314 /* Fork thread #2: program to git. */
1315 pid2 = fork();
1316 if (pid2 < 0)
1317 die_errno("Can't start thread for copying data");
1318 else if (pid2 == 0) {
1319 udt_kill_transfer(&s->gtp);
1320 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1324 * Close both streams in parent as to not interfere with
1325 * end of file detection and wait for both tasks to finish.
1327 udt_kill_transfer(&s->gtp);
1328 udt_kill_transfer(&s->ptg);
1329 ret |= tloop_join(pid1, "Git to program copy");
1330 ret |= tloop_join(pid2, "Program to git copy");
1331 return ret;
1333 #endif
1336 * Copies data from stdin to output and from input to stdout simultaneously.
1337 * Additionally filtering through given filter. If filter is NULL, uses
1338 * identity filter.
1340 int bidirectional_transfer_loop(int input, int output)
1342 struct bidirectional_transfer_state state;
1344 /* Fill the state fields. */
1345 state.ptg.src = input;
1346 state.ptg.dest = 1;
1347 state.ptg.src_is_sock = (input == output);
1348 state.ptg.dest_is_sock = 0;
1349 state.ptg.state = SSTATE_TRANSFERING;
1350 state.ptg.bufuse = 0;
1351 state.ptg.src_name = "remote input";
1352 state.ptg.dest_name = "stdout";
1354 state.gtp.src = 0;
1355 state.gtp.dest = output;
1356 state.gtp.src_is_sock = 0;
1357 state.gtp.dest_is_sock = (input == output);
1358 state.gtp.state = SSTATE_TRANSFERING;
1359 state.gtp.bufuse = 0;
1360 state.gtp.src_name = "stdin";
1361 state.gtp.dest_name = "remote output";
1363 return tloop_spawnwait_tasks(&state);