msysGit-based Git for Windows 1.x was superseded by Git for Windows 2.x
[git/mingw/4msysgit.git] / transport-helper.c
blob9bf11e46298bd631a29a2971a9f44cdbfad59f0d
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;
17 /* TODO: put somewhere sensible, e.g. git_transport_options? */
18 static int auto_gc = 1;
20 struct helper_data {
21 const char *name;
22 struct child_process *helper;
23 FILE *out;
24 unsigned fetch : 1,
25 import : 1,
26 bidi_import : 1,
27 export : 1,
28 option : 1,
29 push : 1,
30 connect : 1,
31 signed_tags : 1,
32 check_connectivity : 1,
33 no_disconnect_req : 1,
34 no_private_update : 1;
35 char *export_marks;
36 char *import_marks;
37 /* These go from remote name (as in "list") to private name */
38 struct refspec *refspecs;
39 int refspec_nr;
40 /* Transport options for fetch-pack/send-pack (should one of
41 * those be invoked).
43 struct git_transport_options transport_options;
46 static void sendline(struct helper_data *helper, struct strbuf *buffer)
48 if (debug)
49 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
50 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
51 != buffer->len)
52 die_errno("Full write to remote helper failed");
55 static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
57 strbuf_reset(buffer);
58 if (debug)
59 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
60 if (strbuf_getline(buffer, helper, '\n') == EOF) {
61 if (debug)
62 fprintf(stderr, "Debug: Remote helper quit.\n");
63 return 1;
66 if (debug)
67 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
68 return 0;
71 static int recvline(struct helper_data *helper, struct strbuf *buffer)
73 return recvline_fh(helper->out, buffer, helper->name);
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 strbuf buf = STRBUF_INIT;
107 struct child_process *helper;
108 const char **refspecs = NULL;
109 int refspec_nr = 0;
110 int refspec_alloc = 0;
111 int duped;
112 int code;
113 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
114 const char *helper_env[] = {
115 git_dir_buf,
116 NULL
120 if (data->helper)
121 return data->helper;
123 helper = xcalloc(1, sizeof(*helper));
124 helper->in = -1;
125 helper->out = -1;
126 helper->err = 0;
127 argv_array_pushf(&helper->args, "git-remote-%s", data->name);
128 argv_array_push(&helper->args, transport->remote->name);
129 argv_array_push(&helper->args, remove_ext_force(transport->url));
130 helper->git_cmd = 0;
131 helper->silent_exec_failure = 1;
133 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
134 helper->env = helper_env;
136 code = start_command(helper);
137 if (code < 0 && errno == ENOENT)
138 die("Unable to find remote helper for '%s'", data->name);
139 else if (code != 0)
140 exit(code);
142 data->helper = helper;
143 data->no_disconnect_req = 0;
146 * Open the output as FILE* so strbuf_getline() can be used.
147 * Do this with duped fd because fclose() will close the fd,
148 * and stuff like taking over will require the fd to remain.
150 duped = dup(helper->out);
151 if (duped < 0)
152 die_errno("Can't dup helper output fd");
153 data->out = xfdopen(duped, "r");
155 write_constant(helper->in, "capabilities\n");
157 while (1) {
158 const char *capname, *arg;
159 int mandatory = 0;
160 if (recvline(data, &buf))
161 exit(128);
163 if (!*buf.buf)
164 break;
166 if (*buf.buf == '*') {
167 capname = buf.buf + 1;
168 mandatory = 1;
169 } else
170 capname = buf.buf;
172 if (debug)
173 fprintf(stderr, "Debug: Got cap %s\n", capname);
174 if (!strcmp(capname, "fetch"))
175 data->fetch = 1;
176 else if (!strcmp(capname, "option"))
177 data->option = 1;
178 else if (!strcmp(capname, "push"))
179 data->push = 1;
180 else if (!strcmp(capname, "import"))
181 data->import = 1;
182 else if (!strcmp(capname, "bidi-import"))
183 data->bidi_import = 1;
184 else if (!strcmp(capname, "export"))
185 data->export = 1;
186 else if (!strcmp(capname, "check-connectivity"))
187 data->check_connectivity = 1;
188 else if (!data->refspecs && skip_prefix(capname, "refspec ", &arg)) {
189 ALLOC_GROW(refspecs,
190 refspec_nr + 1,
191 refspec_alloc);
192 refspecs[refspec_nr++] = xstrdup(arg);
193 } else if (!strcmp(capname, "connect")) {
194 data->connect = 1;
195 } else if (!strcmp(capname, "signed-tags")) {
196 data->signed_tags = 1;
197 } else if (skip_prefix(capname, "export-marks ", &arg)) {
198 data->export_marks = xstrdup(arg);
199 } else if (skip_prefix(capname, "import-marks ", &arg)) {
200 data->import_marks = xstrdup(arg);
201 } else if (starts_with(capname, "no-private-update")) {
202 data->no_private_update = 1;
203 } else if (mandatory) {
204 die("Unknown mandatory capability %s. This remote "
205 "helper probably needs newer version of Git.",
206 capname);
209 if (refspecs) {
210 int i;
211 data->refspec_nr = refspec_nr;
212 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
213 for (i = 0; i < refspec_nr; i++)
214 free((char *)refspecs[i]);
215 free(refspecs);
216 } else if (data->import || data->bidi_import || data->export) {
217 warning("This remote helper should implement refspec capability.");
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 free(data->helper);
249 data->helper = NULL;
251 return res;
254 static const char *unsupported_options[] = {
255 TRANS_OPT_UPLOADPACK,
256 TRANS_OPT_RECEIVEPACK,
257 TRANS_OPT_THIN,
258 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 sendline(data, &buf);
299 if (recvline(data, &buf))
300 exit(128);
302 if (!strcmp(buf.buf, "ok"))
303 ret = 0;
304 else if (starts_with(buf.buf, "error")) {
305 ret = -1;
306 } else if (!strcmp(buf.buf, "unsupported"))
307 ret = 1;
308 else {
309 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
310 ret = 1;
312 strbuf_release(&buf);
313 return ret;
316 static void standard_options(struct transport *t)
318 char buf[16];
319 int n;
320 int v = t->verbose;
322 set_helper_option(t, "progress", t->progress ? "true" : "false");
324 n = snprintf(buf, sizeof(buf), "%d", v + 1);
325 if (n >= sizeof(buf))
326 die("impossibly large verbosity value");
327 set_helper_option(t, "verbosity", buf);
330 static int release_helper(struct transport *transport)
332 int res = 0;
333 struct helper_data *data = transport->data;
334 free_refspec(data->refspec_nr, data->refspecs);
335 data->refspecs = NULL;
336 res = disconnect_helper(transport);
337 free(transport->data);
338 return res;
341 static int fetch_with_fetch(struct transport *transport,
342 int nr_heads, struct ref **to_fetch)
344 struct helper_data *data = transport->data;
345 int i;
346 struct strbuf buf = STRBUF_INIT;
348 standard_options(transport);
349 if (data->check_connectivity &&
350 data->transport_options.check_self_contained_and_connected)
351 set_helper_option(transport, "check-connectivity", "true");
353 if (transport->cloning)
354 set_helper_option(transport, "cloning", "true");
356 if (data->transport_options.update_shallow)
357 set_helper_option(transport, "update-shallow", "true");
359 for (i = 0; i < nr_heads; i++) {
360 const struct ref *posn = to_fetch[i];
361 if (posn->status & REF_STATUS_UPTODATE)
362 continue;
364 strbuf_addf(&buf, "fetch %s %s\n",
365 sha1_to_hex(posn->old_sha1), posn->name);
368 strbuf_addch(&buf, '\n');
369 sendline(data, &buf);
371 while (1) {
372 if (recvline(data, &buf))
373 exit(128);
375 if (starts_with(buf.buf, "lock ")) {
376 const char *name = buf.buf + 5;
377 if (transport->pack_lockfile)
378 warning("%s also locked %s", data->name, name);
379 else
380 transport->pack_lockfile = xstrdup(name);
382 else if (data->check_connectivity &&
383 data->transport_options.check_self_contained_and_connected &&
384 !strcmp(buf.buf, "connectivity-ok"))
385 data->transport_options.self_contained_and_connected = 1;
386 else if (!buf.len)
387 break;
388 else
389 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
391 strbuf_release(&buf);
392 return 0;
395 static int get_importer(struct transport *transport, struct child_process *fastimport)
397 struct child_process *helper = get_helper(transport);
398 struct helper_data *data = transport->data;
399 int cat_blob_fd, code;
400 memset(fastimport, 0, sizeof(*fastimport));
401 fastimport->in = helper->out;
402 argv_array_push(&fastimport->args, "fast-import");
403 argv_array_push(&fastimport->args, debug ? "--stats" : "--quiet");
405 if (data->bidi_import) {
406 cat_blob_fd = xdup(helper->in);
407 argv_array_pushf(&fastimport->args, "--cat-blob-fd=%d", cat_blob_fd);
409 fastimport->git_cmd = 1;
411 code = start_command(fastimport);
412 return code;
415 static int get_exporter(struct transport *transport,
416 struct child_process *fastexport,
417 struct string_list *revlist_args)
419 struct helper_data *data = transport->data;
420 struct child_process *helper = get_helper(transport);
421 int i;
423 memset(fastexport, 0, sizeof(*fastexport));
425 /* we need to duplicate helper->in because we want to use it after
426 * fastexport is done with it. */
427 fastexport->out = dup(helper->in);
428 argv_array_push(&fastexport->args, "fast-export");
429 argv_array_push(&fastexport->args, "--use-done-feature");
430 argv_array_push(&fastexport->args, data->signed_tags ?
431 "--signed-tags=verbatim" : "--signed-tags=warn-strip");
432 if (data->export_marks)
433 argv_array_pushf(&fastexport->args, "--export-marks=%s.tmp", data->export_marks);
434 if (data->import_marks)
435 argv_array_pushf(&fastexport->args, "--import-marks=%s", data->import_marks);
437 for (i = 0; i < revlist_args->nr; i++)
438 argv_array_push(&fastexport->args, revlist_args->items[i].string);
440 argv_array_push(&fastexport->args, "--");
442 fastexport->git_cmd = 1;
443 return start_command(fastexport);
446 static void check_helper_status(struct helper_data *data)
448 int pid, status;
450 pid = waitpid(data->helper->pid, &status, WNOHANG);
451 if (pid < 0)
452 die("Could not retrieve status of remote helper '%s'",
453 data->name);
454 if (pid > 0 && WIFEXITED(status))
455 die("Remote helper '%s' died with %d",
456 data->name, WEXITSTATUS(status));
459 static int fetch_with_import(struct transport *transport,
460 int nr_heads, struct ref **to_fetch)
462 struct child_process fastimport;
463 struct helper_data *data = transport->data;
464 int i;
465 struct ref *posn;
466 struct strbuf buf = STRBUF_INIT;
468 get_helper(transport);
470 if (get_importer(transport, &fastimport))
471 die("Couldn't run fast-import");
473 for (i = 0; i < nr_heads; i++) {
474 posn = to_fetch[i];
475 if (posn->status & REF_STATUS_UPTODATE)
476 continue;
478 strbuf_addf(&buf, "import %s\n", posn->name);
479 sendline(data, &buf);
480 strbuf_reset(&buf);
483 write_constant(data->helper->in, "\n");
485 * remote-helpers that advertise the bidi-import capability are required to
486 * buffer the complete batch of import commands until this newline before
487 * sending data to fast-import.
488 * These helpers read back data from fast-import on their stdin, which could
489 * be mixed with import commands, otherwise.
492 if (finish_command(&fastimport))
493 die("Error while running fast-import");
494 check_helper_status(data);
497 * The fast-import stream of a remote helper that advertises
498 * the "refspec" capability writes to the refs named after the
499 * right hand side of the first refspec matching each ref we
500 * were fetching.
502 * (If no "refspec" capability was specified, for historical
503 * reasons we default to the equivalent of *:*.)
505 * Store the result in to_fetch[i].old_sha1. Callers such
506 * as "git fetch" can use the value to write feedback to the
507 * terminal, populate FETCH_HEAD, and determine what new value
508 * should be written to peer_ref if the update is a
509 * fast-forward or this is a forced update.
511 for (i = 0; i < nr_heads; i++) {
512 char *private;
513 posn = to_fetch[i];
514 if (posn->status & REF_STATUS_UPTODATE)
515 continue;
516 if (data->refspecs)
517 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
518 else
519 private = xstrdup(posn->name);
520 if (private) {
521 read_ref(private, posn->old_sha1);
522 free(private);
525 strbuf_release(&buf);
526 if (auto_gc) {
527 const char *argv_gc_auto[] = {
528 "gc", "--auto", "--quiet", NULL,
530 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
532 return 0;
535 static int process_connect_service(struct transport *transport,
536 const char *name, const char *exec)
538 struct helper_data *data = transport->data;
539 struct strbuf cmdbuf = STRBUF_INIT;
540 struct child_process *helper;
541 int r, duped, ret = 0;
542 FILE *input;
544 helper = get_helper(transport);
547 * Yes, dup the pipe another time, as we need unbuffered version
548 * of input pipe as FILE*. fclose() closes the underlying fd and
549 * stream buffering only can be changed before first I/O operation
550 * on it.
552 duped = dup(helper->out);
553 if (duped < 0)
554 die_errno("Can't dup helper output fd");
555 input = xfdopen(duped, "r");
556 setvbuf(input, NULL, _IONBF, 0);
559 * Handle --upload-pack and friends. This is fire and forget...
560 * just warn if it fails.
562 if (strcmp(name, exec)) {
563 r = set_helper_option(transport, "servpath", exec);
564 if (r > 0)
565 warning("Setting remote service path not supported by protocol.");
566 else if (r < 0)
567 warning("Invalid remote service path.");
570 if (data->connect)
571 strbuf_addf(&cmdbuf, "connect %s\n", name);
572 else
573 goto exit;
575 sendline(data, &cmdbuf);
576 if (recvline_fh(input, &cmdbuf, name))
577 exit(128);
579 if (!strcmp(cmdbuf.buf, "")) {
580 data->no_disconnect_req = 1;
581 if (debug)
582 fprintf(stderr, "Debug: Smart transport connection "
583 "ready.\n");
584 ret = 1;
585 } else if (!strcmp(cmdbuf.buf, "fallback")) {
586 if (debug)
587 fprintf(stderr, "Debug: Falling back to dumb "
588 "transport.\n");
589 } else
590 die("Unknown response to connect: %s",
591 cmdbuf.buf);
593 exit:
594 fclose(input);
595 return ret;
598 static int process_connect(struct transport *transport,
599 int for_push)
601 struct helper_data *data = transport->data;
602 const char *name;
603 const char *exec;
605 name = for_push ? "git-receive-pack" : "git-upload-pack";
606 if (for_push)
607 exec = data->transport_options.receivepack;
608 else
609 exec = data->transport_options.uploadpack;
611 return process_connect_service(transport, name, exec);
614 static int connect_helper(struct transport *transport, const char *name,
615 const char *exec, int fd[2])
617 struct helper_data *data = transport->data;
619 /* Get_helper so connect is inited. */
620 get_helper(transport);
621 if (!data->connect)
622 die("Operation not supported by protocol.");
624 if (!process_connect_service(transport, name, exec))
625 die("Can't connect to subservice %s.", name);
627 fd[0] = data->helper->out;
628 fd[1] = data->helper->in;
629 return 0;
632 static int fetch(struct transport *transport,
633 int nr_heads, struct ref **to_fetch)
635 struct helper_data *data = transport->data;
636 int i, count;
638 if (process_connect(transport, 0)) {
639 do_take_over(transport);
640 return transport->fetch(transport, nr_heads, to_fetch);
643 count = 0;
644 for (i = 0; i < nr_heads; i++)
645 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
646 count++;
648 if (!count)
649 return 0;
651 if (data->fetch)
652 return fetch_with_fetch(transport, nr_heads, to_fetch);
654 if (data->import)
655 return fetch_with_import(transport, nr_heads, to_fetch);
657 return -1;
660 static int push_update_ref_status(struct strbuf *buf,
661 struct ref **ref,
662 struct ref *remote_refs)
664 char *refname, *msg;
665 int status, forced = 0;
667 if (starts_with(buf->buf, "ok ")) {
668 status = REF_STATUS_OK;
669 refname = buf->buf + 3;
670 } else if (starts_with(buf->buf, "error ")) {
671 status = REF_STATUS_REMOTE_REJECT;
672 refname = buf->buf + 6;
673 } else
674 die("expected ok/error, helper said '%s'", buf->buf);
676 msg = strchr(refname, ' ');
677 if (msg) {
678 struct strbuf msg_buf = STRBUF_INIT;
679 const char *end;
681 *msg++ = '\0';
682 if (!unquote_c_style(&msg_buf, msg, &end))
683 msg = strbuf_detach(&msg_buf, NULL);
684 else
685 msg = xstrdup(msg);
686 strbuf_release(&msg_buf);
688 if (!strcmp(msg, "no match")) {
689 status = REF_STATUS_NONE;
690 free(msg);
691 msg = NULL;
693 else if (!strcmp(msg, "up to date")) {
694 status = REF_STATUS_UPTODATE;
695 free(msg);
696 msg = NULL;
698 else if (!strcmp(msg, "non-fast forward")) {
699 status = REF_STATUS_REJECT_NONFASTFORWARD;
700 free(msg);
701 msg = NULL;
703 else if (!strcmp(msg, "already exists")) {
704 status = REF_STATUS_REJECT_ALREADY_EXISTS;
705 free(msg);
706 msg = NULL;
708 else if (!strcmp(msg, "fetch first")) {
709 status = REF_STATUS_REJECT_FETCH_FIRST;
710 free(msg);
711 msg = NULL;
713 else if (!strcmp(msg, "needs force")) {
714 status = REF_STATUS_REJECT_NEEDS_FORCE;
715 free(msg);
716 msg = NULL;
718 else if (!strcmp(msg, "stale info")) {
719 status = REF_STATUS_REJECT_STALE;
720 free(msg);
721 msg = NULL;
723 else if (!strcmp(msg, "forced update")) {
724 forced = 1;
725 free(msg);
726 msg = NULL;
730 if (*ref)
731 *ref = find_ref_by_name(*ref, refname);
732 if (!*ref)
733 *ref = find_ref_by_name(remote_refs, refname);
734 if (!*ref) {
735 warning("helper reported unexpected status of %s", refname);
736 return 1;
739 if ((*ref)->status != REF_STATUS_NONE) {
741 * Earlier, the ref was marked not to be pushed, so ignore the ref
742 * status reported by the remote helper if the latter is 'no match'.
744 if (status == REF_STATUS_NONE)
745 return 1;
748 (*ref)->status = status;
749 (*ref)->forced_update |= forced;
750 (*ref)->remote_status = msg;
751 return !(status == REF_STATUS_OK);
754 static int push_update_refs_status(struct helper_data *data,
755 struct ref *remote_refs,
756 int flags)
758 struct strbuf buf = STRBUF_INIT;
759 struct ref *ref = remote_refs;
760 int ret = 0;
762 for (;;) {
763 char *private;
765 if (recvline(data, &buf)) {
766 ret = 1;
767 break;
770 if (!buf.len)
771 break;
773 if (push_update_ref_status(&buf, &ref, remote_refs))
774 continue;
776 if (flags & TRANSPORT_PUSH_DRY_RUN || !data->refspecs || data->no_private_update)
777 continue;
779 /* propagate back the update to the remote namespace */
780 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
781 if (!private)
782 continue;
783 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
784 free(private);
786 strbuf_release(&buf);
787 return ret;
790 static int push_refs_with_push(struct transport *transport,
791 struct ref *remote_refs, int flags)
793 int force_all = flags & TRANSPORT_PUSH_FORCE;
794 int mirror = flags & TRANSPORT_PUSH_MIRROR;
795 struct helper_data *data = transport->data;
796 struct strbuf buf = STRBUF_INIT;
797 struct ref *ref;
798 struct string_list cas_options = STRING_LIST_INIT_DUP;
799 struct string_list_item *cas_option;
801 get_helper(transport);
802 if (!data->push)
803 return 1;
805 for (ref = remote_refs; ref; ref = ref->next) {
806 if (!ref->peer_ref && !mirror)
807 continue;
809 /* Check for statuses set by set_ref_status_for_push() */
810 switch (ref->status) {
811 case REF_STATUS_REJECT_NONFASTFORWARD:
812 case REF_STATUS_REJECT_STALE:
813 case REF_STATUS_REJECT_ALREADY_EXISTS:
814 case REF_STATUS_UPTODATE:
815 continue;
816 default:
817 ; /* do nothing */
820 if (force_all)
821 ref->force = 1;
823 strbuf_addstr(&buf, "push ");
824 if (!ref->deletion) {
825 if (ref->force)
826 strbuf_addch(&buf, '+');
827 if (ref->peer_ref)
828 strbuf_addstr(&buf, ref->peer_ref->name);
829 else
830 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
832 strbuf_addch(&buf, ':');
833 strbuf_addstr(&buf, ref->name);
834 strbuf_addch(&buf, '\n');
837 * The "--force-with-lease" options without explicit
838 * values to expect have already been expanded into
839 * the ref->old_sha1_expect[] field; we can ignore
840 * transport->smart_options->cas altogether and instead
841 * can enumerate them from the refs.
843 if (ref->expect_old_sha1) {
844 struct strbuf cas = STRBUF_INIT;
845 strbuf_addf(&cas, "%s:%s",
846 ref->name, sha1_to_hex(ref->old_sha1_expect));
847 string_list_append(&cas_options, strbuf_detach(&cas, NULL));
850 if (buf.len == 0) {
851 string_list_clear(&cas_options, 0);
852 return 0;
855 standard_options(transport);
856 for_each_string_list_item(cas_option, &cas_options)
857 set_helper_option(transport, "cas", cas_option->string);
859 if (flags & TRANSPORT_PUSH_DRY_RUN) {
860 if (set_helper_option(transport, "dry-run", "true") != 0)
861 die("helper %s does not support dry-run", data->name);
864 strbuf_addch(&buf, '\n');
865 sendline(data, &buf);
866 strbuf_release(&buf);
868 return push_update_refs_status(data, remote_refs, flags);
871 static int push_refs_with_export(struct transport *transport,
872 struct ref *remote_refs, int flags)
874 struct ref *ref;
875 struct child_process *helper, exporter;
876 struct helper_data *data = transport->data;
877 struct string_list revlist_args = STRING_LIST_INIT_DUP;
878 struct strbuf buf = STRBUF_INIT;
880 if (!data->refspecs)
881 die("remote-helper doesn't support push; refspec needed");
883 if (flags & TRANSPORT_PUSH_DRY_RUN) {
884 if (set_helper_option(transport, "dry-run", "true") != 0)
885 die("helper %s does not support dry-run", data->name);
888 if (flags & TRANSPORT_PUSH_FORCE) {
889 if (set_helper_option(transport, "force", "true") != 0)
890 warning("helper %s does not support 'force'", data->name);
893 helper = get_helper(transport);
895 write_constant(helper->in, "export\n");
897 for (ref = remote_refs; ref; ref = ref->next) {
898 char *private;
899 unsigned char sha1[20];
901 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
902 if (private && !get_sha1(private, sha1)) {
903 strbuf_addf(&buf, "^%s", private);
904 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
905 hashcpy(ref->old_sha1, sha1);
907 free(private);
909 if (ref->peer_ref) {
910 if (strcmp(ref->name, ref->peer_ref->name)) {
911 if (!ref->deletion) {
912 const char *name;
913 int flag;
915 /* Follow symbolic refs (mainly for HEAD). */
916 name = resolve_ref_unsafe(ref->peer_ref->name, sha1, 1, &flag);
917 if (!name || !(flag & REF_ISSYMREF))
918 name = ref->peer_ref->name;
920 strbuf_addf(&buf, "%s:%s", name, ref->name);
921 } else
922 strbuf_addf(&buf, ":%s", ref->name);
924 string_list_append(&revlist_args, "--refspec");
925 string_list_append(&revlist_args, buf.buf);
926 strbuf_release(&buf);
928 if (!ref->deletion)
929 string_list_append(&revlist_args, ref->peer_ref->name);
933 if (get_exporter(transport, &exporter, &revlist_args))
934 die("Couldn't run fast-export");
936 string_list_clear(&revlist_args, 1);
938 if (finish_command(&exporter))
939 die("Error while running fast-export");
940 check_helper_status(data);
941 if (push_update_refs_status(data, remote_refs, flags))
942 return 1;
944 if (data->export_marks) {
945 strbuf_addf(&buf, "%s.tmp", data->export_marks);
946 rename(buf.buf, data->export_marks);
947 strbuf_release(&buf);
950 return 0;
953 static int push_refs(struct transport *transport,
954 struct ref *remote_refs, int flags)
956 struct helper_data *data = transport->data;
958 if (process_connect(transport, 1)) {
959 do_take_over(transport);
960 return transport->push_refs(transport, remote_refs, flags);
963 if (!remote_refs) {
964 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
965 "Perhaps you should specify a branch such as 'master'.\n");
966 return 0;
969 if (data->push)
970 return push_refs_with_push(transport, remote_refs, flags);
972 if (data->export)
973 return push_refs_with_export(transport, remote_refs, flags);
975 return -1;
979 static int has_attribute(const char *attrs, const char *attr) {
980 int len;
981 if (!attrs)
982 return 0;
984 len = strlen(attr);
985 for (;;) {
986 const char *space = strchrnul(attrs, ' ');
987 if (len == space - attrs && !strncmp(attrs, attr, len))
988 return 1;
989 if (!*space)
990 return 0;
991 attrs = space + 1;
995 static struct ref *get_refs_list(struct transport *transport, int for_push)
997 struct helper_data *data = transport->data;
998 struct child_process *helper;
999 struct ref *ret = NULL;
1000 struct ref **tail = &ret;
1001 struct ref *posn;
1002 struct strbuf buf = STRBUF_INIT;
1004 helper = get_helper(transport);
1006 if (process_connect(transport, for_push)) {
1007 do_take_over(transport);
1008 return transport->get_refs_list(transport, for_push);
1011 if (data->push && for_push)
1012 write_str_in_full(helper->in, "list for-push\n");
1013 else
1014 write_str_in_full(helper->in, "list\n");
1016 while (1) {
1017 char *eov, *eon;
1018 if (recvline(data, &buf))
1019 exit(128);
1021 if (!*buf.buf)
1022 break;
1024 eov = strchr(buf.buf, ' ');
1025 if (!eov)
1026 die("Malformed response in ref list: %s", buf.buf);
1027 eon = strchr(eov + 1, ' ');
1028 *eov = '\0';
1029 if (eon)
1030 *eon = '\0';
1031 *tail = alloc_ref(eov + 1);
1032 if (buf.buf[0] == '@')
1033 (*tail)->symref = xstrdup(buf.buf + 1);
1034 else if (buf.buf[0] != '?')
1035 get_sha1_hex(buf.buf, (*tail)->old_sha1);
1036 if (eon) {
1037 if (has_attribute(eon + 1, "unchanged")) {
1038 (*tail)->status |= REF_STATUS_UPTODATE;
1039 read_ref((*tail)->name, (*tail)->old_sha1);
1042 tail = &((*tail)->next);
1044 if (debug)
1045 fprintf(stderr, "Debug: Read ref listing.\n");
1046 strbuf_release(&buf);
1048 for (posn = ret; posn; posn = posn->next)
1049 resolve_remote_symref(posn, ret);
1051 return ret;
1054 int transport_helper_init(struct transport *transport, const char *name)
1056 struct helper_data *data = xcalloc(1, sizeof(*data));
1057 data->name = name;
1059 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1060 debug = 1;
1062 transport->data = data;
1063 transport->set_option = set_helper_option;
1064 transport->get_refs_list = get_refs_list;
1065 transport->fetch = fetch;
1066 transport->push_refs = push_refs;
1067 transport->disconnect = release_helper;
1068 transport->connect = connect_helper;
1069 transport->smart_options = &(data->transport_options);
1070 return 0;
1074 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1075 * buffer less), so attempt reads and writes with up to that size.
1077 #define BUFFERSIZE 65536
1078 /* This should be enough to hold debugging message. */
1079 #define PBUFFERSIZE 8192
1081 /* Print bidirectional transfer loop debug message. */
1082 __attribute__((format (printf, 1, 2)))
1083 static void transfer_debug(const char *fmt, ...)
1085 va_list args;
1086 char msgbuf[PBUFFERSIZE];
1087 static int debug_enabled = -1;
1089 if (debug_enabled < 0)
1090 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1091 if (!debug_enabled)
1092 return;
1094 va_start(args, fmt);
1095 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1096 va_end(args);
1097 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1100 /* Stream state: More data may be coming in this direction. */
1101 #define SSTATE_TRANSFERING 0
1103 * Stream state: No more data coming in this direction, flushing rest of
1104 * data.
1106 #define SSTATE_FLUSHING 1
1107 /* Stream state: Transfer in this direction finished. */
1108 #define SSTATE_FINISHED 2
1110 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1111 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1112 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1114 /* Unidirectional transfer. */
1115 struct unidirectional_transfer {
1116 /* Source */
1117 int src;
1118 /* Destination */
1119 int dest;
1120 /* Is source socket? */
1121 int src_is_sock;
1122 /* Is destination socket? */
1123 int dest_is_sock;
1124 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1125 int state;
1126 /* Buffer. */
1127 char buf[BUFFERSIZE];
1128 /* Buffer used. */
1129 size_t bufuse;
1130 /* Name of source. */
1131 const char *src_name;
1132 /* Name of destination. */
1133 const char *dest_name;
1136 /* Closes the target (for writing) if transfer has finished. */
1137 static void udt_close_if_finished(struct unidirectional_transfer *t)
1139 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1140 t->state = SSTATE_FINISHED;
1141 if (t->dest_is_sock)
1142 shutdown(t->dest, SHUT_WR);
1143 else
1144 close(t->dest);
1145 transfer_debug("Closed %s.", t->dest_name);
1150 * Tries to read read data from source into buffer. If buffer is full,
1151 * no data is read. Returns 0 on success, -1 on error.
1153 static int udt_do_read(struct unidirectional_transfer *t)
1155 ssize_t bytes;
1157 if (t->bufuse == BUFFERSIZE)
1158 return 0; /* No space for more. */
1160 transfer_debug("%s is readable", t->src_name);
1161 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1162 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1163 errno != EINTR) {
1164 error("read(%s) failed: %s", t->src_name, strerror(errno));
1165 return -1;
1166 } else if (bytes == 0) {
1167 transfer_debug("%s EOF (with %i bytes in buffer)",
1168 t->src_name, (int)t->bufuse);
1169 t->state = SSTATE_FLUSHING;
1170 } else if (bytes > 0) {
1171 t->bufuse += bytes;
1172 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1173 (int)bytes, t->src_name, (int)t->bufuse);
1175 return 0;
1178 /* Tries to write data from buffer into destination. If buffer is empty,
1179 * no data is written. Returns 0 on success, -1 on error.
1181 static int udt_do_write(struct unidirectional_transfer *t)
1183 ssize_t bytes;
1185 if (t->bufuse == 0)
1186 return 0; /* Nothing to write. */
1188 transfer_debug("%s is writable", t->dest_name);
1189 bytes = xwrite(t->dest, t->buf, t->bufuse);
1190 if (bytes < 0 && errno != EWOULDBLOCK) {
1191 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1192 return -1;
1193 } else if (bytes > 0) {
1194 t->bufuse -= bytes;
1195 if (t->bufuse)
1196 memmove(t->buf, t->buf + bytes, t->bufuse);
1197 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1198 (int)bytes, t->dest_name, (int)t->bufuse);
1200 return 0;
1204 /* State of bidirectional transfer loop. */
1205 struct bidirectional_transfer_state {
1206 /* Direction from program to git. */
1207 struct unidirectional_transfer ptg;
1208 /* Direction from git to program. */
1209 struct unidirectional_transfer gtp;
1212 static void *udt_copy_task_routine(void *udt)
1214 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1215 while (t->state != SSTATE_FINISHED) {
1216 if (STATE_NEEDS_READING(t->state))
1217 if (udt_do_read(t))
1218 return NULL;
1219 if (STATE_NEEDS_WRITING(t->state))
1220 if (udt_do_write(t))
1221 return NULL;
1222 if (STATE_NEEDS_CLOSING(t->state))
1223 udt_close_if_finished(t);
1225 return udt; /* Just some non-NULL value. */
1228 #ifndef NO_PTHREADS
1231 * Join thread, with appropriate errors on failure. Name is name for the
1232 * thread (for error messages). Returns 0 on success, 1 on failure.
1234 static int tloop_join(pthread_t thread, const char *name)
1236 int err;
1237 void *tret;
1238 err = pthread_join(thread, &tret);
1239 if (!tret) {
1240 error("%s thread failed", name);
1241 return 1;
1243 if (err) {
1244 error("%s thread failed to join: %s", name, strerror(err));
1245 return 1;
1247 return 0;
1251 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1252 * -1 on failure.
1254 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1256 pthread_t gtp_thread;
1257 pthread_t ptg_thread;
1258 int err;
1259 int ret = 0;
1260 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1261 &s->gtp);
1262 if (err)
1263 die("Can't start thread for copying data: %s", strerror(err));
1264 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1265 &s->ptg);
1266 if (err)
1267 die("Can't start thread for copying data: %s", strerror(err));
1269 ret |= tloop_join(gtp_thread, "Git to program copy");
1270 ret |= tloop_join(ptg_thread, "Program to git copy");
1271 return ret;
1273 #else
1275 /* Close the source and target (for writing) for transfer. */
1276 static void udt_kill_transfer(struct unidirectional_transfer *t)
1278 t->state = SSTATE_FINISHED;
1280 * Socket read end left open isn't a disaster if nobody
1281 * attempts to read from it (mingw compat headers do not
1282 * have SHUT_RD)...
1284 * We can't fully close the socket since otherwise gtp
1285 * task would first close the socket it sends data to
1286 * while closing the ptg file descriptors.
1288 if (!t->src_is_sock)
1289 close(t->src);
1290 if (t->dest_is_sock)
1291 shutdown(t->dest, SHUT_WR);
1292 else
1293 close(t->dest);
1297 * Join process, with appropriate errors on failure. Name is name for the
1298 * process (for error messages). Returns 0 on success, 1 on failure.
1300 static int tloop_join(pid_t pid, const char *name)
1302 int tret;
1303 if (waitpid(pid, &tret, 0) < 0) {
1304 error("%s process failed to wait: %s", name, strerror(errno));
1305 return 1;
1307 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1308 error("%s process failed", name);
1309 return 1;
1311 return 0;
1315 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1316 * -1 on failure.
1318 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1320 pid_t pid1, pid2;
1321 int ret = 0;
1323 /* Fork thread #1: git to program. */
1324 pid1 = fork();
1325 if (pid1 < 0)
1326 die_errno("Can't start thread for copying data");
1327 else if (pid1 == 0) {
1328 udt_kill_transfer(&s->ptg);
1329 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1332 /* Fork thread #2: program to git. */
1333 pid2 = fork();
1334 if (pid2 < 0)
1335 die_errno("Can't start thread for copying data");
1336 else if (pid2 == 0) {
1337 udt_kill_transfer(&s->gtp);
1338 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1342 * Close both streams in parent as to not interfere with
1343 * end of file detection and wait for both tasks to finish.
1345 udt_kill_transfer(&s->gtp);
1346 udt_kill_transfer(&s->ptg);
1347 ret |= tloop_join(pid1, "Git to program copy");
1348 ret |= tloop_join(pid2, "Program to git copy");
1349 return ret;
1351 #endif
1354 * Copies data from stdin to output and from input to stdout simultaneously.
1355 * Additionally filtering through given filter. If filter is NULL, uses
1356 * identity filter.
1358 int bidirectional_transfer_loop(int input, int output)
1360 struct bidirectional_transfer_state state;
1362 /* Fill the state fields. */
1363 state.ptg.src = input;
1364 state.ptg.dest = 1;
1365 state.ptg.src_is_sock = (input == output);
1366 state.ptg.dest_is_sock = 0;
1367 state.ptg.state = SSTATE_TRANSFERING;
1368 state.ptg.bufuse = 0;
1369 state.ptg.src_name = "remote input";
1370 state.ptg.dest_name = "stdout";
1372 state.gtp.src = 0;
1373 state.gtp.dest = output;
1374 state.gtp.src_is_sock = 0;
1375 state.gtp.dest_is_sock = (input == output);
1376 state.gtp.state = SSTATE_TRANSFERING;
1377 state.gtp.bufuse = 0;
1378 state.gtp.src_name = "stdin";
1379 state.gtp.dest_name = "remote output";
1381 return tloop_spawnwait_tasks(&state);