t5801: "VAR=VAL shell_func args" is forbidden
[git.git] / transport-helper.c
blob92174095eda4f2446f97bdb2854e533080c0c834
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 no_disconnect_req : 1;
30 char *export_marks;
31 char *import_marks;
32 /* These go from remote name (as in "list") to private name */
33 struct refspec *refspecs;
34 int refspec_nr;
35 /* Transport options for fetch-pack/send-pack (should one of
36 * those be invoked).
38 struct git_transport_options transport_options;
41 static void sendline(struct helper_data *helper, struct strbuf *buffer)
43 if (debug)
44 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
45 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
46 != buffer->len)
47 die_errno("Full write to remote helper failed");
50 static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
52 strbuf_reset(buffer);
53 if (debug)
54 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
55 if (strbuf_getline(buffer, helper, '\n') == EOF) {
56 if (debug)
57 fprintf(stderr, "Debug: Remote helper quit.\n");
58 die("Reading from helper 'git-remote-%s' failed", name);
61 if (debug)
62 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
63 return 0;
66 static int recvline(struct helper_data *helper, struct strbuf *buffer)
68 return recvline_fh(helper->out, buffer, helper->name);
71 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
73 sendline(helper, buffer);
74 recvline(helper, buffer);
77 static void write_constant(int fd, const char *str)
79 if (debug)
80 fprintf(stderr, "Debug: Remote helper: -> %s", str);
81 if (write_in_full(fd, str, strlen(str)) != strlen(str))
82 die_errno("Full write to remote helper failed");
85 static const char *remove_ext_force(const char *url)
87 if (url) {
88 const char *colon = strchr(url, ':');
89 if (colon && colon[1] == ':')
90 return colon + 2;
92 return url;
95 static void do_take_over(struct transport *transport)
97 struct helper_data *data;
98 data = (struct helper_data *)transport->data;
99 transport_take_over(transport, data->helper);
100 fclose(data->out);
101 free(data);
104 static struct child_process *get_helper(struct transport *transport)
106 struct helper_data *data = transport->data;
107 struct argv_array argv = ARGV_ARRAY_INIT;
108 struct strbuf buf = STRBUF_INIT;
109 struct child_process *helper;
110 const char **refspecs = NULL;
111 int refspec_nr = 0;
112 int refspec_alloc = 0;
113 int duped;
114 int code;
115 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
116 const char *helper_env[] = {
117 git_dir_buf,
118 NULL
122 if (data->helper)
123 return data->helper;
125 helper = xcalloc(1, sizeof(*helper));
126 helper->in = -1;
127 helper->out = -1;
128 helper->err = 0;
129 argv_array_pushf(&argv, "git-remote-%s", data->name);
130 argv_array_push(&argv, transport->remote->name);
131 argv_array_push(&argv, remove_ext_force(transport->url));
132 helper->argv = argv_array_detach(&argv, NULL);
133 helper->git_cmd = 0;
134 helper->silent_exec_failure = 1;
136 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
137 helper->env = helper_env;
139 code = start_command(helper);
140 if (code < 0 && errno == ENOENT)
141 die("Unable to find remote helper for '%s'", data->name);
142 else if (code != 0)
143 exit(code);
145 data->helper = helper;
146 data->no_disconnect_req = 0;
149 * Open the output as FILE* so strbuf_getline() can be used.
150 * Do this with duped fd because fclose() will close the fd,
151 * and stuff like taking over will require the fd to remain.
153 duped = dup(helper->out);
154 if (duped < 0)
155 die_errno("Can't dup helper output fd");
156 data->out = xfdopen(duped, "r");
158 write_constant(helper->in, "capabilities\n");
160 while (1) {
161 const char *capname;
162 int mandatory = 0;
163 recvline(data, &buf);
165 if (!*buf.buf)
166 break;
168 if (*buf.buf == '*') {
169 capname = buf.buf + 1;
170 mandatory = 1;
171 } else
172 capname = buf.buf;
174 if (debug)
175 fprintf(stderr, "Debug: Got cap %s\n", capname);
176 if (!strcmp(capname, "fetch"))
177 data->fetch = 1;
178 else if (!strcmp(capname, "option"))
179 data->option = 1;
180 else if (!strcmp(capname, "push"))
181 data->push = 1;
182 else if (!strcmp(capname, "import"))
183 data->import = 1;
184 else if (!strcmp(capname, "bidi-import"))
185 data->bidi_import = 1;
186 else if (!strcmp(capname, "export"))
187 data->export = 1;
188 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
189 ALLOC_GROW(refspecs,
190 refspec_nr + 1,
191 refspec_alloc);
192 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
193 } else if (!strcmp(capname, "connect")) {
194 data->connect = 1;
195 } else if (!prefixcmp(capname, "export-marks ")) {
196 struct strbuf arg = STRBUF_INIT;
197 strbuf_addstr(&arg, "--export-marks=");
198 strbuf_addstr(&arg, capname + strlen("export-marks "));
199 data->export_marks = strbuf_detach(&arg, NULL);
200 } else if (!prefixcmp(capname, "import-marks")) {
201 struct strbuf arg = STRBUF_INIT;
202 strbuf_addstr(&arg, "--import-marks=");
203 strbuf_addstr(&arg, capname + strlen("import-marks "));
204 data->import_marks = strbuf_detach(&arg, NULL);
205 } else if (mandatory) {
206 die("Unknown mandatory capability %s. This remote "
207 "helper probably needs newer version of Git.",
208 capname);
211 if (refspecs) {
212 int i;
213 data->refspec_nr = refspec_nr;
214 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
215 for (i = 0; i < refspec_nr; i++) {
216 free((char *)refspecs[i]);
218 free(refspecs);
219 } else if (data->import || data->bidi_import || data->export) {
220 warning("This remote helper should implement refspec capability.");
222 strbuf_release(&buf);
223 if (debug)
224 fprintf(stderr, "Debug: Capabilities complete.\n");
225 return data->helper;
228 static int disconnect_helper(struct transport *transport)
230 struct helper_data *data = transport->data;
231 int res = 0;
233 if (data->helper) {
234 if (debug)
235 fprintf(stderr, "Debug: Disconnecting.\n");
236 if (!data->no_disconnect_req) {
238 * Ignore write errors; there's nothing we can do,
239 * since we're about to close the pipe anyway. And the
240 * most likely error is EPIPE due to the helper dying
241 * to report an error itself.
243 sigchain_push(SIGPIPE, SIG_IGN);
244 xwrite(data->helper->in, "\n", 1);
245 sigchain_pop(SIGPIPE);
247 close(data->helper->in);
248 close(data->helper->out);
249 fclose(data->out);
250 res = finish_command(data->helper);
251 argv_array_free_detached(data->helper->argv);
252 free(data->helper);
253 data->helper = NULL;
255 return res;
258 static const char *unsupported_options[] = {
259 TRANS_OPT_UPLOADPACK,
260 TRANS_OPT_RECEIVEPACK,
261 TRANS_OPT_THIN,
262 TRANS_OPT_KEEP
264 static const char *boolean_options[] = {
265 TRANS_OPT_THIN,
266 TRANS_OPT_KEEP,
267 TRANS_OPT_FOLLOWTAGS
270 static int set_helper_option(struct transport *transport,
271 const char *name, const char *value)
273 struct helper_data *data = transport->data;
274 struct strbuf buf = STRBUF_INIT;
275 int i, ret, is_bool = 0;
277 get_helper(transport);
279 if (!data->option)
280 return 1;
282 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
283 if (!strcmp(name, unsupported_options[i]))
284 return 1;
287 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
288 if (!strcmp(name, boolean_options[i])) {
289 is_bool = 1;
290 break;
294 strbuf_addf(&buf, "option %s ", name);
295 if (is_bool)
296 strbuf_addstr(&buf, value ? "true" : "false");
297 else
298 quote_c_style(value, &buf, NULL, 0);
299 strbuf_addch(&buf, '\n');
301 xchgline(data, &buf);
303 if (!strcmp(buf.buf, "ok"))
304 ret = 0;
305 else if (!prefixcmp(buf.buf, "error")) {
306 ret = -1;
307 } else if (!strcmp(buf.buf, "unsupported"))
308 ret = 1;
309 else {
310 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
311 ret = 1;
313 strbuf_release(&buf);
314 return ret;
317 static void standard_options(struct transport *t)
319 char buf[16];
320 int n;
321 int v = t->verbose;
323 set_helper_option(t, "progress", t->progress ? "true" : "false");
325 n = snprintf(buf, sizeof(buf), "%d", v + 1);
326 if (n >= sizeof(buf))
327 die("impossibly large verbosity value");
328 set_helper_option(t, "verbosity", buf);
331 static int release_helper(struct transport *transport)
333 int res = 0;
334 struct helper_data *data = transport->data;
335 free_refspec(data->refspec_nr, data->refspecs);
336 data->refspecs = NULL;
337 res = disconnect_helper(transport);
338 free(transport->data);
339 return res;
342 static int fetch_with_fetch(struct transport *transport,
343 int nr_heads, struct ref **to_fetch)
345 struct helper_data *data = transport->data;
346 int i;
347 struct strbuf buf = STRBUF_INIT;
349 standard_options(transport);
351 for (i = 0; i < nr_heads; i++) {
352 const struct ref *posn = to_fetch[i];
353 if (posn->status & REF_STATUS_UPTODATE)
354 continue;
356 strbuf_addf(&buf, "fetch %s %s\n",
357 sha1_to_hex(posn->old_sha1), posn->name);
360 strbuf_addch(&buf, '\n');
361 sendline(data, &buf);
363 while (1) {
364 recvline(data, &buf);
366 if (!prefixcmp(buf.buf, "lock ")) {
367 const char *name = buf.buf + 5;
368 if (transport->pack_lockfile)
369 warning("%s also locked %s", data->name, name);
370 else
371 transport->pack_lockfile = xstrdup(name);
373 else if (!buf.len)
374 break;
375 else
376 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
378 strbuf_release(&buf);
379 return 0;
382 static int get_importer(struct transport *transport, struct child_process *fastimport)
384 struct child_process *helper = get_helper(transport);
385 struct helper_data *data = transport->data;
386 struct argv_array argv = ARGV_ARRAY_INIT;
387 int cat_blob_fd, code;
388 memset(fastimport, 0, sizeof(*fastimport));
389 fastimport->in = helper->out;
390 argv_array_push(&argv, "fast-import");
391 argv_array_push(&argv, debug ? "--stats" : "--quiet");
393 if (data->bidi_import) {
394 cat_blob_fd = xdup(helper->in);
395 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
397 fastimport->argv = argv.argv;
398 fastimport->git_cmd = 1;
400 code = start_command(fastimport);
401 return code;
404 static int get_exporter(struct transport *transport,
405 struct child_process *fastexport,
406 struct string_list *revlist_args)
408 struct helper_data *data = transport->data;
409 struct child_process *helper = get_helper(transport);
410 int argc = 0, i;
411 memset(fastexport, 0, sizeof(*fastexport));
413 /* we need to duplicate helper->in because we want to use it after
414 * fastexport is done with it. */
415 fastexport->out = dup(helper->in);
416 fastexport->argv = xcalloc(5 + revlist_args->nr, sizeof(*fastexport->argv));
417 fastexport->argv[argc++] = "fast-export";
418 fastexport->argv[argc++] = "--use-done-feature";
419 if (data->export_marks)
420 fastexport->argv[argc++] = data->export_marks;
421 if (data->import_marks)
422 fastexport->argv[argc++] = data->import_marks;
424 for (i = 0; i < revlist_args->nr; i++)
425 fastexport->argv[argc++] = revlist_args->items[i].string;
427 fastexport->git_cmd = 1;
428 return start_command(fastexport);
431 static int fetch_with_import(struct transport *transport,
432 int nr_heads, struct ref **to_fetch)
434 struct child_process fastimport;
435 struct helper_data *data = transport->data;
436 int i;
437 struct ref *posn;
438 struct strbuf buf = STRBUF_INIT;
440 get_helper(transport);
442 if (get_importer(transport, &fastimport))
443 die("Couldn't run fast-import");
445 for (i = 0; i < nr_heads; i++) {
446 posn = to_fetch[i];
447 if (posn->status & REF_STATUS_UPTODATE)
448 continue;
450 strbuf_addf(&buf, "import %s\n", posn->name);
451 sendline(data, &buf);
452 strbuf_reset(&buf);
455 write_constant(data->helper->in, "\n");
457 * remote-helpers that advertise the bidi-import capability are required to
458 * buffer the complete batch of import commands until this newline before
459 * sending data to fast-import.
460 * These helpers read back data from fast-import on their stdin, which could
461 * be mixed with import commands, otherwise.
464 if (finish_command(&fastimport))
465 die("Error while running fast-import");
466 argv_array_free_detached(fastimport.argv);
469 * The fast-import stream of a remote helper that advertises
470 * the "refspec" capability writes to the refs named after the
471 * right hand side of the first refspec matching each ref we
472 * were fetching.
474 * (If no "refspec" capability was specified, for historical
475 * reasons we default to the equivalent of *:*.)
477 * Store the result in to_fetch[i].old_sha1. Callers such
478 * as "git fetch" can use the value to write feedback to the
479 * terminal, populate FETCH_HEAD, and determine what new value
480 * should be written to peer_ref if the update is a
481 * fast-forward or this is a forced update.
483 for (i = 0; i < nr_heads; i++) {
484 char *private;
485 posn = to_fetch[i];
486 if (posn->status & REF_STATUS_UPTODATE)
487 continue;
488 if (data->refspecs)
489 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
490 else
491 private = xstrdup(posn->name);
492 if (private) {
493 read_ref(private, posn->old_sha1);
494 free(private);
497 strbuf_release(&buf);
498 return 0;
501 static int process_connect_service(struct transport *transport,
502 const char *name, const char *exec)
504 struct helper_data *data = transport->data;
505 struct strbuf cmdbuf = STRBUF_INIT;
506 struct child_process *helper;
507 int r, duped, ret = 0;
508 FILE *input;
510 helper = get_helper(transport);
513 * Yes, dup the pipe another time, as we need unbuffered version
514 * of input pipe as FILE*. fclose() closes the underlying fd and
515 * stream buffering only can be changed before first I/O operation
516 * on it.
518 duped = dup(helper->out);
519 if (duped < 0)
520 die_errno("Can't dup helper output fd");
521 input = xfdopen(duped, "r");
522 setvbuf(input, NULL, _IONBF, 0);
525 * Handle --upload-pack and friends. This is fire and forget...
526 * just warn if it fails.
528 if (strcmp(name, exec)) {
529 r = set_helper_option(transport, "servpath", exec);
530 if (r > 0)
531 warning("Setting remote service path not supported by protocol.");
532 else if (r < 0)
533 warning("Invalid remote service path.");
536 if (data->connect)
537 strbuf_addf(&cmdbuf, "connect %s\n", name);
538 else
539 goto exit;
541 sendline(data, &cmdbuf);
542 recvline_fh(input, &cmdbuf, name);
543 if (!strcmp(cmdbuf.buf, "")) {
544 data->no_disconnect_req = 1;
545 if (debug)
546 fprintf(stderr, "Debug: Smart transport connection "
547 "ready.\n");
548 ret = 1;
549 } else if (!strcmp(cmdbuf.buf, "fallback")) {
550 if (debug)
551 fprintf(stderr, "Debug: Falling back to dumb "
552 "transport.\n");
553 } else
554 die("Unknown response to connect: %s",
555 cmdbuf.buf);
557 exit:
558 fclose(input);
559 return ret;
562 static int process_connect(struct transport *transport,
563 int for_push)
565 struct helper_data *data = transport->data;
566 const char *name;
567 const char *exec;
569 name = for_push ? "git-receive-pack" : "git-upload-pack";
570 if (for_push)
571 exec = data->transport_options.receivepack;
572 else
573 exec = data->transport_options.uploadpack;
575 return process_connect_service(transport, name, exec);
578 static int connect_helper(struct transport *transport, const char *name,
579 const char *exec, int fd[2])
581 struct helper_data *data = transport->data;
583 /* Get_helper so connect is inited. */
584 get_helper(transport);
585 if (!data->connect)
586 die("Operation not supported by protocol.");
588 if (!process_connect_service(transport, name, exec))
589 die("Can't connect to subservice %s.", name);
591 fd[0] = data->helper->out;
592 fd[1] = data->helper->in;
593 return 0;
596 static int fetch(struct transport *transport,
597 int nr_heads, struct ref **to_fetch)
599 struct helper_data *data = transport->data;
600 int i, count;
602 if (process_connect(transport, 0)) {
603 do_take_over(transport);
604 return transport->fetch(transport, nr_heads, to_fetch);
607 count = 0;
608 for (i = 0; i < nr_heads; i++)
609 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
610 count++;
612 if (!count)
613 return 0;
615 if (data->fetch)
616 return fetch_with_fetch(transport, nr_heads, to_fetch);
618 if (data->import)
619 return fetch_with_import(transport, nr_heads, to_fetch);
621 return -1;
624 static int push_update_ref_status(struct strbuf *buf,
625 struct ref **ref,
626 struct ref *remote_refs)
628 char *refname, *msg;
629 int status;
631 if (!prefixcmp(buf->buf, "ok ")) {
632 status = REF_STATUS_OK;
633 refname = buf->buf + 3;
634 } else if (!prefixcmp(buf->buf, "error ")) {
635 status = REF_STATUS_REMOTE_REJECT;
636 refname = buf->buf + 6;
637 } else
638 die("expected ok/error, helper said '%s'", buf->buf);
640 msg = strchr(refname, ' ');
641 if (msg) {
642 struct strbuf msg_buf = STRBUF_INIT;
643 const char *end;
645 *msg++ = '\0';
646 if (!unquote_c_style(&msg_buf, msg, &end))
647 msg = strbuf_detach(&msg_buf, NULL);
648 else
649 msg = xstrdup(msg);
650 strbuf_release(&msg_buf);
652 if (!strcmp(msg, "no match")) {
653 status = REF_STATUS_NONE;
654 free(msg);
655 msg = NULL;
657 else if (!strcmp(msg, "up to date")) {
658 status = REF_STATUS_UPTODATE;
659 free(msg);
660 msg = NULL;
662 else if (!strcmp(msg, "non-fast forward")) {
663 status = REF_STATUS_REJECT_NONFASTFORWARD;
664 free(msg);
665 msg = NULL;
667 else if (!strcmp(msg, "already exists")) {
668 status = REF_STATUS_REJECT_ALREADY_EXISTS;
669 free(msg);
670 msg = NULL;
672 else if (!strcmp(msg, "fetch first")) {
673 status = REF_STATUS_REJECT_FETCH_FIRST;
674 free(msg);
675 msg = NULL;
677 else if (!strcmp(msg, "needs force")) {
678 status = REF_STATUS_REJECT_NEEDS_FORCE;
679 free(msg);
680 msg = NULL;
684 if (*ref)
685 *ref = find_ref_by_name(*ref, refname);
686 if (!*ref)
687 *ref = find_ref_by_name(remote_refs, refname);
688 if (!*ref) {
689 warning("helper reported unexpected status of %s", refname);
690 return 1;
693 if ((*ref)->status != REF_STATUS_NONE) {
695 * Earlier, the ref was marked not to be pushed, so ignore the ref
696 * status reported by the remote helper if the latter is 'no match'.
698 if (status == REF_STATUS_NONE)
699 return 1;
702 (*ref)->status = status;
703 (*ref)->remote_status = msg;
704 return 0;
707 static void push_update_refs_status(struct helper_data *data,
708 struct ref *remote_refs)
710 struct strbuf buf = STRBUF_INIT;
711 struct ref *ref = remote_refs;
712 for (;;) {
713 char *private;
715 recvline(data, &buf);
716 if (!buf.len)
717 break;
719 if (push_update_ref_status(&buf, &ref, remote_refs))
720 continue;
722 if (!data->refspecs)
723 continue;
725 /* propagate back the update to the remote namespace */
726 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
727 if (!private)
728 continue;
729 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
730 free(private);
732 strbuf_release(&buf);
735 static int push_refs_with_push(struct transport *transport,
736 struct ref *remote_refs, int flags)
738 int force_all = flags & TRANSPORT_PUSH_FORCE;
739 int mirror = flags & TRANSPORT_PUSH_MIRROR;
740 struct helper_data *data = transport->data;
741 struct strbuf buf = STRBUF_INIT;
742 struct ref *ref;
744 get_helper(transport);
745 if (!data->push)
746 return 1;
748 for (ref = remote_refs; ref; ref = ref->next) {
749 if (!ref->peer_ref && !mirror)
750 continue;
752 /* Check for statuses set by set_ref_status_for_push() */
753 switch (ref->status) {
754 case REF_STATUS_REJECT_NONFASTFORWARD:
755 case REF_STATUS_REJECT_ALREADY_EXISTS:
756 case REF_STATUS_UPTODATE:
757 continue;
758 default:
759 ; /* do nothing */
762 if (force_all)
763 ref->force = 1;
765 strbuf_addstr(&buf, "push ");
766 if (!ref->deletion) {
767 if (ref->force)
768 strbuf_addch(&buf, '+');
769 if (ref->peer_ref)
770 strbuf_addstr(&buf, ref->peer_ref->name);
771 else
772 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
774 strbuf_addch(&buf, ':');
775 strbuf_addstr(&buf, ref->name);
776 strbuf_addch(&buf, '\n');
778 if (buf.len == 0)
779 return 0;
781 standard_options(transport);
783 if (flags & TRANSPORT_PUSH_DRY_RUN) {
784 if (set_helper_option(transport, "dry-run", "true") != 0)
785 die("helper %s does not support dry-run", data->name);
788 strbuf_addch(&buf, '\n');
789 sendline(data, &buf);
790 strbuf_release(&buf);
792 push_update_refs_status(data, remote_refs);
793 return 0;
796 static int push_refs_with_export(struct transport *transport,
797 struct ref *remote_refs, int flags)
799 struct ref *ref;
800 struct child_process *helper, exporter;
801 struct helper_data *data = transport->data;
802 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
803 struct strbuf buf = STRBUF_INIT;
805 if (!data->refspecs)
806 die("remote-helper doesn't support push; refspec needed");
808 helper = get_helper(transport);
810 write_constant(helper->in, "export\n");
812 strbuf_reset(&buf);
814 for (ref = remote_refs; ref; ref = ref->next) {
815 char *private;
816 unsigned char sha1[20];
818 if (ref->deletion)
819 die("remote-helpers do not support ref deletion");
821 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
822 if (private && !get_sha1(private, sha1)) {
823 strbuf_addf(&buf, "^%s", private);
824 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
825 hashcpy(ref->old_sha1, sha1);
827 free(private);
829 if (ref->peer_ref)
830 string_list_append(&revlist_args, ref->peer_ref->name);
833 if (get_exporter(transport, &exporter, &revlist_args))
834 die("Couldn't run fast-export");
836 if (finish_command(&exporter))
837 die("Error while running fast-export");
838 push_update_refs_status(data, remote_refs);
839 return 0;
842 static int push_refs(struct transport *transport,
843 struct ref *remote_refs, int flags)
845 struct helper_data *data = transport->data;
847 if (process_connect(transport, 1)) {
848 do_take_over(transport);
849 return transport->push_refs(transport, remote_refs, flags);
852 if (!remote_refs) {
853 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
854 "Perhaps you should specify a branch such as 'master'.\n");
855 return 0;
858 if (data->push)
859 return push_refs_with_push(transport, remote_refs, flags);
861 if (data->export)
862 return push_refs_with_export(transport, remote_refs, flags);
864 return -1;
868 static int has_attribute(const char *attrs, const char *attr) {
869 int len;
870 if (!attrs)
871 return 0;
873 len = strlen(attr);
874 for (;;) {
875 const char *space = strchrnul(attrs, ' ');
876 if (len == space - attrs && !strncmp(attrs, attr, len))
877 return 1;
878 if (!*space)
879 return 0;
880 attrs = space + 1;
884 static struct ref *get_refs_list(struct transport *transport, int for_push)
886 struct helper_data *data = transport->data;
887 struct child_process *helper;
888 struct ref *ret = NULL;
889 struct ref **tail = &ret;
890 struct ref *posn;
891 struct strbuf buf = STRBUF_INIT;
893 helper = get_helper(transport);
895 if (process_connect(transport, for_push)) {
896 do_take_over(transport);
897 return transport->get_refs_list(transport, for_push);
900 if (data->push && for_push)
901 write_str_in_full(helper->in, "list for-push\n");
902 else
903 write_str_in_full(helper->in, "list\n");
905 while (1) {
906 char *eov, *eon;
907 recvline(data, &buf);
909 if (!*buf.buf)
910 break;
912 eov = strchr(buf.buf, ' ');
913 if (!eov)
914 die("Malformed response in ref list: %s", buf.buf);
915 eon = strchr(eov + 1, ' ');
916 *eov = '\0';
917 if (eon)
918 *eon = '\0';
919 *tail = alloc_ref(eov + 1);
920 if (buf.buf[0] == '@')
921 (*tail)->symref = xstrdup(buf.buf + 1);
922 else if (buf.buf[0] != '?')
923 get_sha1_hex(buf.buf, (*tail)->old_sha1);
924 if (eon) {
925 if (has_attribute(eon + 1, "unchanged")) {
926 (*tail)->status |= REF_STATUS_UPTODATE;
927 read_ref((*tail)->name, (*tail)->old_sha1);
930 tail = &((*tail)->next);
932 if (debug)
933 fprintf(stderr, "Debug: Read ref listing.\n");
934 strbuf_release(&buf);
936 for (posn = ret; posn; posn = posn->next)
937 resolve_remote_symref(posn, ret);
939 return ret;
942 int transport_helper_init(struct transport *transport, const char *name)
944 struct helper_data *data = xcalloc(sizeof(*data), 1);
945 data->name = name;
947 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
948 debug = 1;
950 transport->data = data;
951 transport->set_option = set_helper_option;
952 transport->get_refs_list = get_refs_list;
953 transport->fetch = fetch;
954 transport->push_refs = push_refs;
955 transport->disconnect = release_helper;
956 transport->connect = connect_helper;
957 transport->smart_options = &(data->transport_options);
958 return 0;
962 * Linux pipes can buffer 65536 bytes at once (and most platforms can
963 * buffer less), so attempt reads and writes with up to that size.
965 #define BUFFERSIZE 65536
966 /* This should be enough to hold debugging message. */
967 #define PBUFFERSIZE 8192
969 /* Print bidirectional transfer loop debug message. */
970 static void transfer_debug(const char *fmt, ...)
972 va_list args;
973 char msgbuf[PBUFFERSIZE];
974 static int debug_enabled = -1;
976 if (debug_enabled < 0)
977 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
978 if (!debug_enabled)
979 return;
981 va_start(args, fmt);
982 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
983 va_end(args);
984 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
987 /* Stream state: More data may be coming in this direction. */
988 #define SSTATE_TRANSFERING 0
990 * Stream state: No more data coming in this direction, flushing rest of
991 * data.
993 #define SSTATE_FLUSHING 1
994 /* Stream state: Transfer in this direction finished. */
995 #define SSTATE_FINISHED 2
997 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
998 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
999 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1001 /* Unidirectional transfer. */
1002 struct unidirectional_transfer {
1003 /* Source */
1004 int src;
1005 /* Destination */
1006 int dest;
1007 /* Is source socket? */
1008 int src_is_sock;
1009 /* Is destination socket? */
1010 int dest_is_sock;
1011 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
1012 int state;
1013 /* Buffer. */
1014 char buf[BUFFERSIZE];
1015 /* Buffer used. */
1016 size_t bufuse;
1017 /* Name of source. */
1018 const char *src_name;
1019 /* Name of destination. */
1020 const char *dest_name;
1023 /* Closes the target (for writing) if transfer has finished. */
1024 static void udt_close_if_finished(struct unidirectional_transfer *t)
1026 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1027 t->state = SSTATE_FINISHED;
1028 if (t->dest_is_sock)
1029 shutdown(t->dest, SHUT_WR);
1030 else
1031 close(t->dest);
1032 transfer_debug("Closed %s.", t->dest_name);
1037 * Tries to read read data from source into buffer. If buffer is full,
1038 * no data is read. Returns 0 on success, -1 on error.
1040 static int udt_do_read(struct unidirectional_transfer *t)
1042 ssize_t bytes;
1044 if (t->bufuse == BUFFERSIZE)
1045 return 0; /* No space for more. */
1047 transfer_debug("%s is readable", t->src_name);
1048 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1049 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1050 errno != EINTR) {
1051 error("read(%s) failed: %s", t->src_name, strerror(errno));
1052 return -1;
1053 } else if (bytes == 0) {
1054 transfer_debug("%s EOF (with %i bytes in buffer)",
1055 t->src_name, t->bufuse);
1056 t->state = SSTATE_FLUSHING;
1057 } else if (bytes > 0) {
1058 t->bufuse += bytes;
1059 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1060 (int)bytes, t->src_name, (int)t->bufuse);
1062 return 0;
1065 /* Tries to write data from buffer into destination. If buffer is empty,
1066 * no data is written. Returns 0 on success, -1 on error.
1068 static int udt_do_write(struct unidirectional_transfer *t)
1070 ssize_t bytes;
1072 if (t->bufuse == 0)
1073 return 0; /* Nothing to write. */
1075 transfer_debug("%s is writable", t->dest_name);
1076 bytes = write(t->dest, t->buf, t->bufuse);
1077 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1078 errno != EINTR) {
1079 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1080 return -1;
1081 } else if (bytes > 0) {
1082 t->bufuse -= bytes;
1083 if (t->bufuse)
1084 memmove(t->buf, t->buf + bytes, t->bufuse);
1085 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1086 (int)bytes, t->dest_name, (int)t->bufuse);
1088 return 0;
1092 /* State of bidirectional transfer loop. */
1093 struct bidirectional_transfer_state {
1094 /* Direction from program to git. */
1095 struct unidirectional_transfer ptg;
1096 /* Direction from git to program. */
1097 struct unidirectional_transfer gtp;
1100 static void *udt_copy_task_routine(void *udt)
1102 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1103 while (t->state != SSTATE_FINISHED) {
1104 if (STATE_NEEDS_READING(t->state))
1105 if (udt_do_read(t))
1106 return NULL;
1107 if (STATE_NEEDS_WRITING(t->state))
1108 if (udt_do_write(t))
1109 return NULL;
1110 if (STATE_NEEDS_CLOSING(t->state))
1111 udt_close_if_finished(t);
1113 return udt; /* Just some non-NULL value. */
1116 #ifndef NO_PTHREADS
1119 * Join thread, with apporiate errors on failure. Name is name for the
1120 * thread (for error messages). Returns 0 on success, 1 on failure.
1122 static int tloop_join(pthread_t thread, const char *name)
1124 int err;
1125 void *tret;
1126 err = pthread_join(thread, &tret);
1127 if (!tret) {
1128 error("%s thread failed", name);
1129 return 1;
1131 if (err) {
1132 error("%s thread failed to join: %s", name, strerror(err));
1133 return 1;
1135 return 0;
1139 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1140 * -1 on failure.
1142 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1144 pthread_t gtp_thread;
1145 pthread_t ptg_thread;
1146 int err;
1147 int ret = 0;
1148 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1149 &s->gtp);
1150 if (err)
1151 die("Can't start thread for copying data: %s", strerror(err));
1152 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1153 &s->ptg);
1154 if (err)
1155 die("Can't start thread for copying data: %s", strerror(err));
1157 ret |= tloop_join(gtp_thread, "Git to program copy");
1158 ret |= tloop_join(ptg_thread, "Program to git copy");
1159 return ret;
1161 #else
1163 /* Close the source and target (for writing) for transfer. */
1164 static void udt_kill_transfer(struct unidirectional_transfer *t)
1166 t->state = SSTATE_FINISHED;
1168 * Socket read end left open isn't a disaster if nobody
1169 * attempts to read from it (mingw compat headers do not
1170 * have SHUT_RD)...
1172 * We can't fully close the socket since otherwise gtp
1173 * task would first close the socket it sends data to
1174 * while closing the ptg file descriptors.
1176 if (!t->src_is_sock)
1177 close(t->src);
1178 if (t->dest_is_sock)
1179 shutdown(t->dest, SHUT_WR);
1180 else
1181 close(t->dest);
1185 * Join process, with apporiate errors on failure. Name is name for the
1186 * process (for error messages). Returns 0 on success, 1 on failure.
1188 static int tloop_join(pid_t pid, const char *name)
1190 int tret;
1191 if (waitpid(pid, &tret, 0) < 0) {
1192 error("%s process failed to wait: %s", name, strerror(errno));
1193 return 1;
1195 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1196 error("%s process failed", name);
1197 return 1;
1199 return 0;
1203 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1204 * -1 on failure.
1206 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1208 pid_t pid1, pid2;
1209 int ret = 0;
1211 /* Fork thread #1: git to program. */
1212 pid1 = fork();
1213 if (pid1 < 0)
1214 die_errno("Can't start thread for copying data");
1215 else if (pid1 == 0) {
1216 udt_kill_transfer(&s->ptg);
1217 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1220 /* Fork thread #2: program to git. */
1221 pid2 = fork();
1222 if (pid2 < 0)
1223 die_errno("Can't start thread for copying data");
1224 else if (pid2 == 0) {
1225 udt_kill_transfer(&s->gtp);
1226 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1230 * Close both streams in parent as to not interfere with
1231 * end of file detection and wait for both tasks to finish.
1233 udt_kill_transfer(&s->gtp);
1234 udt_kill_transfer(&s->ptg);
1235 ret |= tloop_join(pid1, "Git to program copy");
1236 ret |= tloop_join(pid2, "Program to git copy");
1237 return ret;
1239 #endif
1242 * Copies data from stdin to output and from input to stdout simultaneously.
1243 * Additionally filtering through given filter. If filter is NULL, uses
1244 * identity filter.
1246 int bidirectional_transfer_loop(int input, int output)
1248 struct bidirectional_transfer_state state;
1250 /* Fill the state fields. */
1251 state.ptg.src = input;
1252 state.ptg.dest = 1;
1253 state.ptg.src_is_sock = (input == output);
1254 state.ptg.dest_is_sock = 0;
1255 state.ptg.state = SSTATE_TRANSFERING;
1256 state.ptg.bufuse = 0;
1257 state.ptg.src_name = "remote input";
1258 state.ptg.dest_name = "stdout";
1260 state.gtp.src = 0;
1261 state.gtp.dest = output;
1262 state.gtp.src_is_sock = 0;
1263 state.gtp.dest_is_sock = (input == output);
1264 state.gtp.state = SSTATE_TRANSFERING;
1265 state.gtp.bufuse = 0;
1266 state.gtp.src_name = "stdin";
1267 state.gtp.dest_name = "remote output";
1269 return tloop_spawnwait_tasks(&state);