debian/control: let git-all Suggest instead of Recommending git-daemon-run
[git/debian.git] / transport-helper.c
blob20a7185ec40e1cf4612c259019f325208632373b
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;
38 * As an optimization, the transport code may invoke fetch before
39 * get_refs_list. If this happens, and if the transport helper doesn't
40 * support connect or stateless_connect, we need to invoke
41 * get_refs_list ourselves if we haven't already done so. Keep track of
42 * whether we have invoked get_refs_list.
44 unsigned get_refs_list_called : 1;
46 char *export_marks;
47 char *import_marks;
48 /* These go from remote name (as in "list") to private name */
49 struct refspec rs;
50 /* Transport options for fetch-pack/send-pack (should one of
51 * those be invoked).
53 struct git_transport_options transport_options;
56 static void sendline(struct helper_data *helper, struct strbuf *buffer)
58 if (debug)
59 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
60 if (write_in_full(helper->helper->in, buffer->buf, buffer->len) < 0)
61 die_errno(_("full write to remote helper failed"));
64 static int recvline_fh(FILE *helper, struct strbuf *buffer)
66 strbuf_reset(buffer);
67 if (debug)
68 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
69 if (strbuf_getline(buffer, helper) == EOF) {
70 if (debug)
71 fprintf(stderr, "Debug: Remote helper quit.\n");
72 return 1;
75 if (debug)
76 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
77 return 0;
80 static int recvline(struct helper_data *helper, struct strbuf *buffer)
82 return recvline_fh(helper->out, buffer);
85 static void write_constant(int fd, const char *str)
87 if (debug)
88 fprintf(stderr, "Debug: Remote helper: -> %s", str);
89 if (write_in_full(fd, str, strlen(str)) < 0)
90 die_errno(_("full write to remote helper failed"));
93 static const char *remove_ext_force(const char *url)
95 if (url) {
96 const char *colon = strchr(url, ':');
97 if (colon && colon[1] == ':')
98 return colon + 2;
100 return url;
103 static void do_take_over(struct transport *transport)
105 struct helper_data *data;
106 data = (struct helper_data *)transport->data;
107 transport_take_over(transport, data->helper);
108 fclose(data->out);
109 free(data);
112 static void standard_options(struct transport *t);
114 static struct child_process *get_helper(struct transport *transport)
116 struct helper_data *data = transport->data;
117 struct strbuf buf = STRBUF_INIT;
118 struct child_process *helper;
119 int duped;
120 int code;
122 if (data->helper)
123 return data->helper;
125 helper = xmalloc(sizeof(*helper));
126 child_process_init(helper);
127 helper->in = -1;
128 helper->out = -1;
129 helper->err = 0;
130 argv_array_pushf(&helper->args, "git-remote-%s", data->name);
131 argv_array_push(&helper->args, transport->remote->name);
132 argv_array_push(&helper->args, remove_ext_force(transport->url));
133 helper->git_cmd = 0;
134 helper->silent_exec_failure = 1;
136 if (have_git_dir())
137 argv_array_pushf(&helper->env_array, "%s=%s",
138 GIT_DIR_ENVIRONMENT, get_git_dir());
140 helper->trace2_child_class = helper->args.argv[0]; /* "remote-<name>" */
142 code = start_command(helper);
143 if (code < 0 && errno == ENOENT)
144 die(_("unable to find remote helper for '%s'"), data->name);
145 else if (code != 0)
146 exit(code);
148 data->helper = helper;
149 data->no_disconnect_req = 0;
150 refspec_init(&data->rs, REFSPEC_FETCH);
153 * Open the output as FILE* so strbuf_getline_*() family of
154 * functions can be used.
155 * Do this with duped fd because fclose() will close the fd,
156 * and stuff like taking over will require the fd to remain.
158 duped = dup(helper->out);
159 if (duped < 0)
160 die_errno(_("can't dup helper output fd"));
161 data->out = xfdopen(duped, "r");
163 write_constant(helper->in, "capabilities\n");
165 while (1) {
166 const char *capname, *arg;
167 int mandatory = 0;
168 if (recvline(data, &buf))
169 exit(128);
171 if (!*buf.buf)
172 break;
174 if (*buf.buf == '*') {
175 capname = buf.buf + 1;
176 mandatory = 1;
177 } else
178 capname = buf.buf;
180 if (debug)
181 fprintf(stderr, "Debug: Got cap %s\n", capname);
182 if (!strcmp(capname, "fetch"))
183 data->fetch = 1;
184 else if (!strcmp(capname, "option"))
185 data->option = 1;
186 else if (!strcmp(capname, "push"))
187 data->push = 1;
188 else if (!strcmp(capname, "import"))
189 data->import = 1;
190 else if (!strcmp(capname, "bidi-import"))
191 data->bidi_import = 1;
192 else if (!strcmp(capname, "export"))
193 data->export = 1;
194 else if (!strcmp(capname, "check-connectivity"))
195 data->check_connectivity = 1;
196 else if (skip_prefix(capname, "refspec ", &arg)) {
197 refspec_append(&data->rs, arg);
198 } else if (!strcmp(capname, "connect")) {
199 data->connect = 1;
200 } else if (!strcmp(capname, "stateless-connect")) {
201 data->stateless_connect = 1;
202 } else if (!strcmp(capname, "signed-tags")) {
203 data->signed_tags = 1;
204 } else if (skip_prefix(capname, "export-marks ", &arg)) {
205 data->export_marks = xstrdup(arg);
206 } else if (skip_prefix(capname, "import-marks ", &arg)) {
207 data->import_marks = xstrdup(arg);
208 } else if (starts_with(capname, "no-private-update")) {
209 data->no_private_update = 1;
210 } else if (mandatory) {
211 die(_("unknown mandatory capability %s; this remote "
212 "helper probably needs newer version of Git"),
213 capname);
216 if (!data->rs.nr && (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 standard_options(transport);
223 return data->helper;
226 static int disconnect_helper(struct transport *transport)
228 struct helper_data *data = transport->data;
229 int res = 0;
231 if (data->helper) {
232 if (debug)
233 fprintf(stderr, "Debug: Disconnecting.\n");
234 if (!data->no_disconnect_req) {
236 * Ignore write errors; there's nothing we can do,
237 * since we're about to close the pipe anyway. And the
238 * most likely error is EPIPE due to the helper dying
239 * to report an error itself.
241 sigchain_push(SIGPIPE, SIG_IGN);
242 xwrite(data->helper->in, "\n", 1);
243 sigchain_pop(SIGPIPE);
245 close(data->helper->in);
246 close(data->helper->out);
247 fclose(data->out);
248 res = finish_command(data->helper);
249 FREE_AND_NULL(data->helper);
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,
265 TRANS_OPT_DEEPEN_RELATIVE
268 static int strbuf_set_helper_option(struct helper_data *data,
269 struct strbuf *buf)
271 int ret;
273 sendline(data, buf);
274 if (recvline(data, buf))
275 exit(128);
277 if (!strcmp(buf->buf, "ok"))
278 ret = 0;
279 else if (starts_with(buf->buf, "error"))
280 ret = -1;
281 else if (!strcmp(buf->buf, "unsupported"))
282 ret = 1;
283 else {
284 warning(_("%s unexpectedly said: '%s'"), data->name, buf->buf);
285 ret = 1;
287 return ret;
290 static int string_list_set_helper_option(struct helper_data *data,
291 const char *name,
292 struct string_list *list)
294 struct strbuf buf = STRBUF_INIT;
295 int i, ret = 0;
297 for (i = 0; i < list->nr; i++) {
298 strbuf_addf(&buf, "option %s ", name);
299 quote_c_style(list->items[i].string, &buf, NULL, 0);
300 strbuf_addch(&buf, '\n');
302 if ((ret = strbuf_set_helper_option(data, &buf)))
303 break;
304 strbuf_reset(&buf);
306 strbuf_release(&buf);
307 return ret;
310 static int set_helper_option(struct transport *transport,
311 const char *name, const char *value)
313 struct helper_data *data = transport->data;
314 struct strbuf buf = STRBUF_INIT;
315 int i, ret, is_bool = 0;
317 get_helper(transport);
319 if (!data->option)
320 return 1;
322 if (!strcmp(name, "deepen-not"))
323 return string_list_set_helper_option(data, name,
324 (struct string_list *)value);
326 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
327 if (!strcmp(name, unsupported_options[i]))
328 return 1;
331 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
332 if (!strcmp(name, boolean_options[i])) {
333 is_bool = 1;
334 break;
338 strbuf_addf(&buf, "option %s ", name);
339 if (is_bool)
340 strbuf_addstr(&buf, value ? "true" : "false");
341 else
342 quote_c_style(value, &buf, NULL, 0);
343 strbuf_addch(&buf, '\n');
345 ret = strbuf_set_helper_option(data, &buf);
346 strbuf_release(&buf);
347 return ret;
350 static void standard_options(struct transport *t)
352 char buf[16];
353 int v = t->verbose;
355 set_helper_option(t, "progress", t->progress ? "true" : "false");
357 xsnprintf(buf, sizeof(buf), "%d", v + 1);
358 set_helper_option(t, "verbosity", buf);
360 switch (t->family) {
361 case TRANSPORT_FAMILY_ALL:
363 * this is already the default,
364 * do not break old remote helpers by setting "all" here
366 break;
367 case TRANSPORT_FAMILY_IPV4:
368 set_helper_option(t, "family", "ipv4");
369 break;
370 case TRANSPORT_FAMILY_IPV6:
371 set_helper_option(t, "family", "ipv6");
372 break;
376 static int release_helper(struct transport *transport)
378 int res = 0;
379 struct helper_data *data = transport->data;
380 refspec_clear(&data->rs);
381 res = disconnect_helper(transport);
382 free(transport->data);
383 return res;
386 static int fetch_with_fetch(struct transport *transport,
387 int nr_heads, struct ref **to_fetch)
389 struct helper_data *data = transport->data;
390 int i;
391 struct strbuf buf = STRBUF_INIT;
393 for (i = 0; i < nr_heads; i++) {
394 const struct ref *posn = to_fetch[i];
395 if (posn->status & REF_STATUS_UPTODATE)
396 continue;
398 strbuf_addf(&buf, "fetch %s %s\n",
399 oid_to_hex(&posn->old_oid),
400 posn->symref ? posn->symref : posn->name);
403 strbuf_addch(&buf, '\n');
404 sendline(data, &buf);
406 while (1) {
407 const char *name;
409 if (recvline(data, &buf))
410 exit(128);
412 if (skip_prefix(buf.buf, "lock ", &name)) {
413 if (transport->pack_lockfile)
414 warning(_("%s also locked %s"), data->name, name);
415 else
416 transport->pack_lockfile = xstrdup(name);
418 else if (data->check_connectivity &&
419 data->transport_options.check_self_contained_and_connected &&
420 !strcmp(buf.buf, "connectivity-ok"))
421 data->transport_options.self_contained_and_connected = 1;
422 else if (!buf.len)
423 break;
424 else
425 warning(_("%s unexpectedly said: '%s'"), data->name, buf.buf);
427 strbuf_release(&buf);
428 return 0;
431 static int get_importer(struct transport *transport, struct child_process *fastimport)
433 struct child_process *helper = get_helper(transport);
434 struct helper_data *data = transport->data;
435 int cat_blob_fd, code;
436 child_process_init(fastimport);
437 fastimport->in = xdup(helper->out);
438 argv_array_push(&fastimport->args, "fast-import");
439 argv_array_push(&fastimport->args, "--allow-unsafe-features");
440 argv_array_push(&fastimport->args, debug ? "--stats" : "--quiet");
442 if (data->bidi_import) {
443 cat_blob_fd = xdup(helper->in);
444 argv_array_pushf(&fastimport->args, "--cat-blob-fd=%d", cat_blob_fd);
446 fastimport->git_cmd = 1;
448 code = start_command(fastimport);
449 return code;
452 static int get_exporter(struct transport *transport,
453 struct child_process *fastexport,
454 struct string_list *revlist_args)
456 struct helper_data *data = transport->data;
457 struct child_process *helper = get_helper(transport);
458 int i;
460 child_process_init(fastexport);
462 /* we need to duplicate helper->in because we want to use it after
463 * fastexport is done with it. */
464 fastexport->out = dup(helper->in);
465 argv_array_push(&fastexport->args, "fast-export");
466 argv_array_push(&fastexport->args, "--use-done-feature");
467 argv_array_push(&fastexport->args, data->signed_tags ?
468 "--signed-tags=verbatim" : "--signed-tags=warn-strip");
469 if (data->export_marks)
470 argv_array_pushf(&fastexport->args, "--export-marks=%s.tmp", data->export_marks);
471 if (data->import_marks)
472 argv_array_pushf(&fastexport->args, "--import-marks=%s", data->import_marks);
474 for (i = 0; i < revlist_args->nr; i++)
475 argv_array_push(&fastexport->args, revlist_args->items[i].string);
477 fastexport->git_cmd = 1;
478 return start_command(fastexport);
481 static int fetch_with_import(struct transport *transport,
482 int nr_heads, struct ref **to_fetch)
484 struct child_process fastimport;
485 struct helper_data *data = transport->data;
486 int i;
487 struct ref *posn;
488 struct strbuf buf = STRBUF_INIT;
490 get_helper(transport);
492 if (get_importer(transport, &fastimport))
493 die(_("couldn't run fast-import"));
495 for (i = 0; i < nr_heads; i++) {
496 posn = to_fetch[i];
497 if (posn->status & REF_STATUS_UPTODATE)
498 continue;
500 strbuf_addf(&buf, "import %s\n",
501 posn->symref ? posn->symref : posn->name);
502 sendline(data, &buf);
503 strbuf_reset(&buf);
506 write_constant(data->helper->in, "\n");
508 * remote-helpers that advertise the bidi-import capability are required to
509 * buffer the complete batch of import commands until this newline before
510 * sending data to fast-import.
511 * These helpers read back data from fast-import on their stdin, which could
512 * be mixed with import commands, otherwise.
515 if (finish_command(&fastimport))
516 die(_("error while running fast-import"));
519 * The fast-import stream of a remote helper that advertises
520 * the "refspec" capability writes to the refs named after the
521 * right hand side of the first refspec matching each ref we
522 * were fetching.
524 * (If no "refspec" capability was specified, for historical
525 * reasons we default to the equivalent of *:*.)
527 * Store the result in to_fetch[i].old_sha1. Callers such
528 * as "git fetch" can use the value to write feedback to the
529 * terminal, populate FETCH_HEAD, and determine what new value
530 * should be written to peer_ref if the update is a
531 * fast-forward or this is a forced update.
533 for (i = 0; i < nr_heads; i++) {
534 char *private, *name;
535 posn = to_fetch[i];
536 if (posn->status & REF_STATUS_UPTODATE)
537 continue;
538 name = posn->symref ? posn->symref : posn->name;
539 if (data->rs.nr)
540 private = apply_refspecs(&data->rs, name);
541 else
542 private = xstrdup(name);
543 if (private) {
544 if (read_ref(private, &posn->old_oid) < 0)
545 die(_("could not read ref %s"), private);
546 free(private);
549 strbuf_release(&buf);
550 return 0;
553 static int run_connect(struct transport *transport, struct strbuf *cmdbuf)
555 struct helper_data *data = transport->data;
556 int ret = 0;
557 int duped;
558 FILE *input;
559 struct child_process *helper;
561 helper = get_helper(transport);
564 * Yes, dup the pipe another time, as we need unbuffered version
565 * of input pipe as FILE*. fclose() closes the underlying fd and
566 * stream buffering only can be changed before first I/O operation
567 * on it.
569 duped = dup(helper->out);
570 if (duped < 0)
571 die_errno(_("can't dup helper output fd"));
572 input = xfdopen(duped, "r");
573 setvbuf(input, NULL, _IONBF, 0);
575 sendline(data, cmdbuf);
576 if (recvline_fh(input, cmdbuf))
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);
594 fclose(input);
595 return ret;
598 static int process_connect_service(struct transport *transport,
599 const char *name, const char *exec)
601 struct helper_data *data = transport->data;
602 struct strbuf cmdbuf = STRBUF_INIT;
603 int ret = 0;
606 * Handle --upload-pack and friends. This is fire and forget...
607 * just warn if it fails.
609 if (strcmp(name, exec)) {
610 int r = set_helper_option(transport, "servpath", exec);
611 if (r > 0)
612 warning(_("setting remote service path not supported by protocol"));
613 else if (r < 0)
614 warning(_("invalid remote service path"));
617 if (data->connect) {
618 strbuf_addf(&cmdbuf, "connect %s\n", name);
619 ret = run_connect(transport, &cmdbuf);
620 } else if (data->stateless_connect &&
621 (get_protocol_version_config() == protocol_v2) &&
622 !strcmp("git-upload-pack", name)) {
623 strbuf_addf(&cmdbuf, "stateless-connect %s\n", name);
624 ret = run_connect(transport, &cmdbuf);
625 if (ret)
626 transport->stateless_rpc = 1;
629 strbuf_release(&cmdbuf);
630 return ret;
633 static int process_connect(struct transport *transport,
634 int for_push)
636 struct helper_data *data = transport->data;
637 const char *name;
638 const char *exec;
640 name = for_push ? "git-receive-pack" : "git-upload-pack";
641 if (for_push)
642 exec = data->transport_options.receivepack;
643 else
644 exec = data->transport_options.uploadpack;
646 return process_connect_service(transport, name, exec);
649 static int connect_helper(struct transport *transport, const char *name,
650 const char *exec, int fd[2])
652 struct helper_data *data = transport->data;
654 /* Get_helper so connect is inited. */
655 get_helper(transport);
656 if (!data->connect)
657 die(_("operation not supported by protocol"));
659 if (!process_connect_service(transport, name, exec))
660 die(_("can't connect to subservice %s"), name);
662 fd[0] = data->helper->out;
663 fd[1] = data->helper->in;
664 return 0;
667 static struct ref *get_refs_list_using_list(struct transport *transport,
668 int for_push);
670 static int fetch(struct transport *transport,
671 int nr_heads, struct ref **to_fetch)
673 struct helper_data *data = transport->data;
674 int i, count;
676 get_helper(transport);
678 if (process_connect(transport, 0)) {
679 do_take_over(transport);
680 return transport->vtable->fetch(transport, nr_heads, to_fetch);
683 if (!data->get_refs_list_called)
684 get_refs_list_using_list(transport, 0);
686 count = 0;
687 for (i = 0; i < nr_heads; i++)
688 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
689 count++;
691 if (!count)
692 return 0;
694 if (data->check_connectivity &&
695 data->transport_options.check_self_contained_and_connected)
696 set_helper_option(transport, "check-connectivity", "true");
698 if (transport->cloning)
699 set_helper_option(transport, "cloning", "true");
701 if (data->transport_options.update_shallow)
702 set_helper_option(transport, "update-shallow", "true");
704 if (data->transport_options.filter_options.choice) {
705 const char *spec = expand_list_objects_filter_spec(
706 &data->transport_options.filter_options);
707 set_helper_option(transport, "filter", spec);
710 if (data->transport_options.negotiation_tips)
711 warning("Ignoring --negotiation-tip because the protocol does not support it.");
713 if (data->fetch)
714 return fetch_with_fetch(transport, nr_heads, to_fetch);
716 if (data->import)
717 return fetch_with_import(transport, nr_heads, to_fetch);
719 return -1;
722 static int push_update_ref_status(struct strbuf *buf,
723 struct ref **ref,
724 struct ref *remote_refs)
726 char *refname, *msg;
727 int status, forced = 0;
729 if (starts_with(buf->buf, "ok ")) {
730 status = REF_STATUS_OK;
731 refname = buf->buf + 3;
732 } else if (starts_with(buf->buf, "error ")) {
733 status = REF_STATUS_REMOTE_REJECT;
734 refname = buf->buf + 6;
735 } else
736 die(_("expected ok/error, helper said '%s'"), buf->buf);
738 msg = strchr(refname, ' ');
739 if (msg) {
740 struct strbuf msg_buf = STRBUF_INIT;
741 const char *end;
743 *msg++ = '\0';
744 if (!unquote_c_style(&msg_buf, msg, &end))
745 msg = strbuf_detach(&msg_buf, NULL);
746 else
747 msg = xstrdup(msg);
748 strbuf_release(&msg_buf);
750 if (!strcmp(msg, "no match")) {
751 status = REF_STATUS_NONE;
752 FREE_AND_NULL(msg);
754 else if (!strcmp(msg, "up to date")) {
755 status = REF_STATUS_UPTODATE;
756 FREE_AND_NULL(msg);
758 else if (!strcmp(msg, "non-fast forward")) {
759 status = REF_STATUS_REJECT_NONFASTFORWARD;
760 FREE_AND_NULL(msg);
762 else if (!strcmp(msg, "already exists")) {
763 status = REF_STATUS_REJECT_ALREADY_EXISTS;
764 FREE_AND_NULL(msg);
766 else if (!strcmp(msg, "fetch first")) {
767 status = REF_STATUS_REJECT_FETCH_FIRST;
768 FREE_AND_NULL(msg);
770 else if (!strcmp(msg, "needs force")) {
771 status = REF_STATUS_REJECT_NEEDS_FORCE;
772 FREE_AND_NULL(msg);
774 else if (!strcmp(msg, "stale info")) {
775 status = REF_STATUS_REJECT_STALE;
776 FREE_AND_NULL(msg);
778 else if (!strcmp(msg, "forced update")) {
779 forced = 1;
780 FREE_AND_NULL(msg);
784 if (*ref)
785 *ref = find_ref_by_name(*ref, refname);
786 if (!*ref)
787 *ref = find_ref_by_name(remote_refs, refname);
788 if (!*ref) {
789 warning(_("helper reported unexpected status of %s"), refname);
790 return 1;
793 if ((*ref)->status != REF_STATUS_NONE) {
795 * Earlier, the ref was marked not to be pushed, so ignore the ref
796 * status reported by the remote helper if the latter is 'no match'.
798 if (status == REF_STATUS_NONE)
799 return 1;
802 (*ref)->status = status;
803 (*ref)->forced_update |= forced;
804 (*ref)->remote_status = msg;
805 return !(status == REF_STATUS_OK);
808 static int push_update_refs_status(struct helper_data *data,
809 struct ref *remote_refs,
810 int flags)
812 struct strbuf buf = STRBUF_INIT;
813 struct ref *ref = remote_refs;
814 int ret = 0;
816 for (;;) {
817 char *private;
819 if (recvline(data, &buf)) {
820 ret = 1;
821 break;
824 if (!buf.len)
825 break;
827 if (push_update_ref_status(&buf, &ref, remote_refs))
828 continue;
830 if (flags & TRANSPORT_PUSH_DRY_RUN || !data->rs.nr || data->no_private_update)
831 continue;
833 /* propagate back the update to the remote namespace */
834 private = apply_refspecs(&data->rs, ref->name);
835 if (!private)
836 continue;
837 update_ref("update by helper", private, &ref->new_oid, NULL,
838 0, 0);
839 free(private);
841 strbuf_release(&buf);
842 return ret;
845 static void set_common_push_options(struct transport *transport,
846 const char *name, int flags)
848 if (flags & TRANSPORT_PUSH_DRY_RUN) {
849 if (set_helper_option(transport, "dry-run", "true") != 0)
850 die(_("helper %s does not support dry-run"), name);
851 } else if (flags & TRANSPORT_PUSH_CERT_ALWAYS) {
852 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "true") != 0)
853 die(_("helper %s does not support --signed"), name);
854 } else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED) {
855 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "if-asked") != 0)
856 die(_("helper %s does not support --signed=if-asked"), name);
859 if (flags & TRANSPORT_PUSH_ATOMIC)
860 if (set_helper_option(transport, TRANS_OPT_ATOMIC, "true") != 0)
861 die(_("helper %s does not support --atomic"), name);
863 if (flags & TRANSPORT_PUSH_OPTIONS) {
864 struct string_list_item *item;
865 for_each_string_list_item(item, transport->push_options)
866 if (set_helper_option(transport, "push-option", item->string) != 0)
867 die(_("helper %s does not support 'push-option'"), name);
871 static int push_refs_with_push(struct transport *transport,
872 struct ref *remote_refs, int flags)
874 int force_all = flags & TRANSPORT_PUSH_FORCE;
875 int mirror = flags & TRANSPORT_PUSH_MIRROR;
876 int atomic = flags & TRANSPORT_PUSH_ATOMIC;
877 struct helper_data *data = transport->data;
878 struct strbuf buf = STRBUF_INIT;
879 struct ref *ref;
880 struct string_list cas_options = STRING_LIST_INIT_DUP;
881 struct string_list_item *cas_option;
883 get_helper(transport);
884 if (!data->push)
885 return 1;
887 for (ref = remote_refs; ref; ref = ref->next) {
888 if (!ref->peer_ref && !mirror)
889 continue;
891 /* Check for statuses set by set_ref_status_for_push() */
892 switch (ref->status) {
893 case REF_STATUS_REJECT_NONFASTFORWARD:
894 case REF_STATUS_REJECT_STALE:
895 case REF_STATUS_REJECT_ALREADY_EXISTS:
896 if (atomic) {
897 string_list_clear(&cas_options, 0);
898 return 0;
899 } else
900 continue;
901 case REF_STATUS_UPTODATE:
902 continue;
903 default:
904 ; /* do nothing */
907 if (force_all)
908 ref->force = 1;
910 strbuf_addstr(&buf, "push ");
911 if (!ref->deletion) {
912 if (ref->force)
913 strbuf_addch(&buf, '+');
914 if (ref->peer_ref)
915 strbuf_addstr(&buf, ref->peer_ref->name);
916 else
917 strbuf_addstr(&buf, oid_to_hex(&ref->new_oid));
919 strbuf_addch(&buf, ':');
920 strbuf_addstr(&buf, ref->name);
921 strbuf_addch(&buf, '\n');
924 * The "--force-with-lease" options without explicit
925 * values to expect have already been expanded into
926 * the ref->old_oid_expect[] field; we can ignore
927 * transport->smart_options->cas altogether and instead
928 * can enumerate them from the refs.
930 if (ref->expect_old_sha1) {
931 struct strbuf cas = STRBUF_INIT;
932 strbuf_addf(&cas, "%s:%s",
933 ref->name, oid_to_hex(&ref->old_oid_expect));
934 string_list_append_nodup(&cas_options,
935 strbuf_detach(&cas, NULL));
938 if (buf.len == 0) {
939 string_list_clear(&cas_options, 0);
940 return 0;
943 for_each_string_list_item(cas_option, &cas_options)
944 set_helper_option(transport, "cas", cas_option->string);
945 set_common_push_options(transport, data->name, flags);
947 strbuf_addch(&buf, '\n');
948 sendline(data, &buf);
949 strbuf_release(&buf);
950 string_list_clear(&cas_options, 0);
952 return push_update_refs_status(data, remote_refs, flags);
955 static int push_refs_with_export(struct transport *transport,
956 struct ref *remote_refs, int flags)
958 struct ref *ref;
959 struct child_process *helper, exporter;
960 struct helper_data *data = transport->data;
961 struct string_list revlist_args = STRING_LIST_INIT_DUP;
962 struct strbuf buf = STRBUF_INIT;
964 if (!data->rs.nr)
965 die(_("remote-helper doesn't support push; refspec needed"));
967 set_common_push_options(transport, data->name, flags);
968 if (flags & TRANSPORT_PUSH_FORCE) {
969 if (set_helper_option(transport, "force", "true") != 0)
970 warning(_("helper %s does not support 'force'"), data->name);
973 helper = get_helper(transport);
975 write_constant(helper->in, "export\n");
977 for (ref = remote_refs; ref; ref = ref->next) {
978 char *private;
979 struct object_id oid;
981 private = apply_refspecs(&data->rs, ref->name);
982 if (private && !get_oid(private, &oid)) {
983 strbuf_addf(&buf, "^%s", private);
984 string_list_append_nodup(&revlist_args,
985 strbuf_detach(&buf, NULL));
986 oidcpy(&ref->old_oid, &oid);
988 free(private);
990 if (ref->peer_ref) {
991 if (strcmp(ref->name, ref->peer_ref->name)) {
992 if (!ref->deletion) {
993 const char *name;
994 int flag;
996 /* Follow symbolic refs (mainly for HEAD). */
997 name = resolve_ref_unsafe(ref->peer_ref->name,
998 RESOLVE_REF_READING,
999 &oid, &flag);
1000 if (!name || !(flag & REF_ISSYMREF))
1001 name = ref->peer_ref->name;
1003 strbuf_addf(&buf, "%s:%s", name, ref->name);
1004 } else
1005 strbuf_addf(&buf, ":%s", ref->name);
1007 string_list_append(&revlist_args, "--refspec");
1008 string_list_append(&revlist_args, buf.buf);
1009 strbuf_release(&buf);
1011 if (!ref->deletion)
1012 string_list_append(&revlist_args, ref->peer_ref->name);
1016 if (get_exporter(transport, &exporter, &revlist_args))
1017 die(_("couldn't run fast-export"));
1019 string_list_clear(&revlist_args, 1);
1021 if (finish_command(&exporter))
1022 die(_("error while running fast-export"));
1023 if (push_update_refs_status(data, remote_refs, flags))
1024 return 1;
1026 if (data->export_marks) {
1027 strbuf_addf(&buf, "%s.tmp", data->export_marks);
1028 rename(buf.buf, data->export_marks);
1029 strbuf_release(&buf);
1032 return 0;
1035 static int push_refs(struct transport *transport,
1036 struct ref *remote_refs, int flags)
1038 struct helper_data *data = transport->data;
1040 if (process_connect(transport, 1)) {
1041 do_take_over(transport);
1042 return transport->vtable->push_refs(transport, remote_refs, flags);
1045 if (!remote_refs) {
1046 fprintf(stderr,
1047 _("No refs in common and none specified; doing nothing.\n"
1048 "Perhaps you should specify a branch such as 'master'.\n"));
1049 return 0;
1052 if (data->push)
1053 return push_refs_with_push(transport, remote_refs, flags);
1055 if (data->export)
1056 return push_refs_with_export(transport, remote_refs, flags);
1058 return -1;
1062 static int has_attribute(const char *attrs, const char *attr)
1064 int len;
1065 if (!attrs)
1066 return 0;
1068 len = strlen(attr);
1069 for (;;) {
1070 const char *space = strchrnul(attrs, ' ');
1071 if (len == space - attrs && !strncmp(attrs, attr, len))
1072 return 1;
1073 if (!*space)
1074 return 0;
1075 attrs = space + 1;
1079 static struct ref *get_refs_list(struct transport *transport, int for_push,
1080 const struct argv_array *ref_prefixes)
1082 get_helper(transport);
1084 if (process_connect(transport, for_push)) {
1085 do_take_over(transport);
1086 return transport->vtable->get_refs_list(transport, for_push, ref_prefixes);
1089 return get_refs_list_using_list(transport, for_push);
1092 static struct ref *get_refs_list_using_list(struct transport *transport,
1093 int for_push)
1095 struct helper_data *data = transport->data;
1096 struct child_process *helper;
1097 struct ref *ret = NULL;
1098 struct ref **tail = &ret;
1099 struct ref *posn;
1100 struct strbuf buf = STRBUF_INIT;
1102 data->get_refs_list_called = 1;
1103 helper = get_helper(transport);
1105 if (data->push && for_push)
1106 write_str_in_full(helper->in, "list for-push\n");
1107 else
1108 write_str_in_full(helper->in, "list\n");
1110 while (1) {
1111 char *eov, *eon;
1112 if (recvline(data, &buf))
1113 exit(128);
1115 if (!*buf.buf)
1116 break;
1118 eov = strchr(buf.buf, ' ');
1119 if (!eov)
1120 die(_("malformed response in ref list: %s"), buf.buf);
1121 eon = strchr(eov + 1, ' ');
1122 *eov = '\0';
1123 if (eon)
1124 *eon = '\0';
1125 *tail = alloc_ref(eov + 1);
1126 if (buf.buf[0] == '@')
1127 (*tail)->symref = xstrdup(buf.buf + 1);
1128 else if (buf.buf[0] != '?')
1129 get_oid_hex(buf.buf, &(*tail)->old_oid);
1130 if (eon) {
1131 if (has_attribute(eon + 1, "unchanged")) {
1132 (*tail)->status |= REF_STATUS_UPTODATE;
1133 if (read_ref((*tail)->name, &(*tail)->old_oid) < 0)
1134 die(_("could not read ref %s"),
1135 (*tail)->name);
1138 tail = &((*tail)->next);
1140 if (debug)
1141 fprintf(stderr, "Debug: Read ref listing.\n");
1142 strbuf_release(&buf);
1144 for (posn = ret; posn; posn = posn->next)
1145 resolve_remote_symref(posn, ret);
1147 return ret;
1150 static struct transport_vtable vtable = {
1151 set_helper_option,
1152 get_refs_list,
1153 fetch,
1154 push_refs,
1155 connect_helper,
1156 release_helper
1159 int transport_helper_init(struct transport *transport, const char *name)
1161 struct helper_data *data = xcalloc(1, sizeof(*data));
1162 data->name = name;
1164 transport_check_allowed(name);
1166 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1167 debug = 1;
1169 transport->data = data;
1170 transport->vtable = &vtable;
1171 transport->smart_options = &(data->transport_options);
1172 return 0;
1176 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1177 * buffer less), so attempt reads and writes with up to that size.
1179 #define BUFFERSIZE 65536
1180 /* This should be enough to hold debugging message. */
1181 #define PBUFFERSIZE 8192
1183 /* Print bidirectional transfer loop debug message. */
1184 __attribute__((format (printf, 1, 2)))
1185 static void transfer_debug(const char *fmt, ...)
1188 * NEEDSWORK: This function is sometimes used from multiple threads, and
1189 * we end up using debug_enabled racily. That "should not matter" since
1190 * we always write the same value, but it's still wrong. This function
1191 * is listed in .tsan-suppressions for the time being.
1194 va_list args;
1195 char msgbuf[PBUFFERSIZE];
1196 static int debug_enabled = -1;
1198 if (debug_enabled < 0)
1199 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1200 if (!debug_enabled)
1201 return;
1203 va_start(args, fmt);
1204 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1205 va_end(args);
1206 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1209 /* Stream state: More data may be coming in this direction. */
1210 #define SSTATE_TRANSFERRING 0
1212 * Stream state: No more data coming in this direction, flushing rest of
1213 * data.
1215 #define SSTATE_FLUSHING 1
1216 /* Stream state: Transfer in this direction finished. */
1217 #define SSTATE_FINISHED 2
1219 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERRING)
1220 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1221 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1223 /* Unidirectional transfer. */
1224 struct unidirectional_transfer {
1225 /* Source */
1226 int src;
1227 /* Destination */
1228 int dest;
1229 /* Is source socket? */
1230 int src_is_sock;
1231 /* Is destination socket? */
1232 int dest_is_sock;
1233 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1234 int state;
1235 /* Buffer. */
1236 char buf[BUFFERSIZE];
1237 /* Buffer used. */
1238 size_t bufuse;
1239 /* Name of source. */
1240 const char *src_name;
1241 /* Name of destination. */
1242 const char *dest_name;
1245 /* Closes the target (for writing) if transfer has finished. */
1246 static void udt_close_if_finished(struct unidirectional_transfer *t)
1248 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1249 t->state = SSTATE_FINISHED;
1250 if (t->dest_is_sock)
1251 shutdown(t->dest, SHUT_WR);
1252 else
1253 close(t->dest);
1254 transfer_debug("Closed %s.", t->dest_name);
1259 * Tries to read data from source into buffer. If buffer is full,
1260 * no data is read. Returns 0 on success, -1 on error.
1262 static int udt_do_read(struct unidirectional_transfer *t)
1264 ssize_t bytes;
1266 if (t->bufuse == BUFFERSIZE)
1267 return 0; /* No space for more. */
1269 transfer_debug("%s is readable", t->src_name);
1270 bytes = xread(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1271 if (bytes < 0) {
1272 error_errno(_("read(%s) failed"), t->src_name);
1273 return -1;
1274 } else if (bytes == 0) {
1275 transfer_debug("%s EOF (with %i bytes in buffer)",
1276 t->src_name, (int)t->bufuse);
1277 t->state = SSTATE_FLUSHING;
1278 } else if (bytes > 0) {
1279 t->bufuse += bytes;
1280 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1281 (int)bytes, t->src_name, (int)t->bufuse);
1283 return 0;
1286 /* Tries to write data from buffer into destination. If buffer is empty,
1287 * no data is written. Returns 0 on success, -1 on error.
1289 static int udt_do_write(struct unidirectional_transfer *t)
1291 ssize_t bytes;
1293 if (t->bufuse == 0)
1294 return 0; /* Nothing to write. */
1296 transfer_debug("%s is writable", t->dest_name);
1297 bytes = xwrite(t->dest, t->buf, t->bufuse);
1298 if (bytes < 0) {
1299 error_errno(_("write(%s) failed"), t->dest_name);
1300 return -1;
1301 } else if (bytes > 0) {
1302 t->bufuse -= bytes;
1303 if (t->bufuse)
1304 memmove(t->buf, t->buf + bytes, t->bufuse);
1305 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1306 (int)bytes, t->dest_name, (int)t->bufuse);
1308 return 0;
1312 /* State of bidirectional transfer loop. */
1313 struct bidirectional_transfer_state {
1314 /* Direction from program to git. */
1315 struct unidirectional_transfer ptg;
1316 /* Direction from git to program. */
1317 struct unidirectional_transfer gtp;
1320 static void *udt_copy_task_routine(void *udt)
1322 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1323 while (t->state != SSTATE_FINISHED) {
1324 if (STATE_NEEDS_READING(t->state))
1325 if (udt_do_read(t))
1326 return NULL;
1327 if (STATE_NEEDS_WRITING(t->state))
1328 if (udt_do_write(t))
1329 return NULL;
1330 if (STATE_NEEDS_CLOSING(t->state))
1331 udt_close_if_finished(t);
1333 return udt; /* Just some non-NULL value. */
1336 #ifndef NO_PTHREADS
1339 * Join thread, with appropriate errors on failure. Name is name for the
1340 * thread (for error messages). Returns 0 on success, 1 on failure.
1342 static int tloop_join(pthread_t thread, const char *name)
1344 int err;
1345 void *tret;
1346 err = pthread_join(thread, &tret);
1347 if (!tret) {
1348 error(_("%s thread failed"), name);
1349 return 1;
1351 if (err) {
1352 error(_("%s thread failed to join: %s"), name, strerror(err));
1353 return 1;
1355 return 0;
1359 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1360 * -1 on failure.
1362 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1364 pthread_t gtp_thread;
1365 pthread_t ptg_thread;
1366 int err;
1367 int ret = 0;
1368 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1369 &s->gtp);
1370 if (err)
1371 die(_("can't start thread for copying data: %s"), strerror(err));
1372 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1373 &s->ptg);
1374 if (err)
1375 die(_("can't start thread for copying data: %s"), strerror(err));
1377 ret |= tloop_join(gtp_thread, "Git to program copy");
1378 ret |= tloop_join(ptg_thread, "Program to git copy");
1379 return ret;
1381 #else
1383 /* Close the source and target (for writing) for transfer. */
1384 static void udt_kill_transfer(struct unidirectional_transfer *t)
1386 t->state = SSTATE_FINISHED;
1388 * Socket read end left open isn't a disaster if nobody
1389 * attempts to read from it (mingw compat headers do not
1390 * have SHUT_RD)...
1392 * We can't fully close the socket since otherwise gtp
1393 * task would first close the socket it sends data to
1394 * while closing the ptg file descriptors.
1396 if (!t->src_is_sock)
1397 close(t->src);
1398 if (t->dest_is_sock)
1399 shutdown(t->dest, SHUT_WR);
1400 else
1401 close(t->dest);
1405 * Join process, with appropriate errors on failure. Name is name for the
1406 * process (for error messages). Returns 0 on success, 1 on failure.
1408 static int tloop_join(pid_t pid, const char *name)
1410 int tret;
1411 if (waitpid(pid, &tret, 0) < 0) {
1412 error_errno(_("%s process failed to wait"), name);
1413 return 1;
1415 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1416 error(_("%s process failed"), name);
1417 return 1;
1419 return 0;
1423 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1424 * -1 on failure.
1426 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1428 pid_t pid1, pid2;
1429 int ret = 0;
1431 /* Fork thread #1: git to program. */
1432 pid1 = fork();
1433 if (pid1 < 0)
1434 die_errno(_("can't start thread for copying data"));
1435 else if (pid1 == 0) {
1436 udt_kill_transfer(&s->ptg);
1437 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1440 /* Fork thread #2: program to git. */
1441 pid2 = fork();
1442 if (pid2 < 0)
1443 die_errno(_("can't start thread for copying data"));
1444 else if (pid2 == 0) {
1445 udt_kill_transfer(&s->gtp);
1446 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1450 * Close both streams in parent as to not interfere with
1451 * end of file detection and wait for both tasks to finish.
1453 udt_kill_transfer(&s->gtp);
1454 udt_kill_transfer(&s->ptg);
1455 ret |= tloop_join(pid1, "Git to program copy");
1456 ret |= tloop_join(pid2, "Program to git copy");
1457 return ret;
1459 #endif
1462 * Copies data from stdin to output and from input to stdout simultaneously.
1463 * Additionally filtering through given filter. If filter is NULL, uses
1464 * identity filter.
1466 int bidirectional_transfer_loop(int input, int output)
1468 struct bidirectional_transfer_state state;
1470 /* Fill the state fields. */
1471 state.ptg.src = input;
1472 state.ptg.dest = 1;
1473 state.ptg.src_is_sock = (input == output);
1474 state.ptg.dest_is_sock = 0;
1475 state.ptg.state = SSTATE_TRANSFERRING;
1476 state.ptg.bufuse = 0;
1477 state.ptg.src_name = "remote input";
1478 state.ptg.dest_name = "stdout";
1480 state.gtp.src = 0;
1481 state.gtp.dest = output;
1482 state.gtp.src_is_sock = 0;
1483 state.gtp.dest_is_sock = (input == output);
1484 state.gtp.state = SSTATE_TRANSFERRING;
1485 state.gtp.bufuse = 0;
1486 state.gtp.src_name = "stdin";
1487 state.gtp.dest_name = "remote output";
1489 return tloop_spawnwait_tasks(&state);