t9109: make test hash independent
[git/raj.git] / transport-helper.c
blobae33b0eea7f725bad4ca5a20bb2c0025bbc8b99b
1 #include "cache.h"
2 #include "transport.h"
3 #include "quote.h"
4 #include "run-command.h"
5 #include "commit.h"
6 #include "diff.h"
7 #include "revision.h"
8 #include "remote.h"
9 #include "string-list.h"
10 #include "thread-utils.h"
11 #include "sigchain.h"
12 #include "argv-array.h"
13 #include "refs.h"
14 #include "refspec.h"
15 #include "transport-internal.h"
16 #include "protocol.h"
18 static int debug;
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 stateless_connect : 1,
32 signed_tags : 1,
33 check_connectivity : 1,
34 no_disconnect_req : 1,
35 no_private_update : 1,
36 object_format : 1;
39 * As an optimization, the transport code may invoke fetch before
40 * get_refs_list. If this happens, and if the transport helper doesn't
41 * support connect or stateless_connect, we need to invoke
42 * get_refs_list ourselves if we haven't already done so. Keep track of
43 * whether we have invoked get_refs_list.
45 unsigned get_refs_list_called : 1;
47 char *export_marks;
48 char *import_marks;
49 /* These go from remote name (as in "list") to private name */
50 struct refspec rs;
51 /* Transport options for fetch-pack/send-pack (should one of
52 * those be invoked).
54 struct git_transport_options transport_options;
57 static void sendline(struct helper_data *helper, struct strbuf *buffer)
59 if (debug)
60 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
61 if (write_in_full(helper->helper->in, buffer->buf, buffer->len) < 0)
62 die_errno(_("full write to remote helper failed"));
65 static int recvline_fh(FILE *helper, struct strbuf *buffer)
67 strbuf_reset(buffer);
68 if (debug)
69 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
70 if (strbuf_getline(buffer, helper) == EOF) {
71 if (debug)
72 fprintf(stderr, "Debug: Remote helper quit.\n");
73 return 1;
76 if (debug)
77 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
78 return 0;
81 static int recvline(struct helper_data *helper, struct strbuf *buffer)
83 return recvline_fh(helper->out, buffer);
86 static void write_constant(int fd, const char *str)
88 if (debug)
89 fprintf(stderr, "Debug: Remote helper: -> %s", str);
90 if (write_in_full(fd, str, strlen(str)) < 0)
91 die_errno(_("full write to remote helper failed"));
94 static const char *remove_ext_force(const char *url)
96 if (url) {
97 const char *colon = strchr(url, ':');
98 if (colon && colon[1] == ':')
99 return colon + 2;
101 return url;
104 static void do_take_over(struct transport *transport)
106 struct helper_data *data;
107 data = (struct helper_data *)transport->data;
108 transport_take_over(transport, data->helper);
109 fclose(data->out);
110 free(data);
113 static void standard_options(struct transport *t);
115 static struct child_process *get_helper(struct transport *transport)
117 struct helper_data *data = transport->data;
118 struct strbuf buf = STRBUF_INIT;
119 struct child_process *helper;
120 int duped;
121 int code;
123 if (data->helper)
124 return data->helper;
126 helper = xmalloc(sizeof(*helper));
127 child_process_init(helper);
128 helper->in = -1;
129 helper->out = -1;
130 helper->err = 0;
131 argv_array_pushf(&helper->args, "git-remote-%s", data->name);
132 argv_array_push(&helper->args, transport->remote->name);
133 argv_array_push(&helper->args, remove_ext_force(transport->url));
134 helper->git_cmd = 0;
135 helper->silent_exec_failure = 1;
137 if (have_git_dir())
138 argv_array_pushf(&helper->env_array, "%s=%s",
139 GIT_DIR_ENVIRONMENT, get_git_dir());
141 helper->trace2_child_class = helper->args.argv[0]; /* "remote-<name>" */
143 code = start_command(helper);
144 if (code < 0 && errno == ENOENT)
145 die(_("unable to find remote helper for '%s'"), data->name);
146 else if (code != 0)
147 exit(code);
149 data->helper = helper;
150 data->no_disconnect_req = 0;
151 refspec_init(&data->rs, REFSPEC_FETCH);
154 * Open the output as FILE* so strbuf_getline_*() family of
155 * functions can be used.
156 * Do this with duped fd because fclose() will close the fd,
157 * and stuff like taking over will require the fd to remain.
159 duped = dup(helper->out);
160 if (duped < 0)
161 die_errno(_("can't dup helper output fd"));
162 data->out = xfdopen(duped, "r");
164 write_constant(helper->in, "capabilities\n");
166 while (1) {
167 const char *capname, *arg;
168 int mandatory = 0;
169 if (recvline(data, &buf))
170 exit(128);
172 if (!*buf.buf)
173 break;
175 if (*buf.buf == '*') {
176 capname = buf.buf + 1;
177 mandatory = 1;
178 } else
179 capname = buf.buf;
181 if (debug)
182 fprintf(stderr, "Debug: Got cap %s\n", capname);
183 if (!strcmp(capname, "fetch"))
184 data->fetch = 1;
185 else if (!strcmp(capname, "option"))
186 data->option = 1;
187 else if (!strcmp(capname, "push"))
188 data->push = 1;
189 else if (!strcmp(capname, "import"))
190 data->import = 1;
191 else if (!strcmp(capname, "bidi-import"))
192 data->bidi_import = 1;
193 else if (!strcmp(capname, "export"))
194 data->export = 1;
195 else if (!strcmp(capname, "check-connectivity"))
196 data->check_connectivity = 1;
197 else if (skip_prefix(capname, "refspec ", &arg)) {
198 refspec_append(&data->rs, arg);
199 } else if (!strcmp(capname, "connect")) {
200 data->connect = 1;
201 } else if (!strcmp(capname, "stateless-connect")) {
202 data->stateless_connect = 1;
203 } else if (!strcmp(capname, "signed-tags")) {
204 data->signed_tags = 1;
205 } else if (skip_prefix(capname, "export-marks ", &arg)) {
206 data->export_marks = xstrdup(arg);
207 } else if (skip_prefix(capname, "import-marks ", &arg)) {
208 data->import_marks = xstrdup(arg);
209 } else if (starts_with(capname, "no-private-update")) {
210 data->no_private_update = 1;
211 } else if (starts_with(capname, "object-format")) {
212 data->object_format = 1;
213 } else if (mandatory) {
214 die(_("unknown mandatory capability %s; this remote "
215 "helper probably needs newer version of Git"),
216 capname);
219 if (!data->rs.nr && (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 standard_options(transport);
226 return data->helper;
229 static int disconnect_helper(struct transport *transport)
231 struct helper_data *data = transport->data;
232 int res = 0;
234 if (data->helper) {
235 if (debug)
236 fprintf(stderr, "Debug: Disconnecting.\n");
237 if (!data->no_disconnect_req) {
239 * Ignore write errors; there's nothing we can do,
240 * since we're about to close the pipe anyway. And the
241 * most likely error is EPIPE due to the helper dying
242 * to report an error itself.
244 sigchain_push(SIGPIPE, SIG_IGN);
245 xwrite(data->helper->in, "\n", 1);
246 sigchain_pop(SIGPIPE);
248 close(data->helper->in);
249 close(data->helper->out);
250 fclose(data->out);
251 res = finish_command(data->helper);
252 FREE_AND_NULL(data->helper);
254 return res;
257 static const char *unsupported_options[] = {
258 TRANS_OPT_UPLOADPACK,
259 TRANS_OPT_RECEIVEPACK,
260 TRANS_OPT_THIN,
261 TRANS_OPT_KEEP
264 static const char *boolean_options[] = {
265 TRANS_OPT_THIN,
266 TRANS_OPT_KEEP,
267 TRANS_OPT_FOLLOWTAGS,
268 TRANS_OPT_DEEPEN_RELATIVE
271 static int strbuf_set_helper_option(struct helper_data *data,
272 struct strbuf *buf)
274 int ret;
276 sendline(data, buf);
277 if (recvline(data, buf))
278 exit(128);
280 if (!strcmp(buf->buf, "ok"))
281 ret = 0;
282 else if (starts_with(buf->buf, "error"))
283 ret = -1;
284 else if (!strcmp(buf->buf, "unsupported"))
285 ret = 1;
286 else {
287 warning(_("%s unexpectedly said: '%s'"), data->name, buf->buf);
288 ret = 1;
290 return ret;
293 static int string_list_set_helper_option(struct helper_data *data,
294 const char *name,
295 struct string_list *list)
297 struct strbuf buf = STRBUF_INIT;
298 int i, ret = 0;
300 for (i = 0; i < list->nr; i++) {
301 strbuf_addf(&buf, "option %s ", name);
302 quote_c_style(list->items[i].string, &buf, NULL, 0);
303 strbuf_addch(&buf, '\n');
305 if ((ret = strbuf_set_helper_option(data, &buf)))
306 break;
307 strbuf_reset(&buf);
309 strbuf_release(&buf);
310 return ret;
313 static int set_helper_option(struct transport *transport,
314 const char *name, const char *value)
316 struct helper_data *data = transport->data;
317 struct strbuf buf = STRBUF_INIT;
318 int i, ret, is_bool = 0;
320 get_helper(transport);
322 if (!data->option)
323 return 1;
325 if (!strcmp(name, "deepen-not"))
326 return string_list_set_helper_option(data, name,
327 (struct string_list *)value);
329 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
330 if (!strcmp(name, unsupported_options[i]))
331 return 1;
334 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
335 if (!strcmp(name, boolean_options[i])) {
336 is_bool = 1;
337 break;
341 strbuf_addf(&buf, "option %s ", name);
342 if (is_bool)
343 strbuf_addstr(&buf, value ? "true" : "false");
344 else
345 quote_c_style(value, &buf, NULL, 0);
346 strbuf_addch(&buf, '\n');
348 ret = strbuf_set_helper_option(data, &buf);
349 strbuf_release(&buf);
350 return ret;
353 static void standard_options(struct transport *t)
355 char buf[16];
356 int v = t->verbose;
358 set_helper_option(t, "progress", t->progress ? "true" : "false");
360 xsnprintf(buf, sizeof(buf), "%d", v + 1);
361 set_helper_option(t, "verbosity", buf);
363 switch (t->family) {
364 case TRANSPORT_FAMILY_ALL:
366 * this is already the default,
367 * do not break old remote helpers by setting "all" here
369 break;
370 case TRANSPORT_FAMILY_IPV4:
371 set_helper_option(t, "family", "ipv4");
372 break;
373 case TRANSPORT_FAMILY_IPV6:
374 set_helper_option(t, "family", "ipv6");
375 break;
379 static int release_helper(struct transport *transport)
381 int res = 0;
382 struct helper_data *data = transport->data;
383 refspec_clear(&data->rs);
384 res = disconnect_helper(transport);
385 free(transport->data);
386 return res;
389 static int fetch_with_fetch(struct transport *transport,
390 int nr_heads, struct ref **to_fetch)
392 struct helper_data *data = transport->data;
393 int i;
394 struct strbuf buf = STRBUF_INIT;
396 for (i = 0; i < nr_heads; i++) {
397 const struct ref *posn = to_fetch[i];
398 if (posn->status & REF_STATUS_UPTODATE)
399 continue;
401 strbuf_addf(&buf, "fetch %s %s\n",
402 oid_to_hex(&posn->old_oid),
403 posn->symref ? posn->symref : posn->name);
406 strbuf_addch(&buf, '\n');
407 sendline(data, &buf);
409 while (1) {
410 const char *name;
412 if (recvline(data, &buf))
413 exit(128);
415 if (skip_prefix(buf.buf, "lock ", &name)) {
416 if (transport->pack_lockfile)
417 warning(_("%s also locked %s"), data->name, name);
418 else
419 transport->pack_lockfile = xstrdup(name);
421 else if (data->check_connectivity &&
422 data->transport_options.check_self_contained_and_connected &&
423 !strcmp(buf.buf, "connectivity-ok"))
424 data->transport_options.self_contained_and_connected = 1;
425 else if (!buf.len)
426 break;
427 else
428 warning(_("%s unexpectedly said: '%s'"), data->name, buf.buf);
430 strbuf_release(&buf);
431 return 0;
434 static int get_importer(struct transport *transport, struct child_process *fastimport)
436 struct child_process *helper = get_helper(transport);
437 struct helper_data *data = transport->data;
438 int cat_blob_fd, code;
439 child_process_init(fastimport);
440 fastimport->in = xdup(helper->out);
441 argv_array_push(&fastimport->args, "fast-import");
442 argv_array_push(&fastimport->args, "--allow-unsafe-features");
443 argv_array_push(&fastimport->args, debug ? "--stats" : "--quiet");
445 if (data->bidi_import) {
446 cat_blob_fd = xdup(helper->in);
447 argv_array_pushf(&fastimport->args, "--cat-blob-fd=%d", cat_blob_fd);
449 fastimport->git_cmd = 1;
451 code = start_command(fastimport);
452 return code;
455 static int get_exporter(struct transport *transport,
456 struct child_process *fastexport,
457 struct string_list *revlist_args)
459 struct helper_data *data = transport->data;
460 struct child_process *helper = get_helper(transport);
461 int i;
463 child_process_init(fastexport);
465 /* we need to duplicate helper->in because we want to use it after
466 * fastexport is done with it. */
467 fastexport->out = dup(helper->in);
468 argv_array_push(&fastexport->args, "fast-export");
469 argv_array_push(&fastexport->args, "--use-done-feature");
470 argv_array_push(&fastexport->args, data->signed_tags ?
471 "--signed-tags=verbatim" : "--signed-tags=warn-strip");
472 if (data->export_marks)
473 argv_array_pushf(&fastexport->args, "--export-marks=%s.tmp", data->export_marks);
474 if (data->import_marks)
475 argv_array_pushf(&fastexport->args, "--import-marks=%s", data->import_marks);
477 for (i = 0; i < revlist_args->nr; i++)
478 argv_array_push(&fastexport->args, revlist_args->items[i].string);
480 fastexport->git_cmd = 1;
481 return start_command(fastexport);
484 static int fetch_with_import(struct transport *transport,
485 int nr_heads, struct ref **to_fetch)
487 struct child_process fastimport;
488 struct helper_data *data = transport->data;
489 int i;
490 struct ref *posn;
491 struct strbuf buf = STRBUF_INIT;
493 get_helper(transport);
495 if (get_importer(transport, &fastimport))
496 die(_("couldn't run fast-import"));
498 for (i = 0; i < nr_heads; i++) {
499 posn = to_fetch[i];
500 if (posn->status & REF_STATUS_UPTODATE)
501 continue;
503 strbuf_addf(&buf, "import %s\n",
504 posn->symref ? posn->symref : posn->name);
505 sendline(data, &buf);
506 strbuf_reset(&buf);
509 write_constant(data->helper->in, "\n");
511 * remote-helpers that advertise the bidi-import capability are required to
512 * buffer the complete batch of import commands until this newline before
513 * sending data to fast-import.
514 * These helpers read back data from fast-import on their stdin, which could
515 * be mixed with import commands, otherwise.
518 if (finish_command(&fastimport))
519 die(_("error while running fast-import"));
522 * The fast-import stream of a remote helper that advertises
523 * the "refspec" capability writes to the refs named after the
524 * right hand side of the first refspec matching each ref we
525 * were fetching.
527 * (If no "refspec" capability was specified, for historical
528 * reasons we default to the equivalent of *:*.)
530 * Store the result in to_fetch[i].old_sha1. Callers such
531 * as "git fetch" can use the value to write feedback to the
532 * terminal, populate FETCH_HEAD, and determine what new value
533 * should be written to peer_ref if the update is a
534 * fast-forward or this is a forced update.
536 for (i = 0; i < nr_heads; i++) {
537 char *private, *name;
538 posn = to_fetch[i];
539 if (posn->status & REF_STATUS_UPTODATE)
540 continue;
541 name = posn->symref ? posn->symref : posn->name;
542 if (data->rs.nr)
543 private = apply_refspecs(&data->rs, name);
544 else
545 private = xstrdup(name);
546 if (private) {
547 if (read_ref(private, &posn->old_oid) < 0)
548 die(_("could not read ref %s"), private);
549 free(private);
552 strbuf_release(&buf);
553 return 0;
556 static int run_connect(struct transport *transport, struct strbuf *cmdbuf)
558 struct helper_data *data = transport->data;
559 int ret = 0;
560 int duped;
561 FILE *input;
562 struct child_process *helper;
564 helper = get_helper(transport);
567 * Yes, dup the pipe another time, as we need unbuffered version
568 * of input pipe as FILE*. fclose() closes the underlying fd and
569 * stream buffering only can be changed before first I/O operation
570 * on it.
572 duped = dup(helper->out);
573 if (duped < 0)
574 die_errno(_("can't dup helper output fd"));
575 input = xfdopen(duped, "r");
576 setvbuf(input, NULL, _IONBF, 0);
578 sendline(data, cmdbuf);
579 if (recvline_fh(input, cmdbuf))
580 exit(128);
582 if (!strcmp(cmdbuf->buf, "")) {
583 data->no_disconnect_req = 1;
584 if (debug)
585 fprintf(stderr, "Debug: Smart transport connection "
586 "ready.\n");
587 ret = 1;
588 } else if (!strcmp(cmdbuf->buf, "fallback")) {
589 if (debug)
590 fprintf(stderr, "Debug: Falling back to dumb "
591 "transport.\n");
592 } else {
593 die(_("unknown response to connect: %s"),
594 cmdbuf->buf);
597 fclose(input);
598 return ret;
601 static int process_connect_service(struct transport *transport,
602 const char *name, const char *exec)
604 struct helper_data *data = transport->data;
605 struct strbuf cmdbuf = STRBUF_INIT;
606 int ret = 0;
609 * Handle --upload-pack and friends. This is fire and forget...
610 * just warn if it fails.
612 if (strcmp(name, exec)) {
613 int r = set_helper_option(transport, "servpath", exec);
614 if (r > 0)
615 warning(_("setting remote service path not supported by protocol"));
616 else if (r < 0)
617 warning(_("invalid remote service path"));
620 if (data->connect) {
621 strbuf_addf(&cmdbuf, "connect %s\n", name);
622 ret = run_connect(transport, &cmdbuf);
623 } else if (data->stateless_connect &&
624 (get_protocol_version_config() == protocol_v2) &&
625 !strcmp("git-upload-pack", name)) {
626 strbuf_addf(&cmdbuf, "stateless-connect %s\n", name);
627 ret = run_connect(transport, &cmdbuf);
628 if (ret)
629 transport->stateless_rpc = 1;
632 strbuf_release(&cmdbuf);
633 return ret;
636 static int process_connect(struct transport *transport,
637 int for_push)
639 struct helper_data *data = transport->data;
640 const char *name;
641 const char *exec;
643 name = for_push ? "git-receive-pack" : "git-upload-pack";
644 if (for_push)
645 exec = data->transport_options.receivepack;
646 else
647 exec = data->transport_options.uploadpack;
649 return process_connect_service(transport, name, exec);
652 static int connect_helper(struct transport *transport, const char *name,
653 const char *exec, int fd[2])
655 struct helper_data *data = transport->data;
657 /* Get_helper so connect is inited. */
658 get_helper(transport);
659 if (!data->connect)
660 die(_("operation not supported by protocol"));
662 if (!process_connect_service(transport, name, exec))
663 die(_("can't connect to subservice %s"), name);
665 fd[0] = data->helper->out;
666 fd[1] = data->helper->in;
667 return 0;
670 static struct ref *get_refs_list_using_list(struct transport *transport,
671 int for_push);
673 static int fetch(struct transport *transport,
674 int nr_heads, struct ref **to_fetch)
676 struct helper_data *data = transport->data;
677 int i, count;
679 get_helper(transport);
681 if (process_connect(transport, 0)) {
682 do_take_over(transport);
683 return transport->vtable->fetch(transport, nr_heads, to_fetch);
686 if (!data->get_refs_list_called)
687 get_refs_list_using_list(transport, 0);
689 count = 0;
690 for (i = 0; i < nr_heads; i++)
691 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
692 count++;
694 if (!count)
695 return 0;
697 if (data->check_connectivity &&
698 data->transport_options.check_self_contained_and_connected)
699 set_helper_option(transport, "check-connectivity", "true");
701 if (transport->cloning)
702 set_helper_option(transport, "cloning", "true");
704 if (data->transport_options.update_shallow)
705 set_helper_option(transport, "update-shallow", "true");
707 if (data->transport_options.filter_options.choice) {
708 const char *spec = expand_list_objects_filter_spec(
709 &data->transport_options.filter_options);
710 set_helper_option(transport, "filter", spec);
713 if (data->transport_options.negotiation_tips)
714 warning("Ignoring --negotiation-tip because the protocol does not support it.");
716 if (data->fetch)
717 return fetch_with_fetch(transport, nr_heads, to_fetch);
719 if (data->import)
720 return fetch_with_import(transport, nr_heads, to_fetch);
722 return -1;
725 static int push_update_ref_status(struct strbuf *buf,
726 struct ref **ref,
727 struct ref *remote_refs)
729 char *refname, *msg;
730 int status, forced = 0;
732 if (starts_with(buf->buf, "ok ")) {
733 status = REF_STATUS_OK;
734 refname = buf->buf + 3;
735 } else if (starts_with(buf->buf, "error ")) {
736 status = REF_STATUS_REMOTE_REJECT;
737 refname = buf->buf + 6;
738 } else
739 die(_("expected ok/error, helper said '%s'"), buf->buf);
741 msg = strchr(refname, ' ');
742 if (msg) {
743 struct strbuf msg_buf = STRBUF_INIT;
744 const char *end;
746 *msg++ = '\0';
747 if (!unquote_c_style(&msg_buf, msg, &end))
748 msg = strbuf_detach(&msg_buf, NULL);
749 else
750 msg = xstrdup(msg);
751 strbuf_release(&msg_buf);
753 if (!strcmp(msg, "no match")) {
754 status = REF_STATUS_NONE;
755 FREE_AND_NULL(msg);
757 else if (!strcmp(msg, "up to date")) {
758 status = REF_STATUS_UPTODATE;
759 FREE_AND_NULL(msg);
761 else if (!strcmp(msg, "non-fast forward")) {
762 status = REF_STATUS_REJECT_NONFASTFORWARD;
763 FREE_AND_NULL(msg);
765 else if (!strcmp(msg, "already exists")) {
766 status = REF_STATUS_REJECT_ALREADY_EXISTS;
767 FREE_AND_NULL(msg);
769 else if (!strcmp(msg, "fetch first")) {
770 status = REF_STATUS_REJECT_FETCH_FIRST;
771 FREE_AND_NULL(msg);
773 else if (!strcmp(msg, "needs force")) {
774 status = REF_STATUS_REJECT_NEEDS_FORCE;
775 FREE_AND_NULL(msg);
777 else if (!strcmp(msg, "stale info")) {
778 status = REF_STATUS_REJECT_STALE;
779 FREE_AND_NULL(msg);
781 else if (!strcmp(msg, "forced update")) {
782 forced = 1;
783 FREE_AND_NULL(msg);
787 if (*ref)
788 *ref = find_ref_by_name(*ref, refname);
789 if (!*ref)
790 *ref = find_ref_by_name(remote_refs, refname);
791 if (!*ref) {
792 warning(_("helper reported unexpected status of %s"), refname);
793 return 1;
796 if ((*ref)->status != REF_STATUS_NONE) {
798 * Earlier, the ref was marked not to be pushed, so ignore the ref
799 * status reported by the remote helper if the latter is 'no match'.
801 if (status == REF_STATUS_NONE)
802 return 1;
805 (*ref)->status = status;
806 (*ref)->forced_update |= forced;
807 (*ref)->remote_status = msg;
808 return !(status == REF_STATUS_OK);
811 static int push_update_refs_status(struct helper_data *data,
812 struct ref *remote_refs,
813 int flags)
815 struct strbuf buf = STRBUF_INIT;
816 struct ref *ref = remote_refs;
817 int ret = 0;
819 for (;;) {
820 char *private;
822 if (recvline(data, &buf)) {
823 ret = 1;
824 break;
827 if (!buf.len)
828 break;
830 if (push_update_ref_status(&buf, &ref, remote_refs))
831 continue;
833 if (flags & TRANSPORT_PUSH_DRY_RUN || !data->rs.nr || data->no_private_update)
834 continue;
836 /* propagate back the update to the remote namespace */
837 private = apply_refspecs(&data->rs, ref->name);
838 if (!private)
839 continue;
840 update_ref("update by helper", private, &ref->new_oid, NULL,
841 0, 0);
842 free(private);
844 strbuf_release(&buf);
845 return ret;
848 static void set_common_push_options(struct transport *transport,
849 const char *name, int flags)
851 if (flags & TRANSPORT_PUSH_DRY_RUN) {
852 if (set_helper_option(transport, "dry-run", "true") != 0)
853 die(_("helper %s does not support dry-run"), name);
854 } else if (flags & TRANSPORT_PUSH_CERT_ALWAYS) {
855 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "true") != 0)
856 die(_("helper %s does not support --signed"), name);
857 } else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED) {
858 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "if-asked") != 0)
859 die(_("helper %s does not support --signed=if-asked"), name);
862 if (flags & TRANSPORT_PUSH_ATOMIC)
863 if (set_helper_option(transport, TRANS_OPT_ATOMIC, "true") != 0)
864 die(_("helper %s does not support --atomic"), name);
866 if (flags & TRANSPORT_PUSH_OPTIONS) {
867 struct string_list_item *item;
868 for_each_string_list_item(item, transport->push_options)
869 if (set_helper_option(transport, "push-option", item->string) != 0)
870 die(_("helper %s does not support 'push-option'"), name);
874 static int push_refs_with_push(struct transport *transport,
875 struct ref *remote_refs, int flags)
877 int force_all = flags & TRANSPORT_PUSH_FORCE;
878 int mirror = flags & TRANSPORT_PUSH_MIRROR;
879 int atomic = flags & TRANSPORT_PUSH_ATOMIC;
880 struct helper_data *data = transport->data;
881 struct strbuf buf = STRBUF_INIT;
882 struct ref *ref;
883 struct string_list cas_options = STRING_LIST_INIT_DUP;
884 struct string_list_item *cas_option;
886 get_helper(transport);
887 if (!data->push)
888 return 1;
890 for (ref = remote_refs; ref; ref = ref->next) {
891 if (!ref->peer_ref && !mirror)
892 continue;
894 /* Check for statuses set by set_ref_status_for_push() */
895 switch (ref->status) {
896 case REF_STATUS_REJECT_NONFASTFORWARD:
897 case REF_STATUS_REJECT_STALE:
898 case REF_STATUS_REJECT_ALREADY_EXISTS:
899 if (atomic) {
900 reject_atomic_push(remote_refs, mirror);
901 string_list_clear(&cas_options, 0);
902 return 0;
903 } else
904 continue;
905 case REF_STATUS_UPTODATE:
906 continue;
907 default:
908 ; /* do nothing */
911 if (force_all)
912 ref->force = 1;
914 strbuf_addstr(&buf, "push ");
915 if (!ref->deletion) {
916 if (ref->force)
917 strbuf_addch(&buf, '+');
918 if (ref->peer_ref)
919 strbuf_addstr(&buf, ref->peer_ref->name);
920 else
921 strbuf_addstr(&buf, oid_to_hex(&ref->new_oid));
923 strbuf_addch(&buf, ':');
924 strbuf_addstr(&buf, ref->name);
925 strbuf_addch(&buf, '\n');
928 * The "--force-with-lease" options without explicit
929 * values to expect have already been expanded into
930 * the ref->old_oid_expect[] field; we can ignore
931 * transport->smart_options->cas altogether and instead
932 * can enumerate them from the refs.
934 if (ref->expect_old_sha1) {
935 struct strbuf cas = STRBUF_INIT;
936 strbuf_addf(&cas, "%s:%s",
937 ref->name, oid_to_hex(&ref->old_oid_expect));
938 string_list_append_nodup(&cas_options,
939 strbuf_detach(&cas, NULL));
942 if (buf.len == 0) {
943 string_list_clear(&cas_options, 0);
944 return 0;
947 for_each_string_list_item(cas_option, &cas_options)
948 set_helper_option(transport, "cas", cas_option->string);
949 set_common_push_options(transport, data->name, flags);
951 strbuf_addch(&buf, '\n');
952 sendline(data, &buf);
953 strbuf_release(&buf);
954 string_list_clear(&cas_options, 0);
956 return push_update_refs_status(data, remote_refs, flags);
959 static int push_refs_with_export(struct transport *transport,
960 struct ref *remote_refs, int flags)
962 struct ref *ref;
963 struct child_process *helper, exporter;
964 struct helper_data *data = transport->data;
965 struct string_list revlist_args = STRING_LIST_INIT_DUP;
966 struct strbuf buf = STRBUF_INIT;
968 if (!data->rs.nr)
969 die(_("remote-helper doesn't support push; refspec needed"));
971 set_common_push_options(transport, data->name, flags);
972 if (flags & TRANSPORT_PUSH_FORCE) {
973 if (set_helper_option(transport, "force", "true") != 0)
974 warning(_("helper %s does not support 'force'"), data->name);
977 helper = get_helper(transport);
979 write_constant(helper->in, "export\n");
981 for (ref = remote_refs; ref; ref = ref->next) {
982 char *private;
983 struct object_id oid;
985 private = apply_refspecs(&data->rs, ref->name);
986 if (private && !get_oid(private, &oid)) {
987 strbuf_addf(&buf, "^%s", private);
988 string_list_append_nodup(&revlist_args,
989 strbuf_detach(&buf, NULL));
990 oidcpy(&ref->old_oid, &oid);
992 free(private);
994 if (ref->peer_ref) {
995 if (strcmp(ref->name, ref->peer_ref->name)) {
996 if (!ref->deletion) {
997 const char *name;
998 int flag;
1000 /* Follow symbolic refs (mainly for HEAD). */
1001 name = resolve_ref_unsafe(ref->peer_ref->name,
1002 RESOLVE_REF_READING,
1003 &oid, &flag);
1004 if (!name || !(flag & REF_ISSYMREF))
1005 name = ref->peer_ref->name;
1007 strbuf_addf(&buf, "%s:%s", name, ref->name);
1008 } else
1009 strbuf_addf(&buf, ":%s", ref->name);
1011 string_list_append(&revlist_args, "--refspec");
1012 string_list_append(&revlist_args, buf.buf);
1013 strbuf_release(&buf);
1015 if (!ref->deletion)
1016 string_list_append(&revlist_args, ref->peer_ref->name);
1020 if (get_exporter(transport, &exporter, &revlist_args))
1021 die(_("couldn't run fast-export"));
1023 string_list_clear(&revlist_args, 1);
1025 if (finish_command(&exporter))
1026 die(_("error while running fast-export"));
1027 if (push_update_refs_status(data, remote_refs, flags))
1028 return 1;
1030 if (data->export_marks) {
1031 strbuf_addf(&buf, "%s.tmp", data->export_marks);
1032 rename(buf.buf, data->export_marks);
1033 strbuf_release(&buf);
1036 return 0;
1039 static int push_refs(struct transport *transport,
1040 struct ref *remote_refs, int flags)
1042 struct helper_data *data = transport->data;
1044 if (process_connect(transport, 1)) {
1045 do_take_over(transport);
1046 return transport->vtable->push_refs(transport, remote_refs, flags);
1049 if (!remote_refs) {
1050 fprintf(stderr,
1051 _("No refs in common and none specified; doing nothing.\n"
1052 "Perhaps you should specify a branch such as 'master'.\n"));
1053 return 0;
1056 if (data->push)
1057 return push_refs_with_push(transport, remote_refs, flags);
1059 if (data->export)
1060 return push_refs_with_export(transport, remote_refs, flags);
1062 return -1;
1066 static int has_attribute(const char *attrs, const char *attr)
1068 int len;
1069 if (!attrs)
1070 return 0;
1072 len = strlen(attr);
1073 for (;;) {
1074 const char *space = strchrnul(attrs, ' ');
1075 if (len == space - attrs && !strncmp(attrs, attr, len))
1076 return 1;
1077 if (!*space)
1078 return 0;
1079 attrs = space + 1;
1083 static struct ref *get_refs_list(struct transport *transport, int for_push,
1084 const struct argv_array *ref_prefixes)
1086 get_helper(transport);
1088 if (process_connect(transport, for_push)) {
1089 do_take_over(transport);
1090 return transport->vtable->get_refs_list(transport, for_push, ref_prefixes);
1093 return get_refs_list_using_list(transport, for_push);
1096 static struct ref *get_refs_list_using_list(struct transport *transport,
1097 int for_push)
1099 struct helper_data *data = transport->data;
1100 struct child_process *helper;
1101 struct ref *ret = NULL;
1102 struct ref **tail = &ret;
1103 struct ref *posn;
1104 struct strbuf buf = STRBUF_INIT;
1106 data->get_refs_list_called = 1;
1107 helper = get_helper(transport);
1109 if (data->object_format) {
1110 write_str_in_full(helper->in, "option object-format\n");
1111 if (recvline(data, &buf) || strcmp(buf.buf, "ok"))
1112 exit(128);
1115 if (data->push && for_push)
1116 write_str_in_full(helper->in, "list for-push\n");
1117 else
1118 write_str_in_full(helper->in, "list\n");
1120 while (1) {
1121 char *eov, *eon;
1122 if (recvline(data, &buf))
1123 exit(128);
1125 if (!*buf.buf)
1126 break;
1127 else if (buf.buf[0] == ':') {
1128 const char *value;
1129 if (skip_prefix(buf.buf, ":object-format ", &value)) {
1130 int algo = hash_algo_by_name(value);
1131 if (algo == GIT_HASH_UNKNOWN)
1132 die(_("unsupported object format '%s'"),
1133 value);
1134 transport->hash_algo = &hash_algos[algo];
1136 continue;
1139 eov = strchr(buf.buf, ' ');
1140 if (!eov)
1141 die(_("malformed response in ref list: %s"), buf.buf);
1142 eon = strchr(eov + 1, ' ');
1143 *eov = '\0';
1144 if (eon)
1145 *eon = '\0';
1146 *tail = alloc_ref(eov + 1);
1147 if (buf.buf[0] == '@')
1148 (*tail)->symref = xstrdup(buf.buf + 1);
1149 else if (buf.buf[0] != '?')
1150 get_oid_hex_algop(buf.buf, &(*tail)->old_oid, transport->hash_algo);
1151 if (eon) {
1152 if (has_attribute(eon + 1, "unchanged")) {
1153 (*tail)->status |= REF_STATUS_UPTODATE;
1154 if (read_ref((*tail)->name, &(*tail)->old_oid) < 0)
1155 die(_("could not read ref %s"),
1156 (*tail)->name);
1159 tail = &((*tail)->next);
1161 if (debug)
1162 fprintf(stderr, "Debug: Read ref listing.\n");
1163 strbuf_release(&buf);
1165 for (posn = ret; posn; posn = posn->next)
1166 resolve_remote_symref(posn, ret);
1168 return ret;
1171 static struct transport_vtable vtable = {
1172 set_helper_option,
1173 get_refs_list,
1174 fetch,
1175 push_refs,
1176 connect_helper,
1177 release_helper
1180 int transport_helper_init(struct transport *transport, const char *name)
1182 struct helper_data *data = xcalloc(1, sizeof(*data));
1183 data->name = name;
1185 transport_check_allowed(name);
1187 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1188 debug = 1;
1190 transport->data = data;
1191 transport->vtable = &vtable;
1192 transport->smart_options = &(data->transport_options);
1193 return 0;
1197 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1198 * buffer less), so attempt reads and writes with up to that size.
1200 #define BUFFERSIZE 65536
1201 /* This should be enough to hold debugging message. */
1202 #define PBUFFERSIZE 8192
1204 /* Print bidirectional transfer loop debug message. */
1205 __attribute__((format (printf, 1, 2)))
1206 static void transfer_debug(const char *fmt, ...)
1209 * NEEDSWORK: This function is sometimes used from multiple threads, and
1210 * we end up using debug_enabled racily. That "should not matter" since
1211 * we always write the same value, but it's still wrong. This function
1212 * is listed in .tsan-suppressions for the time being.
1215 va_list args;
1216 char msgbuf[PBUFFERSIZE];
1217 static int debug_enabled = -1;
1219 if (debug_enabled < 0)
1220 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1221 if (!debug_enabled)
1222 return;
1224 va_start(args, fmt);
1225 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1226 va_end(args);
1227 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1230 /* Stream state: More data may be coming in this direction. */
1231 #define SSTATE_TRANSFERRING 0
1233 * Stream state: No more data coming in this direction, flushing rest of
1234 * data.
1236 #define SSTATE_FLUSHING 1
1237 /* Stream state: Transfer in this direction finished. */
1238 #define SSTATE_FINISHED 2
1240 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERRING)
1241 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1242 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1244 /* Unidirectional transfer. */
1245 struct unidirectional_transfer {
1246 /* Source */
1247 int src;
1248 /* Destination */
1249 int dest;
1250 /* Is source socket? */
1251 int src_is_sock;
1252 /* Is destination socket? */
1253 int dest_is_sock;
1254 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1255 int state;
1256 /* Buffer. */
1257 char buf[BUFFERSIZE];
1258 /* Buffer used. */
1259 size_t bufuse;
1260 /* Name of source. */
1261 const char *src_name;
1262 /* Name of destination. */
1263 const char *dest_name;
1266 /* Closes the target (for writing) if transfer has finished. */
1267 static void udt_close_if_finished(struct unidirectional_transfer *t)
1269 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1270 t->state = SSTATE_FINISHED;
1271 if (t->dest_is_sock)
1272 shutdown(t->dest, SHUT_WR);
1273 else
1274 close(t->dest);
1275 transfer_debug("Closed %s.", t->dest_name);
1280 * Tries to read data from source into buffer. If buffer is full,
1281 * no data is read. Returns 0 on success, -1 on error.
1283 static int udt_do_read(struct unidirectional_transfer *t)
1285 ssize_t bytes;
1287 if (t->bufuse == BUFFERSIZE)
1288 return 0; /* No space for more. */
1290 transfer_debug("%s is readable", t->src_name);
1291 bytes = xread(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1292 if (bytes < 0) {
1293 error_errno(_("read(%s) failed"), t->src_name);
1294 return -1;
1295 } else if (bytes == 0) {
1296 transfer_debug("%s EOF (with %i bytes in buffer)",
1297 t->src_name, (int)t->bufuse);
1298 t->state = SSTATE_FLUSHING;
1299 } else if (bytes > 0) {
1300 t->bufuse += bytes;
1301 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1302 (int)bytes, t->src_name, (int)t->bufuse);
1304 return 0;
1307 /* Tries to write data from buffer into destination. If buffer is empty,
1308 * no data is written. Returns 0 on success, -1 on error.
1310 static int udt_do_write(struct unidirectional_transfer *t)
1312 ssize_t bytes;
1314 if (t->bufuse == 0)
1315 return 0; /* Nothing to write. */
1317 transfer_debug("%s is writable", t->dest_name);
1318 bytes = xwrite(t->dest, t->buf, t->bufuse);
1319 if (bytes < 0) {
1320 error_errno(_("write(%s) failed"), t->dest_name);
1321 return -1;
1322 } else if (bytes > 0) {
1323 t->bufuse -= bytes;
1324 if (t->bufuse)
1325 memmove(t->buf, t->buf + bytes, t->bufuse);
1326 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1327 (int)bytes, t->dest_name, (int)t->bufuse);
1329 return 0;
1333 /* State of bidirectional transfer loop. */
1334 struct bidirectional_transfer_state {
1335 /* Direction from program to git. */
1336 struct unidirectional_transfer ptg;
1337 /* Direction from git to program. */
1338 struct unidirectional_transfer gtp;
1341 static void *udt_copy_task_routine(void *udt)
1343 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1344 while (t->state != SSTATE_FINISHED) {
1345 if (STATE_NEEDS_READING(t->state))
1346 if (udt_do_read(t))
1347 return NULL;
1348 if (STATE_NEEDS_WRITING(t->state))
1349 if (udt_do_write(t))
1350 return NULL;
1351 if (STATE_NEEDS_CLOSING(t->state))
1352 udt_close_if_finished(t);
1354 return udt; /* Just some non-NULL value. */
1357 #ifndef NO_PTHREADS
1360 * Join thread, with appropriate errors on failure. Name is name for the
1361 * thread (for error messages). Returns 0 on success, 1 on failure.
1363 static int tloop_join(pthread_t thread, const char *name)
1365 int err;
1366 void *tret;
1367 err = pthread_join(thread, &tret);
1368 if (!tret) {
1369 error(_("%s thread failed"), name);
1370 return 1;
1372 if (err) {
1373 error(_("%s thread failed to join: %s"), name, strerror(err));
1374 return 1;
1376 return 0;
1380 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1381 * -1 on failure.
1383 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1385 pthread_t gtp_thread;
1386 pthread_t ptg_thread;
1387 int err;
1388 int ret = 0;
1389 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1390 &s->gtp);
1391 if (err)
1392 die(_("can't start thread for copying data: %s"), strerror(err));
1393 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1394 &s->ptg);
1395 if (err)
1396 die(_("can't start thread for copying data: %s"), strerror(err));
1398 ret |= tloop_join(gtp_thread, "Git to program copy");
1399 ret |= tloop_join(ptg_thread, "Program to git copy");
1400 return ret;
1402 #else
1404 /* Close the source and target (for writing) for transfer. */
1405 static void udt_kill_transfer(struct unidirectional_transfer *t)
1407 t->state = SSTATE_FINISHED;
1409 * Socket read end left open isn't a disaster if nobody
1410 * attempts to read from it (mingw compat headers do not
1411 * have SHUT_RD)...
1413 * We can't fully close the socket since otherwise gtp
1414 * task would first close the socket it sends data to
1415 * while closing the ptg file descriptors.
1417 if (!t->src_is_sock)
1418 close(t->src);
1419 if (t->dest_is_sock)
1420 shutdown(t->dest, SHUT_WR);
1421 else
1422 close(t->dest);
1426 * Join process, with appropriate errors on failure. Name is name for the
1427 * process (for error messages). Returns 0 on success, 1 on failure.
1429 static int tloop_join(pid_t pid, const char *name)
1431 int tret;
1432 if (waitpid(pid, &tret, 0) < 0) {
1433 error_errno(_("%s process failed to wait"), name);
1434 return 1;
1436 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1437 error(_("%s process failed"), name);
1438 return 1;
1440 return 0;
1444 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1445 * -1 on failure.
1447 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1449 pid_t pid1, pid2;
1450 int ret = 0;
1452 /* Fork thread #1: git to program. */
1453 pid1 = fork();
1454 if (pid1 < 0)
1455 die_errno(_("can't start thread for copying data"));
1456 else if (pid1 == 0) {
1457 udt_kill_transfer(&s->ptg);
1458 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1461 /* Fork thread #2: program to git. */
1462 pid2 = fork();
1463 if (pid2 < 0)
1464 die_errno(_("can't start thread for copying data"));
1465 else if (pid2 == 0) {
1466 udt_kill_transfer(&s->gtp);
1467 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1471 * Close both streams in parent as to not interfere with
1472 * end of file detection and wait for both tasks to finish.
1474 udt_kill_transfer(&s->gtp);
1475 udt_kill_transfer(&s->ptg);
1476 ret |= tloop_join(pid1, "Git to program copy");
1477 ret |= tloop_join(pid2, "Program to git copy");
1478 return ret;
1480 #endif
1483 * Copies data from stdin to output and from input to stdout simultaneously.
1484 * Additionally filtering through given filter. If filter is NULL, uses
1485 * identity filter.
1487 int bidirectional_transfer_loop(int input, int output)
1489 struct bidirectional_transfer_state state;
1491 /* Fill the state fields. */
1492 state.ptg.src = input;
1493 state.ptg.dest = 1;
1494 state.ptg.src_is_sock = (input == output);
1495 state.ptg.dest_is_sock = 0;
1496 state.ptg.state = SSTATE_TRANSFERRING;
1497 state.ptg.bufuse = 0;
1498 state.ptg.src_name = "remote input";
1499 state.ptg.dest_name = "stdout";
1501 state.gtp.src = 0;
1502 state.gtp.dest = output;
1503 state.gtp.src_is_sock = 0;
1504 state.gtp.dest_is_sock = (input == output);
1505 state.gtp.state = SSTATE_TRANSFERRING;
1506 state.gtp.bufuse = 0;
1507 state.gtp.src_name = "stdin";
1508 state.gtp.dest_name = "remote output";
1510 return tloop_spawnwait_tasks(&state);
1513 void reject_atomic_push(struct ref *remote_refs, int mirror_mode)
1515 struct ref *ref;
1517 /* Mark other refs as failed */
1518 for (ref = remote_refs; ref; ref = ref->next) {
1519 if (!ref->peer_ref && !mirror_mode)
1520 continue;
1522 switch (ref->status) {
1523 case REF_STATUS_NONE:
1524 case REF_STATUS_OK:
1525 case REF_STATUS_EXPECTING_REPORT:
1526 ref->status = REF_STATUS_ATOMIC_PUSH_FAILED;
1527 continue;
1528 default:
1529 break; /* do nothing */
1532 return;