git-p4: auto-size the block
[git.git] / transport-helper.c
blob11f1055b47e5e204a272e3588f74f161bdf73895
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 "transport-internal.h"
15 #include "protocol.h"
17 static int debug;
19 struct helper_data {
20 const char *name;
21 struct child_process *helper;
22 FILE *out;
23 unsigned fetch : 1,
24 import : 1,
25 bidi_import : 1,
26 export : 1,
27 option : 1,
28 push : 1,
29 connect : 1,
30 stateless_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) < 0)
51 die_errno("Full write to remote helper failed");
54 static int recvline_fh(FILE *helper, struct strbuf *buffer)
56 strbuf_reset(buffer);
57 if (debug)
58 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
59 if (strbuf_getline(buffer, helper) == EOF) {
60 if (debug)
61 fprintf(stderr, "Debug: Remote helper quit.\n");
62 return 1;
65 if (debug)
66 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
67 return 0;
70 static int recvline(struct helper_data *helper, struct strbuf *buffer)
72 return recvline_fh(helper->out, buffer);
75 static void write_constant(int fd, const char *str)
77 if (debug)
78 fprintf(stderr, "Debug: Remote helper: -> %s", str);
79 if (write_in_full(fd, str, strlen(str)) < 0)
80 die_errno("Full write to remote helper failed");
83 static const char *remove_ext_force(const char *url)
85 if (url) {
86 const char *colon = strchr(url, ':');
87 if (colon && colon[1] == ':')
88 return colon + 2;
90 return url;
93 static void do_take_over(struct transport *transport)
95 struct helper_data *data;
96 data = (struct helper_data *)transport->data;
97 transport_take_over(transport, data->helper);
98 fclose(data->out);
99 free(data);
102 static void standard_options(struct transport *t);
104 static struct child_process *get_helper(struct transport *transport)
106 struct helper_data *data = transport->data;
107 struct strbuf buf = STRBUF_INIT;
108 struct child_process *helper;
109 const char **refspecs = NULL;
110 int refspec_nr = 0;
111 int refspec_alloc = 0;
112 int duped;
113 int code;
115 if (data->helper)
116 return data->helper;
118 helper = xmalloc(sizeof(*helper));
119 child_process_init(helper);
120 helper->in = -1;
121 helper->out = -1;
122 helper->err = 0;
123 argv_array_pushf(&helper->args, "git-remote-%s", data->name);
124 argv_array_push(&helper->args, transport->remote->name);
125 argv_array_push(&helper->args, remove_ext_force(transport->url));
126 helper->git_cmd = 0;
127 helper->silent_exec_failure = 1;
129 if (have_git_dir())
130 argv_array_pushf(&helper->env_array, "%s=%s",
131 GIT_DIR_ENVIRONMENT, get_git_dir());
133 code = start_command(helper);
134 if (code < 0 && errno == ENOENT)
135 die("Unable to find remote helper for '%s'", data->name);
136 else if (code != 0)
137 exit(code);
139 data->helper = helper;
140 data->no_disconnect_req = 0;
143 * Open the output as FILE* so strbuf_getline_*() family of
144 * functions can be used.
145 * Do this with duped fd because fclose() will close the fd,
146 * and stuff like taking over will require the fd to remain.
148 duped = dup(helper->out);
149 if (duped < 0)
150 die_errno("Can't dup helper output fd");
151 data->out = xfdopen(duped, "r");
153 write_constant(helper->in, "capabilities\n");
155 while (1) {
156 const char *capname, *arg;
157 int mandatory = 0;
158 if (recvline(data, &buf))
159 exit(128);
161 if (!*buf.buf)
162 break;
164 if (*buf.buf == '*') {
165 capname = buf.buf + 1;
166 mandatory = 1;
167 } else
168 capname = buf.buf;
170 if (debug)
171 fprintf(stderr, "Debug: Got cap %s\n", capname);
172 if (!strcmp(capname, "fetch"))
173 data->fetch = 1;
174 else if (!strcmp(capname, "option"))
175 data->option = 1;
176 else if (!strcmp(capname, "push"))
177 data->push = 1;
178 else if (!strcmp(capname, "import"))
179 data->import = 1;
180 else if (!strcmp(capname, "bidi-import"))
181 data->bidi_import = 1;
182 else if (!strcmp(capname, "export"))
183 data->export = 1;
184 else if (!strcmp(capname, "check-connectivity"))
185 data->check_connectivity = 1;
186 else if (!data->refspecs && skip_prefix(capname, "refspec ", &arg)) {
187 ALLOC_GROW(refspecs,
188 refspec_nr + 1,
189 refspec_alloc);
190 refspecs[refspec_nr++] = xstrdup(arg);
191 } else if (!strcmp(capname, "connect")) {
192 data->connect = 1;
193 } else if (!strcmp(capname, "stateless-connect")) {
194 data->stateless_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 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 free_refspec(data->refspec_nr, data->refspecs);
381 data->refspecs = NULL;
382 res = disconnect_helper(transport);
383 free(transport->data);
384 return res;
387 static int fetch_with_fetch(struct transport *transport,
388 int nr_heads, struct ref **to_fetch)
390 struct helper_data *data = transport->data;
391 int i;
392 struct strbuf buf = STRBUF_INIT;
394 for (i = 0; i < nr_heads; i++) {
395 const struct ref *posn = to_fetch[i];
396 if (posn->status & REF_STATUS_UPTODATE)
397 continue;
399 strbuf_addf(&buf, "fetch %s %s\n",
400 oid_to_hex(&posn->old_oid),
401 posn->symref ? posn->symref : posn->name);
404 strbuf_addch(&buf, '\n');
405 sendline(data, &buf);
407 while (1) {
408 if (recvline(data, &buf))
409 exit(128);
411 if (starts_with(buf.buf, "lock ")) {
412 const char *name = buf.buf + 5;
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 = helper->out;
438 argv_array_push(&fastimport->args, "fast-import");
439 argv_array_push(&fastimport->args, debug ? "--stats" : "--quiet");
441 if (data->bidi_import) {
442 cat_blob_fd = xdup(helper->in);
443 argv_array_pushf(&fastimport->args, "--cat-blob-fd=%d", cat_blob_fd);
445 fastimport->git_cmd = 1;
447 code = start_command(fastimport);
448 return code;
451 static int get_exporter(struct transport *transport,
452 struct child_process *fastexport,
453 struct string_list *revlist_args)
455 struct helper_data *data = transport->data;
456 struct child_process *helper = get_helper(transport);
457 int i;
459 child_process_init(fastexport);
461 /* we need to duplicate helper->in because we want to use it after
462 * fastexport is done with it. */
463 fastexport->out = dup(helper->in);
464 argv_array_push(&fastexport->args, "fast-export");
465 argv_array_push(&fastexport->args, "--use-done-feature");
466 argv_array_push(&fastexport->args, data->signed_tags ?
467 "--signed-tags=verbatim" : "--signed-tags=warn-strip");
468 if (data->export_marks)
469 argv_array_pushf(&fastexport->args, "--export-marks=%s.tmp", data->export_marks);
470 if (data->import_marks)
471 argv_array_pushf(&fastexport->args, "--import-marks=%s", data->import_marks);
473 for (i = 0; i < revlist_args->nr; i++)
474 argv_array_push(&fastexport->args, revlist_args->items[i].string);
476 fastexport->git_cmd = 1;
477 return start_command(fastexport);
480 static int fetch_with_import(struct transport *transport,
481 int nr_heads, struct ref **to_fetch)
483 struct child_process fastimport;
484 struct helper_data *data = transport->data;
485 int i;
486 struct ref *posn;
487 struct strbuf buf = STRBUF_INIT;
489 get_helper(transport);
491 if (get_importer(transport, &fastimport))
492 die("Couldn't run fast-import");
494 for (i = 0; i < nr_heads; i++) {
495 posn = to_fetch[i];
496 if (posn->status & REF_STATUS_UPTODATE)
497 continue;
499 strbuf_addf(&buf, "import %s\n",
500 posn->symref ? posn->symref : posn->name);
501 sendline(data, &buf);
502 strbuf_reset(&buf);
505 write_constant(data->helper->in, "\n");
507 * remote-helpers that advertise the bidi-import capability are required to
508 * buffer the complete batch of import commands until this newline before
509 * sending data to fast-import.
510 * These helpers read back data from fast-import on their stdin, which could
511 * be mixed with import commands, otherwise.
514 if (finish_command(&fastimport))
515 die("Error while running fast-import");
518 * The fast-import stream of a remote helper that advertises
519 * the "refspec" capability writes to the refs named after the
520 * right hand side of the first refspec matching each ref we
521 * were fetching.
523 * (If no "refspec" capability was specified, for historical
524 * reasons we default to the equivalent of *:*.)
526 * Store the result in to_fetch[i].old_sha1. Callers such
527 * as "git fetch" can use the value to write feedback to the
528 * terminal, populate FETCH_HEAD, and determine what new value
529 * should be written to peer_ref if the update is a
530 * fast-forward or this is a forced update.
532 for (i = 0; i < nr_heads; i++) {
533 char *private, *name;
534 posn = to_fetch[i];
535 if (posn->status & REF_STATUS_UPTODATE)
536 continue;
537 name = posn->symref ? posn->symref : posn->name;
538 if (data->refspecs)
539 private = apply_refspecs(data->refspecs, data->refspec_nr, name);
540 else
541 private = xstrdup(name);
542 if (private) {
543 if (read_ref(private, &posn->old_oid) < 0)
544 die("Could not read ref %s", private);
545 free(private);
548 strbuf_release(&buf);
549 return 0;
552 static int run_connect(struct transport *transport, struct strbuf *cmdbuf)
554 struct helper_data *data = transport->data;
555 int ret = 0;
556 int duped;
557 FILE *input;
558 struct child_process *helper;
560 helper = get_helper(transport);
563 * Yes, dup the pipe another time, as we need unbuffered version
564 * of input pipe as FILE*. fclose() closes the underlying fd and
565 * stream buffering only can be changed before first I/O operation
566 * on it.
568 duped = dup(helper->out);
569 if (duped < 0)
570 die_errno("Can't dup helper output fd");
571 input = xfdopen(duped, "r");
572 setvbuf(input, NULL, _IONBF, 0);
574 sendline(data, cmdbuf);
575 if (recvline_fh(input, cmdbuf))
576 exit(128);
578 if (!strcmp(cmdbuf->buf, "")) {
579 data->no_disconnect_req = 1;
580 if (debug)
581 fprintf(stderr, "Debug: Smart transport connection "
582 "ready.\n");
583 ret = 1;
584 } else if (!strcmp(cmdbuf->buf, "fallback")) {
585 if (debug)
586 fprintf(stderr, "Debug: Falling back to dumb "
587 "transport.\n");
588 } else {
589 die("Unknown response to connect: %s",
590 cmdbuf->buf);
593 fclose(input);
594 return ret;
597 static int process_connect_service(struct transport *transport,
598 const char *name, const char *exec)
600 struct helper_data *data = transport->data;
601 struct strbuf cmdbuf = STRBUF_INIT;
602 int ret = 0;
605 * Handle --upload-pack and friends. This is fire and forget...
606 * just warn if it fails.
608 if (strcmp(name, exec)) {
609 int r = set_helper_option(transport, "servpath", exec);
610 if (r > 0)
611 warning("Setting remote service path not supported by protocol.");
612 else if (r < 0)
613 warning("Invalid remote service path.");
616 if (data->connect) {
617 strbuf_addf(&cmdbuf, "connect %s\n", name);
618 ret = run_connect(transport, &cmdbuf);
619 } else if (data->stateless_connect &&
620 (get_protocol_version_config() == protocol_v2) &&
621 !strcmp("git-upload-pack", name)) {
622 strbuf_addf(&cmdbuf, "stateless-connect %s\n", name);
623 ret = run_connect(transport, &cmdbuf);
624 if (ret)
625 transport->stateless_rpc = 1;
628 strbuf_release(&cmdbuf);
629 return ret;
632 static int process_connect(struct transport *transport,
633 int for_push)
635 struct helper_data *data = transport->data;
636 const char *name;
637 const char *exec;
639 name = for_push ? "git-receive-pack" : "git-upload-pack";
640 if (for_push)
641 exec = data->transport_options.receivepack;
642 else
643 exec = data->transport_options.uploadpack;
645 return process_connect_service(transport, name, exec);
648 static int connect_helper(struct transport *transport, const char *name,
649 const char *exec, int fd[2])
651 struct helper_data *data = transport->data;
653 /* Get_helper so connect is inited. */
654 get_helper(transport);
655 if (!data->connect)
656 die("Operation not supported by protocol.");
658 if (!process_connect_service(transport, name, exec))
659 die("Can't connect to subservice %s.", name);
661 fd[0] = data->helper->out;
662 fd[1] = data->helper->in;
663 return 0;
666 static int fetch(struct transport *transport,
667 int nr_heads, struct ref **to_fetch)
669 struct helper_data *data = transport->data;
670 int i, count;
672 if (process_connect(transport, 0)) {
673 do_take_over(transport);
674 return transport->vtable->fetch(transport, nr_heads, to_fetch);
677 count = 0;
678 for (i = 0; i < nr_heads; i++)
679 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
680 count++;
682 if (!count)
683 return 0;
685 if (data->check_connectivity &&
686 data->transport_options.check_self_contained_and_connected)
687 set_helper_option(transport, "check-connectivity", "true");
689 if (transport->cloning)
690 set_helper_option(transport, "cloning", "true");
692 if (data->transport_options.update_shallow)
693 set_helper_option(transport, "update-shallow", "true");
695 if (data->transport_options.filter_options.choice)
696 set_helper_option(
697 transport, "filter",
698 data->transport_options.filter_options.filter_spec);
700 if (data->fetch)
701 return fetch_with_fetch(transport, nr_heads, to_fetch);
703 if (data->import)
704 return fetch_with_import(transport, nr_heads, to_fetch);
706 return -1;
709 static int push_update_ref_status(struct strbuf *buf,
710 struct ref **ref,
711 struct ref *remote_refs)
713 char *refname, *msg;
714 int status, forced = 0;
716 if (starts_with(buf->buf, "ok ")) {
717 status = REF_STATUS_OK;
718 refname = buf->buf + 3;
719 } else if (starts_with(buf->buf, "error ")) {
720 status = REF_STATUS_REMOTE_REJECT;
721 refname = buf->buf + 6;
722 } else
723 die("expected ok/error, helper said '%s'", buf->buf);
725 msg = strchr(refname, ' ');
726 if (msg) {
727 struct strbuf msg_buf = STRBUF_INIT;
728 const char *end;
730 *msg++ = '\0';
731 if (!unquote_c_style(&msg_buf, msg, &end))
732 msg = strbuf_detach(&msg_buf, NULL);
733 else
734 msg = xstrdup(msg);
735 strbuf_release(&msg_buf);
737 if (!strcmp(msg, "no match")) {
738 status = REF_STATUS_NONE;
739 FREE_AND_NULL(msg);
741 else if (!strcmp(msg, "up to date")) {
742 status = REF_STATUS_UPTODATE;
743 FREE_AND_NULL(msg);
745 else if (!strcmp(msg, "non-fast forward")) {
746 status = REF_STATUS_REJECT_NONFASTFORWARD;
747 FREE_AND_NULL(msg);
749 else if (!strcmp(msg, "already exists")) {
750 status = REF_STATUS_REJECT_ALREADY_EXISTS;
751 FREE_AND_NULL(msg);
753 else if (!strcmp(msg, "fetch first")) {
754 status = REF_STATUS_REJECT_FETCH_FIRST;
755 FREE_AND_NULL(msg);
757 else if (!strcmp(msg, "needs force")) {
758 status = REF_STATUS_REJECT_NEEDS_FORCE;
759 FREE_AND_NULL(msg);
761 else if (!strcmp(msg, "stale info")) {
762 status = REF_STATUS_REJECT_STALE;
763 FREE_AND_NULL(msg);
765 else if (!strcmp(msg, "forced update")) {
766 forced = 1;
767 FREE_AND_NULL(msg);
771 if (*ref)
772 *ref = find_ref_by_name(*ref, refname);
773 if (!*ref)
774 *ref = find_ref_by_name(remote_refs, refname);
775 if (!*ref) {
776 warning("helper reported unexpected status of %s", refname);
777 return 1;
780 if ((*ref)->status != REF_STATUS_NONE) {
782 * Earlier, the ref was marked not to be pushed, so ignore the ref
783 * status reported by the remote helper if the latter is 'no match'.
785 if (status == REF_STATUS_NONE)
786 return 1;
789 (*ref)->status = status;
790 (*ref)->forced_update |= forced;
791 (*ref)->remote_status = msg;
792 return !(status == REF_STATUS_OK);
795 static int push_update_refs_status(struct helper_data *data,
796 struct ref *remote_refs,
797 int flags)
799 struct strbuf buf = STRBUF_INIT;
800 struct ref *ref = remote_refs;
801 int ret = 0;
803 for (;;) {
804 char *private;
806 if (recvline(data, &buf)) {
807 ret = 1;
808 break;
811 if (!buf.len)
812 break;
814 if (push_update_ref_status(&buf, &ref, remote_refs))
815 continue;
817 if (flags & TRANSPORT_PUSH_DRY_RUN || !data->refspecs || data->no_private_update)
818 continue;
820 /* propagate back the update to the remote namespace */
821 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
822 if (!private)
823 continue;
824 update_ref("update by helper", private, &ref->new_oid, NULL,
825 0, 0);
826 free(private);
828 strbuf_release(&buf);
829 return ret;
832 static void set_common_push_options(struct transport *transport,
833 const char *name, int flags)
835 if (flags & TRANSPORT_PUSH_DRY_RUN) {
836 if (set_helper_option(transport, "dry-run", "true") != 0)
837 die("helper %s does not support dry-run", name);
838 } else if (flags & TRANSPORT_PUSH_CERT_ALWAYS) {
839 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "true") != 0)
840 die("helper %s does not support --signed", name);
841 } else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED) {
842 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "if-asked") != 0)
843 die("helper %s does not support --signed=if-asked", name);
846 if (flags & TRANSPORT_PUSH_OPTIONS) {
847 struct string_list_item *item;
848 for_each_string_list_item(item, transport->push_options)
849 if (set_helper_option(transport, "push-option", item->string) != 0)
850 die("helper %s does not support 'push-option'", name);
854 static int push_refs_with_push(struct transport *transport,
855 struct ref *remote_refs, int flags)
857 int force_all = flags & TRANSPORT_PUSH_FORCE;
858 int mirror = flags & TRANSPORT_PUSH_MIRROR;
859 struct helper_data *data = transport->data;
860 struct strbuf buf = STRBUF_INIT;
861 struct ref *ref;
862 struct string_list cas_options = STRING_LIST_INIT_DUP;
863 struct string_list_item *cas_option;
865 get_helper(transport);
866 if (!data->push)
867 return 1;
869 for (ref = remote_refs; ref; ref = ref->next) {
870 if (!ref->peer_ref && !mirror)
871 continue;
873 /* Check for statuses set by set_ref_status_for_push() */
874 switch (ref->status) {
875 case REF_STATUS_REJECT_NONFASTFORWARD:
876 case REF_STATUS_REJECT_STALE:
877 case REF_STATUS_REJECT_ALREADY_EXISTS:
878 case REF_STATUS_UPTODATE:
879 continue;
880 default:
881 ; /* do nothing */
884 if (force_all)
885 ref->force = 1;
887 strbuf_addstr(&buf, "push ");
888 if (!ref->deletion) {
889 if (ref->force)
890 strbuf_addch(&buf, '+');
891 if (ref->peer_ref)
892 strbuf_addstr(&buf, ref->peer_ref->name);
893 else
894 strbuf_addstr(&buf, oid_to_hex(&ref->new_oid));
896 strbuf_addch(&buf, ':');
897 strbuf_addstr(&buf, ref->name);
898 strbuf_addch(&buf, '\n');
901 * The "--force-with-lease" options without explicit
902 * values to expect have already been expanded into
903 * the ref->old_oid_expect[] field; we can ignore
904 * transport->smart_options->cas altogether and instead
905 * can enumerate them from the refs.
907 if (ref->expect_old_sha1) {
908 struct strbuf cas = STRBUF_INIT;
909 strbuf_addf(&cas, "%s:%s",
910 ref->name, oid_to_hex(&ref->old_oid_expect));
911 string_list_append_nodup(&cas_options,
912 strbuf_detach(&cas, NULL));
915 if (buf.len == 0) {
916 string_list_clear(&cas_options, 0);
917 return 0;
920 for_each_string_list_item(cas_option, &cas_options)
921 set_helper_option(transport, "cas", cas_option->string);
922 set_common_push_options(transport, data->name, flags);
924 strbuf_addch(&buf, '\n');
925 sendline(data, &buf);
926 strbuf_release(&buf);
927 string_list_clear(&cas_options, 0);
929 return push_update_refs_status(data, remote_refs, flags);
932 static int push_refs_with_export(struct transport *transport,
933 struct ref *remote_refs, int flags)
935 struct ref *ref;
936 struct child_process *helper, exporter;
937 struct helper_data *data = transport->data;
938 struct string_list revlist_args = STRING_LIST_INIT_DUP;
939 struct strbuf buf = STRBUF_INIT;
941 if (!data->refspecs)
942 die("remote-helper doesn't support push; refspec needed");
944 set_common_push_options(transport, data->name, flags);
945 if (flags & TRANSPORT_PUSH_FORCE) {
946 if (set_helper_option(transport, "force", "true") != 0)
947 warning("helper %s does not support 'force'", data->name);
950 helper = get_helper(transport);
952 write_constant(helper->in, "export\n");
954 for (ref = remote_refs; ref; ref = ref->next) {
955 char *private;
956 struct object_id oid;
958 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
959 if (private && !get_oid(private, &oid)) {
960 strbuf_addf(&buf, "^%s", private);
961 string_list_append_nodup(&revlist_args,
962 strbuf_detach(&buf, NULL));
963 oidcpy(&ref->old_oid, &oid);
965 free(private);
967 if (ref->peer_ref) {
968 if (strcmp(ref->name, ref->peer_ref->name)) {
969 if (!ref->deletion) {
970 const char *name;
971 int flag;
973 /* Follow symbolic refs (mainly for HEAD). */
974 name = resolve_ref_unsafe(ref->peer_ref->name,
975 RESOLVE_REF_READING,
976 &oid, &flag);
977 if (!name || !(flag & REF_ISSYMREF))
978 name = ref->peer_ref->name;
980 strbuf_addf(&buf, "%s:%s", name, ref->name);
981 } else
982 strbuf_addf(&buf, ":%s", ref->name);
984 string_list_append(&revlist_args, "--refspec");
985 string_list_append(&revlist_args, buf.buf);
986 strbuf_release(&buf);
988 if (!ref->deletion)
989 string_list_append(&revlist_args, ref->peer_ref->name);
993 if (get_exporter(transport, &exporter, &revlist_args))
994 die("Couldn't run fast-export");
996 string_list_clear(&revlist_args, 1);
998 if (finish_command(&exporter))
999 die("Error while running fast-export");
1000 if (push_update_refs_status(data, remote_refs, flags))
1001 return 1;
1003 if (data->export_marks) {
1004 strbuf_addf(&buf, "%s.tmp", data->export_marks);
1005 rename(buf.buf, data->export_marks);
1006 strbuf_release(&buf);
1009 return 0;
1012 static int push_refs(struct transport *transport,
1013 struct ref *remote_refs, int flags)
1015 struct helper_data *data = transport->data;
1017 if (process_connect(transport, 1)) {
1018 do_take_over(transport);
1019 return transport->vtable->push_refs(transport, remote_refs, flags);
1022 if (!remote_refs) {
1023 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
1024 "Perhaps you should specify a branch such as 'master'.\n");
1025 return 0;
1028 if (data->push)
1029 return push_refs_with_push(transport, remote_refs, flags);
1031 if (data->export)
1032 return push_refs_with_export(transport, remote_refs, flags);
1034 return -1;
1038 static int has_attribute(const char *attrs, const char *attr) {
1039 int len;
1040 if (!attrs)
1041 return 0;
1043 len = strlen(attr);
1044 for (;;) {
1045 const char *space = strchrnul(attrs, ' ');
1046 if (len == space - attrs && !strncmp(attrs, attr, len))
1047 return 1;
1048 if (!*space)
1049 return 0;
1050 attrs = space + 1;
1054 static struct ref *get_refs_list(struct transport *transport, int for_push,
1055 const struct argv_array *ref_prefixes)
1057 struct helper_data *data = transport->data;
1058 struct child_process *helper;
1059 struct ref *ret = NULL;
1060 struct ref **tail = &ret;
1061 struct ref *posn;
1062 struct strbuf buf = STRBUF_INIT;
1064 helper = get_helper(transport);
1066 if (process_connect(transport, for_push)) {
1067 do_take_over(transport);
1068 return transport->vtable->get_refs_list(transport, for_push, ref_prefixes);
1071 if (data->push && for_push)
1072 write_str_in_full(helper->in, "list for-push\n");
1073 else
1074 write_str_in_full(helper->in, "list\n");
1076 while (1) {
1077 char *eov, *eon;
1078 if (recvline(data, &buf))
1079 exit(128);
1081 if (!*buf.buf)
1082 break;
1084 eov = strchr(buf.buf, ' ');
1085 if (!eov)
1086 die("Malformed response in ref list: %s", buf.buf);
1087 eon = strchr(eov + 1, ' ');
1088 *eov = '\0';
1089 if (eon)
1090 *eon = '\0';
1091 *tail = alloc_ref(eov + 1);
1092 if (buf.buf[0] == '@')
1093 (*tail)->symref = xstrdup(buf.buf + 1);
1094 else if (buf.buf[0] != '?')
1095 get_oid_hex(buf.buf, &(*tail)->old_oid);
1096 if (eon) {
1097 if (has_attribute(eon + 1, "unchanged")) {
1098 (*tail)->status |= REF_STATUS_UPTODATE;
1099 if (read_ref((*tail)->name, &(*tail)->old_oid) < 0)
1100 die(_("Could not read ref %s"),
1101 (*tail)->name);
1104 tail = &((*tail)->next);
1106 if (debug)
1107 fprintf(stderr, "Debug: Read ref listing.\n");
1108 strbuf_release(&buf);
1110 for (posn = ret; posn; posn = posn->next)
1111 resolve_remote_symref(posn, ret);
1113 return ret;
1116 static struct transport_vtable vtable = {
1117 set_helper_option,
1118 get_refs_list,
1119 fetch,
1120 push_refs,
1121 connect_helper,
1122 release_helper
1125 int transport_helper_init(struct transport *transport, const char *name)
1127 struct helper_data *data = xcalloc(1, sizeof(*data));
1128 data->name = name;
1130 transport_check_allowed(name);
1132 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1133 debug = 1;
1135 transport->data = data;
1136 transport->vtable = &vtable;
1137 transport->smart_options = &(data->transport_options);
1138 return 0;
1142 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1143 * buffer less), so attempt reads and writes with up to that size.
1145 #define BUFFERSIZE 65536
1146 /* This should be enough to hold debugging message. */
1147 #define PBUFFERSIZE 8192
1149 /* Print bidirectional transfer loop debug message. */
1150 __attribute__((format (printf, 1, 2)))
1151 static void transfer_debug(const char *fmt, ...)
1154 * NEEDSWORK: This function is sometimes used from multiple threads, and
1155 * we end up using debug_enabled racily. That "should not matter" since
1156 * we always write the same value, but it's still wrong. This function
1157 * is listed in .tsan-suppressions for the time being.
1160 va_list args;
1161 char msgbuf[PBUFFERSIZE];
1162 static int debug_enabled = -1;
1164 if (debug_enabled < 0)
1165 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1166 if (!debug_enabled)
1167 return;
1169 va_start(args, fmt);
1170 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1171 va_end(args);
1172 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1175 /* Stream state: More data may be coming in this direction. */
1176 #define SSTATE_TRANSFERRING 0
1178 * Stream state: No more data coming in this direction, flushing rest of
1179 * data.
1181 #define SSTATE_FLUSHING 1
1182 /* Stream state: Transfer in this direction finished. */
1183 #define SSTATE_FINISHED 2
1185 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERRING)
1186 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1187 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1189 /* Unidirectional transfer. */
1190 struct unidirectional_transfer {
1191 /* Source */
1192 int src;
1193 /* Destination */
1194 int dest;
1195 /* Is source socket? */
1196 int src_is_sock;
1197 /* Is destination socket? */
1198 int dest_is_sock;
1199 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1200 int state;
1201 /* Buffer. */
1202 char buf[BUFFERSIZE];
1203 /* Buffer used. */
1204 size_t bufuse;
1205 /* Name of source. */
1206 const char *src_name;
1207 /* Name of destination. */
1208 const char *dest_name;
1211 /* Closes the target (for writing) if transfer has finished. */
1212 static void udt_close_if_finished(struct unidirectional_transfer *t)
1214 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1215 t->state = SSTATE_FINISHED;
1216 if (t->dest_is_sock)
1217 shutdown(t->dest, SHUT_WR);
1218 else
1219 close(t->dest);
1220 transfer_debug("Closed %s.", t->dest_name);
1225 * Tries to read data from source into buffer. If buffer is full,
1226 * no data is read. Returns 0 on success, -1 on error.
1228 static int udt_do_read(struct unidirectional_transfer *t)
1230 ssize_t bytes;
1232 if (t->bufuse == BUFFERSIZE)
1233 return 0; /* No space for more. */
1235 transfer_debug("%s is readable", t->src_name);
1236 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1237 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1238 errno != EINTR) {
1239 error_errno("read(%s) failed", t->src_name);
1240 return -1;
1241 } else if (bytes == 0) {
1242 transfer_debug("%s EOF (with %i bytes in buffer)",
1243 t->src_name, (int)t->bufuse);
1244 t->state = SSTATE_FLUSHING;
1245 } else if (bytes > 0) {
1246 t->bufuse += bytes;
1247 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1248 (int)bytes, t->src_name, (int)t->bufuse);
1250 return 0;
1253 /* Tries to write data from buffer into destination. If buffer is empty,
1254 * no data is written. Returns 0 on success, -1 on error.
1256 static int udt_do_write(struct unidirectional_transfer *t)
1258 ssize_t bytes;
1260 if (t->bufuse == 0)
1261 return 0; /* Nothing to write. */
1263 transfer_debug("%s is writable", t->dest_name);
1264 bytes = xwrite(t->dest, t->buf, t->bufuse);
1265 if (bytes < 0 && errno != EWOULDBLOCK) {
1266 error_errno("write(%s) failed", t->dest_name);
1267 return -1;
1268 } else if (bytes > 0) {
1269 t->bufuse -= bytes;
1270 if (t->bufuse)
1271 memmove(t->buf, t->buf + bytes, t->bufuse);
1272 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1273 (int)bytes, t->dest_name, (int)t->bufuse);
1275 return 0;
1279 /* State of bidirectional transfer loop. */
1280 struct bidirectional_transfer_state {
1281 /* Direction from program to git. */
1282 struct unidirectional_transfer ptg;
1283 /* Direction from git to program. */
1284 struct unidirectional_transfer gtp;
1287 static void *udt_copy_task_routine(void *udt)
1289 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1290 while (t->state != SSTATE_FINISHED) {
1291 if (STATE_NEEDS_READING(t->state))
1292 if (udt_do_read(t))
1293 return NULL;
1294 if (STATE_NEEDS_WRITING(t->state))
1295 if (udt_do_write(t))
1296 return NULL;
1297 if (STATE_NEEDS_CLOSING(t->state))
1298 udt_close_if_finished(t);
1300 return udt; /* Just some non-NULL value. */
1303 #ifndef NO_PTHREADS
1306 * Join thread, with appropriate errors on failure. Name is name for the
1307 * thread (for error messages). Returns 0 on success, 1 on failure.
1309 static int tloop_join(pthread_t thread, const char *name)
1311 int err;
1312 void *tret;
1313 err = pthread_join(thread, &tret);
1314 if (!tret) {
1315 error("%s thread failed", name);
1316 return 1;
1318 if (err) {
1319 error("%s thread failed to join: %s", name, strerror(err));
1320 return 1;
1322 return 0;
1326 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1327 * -1 on failure.
1329 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1331 pthread_t gtp_thread;
1332 pthread_t ptg_thread;
1333 int err;
1334 int ret = 0;
1335 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1336 &s->gtp);
1337 if (err)
1338 die("Can't start thread for copying data: %s", strerror(err));
1339 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1340 &s->ptg);
1341 if (err)
1342 die("Can't start thread for copying data: %s", strerror(err));
1344 ret |= tloop_join(gtp_thread, "Git to program copy");
1345 ret |= tloop_join(ptg_thread, "Program to git copy");
1346 return ret;
1348 #else
1350 /* Close the source and target (for writing) for transfer. */
1351 static void udt_kill_transfer(struct unidirectional_transfer *t)
1353 t->state = SSTATE_FINISHED;
1355 * Socket read end left open isn't a disaster if nobody
1356 * attempts to read from it (mingw compat headers do not
1357 * have SHUT_RD)...
1359 * We can't fully close the socket since otherwise gtp
1360 * task would first close the socket it sends data to
1361 * while closing the ptg file descriptors.
1363 if (!t->src_is_sock)
1364 close(t->src);
1365 if (t->dest_is_sock)
1366 shutdown(t->dest, SHUT_WR);
1367 else
1368 close(t->dest);
1372 * Join process, with appropriate errors on failure. Name is name for the
1373 * process (for error messages). Returns 0 on success, 1 on failure.
1375 static int tloop_join(pid_t pid, const char *name)
1377 int tret;
1378 if (waitpid(pid, &tret, 0) < 0) {
1379 error_errno("%s process failed to wait", name);
1380 return 1;
1382 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1383 error("%s process failed", name);
1384 return 1;
1386 return 0;
1390 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1391 * -1 on failure.
1393 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1395 pid_t pid1, pid2;
1396 int ret = 0;
1398 /* Fork thread #1: git to program. */
1399 pid1 = fork();
1400 if (pid1 < 0)
1401 die_errno("Can't start thread for copying data");
1402 else if (pid1 == 0) {
1403 udt_kill_transfer(&s->ptg);
1404 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1407 /* Fork thread #2: program to git. */
1408 pid2 = fork();
1409 if (pid2 < 0)
1410 die_errno("Can't start thread for copying data");
1411 else if (pid2 == 0) {
1412 udt_kill_transfer(&s->gtp);
1413 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1417 * Close both streams in parent as to not interfere with
1418 * end of file detection and wait for both tasks to finish.
1420 udt_kill_transfer(&s->gtp);
1421 udt_kill_transfer(&s->ptg);
1422 ret |= tloop_join(pid1, "Git to program copy");
1423 ret |= tloop_join(pid2, "Program to git copy");
1424 return ret;
1426 #endif
1429 * Copies data from stdin to output and from input to stdout simultaneously.
1430 * Additionally filtering through given filter. If filter is NULL, uses
1431 * identity filter.
1433 int bidirectional_transfer_loop(int input, int output)
1435 struct bidirectional_transfer_state state;
1437 /* Fill the state fields. */
1438 state.ptg.src = input;
1439 state.ptg.dest = 1;
1440 state.ptg.src_is_sock = (input == output);
1441 state.ptg.dest_is_sock = 0;
1442 state.ptg.state = SSTATE_TRANSFERRING;
1443 state.ptg.bufuse = 0;
1444 state.ptg.src_name = "remote input";
1445 state.ptg.dest_name = "stdout";
1447 state.gtp.src = 0;
1448 state.gtp.dest = output;
1449 state.gtp.src_is_sock = 0;
1450 state.gtp.dest_is_sock = (input == output);
1451 state.gtp.state = SSTATE_TRANSFERRING;
1452 state.gtp.bufuse = 0;
1453 state.gtp.src_name = "stdin";
1454 state.gtp.dest_name = "remote output";
1456 return tloop_spawnwait_tasks(&state);