t5801: skip without hg
[git/mjg.git] / transport-helper.c
bloba505afb5a7e5cc0da12eb754abd762318fa057e2
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"
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 no_disconnect_req : 1;
29 char *export_marks;
30 char *import_marks;
31 /* These go from remote name (as in "list") to private name */
32 struct refspec *refspecs;
33 int refspec_nr;
34 /* Transport options for fetch-pack/send-pack (should one of
35 * those be invoked).
37 struct git_transport_options transport_options;
40 static void sendline(struct helper_data *helper, struct strbuf *buffer)
42 if (debug)
43 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
44 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
45 != buffer->len)
46 die_errno("Full write to remote helper failed");
49 static int recvline_fh(FILE *helper, struct strbuf *buffer)
51 strbuf_reset(buffer);
52 if (debug)
53 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
54 if (strbuf_getline(buffer, helper, '\n') == EOF) {
55 if (debug)
56 fprintf(stderr, "Debug: Remote helper quit.\n");
57 exit(128);
60 if (debug)
61 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
62 return 0;
65 static int recvline(struct helper_data *helper, struct strbuf *buffer)
67 return recvline_fh(helper->out, buffer);
70 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
72 sendline(helper, buffer);
73 recvline(helper, buffer);
76 static void write_constant(int fd, const char *str)
78 if (debug)
79 fprintf(stderr, "Debug: Remote helper: -> %s", str);
80 if (write_in_full(fd, str, strlen(str)) != strlen(str))
81 die_errno("Full write to remote helper failed");
84 static const char *remove_ext_force(const char *url)
86 if (url) {
87 const char *colon = strchr(url, ':');
88 if (colon && colon[1] == ':')
89 return colon + 2;
91 return url;
94 static void do_take_over(struct transport *transport)
96 struct helper_data *data;
97 data = (struct helper_data *)transport->data;
98 transport_take_over(transport, data->helper);
99 fclose(data->out);
100 free(data);
103 static struct child_process *get_helper(struct transport *transport)
105 struct helper_data *data = transport->data;
106 struct argv_array argv = ARGV_ARRAY_INIT;
107 struct strbuf buf = STRBUF_INIT;
108 struct child_process *helper;
109 const char **refspecs = NULL;
110 int refspec_nr = 0;
111 int refspec_alloc = 0;
112 int duped;
113 int code;
114 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
115 const char *helper_env[] = {
116 git_dir_buf,
117 NULL
121 if (data->helper)
122 return data->helper;
124 helper = xcalloc(1, sizeof(*helper));
125 helper->in = -1;
126 helper->out = -1;
127 helper->err = 0;
128 argv_array_pushf(&argv, "git-remote-%s", data->name);
129 argv_array_push(&argv, transport->remote->name);
130 argv_array_push(&argv, remove_ext_force(transport->url));
131 helper->argv = argv_array_detach(&argv, NULL);
132 helper->git_cmd = 0;
133 helper->silent_exec_failure = 1;
135 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
136 helper->env = helper_env;
138 code = start_command(helper);
139 if (code < 0 && errno == ENOENT)
140 die("Unable to find remote helper for '%s'", data->name);
141 else if (code != 0)
142 exit(code);
144 data->helper = helper;
145 data->no_disconnect_req = 0;
148 * Open the output as FILE* so strbuf_getline() can be used.
149 * Do this with duped fd because fclose() will close the fd,
150 * and stuff like taking over will require the fd to remain.
152 duped = dup(helper->out);
153 if (duped < 0)
154 die_errno("Can't dup helper output fd");
155 data->out = xfdopen(duped, "r");
157 write_constant(helper->in, "capabilities\n");
159 while (1) {
160 const char *capname;
161 int mandatory = 0;
162 recvline(data, &buf);
164 if (!*buf.buf)
165 break;
167 if (*buf.buf == '*') {
168 capname = buf.buf + 1;
169 mandatory = 1;
170 } else
171 capname = buf.buf;
173 if (debug)
174 fprintf(stderr, "Debug: Got cap %s\n", capname);
175 if (!strcmp(capname, "fetch"))
176 data->fetch = 1;
177 else if (!strcmp(capname, "option"))
178 data->option = 1;
179 else if (!strcmp(capname, "push"))
180 data->push = 1;
181 else if (!strcmp(capname, "import"))
182 data->import = 1;
183 else if (!strcmp(capname, "bidi-import"))
184 data->bidi_import = 1;
185 else if (!strcmp(capname, "export"))
186 data->export = 1;
187 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
188 ALLOC_GROW(refspecs,
189 refspec_nr + 1,
190 refspec_alloc);
191 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
192 } else if (!strcmp(capname, "connect")) {
193 data->connect = 1;
194 } else if (!prefixcmp(capname, "export-marks ")) {
195 struct strbuf arg = STRBUF_INIT;
196 strbuf_addstr(&arg, "--export-marks=");
197 strbuf_addstr(&arg, capname + strlen("export-marks "));
198 data->export_marks = strbuf_detach(&arg, NULL);
199 } else if (!prefixcmp(capname, "import-marks")) {
200 struct strbuf arg = STRBUF_INIT;
201 strbuf_addstr(&arg, "--import-marks=");
202 strbuf_addstr(&arg, capname + strlen("import-marks "));
203 data->import_marks = strbuf_detach(&arg, NULL);
204 } else if (mandatory) {
205 die("Unknown mandatory capability %s. This remote "
206 "helper probably needs newer version of Git.",
207 capname);
210 if (refspecs) {
211 int i;
212 data->refspec_nr = refspec_nr;
213 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
214 for (i = 0; i < refspec_nr; i++) {
215 free((char *)refspecs[i]);
217 free(refspecs);
219 strbuf_release(&buf);
220 if (debug)
221 fprintf(stderr, "Debug: Capabilities complete.\n");
222 return data->helper;
225 static int disconnect_helper(struct transport *transport)
227 struct helper_data *data = transport->data;
228 int res = 0;
230 if (data->helper) {
231 if (debug)
232 fprintf(stderr, "Debug: Disconnecting.\n");
233 if (!data->no_disconnect_req) {
235 * Ignore write errors; there's nothing we can do,
236 * since we're about to close the pipe anyway. And the
237 * most likely error is EPIPE due to the helper dying
238 * to report an error itself.
240 sigchain_push(SIGPIPE, SIG_IGN);
241 xwrite(data->helper->in, "\n", 1);
242 sigchain_pop(SIGPIPE);
244 close(data->helper->in);
245 close(data->helper->out);
246 fclose(data->out);
247 res = finish_command(data->helper);
248 argv_array_free_detached(data->helper->argv);
249 free(data->helper);
250 data->helper = NULL;
252 return res;
255 static const char *unsupported_options[] = {
256 TRANS_OPT_UPLOADPACK,
257 TRANS_OPT_RECEIVEPACK,
258 TRANS_OPT_THIN,
259 TRANS_OPT_KEEP
261 static const char *boolean_options[] = {
262 TRANS_OPT_THIN,
263 TRANS_OPT_KEEP,
264 TRANS_OPT_FOLLOWTAGS
267 static int set_helper_option(struct transport *transport,
268 const char *name, const char *value)
270 struct helper_data *data = transport->data;
271 struct strbuf buf = STRBUF_INIT;
272 int i, ret, is_bool = 0;
274 get_helper(transport);
276 if (!data->option)
277 return 1;
279 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
280 if (!strcmp(name, unsupported_options[i]))
281 return 1;
284 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
285 if (!strcmp(name, boolean_options[i])) {
286 is_bool = 1;
287 break;
291 strbuf_addf(&buf, "option %s ", name);
292 if (is_bool)
293 strbuf_addstr(&buf, value ? "true" : "false");
294 else
295 quote_c_style(value, &buf, NULL, 0);
296 strbuf_addch(&buf, '\n');
298 xchgline(data, &buf);
300 if (!strcmp(buf.buf, "ok"))
301 ret = 0;
302 else if (!prefixcmp(buf.buf, "error")) {
303 ret = -1;
304 } else if (!strcmp(buf.buf, "unsupported"))
305 ret = 1;
306 else {
307 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
308 ret = 1;
310 strbuf_release(&buf);
311 return ret;
314 static void standard_options(struct transport *t)
316 char buf[16];
317 int n;
318 int v = t->verbose;
320 set_helper_option(t, "progress", t->progress ? "true" : "false");
322 n = snprintf(buf, sizeof(buf), "%d", v + 1);
323 if (n >= sizeof(buf))
324 die("impossibly large verbosity value");
325 set_helper_option(t, "verbosity", buf);
328 static int release_helper(struct transport *transport)
330 int res = 0;
331 struct helper_data *data = transport->data;
332 free_refspec(data->refspec_nr, data->refspecs);
333 data->refspecs = NULL;
334 res = disconnect_helper(transport);
335 free(transport->data);
336 return res;
339 static int fetch_with_fetch(struct transport *transport,
340 int nr_heads, struct ref **to_fetch)
342 struct helper_data *data = transport->data;
343 int i;
344 struct strbuf buf = STRBUF_INIT;
346 standard_options(transport);
348 for (i = 0; i < nr_heads; i++) {
349 const struct ref *posn = to_fetch[i];
350 if (posn->status & REF_STATUS_UPTODATE)
351 continue;
353 strbuf_addf(&buf, "fetch %s %s\n",
354 sha1_to_hex(posn->old_sha1), posn->name);
357 strbuf_addch(&buf, '\n');
358 sendline(data, &buf);
360 while (1) {
361 recvline(data, &buf);
363 if (!prefixcmp(buf.buf, "lock ")) {
364 const char *name = buf.buf + 5;
365 if (transport->pack_lockfile)
366 warning("%s also locked %s", data->name, name);
367 else
368 transport->pack_lockfile = xstrdup(name);
370 else if (!buf.len)
371 break;
372 else
373 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
375 strbuf_release(&buf);
376 return 0;
379 static int get_importer(struct transport *transport, struct child_process *fastimport)
381 struct child_process *helper = get_helper(transport);
382 struct helper_data *data = transport->data;
383 struct argv_array argv = ARGV_ARRAY_INIT;
384 int cat_blob_fd, code;
385 memset(fastimport, 0, sizeof(*fastimport));
386 fastimport->in = helper->out;
387 argv_array_push(&argv, "fast-import");
388 argv_array_push(&argv, debug ? "--stats" : "--quiet");
390 if (data->bidi_import) {
391 cat_blob_fd = xdup(helper->in);
392 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
394 fastimport->argv = argv.argv;
395 fastimport->git_cmd = 1;
397 code = start_command(fastimport);
398 return code;
401 static int get_exporter(struct transport *transport,
402 struct child_process *fastexport,
403 struct string_list *revlist_args)
405 struct helper_data *data = transport->data;
406 struct child_process *helper = get_helper(transport);
407 int argc = 0, i;
408 memset(fastexport, 0, sizeof(*fastexport));
410 /* we need to duplicate helper->in because we want to use it after
411 * fastexport is done with it. */
412 fastexport->out = dup(helper->in);
413 fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
414 fastexport->argv[argc++] = "fast-export";
415 fastexport->argv[argc++] = "--use-done-feature";
416 if (data->export_marks)
417 fastexport->argv[argc++] = data->export_marks;
418 if (data->import_marks)
419 fastexport->argv[argc++] = data->import_marks;
421 for (i = 0; i < revlist_args->nr; i++)
422 fastexport->argv[argc++] = revlist_args->items[i].string;
424 fastexport->argv[argc++] = "--";
426 fastexport->git_cmd = 1;
427 return start_command(fastexport);
430 static void check_helper_status(struct helper_data *data)
432 int pid, status;
434 pid = waitpid(data->helper->pid, &status, WNOHANG);
435 if (pid < 0)
436 die("Could not retrieve status of remote helper '%s'",
437 data->name);
438 if (pid > 0 && WIFEXITED(status))
439 die("Remote helper '%s' died with %d",
440 data->name, WEXITSTATUS(status));
443 static int fetch_with_import(struct transport *transport,
444 int nr_heads, struct ref **to_fetch)
446 struct child_process fastimport;
447 struct helper_data *data = transport->data;
448 int i;
449 struct ref *posn;
450 struct strbuf buf = STRBUF_INIT;
452 get_helper(transport);
454 if (get_importer(transport, &fastimport))
455 die("Couldn't run fast-import");
457 for (i = 0; i < nr_heads; i++) {
458 posn = to_fetch[i];
459 if (posn->status & REF_STATUS_UPTODATE)
460 continue;
462 strbuf_addf(&buf, "import %s\n", posn->name);
463 sendline(data, &buf);
464 strbuf_reset(&buf);
467 write_constant(data->helper->in, "\n");
469 * remote-helpers that advertise the bidi-import capability are required to
470 * buffer the complete batch of import commands until this newline before
471 * sending data to fast-import.
472 * These helpers read back data from fast-import on their stdin, which could
473 * be mixed with import commands, otherwise.
476 if (finish_command(&fastimport))
477 die("Error while running fast-import");
478 check_helper_status(data);
480 argv_array_free_detached(fastimport.argv);
483 * The fast-import stream of a remote helper that advertises
484 * the "refspec" capability writes to the refs named after the
485 * right hand side of the first refspec matching each ref we
486 * were fetching.
488 * (If no "refspec" capability was specified, for historical
489 * reasons we default to *:*.)
491 * Store the result in to_fetch[i].old_sha1. Callers such
492 * as "git fetch" can use the value to write feedback to the
493 * terminal, populate FETCH_HEAD, and determine what new value
494 * should be written to peer_ref if the update is a
495 * fast-forward or this is a forced update.
497 for (i = 0; i < nr_heads; i++) {
498 char *private;
499 posn = to_fetch[i];
500 if (posn->status & REF_STATUS_UPTODATE)
501 continue;
502 if (data->refspecs)
503 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
504 else
505 private = xstrdup(posn->name);
506 if (private) {
507 read_ref(private, posn->old_sha1);
508 free(private);
511 strbuf_release(&buf);
512 return 0;
515 static int process_connect_service(struct transport *transport,
516 const char *name, const char *exec)
518 struct helper_data *data = transport->data;
519 struct strbuf cmdbuf = STRBUF_INIT;
520 struct child_process *helper;
521 int r, duped, ret = 0;
522 FILE *input;
524 helper = get_helper(transport);
527 * Yes, dup the pipe another time, as we need unbuffered version
528 * of input pipe as FILE*. fclose() closes the underlying fd and
529 * stream buffering only can be changed before first I/O operation
530 * on it.
532 duped = dup(helper->out);
533 if (duped < 0)
534 die_errno("Can't dup helper output fd");
535 input = xfdopen(duped, "r");
536 setvbuf(input, NULL, _IONBF, 0);
539 * Handle --upload-pack and friends. This is fire and forget...
540 * just warn if it fails.
542 if (strcmp(name, exec)) {
543 r = set_helper_option(transport, "servpath", exec);
544 if (r > 0)
545 warning("Setting remote service path not supported by protocol.");
546 else if (r < 0)
547 warning("Invalid remote service path.");
550 if (data->connect)
551 strbuf_addf(&cmdbuf, "connect %s\n", name);
552 else
553 goto exit;
555 sendline(data, &cmdbuf);
556 recvline_fh(input, &cmdbuf);
557 if (!strcmp(cmdbuf.buf, "")) {
558 data->no_disconnect_req = 1;
559 if (debug)
560 fprintf(stderr, "Debug: Smart transport connection "
561 "ready.\n");
562 ret = 1;
563 } else if (!strcmp(cmdbuf.buf, "fallback")) {
564 if (debug)
565 fprintf(stderr, "Debug: Falling back to dumb "
566 "transport.\n");
567 } else
568 die("Unknown response to connect: %s",
569 cmdbuf.buf);
571 exit:
572 fclose(input);
573 return ret;
576 static int process_connect(struct transport *transport,
577 int for_push)
579 struct helper_data *data = transport->data;
580 const char *name;
581 const char *exec;
583 name = for_push ? "git-receive-pack" : "git-upload-pack";
584 if (for_push)
585 exec = data->transport_options.receivepack;
586 else
587 exec = data->transport_options.uploadpack;
589 return process_connect_service(transport, name, exec);
592 static int connect_helper(struct transport *transport, const char *name,
593 const char *exec, int fd[2])
595 struct helper_data *data = transport->data;
597 /* Get_helper so connect is inited. */
598 get_helper(transport);
599 if (!data->connect)
600 die("Operation not supported by protocol.");
602 if (!process_connect_service(transport, name, exec))
603 die("Can't connect to subservice %s.", name);
605 fd[0] = data->helper->out;
606 fd[1] = data->helper->in;
607 return 0;
610 static int fetch(struct transport *transport,
611 int nr_heads, struct ref **to_fetch)
613 struct helper_data *data = transport->data;
614 int i, count;
616 if (process_connect(transport, 0)) {
617 do_take_over(transport);
618 return transport->fetch(transport, nr_heads, to_fetch);
621 count = 0;
622 for (i = 0; i < nr_heads; i++)
623 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
624 count++;
626 if (!count)
627 return 0;
629 if (data->fetch)
630 return fetch_with_fetch(transport, nr_heads, to_fetch);
632 if (data->import)
633 return fetch_with_import(transport, nr_heads, to_fetch);
635 return -1;
638 static void push_update_ref_status(struct strbuf *buf,
639 struct ref **ref,
640 struct ref *remote_refs)
642 char *refname, *msg;
643 int status;
645 if (!prefixcmp(buf->buf, "ok ")) {
646 status = REF_STATUS_OK;
647 refname = buf->buf + 3;
648 } else if (!prefixcmp(buf->buf, "error ")) {
649 status = REF_STATUS_REMOTE_REJECT;
650 refname = buf->buf + 6;
651 } else
652 die("expected ok/error, helper said '%s'", buf->buf);
654 msg = strchr(refname, ' ');
655 if (msg) {
656 struct strbuf msg_buf = STRBUF_INIT;
657 const char *end;
659 *msg++ = '\0';
660 if (!unquote_c_style(&msg_buf, msg, &end))
661 msg = strbuf_detach(&msg_buf, NULL);
662 else
663 msg = xstrdup(msg);
664 strbuf_release(&msg_buf);
666 if (!strcmp(msg, "no match")) {
667 status = REF_STATUS_NONE;
668 free(msg);
669 msg = NULL;
671 else if (!strcmp(msg, "up to date")) {
672 status = REF_STATUS_UPTODATE;
673 free(msg);
674 msg = NULL;
676 else if (!strcmp(msg, "non-fast forward")) {
677 status = REF_STATUS_REJECT_NONFASTFORWARD;
678 free(msg);
679 msg = NULL;
683 if (*ref)
684 *ref = find_ref_by_name(*ref, refname);
685 if (!*ref)
686 *ref = find_ref_by_name(remote_refs, refname);
687 if (!*ref) {
688 warning("helper reported unexpected status of %s", refname);
689 return;
692 if ((*ref)->status != REF_STATUS_NONE) {
694 * Earlier, the ref was marked not to be pushed, so ignore the ref
695 * status reported by the remote helper if the latter is 'no match'.
697 if (status == REF_STATUS_NONE)
698 return;
701 (*ref)->status = status;
702 (*ref)->remote_status = msg;
705 static void push_update_refs_status(struct helper_data *data,
706 struct ref *remote_refs)
708 struct strbuf buf = STRBUF_INIT;
709 struct ref *ref = remote_refs;
710 for (;;) {
711 recvline(data, &buf);
712 if (!buf.len)
713 break;
715 push_update_ref_status(&buf, &ref, remote_refs);
717 strbuf_release(&buf);
720 static int push_refs_with_push(struct transport *transport,
721 struct ref *remote_refs, int flags)
723 int force_all = flags & TRANSPORT_PUSH_FORCE;
724 int mirror = flags & TRANSPORT_PUSH_MIRROR;
725 struct helper_data *data = transport->data;
726 struct strbuf buf = STRBUF_INIT;
727 struct ref *ref;
729 get_helper(transport);
730 if (!data->push)
731 return 1;
733 for (ref = remote_refs; ref; ref = ref->next) {
734 if (!ref->peer_ref && !mirror)
735 continue;
737 /* Check for statuses set by set_ref_status_for_push() */
738 switch (ref->status) {
739 case REF_STATUS_REJECT_NONFASTFORWARD:
740 case REF_STATUS_UPTODATE:
741 continue;
742 default:
743 ; /* do nothing */
746 if (force_all)
747 ref->force = 1;
749 strbuf_addstr(&buf, "push ");
750 if (!ref->deletion) {
751 if (ref->force)
752 strbuf_addch(&buf, '+');
753 if (ref->peer_ref)
754 strbuf_addstr(&buf, ref->peer_ref->name);
755 else
756 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
758 strbuf_addch(&buf, ':');
759 strbuf_addstr(&buf, ref->name);
760 strbuf_addch(&buf, '\n');
762 if (buf.len == 0)
763 return 0;
765 standard_options(transport);
767 if (flags & TRANSPORT_PUSH_DRY_RUN) {
768 if (set_helper_option(transport, "dry-run", "true") != 0)
769 die("helper %s does not support dry-run", data->name);
772 strbuf_addch(&buf, '\n');
773 sendline(data, &buf);
774 strbuf_release(&buf);
776 push_update_refs_status(data, remote_refs);
777 return 0;
780 static int push_refs_with_export(struct transport *transport,
781 struct ref *remote_refs, int flags)
783 struct ref *ref;
784 struct child_process *helper, exporter;
785 struct helper_data *data = transport->data;
786 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
787 struct strbuf buf = STRBUF_INIT;
789 helper = get_helper(transport);
791 write_constant(helper->in, "export\n");
793 strbuf_reset(&buf);
795 for (ref = remote_refs; ref; ref = ref->next) {
796 char *private;
797 unsigned char sha1[20];
799 if (!data->refspecs)
800 continue;
801 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
802 if (private && !get_sha1(private, sha1)) {
803 strbuf_addf(&buf, "^%s", private);
804 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
806 free(private);
808 if (ref->deletion) {
809 die("remote-helpers do not support ref deletion");
812 if (ref->peer_ref)
813 string_list_append(&revlist_args, ref->peer_ref->name);
817 if (get_exporter(transport, &exporter, &revlist_args))
818 die("Couldn't run fast-export");
820 if (finish_command(&exporter))
821 die("Error while running fast-export");
822 check_helper_status(data);
823 push_update_refs_status(data, remote_refs);
824 return 0;
827 static int push_refs(struct transport *transport,
828 struct ref *remote_refs, int flags)
830 struct helper_data *data = transport->data;
832 if (process_connect(transport, 1)) {
833 do_take_over(transport);
834 return transport->push_refs(transport, remote_refs, flags);
837 if (!remote_refs) {
838 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
839 "Perhaps you should specify a branch such as 'master'.\n");
840 return 0;
843 if (data->push)
844 return push_refs_with_push(transport, remote_refs, flags);
846 if (data->export)
847 return push_refs_with_export(transport, remote_refs, flags);
849 return -1;
853 static int has_attribute(const char *attrs, const char *attr) {
854 int len;
855 if (!attrs)
856 return 0;
858 len = strlen(attr);
859 for (;;) {
860 const char *space = strchrnul(attrs, ' ');
861 if (len == space - attrs && !strncmp(attrs, attr, len))
862 return 1;
863 if (!*space)
864 return 0;
865 attrs = space + 1;
869 static struct ref *get_refs_list(struct transport *transport, int for_push)
871 struct helper_data *data = transport->data;
872 struct child_process *helper;
873 struct ref *ret = NULL;
874 struct ref **tail = &ret;
875 struct ref *posn;
876 struct strbuf buf = STRBUF_INIT;
878 helper = get_helper(transport);
880 if (process_connect(transport, for_push)) {
881 do_take_over(transport);
882 return transport->get_refs_list(transport, for_push);
885 if (data->push && for_push)
886 write_str_in_full(helper->in, "list for-push\n");
887 else
888 write_str_in_full(helper->in, "list\n");
890 while (1) {
891 char *eov, *eon;
892 recvline(data, &buf);
894 if (!*buf.buf)
895 break;
897 eov = strchr(buf.buf, ' ');
898 if (!eov)
899 die("Malformed response in ref list: %s", buf.buf);
900 eon = strchr(eov + 1, ' ');
901 *eov = '\0';
902 if (eon)
903 *eon = '\0';
904 *tail = alloc_ref(eov + 1);
905 if (buf.buf[0] == '@')
906 (*tail)->symref = xstrdup(buf.buf + 1);
907 else if (buf.buf[0] != '?')
908 get_sha1_hex(buf.buf, (*tail)->old_sha1);
909 if (eon) {
910 if (has_attribute(eon + 1, "unchanged")) {
911 (*tail)->status |= REF_STATUS_UPTODATE;
912 read_ref((*tail)->name, (*tail)->old_sha1);
915 tail = &((*tail)->next);
917 if (debug)
918 fprintf(stderr, "Debug: Read ref listing.\n");
919 strbuf_release(&buf);
921 for (posn = ret; posn; posn = posn->next)
922 resolve_remote_symref(posn, ret);
924 return ret;
927 int transport_helper_init(struct transport *transport, const char *name)
929 struct helper_data *data = xcalloc(sizeof(*data), 1);
930 data->name = name;
932 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
933 debug = 1;
935 transport->data = data;
936 transport->set_option = set_helper_option;
937 transport->get_refs_list = get_refs_list;
938 transport->fetch = fetch;
939 transport->push_refs = push_refs;
940 transport->disconnect = release_helper;
941 transport->connect = connect_helper;
942 transport->smart_options = &(data->transport_options);
943 return 0;
947 * Linux pipes can buffer 65536 bytes at once (and most platforms can
948 * buffer less), so attempt reads and writes with up to that size.
950 #define BUFFERSIZE 65536
951 /* This should be enough to hold debugging message. */
952 #define PBUFFERSIZE 8192
954 /* Print bidirectional transfer loop debug message. */
955 static void transfer_debug(const char *fmt, ...)
957 va_list args;
958 char msgbuf[PBUFFERSIZE];
959 static int debug_enabled = -1;
961 if (debug_enabled < 0)
962 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
963 if (!debug_enabled)
964 return;
966 va_start(args, fmt);
967 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
968 va_end(args);
969 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
972 /* Stream state: More data may be coming in this direction. */
973 #define SSTATE_TRANSFERING 0
975 * Stream state: No more data coming in this direction, flushing rest of
976 * data.
978 #define SSTATE_FLUSHING 1
979 /* Stream state: Transfer in this direction finished. */
980 #define SSTATE_FINISHED 2
982 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
983 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
984 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
986 /* Unidirectional transfer. */
987 struct unidirectional_transfer {
988 /* Source */
989 int src;
990 /* Destination */
991 int dest;
992 /* Is source socket? */
993 int src_is_sock;
994 /* Is destination socket? */
995 int dest_is_sock;
996 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
997 int state;
998 /* Buffer. */
999 char buf[BUFFERSIZE];
1000 /* Buffer used. */
1001 size_t bufuse;
1002 /* Name of source. */
1003 const char *src_name;
1004 /* Name of destination. */
1005 const char *dest_name;
1008 /* Closes the target (for writing) if transfer has finished. */
1009 static void udt_close_if_finished(struct unidirectional_transfer *t)
1011 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1012 t->state = SSTATE_FINISHED;
1013 if (t->dest_is_sock)
1014 shutdown(t->dest, SHUT_WR);
1015 else
1016 close(t->dest);
1017 transfer_debug("Closed %s.", t->dest_name);
1022 * Tries to read read data from source into buffer. If buffer is full,
1023 * no data is read. Returns 0 on success, -1 on error.
1025 static int udt_do_read(struct unidirectional_transfer *t)
1027 ssize_t bytes;
1029 if (t->bufuse == BUFFERSIZE)
1030 return 0; /* No space for more. */
1032 transfer_debug("%s is readable", t->src_name);
1033 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1034 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1035 errno != EINTR) {
1036 error("read(%s) failed: %s", t->src_name, strerror(errno));
1037 return -1;
1038 } else if (bytes == 0) {
1039 transfer_debug("%s EOF (with %i bytes in buffer)",
1040 t->src_name, t->bufuse);
1041 t->state = SSTATE_FLUSHING;
1042 } else if (bytes > 0) {
1043 t->bufuse += bytes;
1044 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1045 (int)bytes, t->src_name, (int)t->bufuse);
1047 return 0;
1050 /* Tries to write data from buffer into destination. If buffer is empty,
1051 * no data is written. Returns 0 on success, -1 on error.
1053 static int udt_do_write(struct unidirectional_transfer *t)
1055 ssize_t bytes;
1057 if (t->bufuse == 0)
1058 return 0; /* Nothing to write. */
1060 transfer_debug("%s is writable", t->dest_name);
1061 bytes = write(t->dest, t->buf, t->bufuse);
1062 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1063 errno != EINTR) {
1064 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1065 return -1;
1066 } else if (bytes > 0) {
1067 t->bufuse -= bytes;
1068 if (t->bufuse)
1069 memmove(t->buf, t->buf + bytes, t->bufuse);
1070 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1071 (int)bytes, t->dest_name, (int)t->bufuse);
1073 return 0;
1077 /* State of bidirectional transfer loop. */
1078 struct bidirectional_transfer_state {
1079 /* Direction from program to git. */
1080 struct unidirectional_transfer ptg;
1081 /* Direction from git to program. */
1082 struct unidirectional_transfer gtp;
1085 static void *udt_copy_task_routine(void *udt)
1087 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1088 while (t->state != SSTATE_FINISHED) {
1089 if (STATE_NEEDS_READING(t->state))
1090 if (udt_do_read(t))
1091 return NULL;
1092 if (STATE_NEEDS_WRITING(t->state))
1093 if (udt_do_write(t))
1094 return NULL;
1095 if (STATE_NEEDS_CLOSING(t->state))
1096 udt_close_if_finished(t);
1098 return udt; /* Just some non-NULL value. */
1101 #ifndef NO_PTHREADS
1104 * Join thread, with apporiate errors on failure. Name is name for the
1105 * thread (for error messages). Returns 0 on success, 1 on failure.
1107 static int tloop_join(pthread_t thread, const char *name)
1109 int err;
1110 void *tret;
1111 err = pthread_join(thread, &tret);
1112 if (!tret) {
1113 error("%s thread failed", name);
1114 return 1;
1116 if (err) {
1117 error("%s thread failed to join: %s", name, strerror(err));
1118 return 1;
1120 return 0;
1124 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1125 * -1 on failure.
1127 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1129 pthread_t gtp_thread;
1130 pthread_t ptg_thread;
1131 int err;
1132 int ret = 0;
1133 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1134 &s->gtp);
1135 if (err)
1136 die("Can't start thread for copying data: %s", strerror(err));
1137 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1138 &s->ptg);
1139 if (err)
1140 die("Can't start thread for copying data: %s", strerror(err));
1142 ret |= tloop_join(gtp_thread, "Git to program copy");
1143 ret |= tloop_join(ptg_thread, "Program to git copy");
1144 return ret;
1146 #else
1148 /* Close the source and target (for writing) for transfer. */
1149 static void udt_kill_transfer(struct unidirectional_transfer *t)
1151 t->state = SSTATE_FINISHED;
1153 * Socket read end left open isn't a disaster if nobody
1154 * attempts to read from it (mingw compat headers do not
1155 * have SHUT_RD)...
1157 * We can't fully close the socket since otherwise gtp
1158 * task would first close the socket it sends data to
1159 * while closing the ptg file descriptors.
1161 if (!t->src_is_sock)
1162 close(t->src);
1163 if (t->dest_is_sock)
1164 shutdown(t->dest, SHUT_WR);
1165 else
1166 close(t->dest);
1170 * Join process, with apporiate errors on failure. Name is name for the
1171 * process (for error messages). Returns 0 on success, 1 on failure.
1173 static int tloop_join(pid_t pid, const char *name)
1175 int tret;
1176 if (waitpid(pid, &tret, 0) < 0) {
1177 error("%s process failed to wait: %s", name, strerror(errno));
1178 return 1;
1180 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1181 error("%s process failed", name);
1182 return 1;
1184 return 0;
1188 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1189 * -1 on failure.
1191 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1193 pid_t pid1, pid2;
1194 int ret = 0;
1196 /* Fork thread #1: git to program. */
1197 pid1 = fork();
1198 if (pid1 < 0)
1199 die_errno("Can't start thread for copying data");
1200 else if (pid1 == 0) {
1201 udt_kill_transfer(&s->ptg);
1202 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1205 /* Fork thread #2: program to git. */
1206 pid2 = fork();
1207 if (pid2 < 0)
1208 die_errno("Can't start thread for copying data");
1209 else if (pid2 == 0) {
1210 udt_kill_transfer(&s->gtp);
1211 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1215 * Close both streams in parent as to not interfere with
1216 * end of file detection and wait for both tasks to finish.
1218 udt_kill_transfer(&s->gtp);
1219 udt_kill_transfer(&s->ptg);
1220 ret |= tloop_join(pid1, "Git to program copy");
1221 ret |= tloop_join(pid2, "Program to git copy");
1222 return ret;
1224 #endif
1227 * Copies data from stdin to output and from input to stdout simultaneously.
1228 * Additionally filtering through given filter. If filter is NULL, uses
1229 * identity filter.
1231 int bidirectional_transfer_loop(int input, int output)
1233 struct bidirectional_transfer_state state;
1235 /* Fill the state fields. */
1236 state.ptg.src = input;
1237 state.ptg.dest = 1;
1238 state.ptg.src_is_sock = (input == output);
1239 state.ptg.dest_is_sock = 0;
1240 state.ptg.state = SSTATE_TRANSFERING;
1241 state.ptg.bufuse = 0;
1242 state.ptg.src_name = "remote input";
1243 state.ptg.dest_name = "stdout";
1245 state.gtp.src = 0;
1246 state.gtp.dest = output;
1247 state.gtp.src_is_sock = 0;
1248 state.gtp.dest_is_sock = (input == output);
1249 state.gtp.state = SSTATE_TRANSFERING;
1250 state.gtp.bufuse = 0;
1251 state.gtp.src_name = "stdin";
1252 state.gtp.dest_name = "remote output";
1254 return tloop_spawnwait_tasks(&state);