Merge branch 'mh/fetch-into-shallow' into next
[git/mjg.git] / transport-helper.c
blob3ebfae9808daf7696f4d5fb11f4dc2438f502006
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 no_disconnect_req : 1;
31 char *export_marks;
32 char *import_marks;
33 /* These go from remote name (as in "list") to private name */
34 struct refspec *refspecs;
35 int refspec_nr;
36 /* Transport options for fetch-pack/send-pack (should one of
37 * those be invoked).
39 struct git_transport_options transport_options;
42 static void sendline(struct helper_data *helper, struct strbuf *buffer)
44 if (debug)
45 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
46 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
47 != buffer->len)
48 die_errno("Full write to remote helper failed");
51 static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
53 strbuf_reset(buffer);
54 if (debug)
55 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
56 if (strbuf_getline(buffer, helper, '\n') == EOF) {
57 if (debug)
58 fprintf(stderr, "Debug: Remote helper quit.\n");
59 die("Reading from helper 'git-remote-%s' failed", name);
62 if (debug)
63 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
64 return 0;
67 static int recvline(struct helper_data *helper, struct strbuf *buffer)
69 return recvline_fh(helper->out, buffer, helper->name);
72 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
74 sendline(helper, buffer);
75 recvline(helper, buffer);
78 static void write_constant(int fd, const char *str)
80 if (debug)
81 fprintf(stderr, "Debug: Remote helper: -> %s", str);
82 if (write_in_full(fd, str, strlen(str)) != strlen(str))
83 die_errno("Full write to remote helper failed");
86 static const char *remove_ext_force(const char *url)
88 if (url) {
89 const char *colon = strchr(url, ':');
90 if (colon && colon[1] == ':')
91 return colon + 2;
93 return url;
96 static void do_take_over(struct transport *transport)
98 struct helper_data *data;
99 data = (struct helper_data *)transport->data;
100 transport_take_over(transport, data->helper);
101 fclose(data->out);
102 free(data);
105 static struct child_process *get_helper(struct transport *transport)
107 struct helper_data *data = transport->data;
108 struct argv_array argv = ARGV_ARRAY_INIT;
109 struct strbuf buf = STRBUF_INIT;
110 struct child_process *helper;
111 const char **refspecs = NULL;
112 int refspec_nr = 0;
113 int refspec_alloc = 0;
114 int duped;
115 int code;
116 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
117 const char *helper_env[] = {
118 git_dir_buf,
119 NULL
123 if (data->helper)
124 return data->helper;
126 helper = xcalloc(1, sizeof(*helper));
127 helper->in = -1;
128 helper->out = -1;
129 helper->err = 0;
130 argv_array_pushf(&argv, "git-remote-%s", data->name);
131 argv_array_push(&argv, transport->remote->name);
132 argv_array_push(&argv, remove_ext_force(transport->url));
133 helper->argv = argv_array_detach(&argv, NULL);
134 helper->git_cmd = 0;
135 helper->silent_exec_failure = 1;
137 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
138 helper->env = helper_env;
140 code = start_command(helper);
141 if (code < 0 && errno == ENOENT)
142 die("Unable to find remote helper for '%s'", data->name);
143 else if (code != 0)
144 exit(code);
146 data->helper = helper;
147 data->no_disconnect_req = 0;
150 * Open the output as FILE* so strbuf_getline() can be used.
151 * Do this with duped fd because fclose() will close the fd,
152 * and stuff like taking over will require the fd to remain.
154 duped = dup(helper->out);
155 if (duped < 0)
156 die_errno("Can't dup helper output fd");
157 data->out = xfdopen(duped, "r");
159 write_constant(helper->in, "capabilities\n");
161 while (1) {
162 const char *capname;
163 int mandatory = 0;
164 recvline(data, &buf);
166 if (!*buf.buf)
167 break;
169 if (*buf.buf == '*') {
170 capname = buf.buf + 1;
171 mandatory = 1;
172 } else
173 capname = buf.buf;
175 if (debug)
176 fprintf(stderr, "Debug: Got cap %s\n", capname);
177 if (!strcmp(capname, "fetch"))
178 data->fetch = 1;
179 else if (!strcmp(capname, "option"))
180 data->option = 1;
181 else if (!strcmp(capname, "push"))
182 data->push = 1;
183 else if (!strcmp(capname, "import"))
184 data->import = 1;
185 else if (!strcmp(capname, "bidi-import"))
186 data->bidi_import = 1;
187 else if (!strcmp(capname, "export"))
188 data->export = 1;
189 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
190 ALLOC_GROW(refspecs,
191 refspec_nr + 1,
192 refspec_alloc);
193 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
194 } else if (!strcmp(capname, "connect")) {
195 data->connect = 1;
196 } else if (!strcmp(capname, "signed-tags")) {
197 data->signed_tags = 1;
198 } else if (!prefixcmp(capname, "export-marks ")) {
199 struct strbuf arg = STRBUF_INIT;
200 strbuf_addstr(&arg, "--export-marks=");
201 strbuf_addstr(&arg, capname + strlen("export-marks "));
202 data->export_marks = strbuf_detach(&arg, NULL);
203 } else if (!prefixcmp(capname, "import-marks")) {
204 struct strbuf arg = STRBUF_INIT;
205 strbuf_addstr(&arg, "--import-marks=");
206 strbuf_addstr(&arg, capname + strlen("import-marks "));
207 data->import_marks = strbuf_detach(&arg, NULL);
208 } else if (mandatory) {
209 die("Unknown mandatory capability %s. This remote "
210 "helper probably needs newer version of Git.",
211 capname);
214 if (refspecs) {
215 int i;
216 data->refspec_nr = refspec_nr;
217 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
218 for (i = 0; i < refspec_nr; i++) {
219 free((char *)refspecs[i]);
221 free(refspecs);
222 } else if (data->import || data->bidi_import || data->export) {
223 warning("This remote helper should implement refspec capability.");
225 strbuf_release(&buf);
226 if (debug)
227 fprintf(stderr, "Debug: Capabilities complete.\n");
228 return data->helper;
231 static int disconnect_helper(struct transport *transport)
233 struct helper_data *data = transport->data;
234 int res = 0;
236 if (data->helper) {
237 if (debug)
238 fprintf(stderr, "Debug: Disconnecting.\n");
239 if (!data->no_disconnect_req) {
241 * Ignore write errors; there's nothing we can do,
242 * since we're about to close the pipe anyway. And the
243 * most likely error is EPIPE due to the helper dying
244 * to report an error itself.
246 sigchain_push(SIGPIPE, SIG_IGN);
247 xwrite(data->helper->in, "\n", 1);
248 sigchain_pop(SIGPIPE);
250 close(data->helper->in);
251 close(data->helper->out);
252 fclose(data->out);
253 res = finish_command(data->helper);
254 argv_array_free_detached(data->helper->argv);
255 free(data->helper);
256 data->helper = NULL;
258 return res;
261 static const char *unsupported_options[] = {
262 TRANS_OPT_UPLOADPACK,
263 TRANS_OPT_RECEIVEPACK,
264 TRANS_OPT_THIN,
265 TRANS_OPT_KEEP
267 static const char *boolean_options[] = {
268 TRANS_OPT_THIN,
269 TRANS_OPT_KEEP,
270 TRANS_OPT_FOLLOWTAGS
273 static int set_helper_option(struct transport *transport,
274 const char *name, const char *value)
276 struct helper_data *data = transport->data;
277 struct strbuf buf = STRBUF_INIT;
278 int i, ret, is_bool = 0;
280 get_helper(transport);
282 if (!data->option)
283 return 1;
285 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
286 if (!strcmp(name, unsupported_options[i]))
287 return 1;
290 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
291 if (!strcmp(name, boolean_options[i])) {
292 is_bool = 1;
293 break;
297 strbuf_addf(&buf, "option %s ", name);
298 if (is_bool)
299 strbuf_addstr(&buf, value ? "true" : "false");
300 else
301 quote_c_style(value, &buf, NULL, 0);
302 strbuf_addch(&buf, '\n');
304 xchgline(data, &buf);
306 if (!strcmp(buf.buf, "ok"))
307 ret = 0;
308 else if (!prefixcmp(buf.buf, "error")) {
309 ret = -1;
310 } else if (!strcmp(buf.buf, "unsupported"))
311 ret = 1;
312 else {
313 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
314 ret = 1;
316 strbuf_release(&buf);
317 return ret;
320 static void standard_options(struct transport *t)
322 char buf[16];
323 int n;
324 int v = t->verbose;
326 set_helper_option(t, "progress", t->progress ? "true" : "false");
328 n = snprintf(buf, sizeof(buf), "%d", v + 1);
329 if (n >= sizeof(buf))
330 die("impossibly large verbosity value");
331 set_helper_option(t, "verbosity", buf);
334 static int release_helper(struct transport *transport)
336 int res = 0;
337 struct helper_data *data = transport->data;
338 free_refspec(data->refspec_nr, data->refspecs);
339 data->refspecs = NULL;
340 res = disconnect_helper(transport);
341 free(transport->data);
342 return res;
345 static int fetch_with_fetch(struct transport *transport,
346 int nr_heads, struct ref **to_fetch)
348 struct helper_data *data = transport->data;
349 int i;
350 struct strbuf buf = STRBUF_INIT;
352 standard_options(transport);
354 for (i = 0; i < nr_heads; i++) {
355 const struct ref *posn = to_fetch[i];
356 if (posn->status & REF_STATUS_UPTODATE)
357 continue;
359 strbuf_addf(&buf, "fetch %s %s\n",
360 sha1_to_hex(posn->old_sha1), posn->name);
363 strbuf_addch(&buf, '\n');
364 sendline(data, &buf);
366 while (1) {
367 recvline(data, &buf);
369 if (!prefixcmp(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 (!buf.len)
377 break;
378 else
379 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
381 strbuf_release(&buf);
382 return 0;
385 static int get_importer(struct transport *transport, struct child_process *fastimport)
387 struct child_process *helper = get_helper(transport);
388 struct helper_data *data = transport->data;
389 struct argv_array argv = ARGV_ARRAY_INIT;
390 int cat_blob_fd, code;
391 memset(fastimport, 0, sizeof(*fastimport));
392 fastimport->in = helper->out;
393 argv_array_push(&argv, "fast-import");
394 argv_array_push(&argv, debug ? "--stats" : "--quiet");
396 if (data->bidi_import) {
397 cat_blob_fd = xdup(helper->in);
398 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
400 fastimport->argv = argv.argv;
401 fastimport->git_cmd = 1;
403 code = start_command(fastimport);
404 return code;
407 static int get_exporter(struct transport *transport,
408 struct child_process *fastexport,
409 struct string_list *revlist_args)
411 struct helper_data *data = transport->data;
412 struct child_process *helper = get_helper(transport);
413 int argc = 0, i;
414 memset(fastexport, 0, sizeof(*fastexport));
416 /* we need to duplicate helper->in because we want to use it after
417 * fastexport is done with it. */
418 fastexport->out = dup(helper->in);
419 fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
420 fastexport->argv[argc++] = "fast-export";
421 fastexport->argv[argc++] = "--use-done-feature";
422 fastexport->argv[argc++] = data->signed_tags ?
423 "--signed-tags=verbatim" : "--signed-tags=warn-strip";
424 if (data->export_marks)
425 fastexport->argv[argc++] = data->export_marks;
426 if (data->import_marks)
427 fastexport->argv[argc++] = data->import_marks;
429 for (i = 0; i < revlist_args->nr; i++)
430 fastexport->argv[argc++] = revlist_args->items[i].string;
432 fastexport->git_cmd = 1;
433 return start_command(fastexport);
436 static int fetch_with_import(struct transport *transport,
437 int nr_heads, struct ref **to_fetch)
439 struct child_process fastimport;
440 struct helper_data *data = transport->data;
441 int i;
442 struct ref *posn;
443 struct strbuf buf = STRBUF_INIT;
445 get_helper(transport);
447 if (get_importer(transport, &fastimport))
448 die("Couldn't run fast-import");
450 for (i = 0; i < nr_heads; i++) {
451 posn = to_fetch[i];
452 if (posn->status & REF_STATUS_UPTODATE)
453 continue;
455 strbuf_addf(&buf, "import %s\n", posn->name);
456 sendline(data, &buf);
457 strbuf_reset(&buf);
460 write_constant(data->helper->in, "\n");
462 * remote-helpers that advertise the bidi-import capability are required to
463 * buffer the complete batch of import commands until this newline before
464 * sending data to fast-import.
465 * These helpers read back data from fast-import on their stdin, which could
466 * be mixed with import commands, otherwise.
469 if (finish_command(&fastimport))
470 die("Error while running fast-import");
471 argv_array_free_detached(fastimport.argv);
474 * The fast-import stream of a remote helper that advertises
475 * the "refspec" capability writes to the refs named after the
476 * right hand side of the first refspec matching each ref we
477 * were fetching.
479 * (If no "refspec" capability was specified, for historical
480 * reasons we default to the equivalent of *:*.)
482 * Store the result in to_fetch[i].old_sha1. Callers such
483 * as "git fetch" can use the value to write feedback to the
484 * terminal, populate FETCH_HEAD, and determine what new value
485 * should be written to peer_ref if the update is a
486 * fast-forward or this is a forced update.
488 for (i = 0; i < nr_heads; i++) {
489 char *private;
490 posn = to_fetch[i];
491 if (posn->status & REF_STATUS_UPTODATE)
492 continue;
493 if (data->refspecs)
494 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
495 else
496 private = xstrdup(posn->name);
497 if (private) {
498 read_ref(private, posn->old_sha1);
499 free(private);
502 strbuf_release(&buf);
503 return 0;
506 static int process_connect_service(struct transport *transport,
507 const char *name, const char *exec)
509 struct helper_data *data = transport->data;
510 struct strbuf cmdbuf = STRBUF_INIT;
511 struct child_process *helper;
512 int r, duped, ret = 0;
513 FILE *input;
515 helper = get_helper(transport);
518 * Yes, dup the pipe another time, as we need unbuffered version
519 * of input pipe as FILE*. fclose() closes the underlying fd and
520 * stream buffering only can be changed before first I/O operation
521 * on it.
523 duped = dup(helper->out);
524 if (duped < 0)
525 die_errno("Can't dup helper output fd");
526 input = xfdopen(duped, "r");
527 setvbuf(input, NULL, _IONBF, 0);
530 * Handle --upload-pack and friends. This is fire and forget...
531 * just warn if it fails.
533 if (strcmp(name, exec)) {
534 r = set_helper_option(transport, "servpath", exec);
535 if (r > 0)
536 warning("Setting remote service path not supported by protocol.");
537 else if (r < 0)
538 warning("Invalid remote service path.");
541 if (data->connect)
542 strbuf_addf(&cmdbuf, "connect %s\n", name);
543 else
544 goto exit;
546 sendline(data, &cmdbuf);
547 recvline_fh(input, &cmdbuf, name);
548 if (!strcmp(cmdbuf.buf, "")) {
549 data->no_disconnect_req = 1;
550 if (debug)
551 fprintf(stderr, "Debug: Smart transport connection "
552 "ready.\n");
553 ret = 1;
554 } else if (!strcmp(cmdbuf.buf, "fallback")) {
555 if (debug)
556 fprintf(stderr, "Debug: Falling back to dumb "
557 "transport.\n");
558 } else
559 die("Unknown response to connect: %s",
560 cmdbuf.buf);
562 exit:
563 fclose(input);
564 return ret;
567 static int process_connect(struct transport *transport,
568 int for_push)
570 struct helper_data *data = transport->data;
571 const char *name;
572 const char *exec;
574 name = for_push ? "git-receive-pack" : "git-upload-pack";
575 if (for_push)
576 exec = data->transport_options.receivepack;
577 else
578 exec = data->transport_options.uploadpack;
580 return process_connect_service(transport, name, exec);
583 static int connect_helper(struct transport *transport, const char *name,
584 const char *exec, int fd[2])
586 struct helper_data *data = transport->data;
588 /* Get_helper so connect is inited. */
589 get_helper(transport);
590 if (!data->connect)
591 die("Operation not supported by protocol.");
593 if (!process_connect_service(transport, name, exec))
594 die("Can't connect to subservice %s.", name);
596 fd[0] = data->helper->out;
597 fd[1] = data->helper->in;
598 return 0;
601 static int fetch(struct transport *transport,
602 int nr_heads, struct ref **to_fetch)
604 struct helper_data *data = transport->data;
605 int i, count;
607 if (process_connect(transport, 0)) {
608 do_take_over(transport);
609 return transport->fetch(transport, nr_heads, to_fetch);
612 count = 0;
613 for (i = 0; i < nr_heads; i++)
614 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
615 count++;
617 if (!count)
618 return 0;
620 if (data->fetch)
621 return fetch_with_fetch(transport, nr_heads, to_fetch);
623 if (data->import)
624 return fetch_with_import(transport, nr_heads, to_fetch);
626 return -1;
629 static int push_update_ref_status(struct strbuf *buf,
630 struct ref **ref,
631 struct ref *remote_refs)
633 char *refname, *msg;
634 int status;
636 if (!prefixcmp(buf->buf, "ok ")) {
637 status = REF_STATUS_OK;
638 refname = buf->buf + 3;
639 } else if (!prefixcmp(buf->buf, "error ")) {
640 status = REF_STATUS_REMOTE_REJECT;
641 refname = buf->buf + 6;
642 } else
643 die("expected ok/error, helper said '%s'", buf->buf);
645 msg = strchr(refname, ' ');
646 if (msg) {
647 struct strbuf msg_buf = STRBUF_INIT;
648 const char *end;
650 *msg++ = '\0';
651 if (!unquote_c_style(&msg_buf, msg, &end))
652 msg = strbuf_detach(&msg_buf, NULL);
653 else
654 msg = xstrdup(msg);
655 strbuf_release(&msg_buf);
657 if (!strcmp(msg, "no match")) {
658 status = REF_STATUS_NONE;
659 free(msg);
660 msg = NULL;
662 else if (!strcmp(msg, "up to date")) {
663 status = REF_STATUS_UPTODATE;
664 free(msg);
665 msg = NULL;
667 else if (!strcmp(msg, "non-fast forward")) {
668 status = REF_STATUS_REJECT_NONFASTFORWARD;
669 free(msg);
670 msg = NULL;
672 else if (!strcmp(msg, "already exists")) {
673 status = REF_STATUS_REJECT_ALREADY_EXISTS;
674 free(msg);
675 msg = NULL;
677 else if (!strcmp(msg, "fetch first")) {
678 status = REF_STATUS_REJECT_FETCH_FIRST;
679 free(msg);
680 msg = NULL;
682 else if (!strcmp(msg, "needs force")) {
683 status = REF_STATUS_REJECT_NEEDS_FORCE;
684 free(msg);
685 msg = NULL;
689 if (*ref)
690 *ref = find_ref_by_name(*ref, refname);
691 if (!*ref)
692 *ref = find_ref_by_name(remote_refs, refname);
693 if (!*ref) {
694 warning("helper reported unexpected status of %s", refname);
695 return 1;
698 if ((*ref)->status != REF_STATUS_NONE) {
700 * Earlier, the ref was marked not to be pushed, so ignore the ref
701 * status reported by the remote helper if the latter is 'no match'.
703 if (status == REF_STATUS_NONE)
704 return 1;
707 (*ref)->status = status;
708 (*ref)->remote_status = msg;
709 return 0;
712 static void push_update_refs_status(struct helper_data *data,
713 struct ref *remote_refs)
715 struct strbuf buf = STRBUF_INIT;
716 struct ref *ref = remote_refs;
717 for (;;) {
718 char *private;
720 recvline(data, &buf);
721 if (!buf.len)
722 break;
724 if (push_update_ref_status(&buf, &ref, remote_refs))
725 continue;
727 if (!data->refspecs)
728 continue;
730 /* propagate back the update to the remote namespace */
731 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
732 if (!private)
733 continue;
734 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
735 free(private);
737 strbuf_release(&buf);
740 static int push_refs_with_push(struct transport *transport,
741 struct ref *remote_refs, int flags)
743 int force_all = flags & TRANSPORT_PUSH_FORCE;
744 int mirror = flags & TRANSPORT_PUSH_MIRROR;
745 struct helper_data *data = transport->data;
746 struct strbuf buf = STRBUF_INIT;
747 struct ref *ref;
749 get_helper(transport);
750 if (!data->push)
751 return 1;
753 for (ref = remote_refs; ref; ref = ref->next) {
754 if (!ref->peer_ref && !mirror)
755 continue;
757 /* Check for statuses set by set_ref_status_for_push() */
758 switch (ref->status) {
759 case REF_STATUS_REJECT_NONFASTFORWARD:
760 case REF_STATUS_REJECT_ALREADY_EXISTS:
761 case REF_STATUS_UPTODATE:
762 continue;
763 default:
764 ; /* do nothing */
767 if (force_all)
768 ref->force = 1;
770 strbuf_addstr(&buf, "push ");
771 if (!ref->deletion) {
772 if (ref->force)
773 strbuf_addch(&buf, '+');
774 if (ref->peer_ref)
775 strbuf_addstr(&buf, ref->peer_ref->name);
776 else
777 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
779 strbuf_addch(&buf, ':');
780 strbuf_addstr(&buf, ref->name);
781 strbuf_addch(&buf, '\n');
783 if (buf.len == 0)
784 return 0;
786 standard_options(transport);
788 if (flags & TRANSPORT_PUSH_DRY_RUN) {
789 if (set_helper_option(transport, "dry-run", "true") != 0)
790 die("helper %s does not support dry-run", data->name);
793 strbuf_addch(&buf, '\n');
794 sendline(data, &buf);
795 strbuf_release(&buf);
797 push_update_refs_status(data, remote_refs);
798 return 0;
801 static int push_refs_with_export(struct transport *transport,
802 struct ref *remote_refs, int flags)
804 struct ref *ref;
805 struct child_process *helper, exporter;
806 struct helper_data *data = transport->data;
807 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
808 struct strbuf buf = STRBUF_INIT;
810 if (!data->refspecs)
811 die("remote-helper doesn't support push; refspec needed");
813 helper = get_helper(transport);
815 write_constant(helper->in, "export\n");
817 strbuf_reset(&buf);
819 for (ref = remote_refs; ref; ref = ref->next) {
820 char *private;
821 unsigned char sha1[20];
823 if (ref->deletion)
824 die("remote-helpers do not support ref deletion");
826 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
827 if (private && !get_sha1(private, sha1)) {
828 strbuf_addf(&buf, "^%s", private);
829 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
830 hashcpy(ref->old_sha1, sha1);
832 free(private);
834 if (ref->peer_ref)
835 string_list_append(&revlist_args, ref->peer_ref->name);
838 if (get_exporter(transport, &exporter, &revlist_args))
839 die("Couldn't run fast-export");
841 if (finish_command(&exporter))
842 die("Error while running fast-export");
843 push_update_refs_status(data, remote_refs);
844 return 0;
847 static int push_refs(struct transport *transport,
848 struct ref *remote_refs, int flags)
850 struct helper_data *data = transport->data;
852 if (process_connect(transport, 1)) {
853 do_take_over(transport);
854 return transport->push_refs(transport, remote_refs, flags);
857 if (!remote_refs) {
858 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
859 "Perhaps you should specify a branch such as 'master'.\n");
860 return 0;
863 if (data->push)
864 return push_refs_with_push(transport, remote_refs, flags);
866 if (data->export)
867 return push_refs_with_export(transport, remote_refs, flags);
869 return -1;
873 static int has_attribute(const char *attrs, const char *attr) {
874 int len;
875 if (!attrs)
876 return 0;
878 len = strlen(attr);
879 for (;;) {
880 const char *space = strchrnul(attrs, ' ');
881 if (len == space - attrs && !strncmp(attrs, attr, len))
882 return 1;
883 if (!*space)
884 return 0;
885 attrs = space + 1;
889 static struct ref *get_refs_list(struct transport *transport, int for_push)
891 struct helper_data *data = transport->data;
892 struct child_process *helper;
893 struct ref *ret = NULL;
894 struct ref **tail = &ret;
895 struct ref *posn;
896 struct strbuf buf = STRBUF_INIT;
898 helper = get_helper(transport);
900 if (process_connect(transport, for_push)) {
901 do_take_over(transport);
902 return transport->get_refs_list(transport, for_push);
905 if (data->push && for_push)
906 write_str_in_full(helper->in, "list for-push\n");
907 else
908 write_str_in_full(helper->in, "list\n");
910 while (1) {
911 char *eov, *eon;
912 recvline(data, &buf);
914 if (!*buf.buf)
915 break;
917 eov = strchr(buf.buf, ' ');
918 if (!eov)
919 die("Malformed response in ref list: %s", buf.buf);
920 eon = strchr(eov + 1, ' ');
921 *eov = '\0';
922 if (eon)
923 *eon = '\0';
924 *tail = alloc_ref(eov + 1);
925 if (buf.buf[0] == '@')
926 (*tail)->symref = xstrdup(buf.buf + 1);
927 else if (buf.buf[0] != '?')
928 get_sha1_hex(buf.buf, (*tail)->old_sha1);
929 if (eon) {
930 if (has_attribute(eon + 1, "unchanged")) {
931 (*tail)->status |= REF_STATUS_UPTODATE;
932 read_ref((*tail)->name, (*tail)->old_sha1);
935 tail = &((*tail)->next);
937 if (debug)
938 fprintf(stderr, "Debug: Read ref listing.\n");
939 strbuf_release(&buf);
941 for (posn = ret; posn; posn = posn->next)
942 resolve_remote_symref(posn, ret);
944 return ret;
947 int transport_helper_init(struct transport *transport, const char *name)
949 struct helper_data *data = xcalloc(sizeof(*data), 1);
950 data->name = name;
952 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
953 debug = 1;
955 transport->data = data;
956 transport->set_option = set_helper_option;
957 transport->get_refs_list = get_refs_list;
958 transport->fetch = fetch;
959 transport->push_refs = push_refs;
960 transport->disconnect = release_helper;
961 transport->connect = connect_helper;
962 transport->smart_options = &(data->transport_options);
963 return 0;
967 * Linux pipes can buffer 65536 bytes at once (and most platforms can
968 * buffer less), so attempt reads and writes with up to that size.
970 #define BUFFERSIZE 65536
971 /* This should be enough to hold debugging message. */
972 #define PBUFFERSIZE 8192
974 /* Print bidirectional transfer loop debug message. */
975 static void transfer_debug(const char *fmt, ...)
977 va_list args;
978 char msgbuf[PBUFFERSIZE];
979 static int debug_enabled = -1;
981 if (debug_enabled < 0)
982 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
983 if (!debug_enabled)
984 return;
986 va_start(args, fmt);
987 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
988 va_end(args);
989 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
992 /* Stream state: More data may be coming in this direction. */
993 #define SSTATE_TRANSFERING 0
995 * Stream state: No more data coming in this direction, flushing rest of
996 * data.
998 #define SSTATE_FLUSHING 1
999 /* Stream state: Transfer in this direction finished. */
1000 #define SSTATE_FINISHED 2
1002 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1003 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1004 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1006 /* Unidirectional transfer. */
1007 struct unidirectional_transfer {
1008 /* Source */
1009 int src;
1010 /* Destination */
1011 int dest;
1012 /* Is source socket? */
1013 int src_is_sock;
1014 /* Is destination socket? */
1015 int dest_is_sock;
1016 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1017 int state;
1018 /* Buffer. */
1019 char buf[BUFFERSIZE];
1020 /* Buffer used. */
1021 size_t bufuse;
1022 /* Name of source. */
1023 const char *src_name;
1024 /* Name of destination. */
1025 const char *dest_name;
1028 /* Closes the target (for writing) if transfer has finished. */
1029 static void udt_close_if_finished(struct unidirectional_transfer *t)
1031 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1032 t->state = SSTATE_FINISHED;
1033 if (t->dest_is_sock)
1034 shutdown(t->dest, SHUT_WR);
1035 else
1036 close(t->dest);
1037 transfer_debug("Closed %s.", t->dest_name);
1042 * Tries to read read data from source into buffer. If buffer is full,
1043 * no data is read. Returns 0 on success, -1 on error.
1045 static int udt_do_read(struct unidirectional_transfer *t)
1047 ssize_t bytes;
1049 if (t->bufuse == BUFFERSIZE)
1050 return 0; /* No space for more. */
1052 transfer_debug("%s is readable", t->src_name);
1053 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1054 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1055 errno != EINTR) {
1056 error("read(%s) failed: %s", t->src_name, strerror(errno));
1057 return -1;
1058 } else if (bytes == 0) {
1059 transfer_debug("%s EOF (with %i bytes in buffer)",
1060 t->src_name, t->bufuse);
1061 t->state = SSTATE_FLUSHING;
1062 } else if (bytes > 0) {
1063 t->bufuse += bytes;
1064 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1065 (int)bytes, t->src_name, (int)t->bufuse);
1067 return 0;
1070 /* Tries to write data from buffer into destination. If buffer is empty,
1071 * no data is written. Returns 0 on success, -1 on error.
1073 static int udt_do_write(struct unidirectional_transfer *t)
1075 ssize_t bytes;
1077 if (t->bufuse == 0)
1078 return 0; /* Nothing to write. */
1080 transfer_debug("%s is writable", t->dest_name);
1081 bytes = write(t->dest, t->buf, t->bufuse);
1082 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1083 errno != EINTR) {
1084 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1085 return -1;
1086 } else if (bytes > 0) {
1087 t->bufuse -= bytes;
1088 if (t->bufuse)
1089 memmove(t->buf, t->buf + bytes, t->bufuse);
1090 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1091 (int)bytes, t->dest_name, (int)t->bufuse);
1093 return 0;
1097 /* State of bidirectional transfer loop. */
1098 struct bidirectional_transfer_state {
1099 /* Direction from program to git. */
1100 struct unidirectional_transfer ptg;
1101 /* Direction from git to program. */
1102 struct unidirectional_transfer gtp;
1105 static void *udt_copy_task_routine(void *udt)
1107 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1108 while (t->state != SSTATE_FINISHED) {
1109 if (STATE_NEEDS_READING(t->state))
1110 if (udt_do_read(t))
1111 return NULL;
1112 if (STATE_NEEDS_WRITING(t->state))
1113 if (udt_do_write(t))
1114 return NULL;
1115 if (STATE_NEEDS_CLOSING(t->state))
1116 udt_close_if_finished(t);
1118 return udt; /* Just some non-NULL value. */
1121 #ifndef NO_PTHREADS
1124 * Join thread, with apporiate errors on failure. Name is name for the
1125 * thread (for error messages). Returns 0 on success, 1 on failure.
1127 static int tloop_join(pthread_t thread, const char *name)
1129 int err;
1130 void *tret;
1131 err = pthread_join(thread, &tret);
1132 if (!tret) {
1133 error("%s thread failed", name);
1134 return 1;
1136 if (err) {
1137 error("%s thread failed to join: %s", name, strerror(err));
1138 return 1;
1140 return 0;
1144 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1145 * -1 on failure.
1147 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1149 pthread_t gtp_thread;
1150 pthread_t ptg_thread;
1151 int err;
1152 int ret = 0;
1153 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1154 &s->gtp);
1155 if (err)
1156 die("Can't start thread for copying data: %s", strerror(err));
1157 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1158 &s->ptg);
1159 if (err)
1160 die("Can't start thread for copying data: %s", strerror(err));
1162 ret |= tloop_join(gtp_thread, "Git to program copy");
1163 ret |= tloop_join(ptg_thread, "Program to git copy");
1164 return ret;
1166 #else
1168 /* Close the source and target (for writing) for transfer. */
1169 static void udt_kill_transfer(struct unidirectional_transfer *t)
1171 t->state = SSTATE_FINISHED;
1173 * Socket read end left open isn't a disaster if nobody
1174 * attempts to read from it (mingw compat headers do not
1175 * have SHUT_RD)...
1177 * We can't fully close the socket since otherwise gtp
1178 * task would first close the socket it sends data to
1179 * while closing the ptg file descriptors.
1181 if (!t->src_is_sock)
1182 close(t->src);
1183 if (t->dest_is_sock)
1184 shutdown(t->dest, SHUT_WR);
1185 else
1186 close(t->dest);
1190 * Join process, with apporiate errors on failure. Name is name for the
1191 * process (for error messages). Returns 0 on success, 1 on failure.
1193 static int tloop_join(pid_t pid, const char *name)
1195 int tret;
1196 if (waitpid(pid, &tret, 0) < 0) {
1197 error("%s process failed to wait: %s", name, strerror(errno));
1198 return 1;
1200 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1201 error("%s process failed", name);
1202 return 1;
1204 return 0;
1208 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1209 * -1 on failure.
1211 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1213 pid_t pid1, pid2;
1214 int ret = 0;
1216 /* Fork thread #1: git to program. */
1217 pid1 = fork();
1218 if (pid1 < 0)
1219 die_errno("Can't start thread for copying data");
1220 else if (pid1 == 0) {
1221 udt_kill_transfer(&s->ptg);
1222 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1225 /* Fork thread #2: program to git. */
1226 pid2 = fork();
1227 if (pid2 < 0)
1228 die_errno("Can't start thread for copying data");
1229 else if (pid2 == 0) {
1230 udt_kill_transfer(&s->gtp);
1231 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1235 * Close both streams in parent as to not interfere with
1236 * end of file detection and wait for both tasks to finish.
1238 udt_kill_transfer(&s->gtp);
1239 udt_kill_transfer(&s->ptg);
1240 ret |= tloop_join(pid1, "Git to program copy");
1241 ret |= tloop_join(pid2, "Program to git copy");
1242 return ret;
1244 #endif
1247 * Copies data from stdin to output and from input to stdout simultaneously.
1248 * Additionally filtering through given filter. If filter is NULL, uses
1249 * identity filter.
1251 int bidirectional_transfer_loop(int input, int output)
1253 struct bidirectional_transfer_state state;
1255 /* Fill the state fields. */
1256 state.ptg.src = input;
1257 state.ptg.dest = 1;
1258 state.ptg.src_is_sock = (input == output);
1259 state.ptg.dest_is_sock = 0;
1260 state.ptg.state = SSTATE_TRANSFERING;
1261 state.ptg.bufuse = 0;
1262 state.ptg.src_name = "remote input";
1263 state.ptg.dest_name = "stdout";
1265 state.gtp.src = 0;
1266 state.gtp.dest = output;
1267 state.gtp.src_is_sock = 0;
1268 state.gtp.dest_is_sock = (input == output);
1269 state.gtp.state = SSTATE_TRANSFERING;
1270 state.gtp.bufuse = 0;
1271 state.gtp.src_name = "stdin";
1272 state.gtp.dest_name = "remote output";
1274 return tloop_spawnwait_tasks(&state);