Use a strbuf in symlink
[git/mingw/4msysgit.git] / transport-helper.c
blob4d977b3e90423cf749dc6b8633cd802d98eff5e7
1 #include "cache.h"
2 #include "transport.h"
3 #include "quote.h"
4 #include "run-command.h"
5 #include "commit.h"
6 #include "diff.h"
7 #include "revision.h"
8 #include "quote.h"
9 #include "remote.h"
10 #include "string-list.h"
11 #include "thread-utils.h"
12 #include "sigchain.h"
13 #include "argv-array.h"
14 #include "refs.h"
16 static int debug;
17 /* TODO: put somewhere sensible, e.g. git_transport_options? */
18 static int auto_gc = 1;
20 struct helper_data {
21 const char *name;
22 struct child_process *helper;
23 FILE *out;
24 unsigned fetch : 1,
25 import : 1,
26 bidi_import : 1,
27 export : 1,
28 option : 1,
29 push : 1,
30 connect : 1,
31 signed_tags : 1,
32 check_connectivity : 1,
33 no_disconnect_req : 1,
34 no_private_update : 1;
35 char *export_marks;
36 char *import_marks;
37 /* These go from remote name (as in "list") to private name */
38 struct refspec *refspecs;
39 int refspec_nr;
40 /* Transport options for fetch-pack/send-pack (should one of
41 * those be invoked).
43 struct git_transport_options transport_options;
46 static void sendline(struct helper_data *helper, struct strbuf *buffer)
48 if (debug)
49 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
50 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
51 != buffer->len)
52 die_errno("Full write to remote helper failed");
55 static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
57 strbuf_reset(buffer);
58 if (debug)
59 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
60 if (strbuf_getline(buffer, helper, '\n') == EOF) {
61 if (debug)
62 fprintf(stderr, "Debug: Remote helper quit.\n");
63 return 1;
66 if (debug)
67 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
68 return 0;
71 static int recvline(struct helper_data *helper, struct strbuf *buffer)
73 return recvline_fh(helper->out, buffer, helper->name);
76 static void write_constant(int fd, const char *str)
78 if (debug)
79 fprintf(stderr, "Debug: Remote helper: -> %s", str);
80 if (write_in_full(fd, str, strlen(str)) != strlen(str))
81 die_errno("Full write to remote helper failed");
84 static const char *remove_ext_force(const char *url)
86 if (url) {
87 const char *colon = strchr(url, ':');
88 if (colon && colon[1] == ':')
89 return colon + 2;
91 return url;
94 static void do_take_over(struct transport *transport)
96 struct helper_data *data;
97 data = (struct helper_data *)transport->data;
98 transport_take_over(transport, data->helper);
99 fclose(data->out);
100 free(data);
103 static struct child_process *get_helper(struct transport *transport)
105 struct helper_data *data = transport->data;
106 struct argv_array argv = ARGV_ARRAY_INIT;
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;
114 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
115 const char *helper_env[] = {
116 git_dir_buf,
117 NULL
121 if (data->helper)
122 return data->helper;
124 helper = xcalloc(1, sizeof(*helper));
125 helper->in = -1;
126 helper->out = -1;
127 helper->err = 0;
128 argv_array_pushf(&argv, "git-remote-%s", data->name);
129 argv_array_push(&argv, transport->remote->name);
130 argv_array_push(&argv, remove_ext_force(transport->url));
131 helper->argv = argv_array_detach(&argv, NULL);
132 helper->git_cmd = 0;
133 helper->silent_exec_failure = 1;
135 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
136 helper->env = helper_env;
138 code = start_command(helper);
139 if (code < 0 && errno == ENOENT)
140 die("Unable to find remote helper for '%s'", data->name);
141 else if (code != 0)
142 exit(code);
144 data->helper = helper;
145 data->no_disconnect_req = 0;
148 * Open the output as FILE* so strbuf_getline() can be used.
149 * Do this with duped fd because fclose() will close the fd,
150 * and stuff like taking over will require the fd to remain.
152 duped = dup(helper->out);
153 if (duped < 0)
154 die_errno("Can't dup helper output fd");
155 data->out = xfdopen(duped, "r");
157 write_constant(helper->in, "capabilities\n");
159 while (1) {
160 const char *capname;
161 int mandatory = 0;
162 if (recvline(data, &buf))
163 exit(128);
165 if (!*buf.buf)
166 break;
168 if (*buf.buf == '*') {
169 capname = buf.buf + 1;
170 mandatory = 1;
171 } else
172 capname = buf.buf;
174 if (debug)
175 fprintf(stderr, "Debug: Got cap %s\n", capname);
176 if (!strcmp(capname, "fetch"))
177 data->fetch = 1;
178 else if (!strcmp(capname, "option"))
179 data->option = 1;
180 else if (!strcmp(capname, "push"))
181 data->push = 1;
182 else if (!strcmp(capname, "import"))
183 data->import = 1;
184 else if (!strcmp(capname, "bidi-import"))
185 data->bidi_import = 1;
186 else if (!strcmp(capname, "export"))
187 data->export = 1;
188 else if (!strcmp(capname, "check-connectivity"))
189 data->check_connectivity = 1;
190 else if (!data->refspecs && starts_with(capname, "refspec ")) {
191 ALLOC_GROW(refspecs,
192 refspec_nr + 1,
193 refspec_alloc);
194 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
195 } else if (!strcmp(capname, "connect")) {
196 data->connect = 1;
197 } else if (!strcmp(capname, "signed-tags")) {
198 data->signed_tags = 1;
199 } else if (starts_with(capname, "export-marks ")) {
200 data->export_marks = xstrdup(capname + strlen("export-marks "));
201 } else if (starts_with(capname, "import-marks")) {
202 data->import_marks = xstrdup(capname + strlen("import-marks "));
203 } else if (starts_with(capname, "no-private-update")) {
204 data->no_private_update = 1;
205 } else if (mandatory) {
206 die("Unknown mandatory capability %s. This remote "
207 "helper probably needs newer version of Git.",
208 capname);
211 if (refspecs) {
212 int i;
213 data->refspec_nr = refspec_nr;
214 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
215 for (i = 0; i < refspec_nr; i++)
216 free((char *)refspecs[i]);
217 free(refspecs);
218 } else if (data->import || data->bidi_import || data->export) {
219 warning("This remote helper should implement refspec capability.");
221 strbuf_release(&buf);
222 if (debug)
223 fprintf(stderr, "Debug: Capabilities complete.\n");
224 return data->helper;
227 static int disconnect_helper(struct transport *transport)
229 struct helper_data *data = transport->data;
230 int res = 0;
232 if (data->helper) {
233 if (debug)
234 fprintf(stderr, "Debug: Disconnecting.\n");
235 if (!data->no_disconnect_req) {
237 * Ignore write errors; there's nothing we can do,
238 * since we're about to close the pipe anyway. And the
239 * most likely error is EPIPE due to the helper dying
240 * to report an error itself.
242 sigchain_push(SIGPIPE, SIG_IGN);
243 xwrite(data->helper->in, "\n", 1);
244 sigchain_pop(SIGPIPE);
246 close(data->helper->in);
247 close(data->helper->out);
248 fclose(data->out);
249 res = finish_command(data->helper);
250 argv_array_free_detached(data->helper->argv);
251 free(data->helper);
252 data->helper = NULL;
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
270 static int set_helper_option(struct transport *transport,
271 const char *name, const char *value)
273 struct helper_data *data = transport->data;
274 struct strbuf buf = STRBUF_INIT;
275 int i, ret, is_bool = 0;
277 get_helper(transport);
279 if (!data->option)
280 return 1;
282 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
283 if (!strcmp(name, unsupported_options[i]))
284 return 1;
287 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
288 if (!strcmp(name, boolean_options[i])) {
289 is_bool = 1;
290 break;
294 strbuf_addf(&buf, "option %s ", name);
295 if (is_bool)
296 strbuf_addstr(&buf, value ? "true" : "false");
297 else
298 quote_c_style(value, &buf, NULL, 0);
299 strbuf_addch(&buf, '\n');
301 sendline(data, &buf);
302 if (recvline(data, &buf))
303 exit(128);
305 if (!strcmp(buf.buf, "ok"))
306 ret = 0;
307 else if (starts_with(buf.buf, "error")) {
308 ret = -1;
309 } else if (!strcmp(buf.buf, "unsupported"))
310 ret = 1;
311 else {
312 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
313 ret = 1;
315 strbuf_release(&buf);
316 return ret;
319 static void standard_options(struct transport *t)
321 char buf[16];
322 int n;
323 int v = t->verbose;
325 set_helper_option(t, "progress", t->progress ? "true" : "false");
327 n = snprintf(buf, sizeof(buf), "%d", v + 1);
328 if (n >= sizeof(buf))
329 die("impossibly large verbosity value");
330 set_helper_option(t, "verbosity", buf);
333 static int release_helper(struct transport *transport)
335 int res = 0;
336 struct helper_data *data = transport->data;
337 free_refspec(data->refspec_nr, data->refspecs);
338 data->refspecs = NULL;
339 res = disconnect_helper(transport);
340 free(transport->data);
341 return res;
344 static int fetch_with_fetch(struct transport *transport,
345 int nr_heads, struct ref **to_fetch)
347 struct helper_data *data = transport->data;
348 int i;
349 struct strbuf buf = STRBUF_INIT;
351 standard_options(transport);
352 if (data->check_connectivity &&
353 data->transport_options.check_self_contained_and_connected)
354 set_helper_option(transport, "check-connectivity", "true");
356 if (transport->cloning)
357 set_helper_option(transport, "cloning", "true");
359 if (data->transport_options.update_shallow)
360 set_helper_option(transport, "update-shallow", "true");
362 for (i = 0; i < nr_heads; i++) {
363 const struct ref *posn = to_fetch[i];
364 if (posn->status & REF_STATUS_UPTODATE)
365 continue;
367 strbuf_addf(&buf, "fetch %s %s\n",
368 sha1_to_hex(posn->old_sha1), posn->name);
371 strbuf_addch(&buf, '\n');
372 sendline(data, &buf);
374 while (1) {
375 if (recvline(data, &buf))
376 exit(128);
378 if (starts_with(buf.buf, "lock ")) {
379 const char *name = buf.buf + 5;
380 if (transport->pack_lockfile)
381 warning("%s also locked %s", data->name, name);
382 else
383 transport->pack_lockfile = xstrdup(name);
385 else if (data->check_connectivity &&
386 data->transport_options.check_self_contained_and_connected &&
387 !strcmp(buf.buf, "connectivity-ok"))
388 data->transport_options.self_contained_and_connected = 1;
389 else if (!buf.len)
390 break;
391 else
392 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
394 strbuf_release(&buf);
395 return 0;
398 static int get_importer(struct transport *transport, struct child_process *fastimport)
400 struct child_process *helper = get_helper(transport);
401 struct helper_data *data = transport->data;
402 struct argv_array argv = ARGV_ARRAY_INIT;
403 int cat_blob_fd, code;
404 memset(fastimport, 0, sizeof(*fastimport));
405 fastimport->in = helper->out;
406 argv_array_push(&argv, "fast-import");
407 argv_array_push(&argv, debug ? "--stats" : "--quiet");
409 if (data->bidi_import) {
410 cat_blob_fd = xdup(helper->in);
411 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
413 fastimport->argv = argv.argv;
414 fastimport->git_cmd = 1;
416 code = start_command(fastimport);
417 return code;
420 static int get_exporter(struct transport *transport,
421 struct child_process *fastexport,
422 struct string_list *revlist_args)
424 struct helper_data *data = transport->data;
425 struct child_process *helper = get_helper(transport);
426 int argc = 0, i;
427 struct strbuf tmp = STRBUF_INIT;
429 memset(fastexport, 0, sizeof(*fastexport));
431 /* we need to duplicate helper->in because we want to use it after
432 * fastexport is done with it. */
433 fastexport->out = dup(helper->in);
434 fastexport->argv = xcalloc(7 + revlist_args->nr, sizeof(*fastexport->argv));
435 fastexport->argv[argc++] = "fast-export";
436 fastexport->argv[argc++] = "--use-done-feature";
437 fastexport->argv[argc++] = data->signed_tags ?
438 "--signed-tags=verbatim" : "--signed-tags=warn-strip";
439 if (data->export_marks) {
440 strbuf_addf(&tmp, "--export-marks=%s.tmp", data->export_marks);
441 fastexport->argv[argc++] = strbuf_detach(&tmp, NULL);
443 if (data->import_marks) {
444 strbuf_addf(&tmp, "--import-marks=%s", data->import_marks);
445 fastexport->argv[argc++] = strbuf_detach(&tmp, NULL);
448 for (i = 0; i < revlist_args->nr; i++)
449 fastexport->argv[argc++] = revlist_args->items[i].string;
451 fastexport->argv[argc++] = "--";
453 fastexport->git_cmd = 1;
454 return start_command(fastexport);
457 static void check_helper_status(struct helper_data *data)
459 int pid, status;
461 pid = waitpid(data->helper->pid, &status, WNOHANG);
462 if (pid < 0)
463 die("Could not retrieve status of remote helper '%s'",
464 data->name);
465 if (pid > 0 && WIFEXITED(status))
466 die("Remote helper '%s' died with %d",
467 data->name, WEXITSTATUS(status));
470 static int fetch_with_import(struct transport *transport,
471 int nr_heads, struct ref **to_fetch)
473 struct child_process fastimport;
474 struct helper_data *data = transport->data;
475 int i;
476 struct ref *posn;
477 struct strbuf buf = STRBUF_INIT;
479 get_helper(transport);
481 if (get_importer(transport, &fastimport))
482 die("Couldn't run fast-import");
484 for (i = 0; i < nr_heads; i++) {
485 posn = to_fetch[i];
486 if (posn->status & REF_STATUS_UPTODATE)
487 continue;
489 strbuf_addf(&buf, "import %s\n", posn->name);
490 sendline(data, &buf);
491 strbuf_reset(&buf);
494 write_constant(data->helper->in, "\n");
496 * remote-helpers that advertise the bidi-import capability are required to
497 * buffer the complete batch of import commands until this newline before
498 * sending data to fast-import.
499 * These helpers read back data from fast-import on their stdin, which could
500 * be mixed with import commands, otherwise.
503 if (finish_command(&fastimport))
504 die("Error while running fast-import");
505 argv_array_free_detached(fastimport.argv);
506 check_helper_status(data);
509 * The fast-import stream of a remote helper that advertises
510 * the "refspec" capability writes to the refs named after the
511 * right hand side of the first refspec matching each ref we
512 * were fetching.
514 * (If no "refspec" capability was specified, for historical
515 * reasons we default to the equivalent of *:*.)
517 * Store the result in to_fetch[i].old_sha1. Callers such
518 * as "git fetch" can use the value to write feedback to the
519 * terminal, populate FETCH_HEAD, and determine what new value
520 * should be written to peer_ref if the update is a
521 * fast-forward or this is a forced update.
523 for (i = 0; i < nr_heads; i++) {
524 char *private;
525 posn = to_fetch[i];
526 if (posn->status & REF_STATUS_UPTODATE)
527 continue;
528 if (data->refspecs)
529 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
530 else
531 private = xstrdup(posn->name);
532 if (private) {
533 read_ref(private, posn->old_sha1);
534 free(private);
537 strbuf_release(&buf);
538 if (auto_gc) {
539 const char *argv_gc_auto[] = {
540 "gc", "--auto", "--quiet", NULL,
542 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
544 return 0;
547 static int process_connect_service(struct transport *transport,
548 const char *name, const char *exec)
550 struct helper_data *data = transport->data;
551 struct strbuf cmdbuf = STRBUF_INIT;
552 struct child_process *helper;
553 int r, duped, ret = 0;
554 FILE *input;
556 helper = get_helper(transport);
559 * Yes, dup the pipe another time, as we need unbuffered version
560 * of input pipe as FILE*. fclose() closes the underlying fd and
561 * stream buffering only can be changed before first I/O operation
562 * on it.
564 duped = dup(helper->out);
565 if (duped < 0)
566 die_errno("Can't dup helper output fd");
567 input = xfdopen(duped, "r");
568 setvbuf(input, NULL, _IONBF, 0);
571 * Handle --upload-pack and friends. This is fire and forget...
572 * just warn if it fails.
574 if (strcmp(name, exec)) {
575 r = set_helper_option(transport, "servpath", exec);
576 if (r > 0)
577 warning("Setting remote service path not supported by protocol.");
578 else if (r < 0)
579 warning("Invalid remote service path.");
582 if (data->connect)
583 strbuf_addf(&cmdbuf, "connect %s\n", name);
584 else
585 goto exit;
587 sendline(data, &cmdbuf);
588 if (recvline_fh(input, &cmdbuf, name))
589 exit(128);
591 if (!strcmp(cmdbuf.buf, "")) {
592 data->no_disconnect_req = 1;
593 if (debug)
594 fprintf(stderr, "Debug: Smart transport connection "
595 "ready.\n");
596 ret = 1;
597 } else if (!strcmp(cmdbuf.buf, "fallback")) {
598 if (debug)
599 fprintf(stderr, "Debug: Falling back to dumb "
600 "transport.\n");
601 } else
602 die("Unknown response to connect: %s",
603 cmdbuf.buf);
605 exit:
606 fclose(input);
607 return ret;
610 static int process_connect(struct transport *transport,
611 int for_push)
613 struct helper_data *data = transport->data;
614 const char *name;
615 const char *exec;
617 name = for_push ? "git-receive-pack" : "git-upload-pack";
618 if (for_push)
619 exec = data->transport_options.receivepack;
620 else
621 exec = data->transport_options.uploadpack;
623 return process_connect_service(transport, name, exec);
626 static int connect_helper(struct transport *transport, const char *name,
627 const char *exec, int fd[2])
629 struct helper_data *data = transport->data;
631 /* Get_helper so connect is inited. */
632 get_helper(transport);
633 if (!data->connect)
634 die("Operation not supported by protocol.");
636 if (!process_connect_service(transport, name, exec))
637 die("Can't connect to subservice %s.", name);
639 fd[0] = data->helper->out;
640 fd[1] = data->helper->in;
641 return 0;
644 static int fetch(struct transport *transport,
645 int nr_heads, struct ref **to_fetch)
647 struct helper_data *data = transport->data;
648 int i, count;
650 if (process_connect(transport, 0)) {
651 do_take_over(transport);
652 return transport->fetch(transport, nr_heads, to_fetch);
655 count = 0;
656 for (i = 0; i < nr_heads; i++)
657 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
658 count++;
660 if (!count)
661 return 0;
663 if (data->fetch)
664 return fetch_with_fetch(transport, nr_heads, to_fetch);
666 if (data->import)
667 return fetch_with_import(transport, nr_heads, to_fetch);
669 return -1;
672 static int push_update_ref_status(struct strbuf *buf,
673 struct ref **ref,
674 struct ref *remote_refs)
676 char *refname, *msg;
677 int status, forced = 0;
679 if (starts_with(buf->buf, "ok ")) {
680 status = REF_STATUS_OK;
681 refname = buf->buf + 3;
682 } else if (starts_with(buf->buf, "error ")) {
683 status = REF_STATUS_REMOTE_REJECT;
684 refname = buf->buf + 6;
685 } else
686 die("expected ok/error, helper said '%s'", buf->buf);
688 msg = strchr(refname, ' ');
689 if (msg) {
690 struct strbuf msg_buf = STRBUF_INIT;
691 const char *end;
693 *msg++ = '\0';
694 if (!unquote_c_style(&msg_buf, msg, &end))
695 msg = strbuf_detach(&msg_buf, NULL);
696 else
697 msg = xstrdup(msg);
698 strbuf_release(&msg_buf);
700 if (!strcmp(msg, "no match")) {
701 status = REF_STATUS_NONE;
702 free(msg);
703 msg = NULL;
705 else if (!strcmp(msg, "up to date")) {
706 status = REF_STATUS_UPTODATE;
707 free(msg);
708 msg = NULL;
710 else if (!strcmp(msg, "non-fast forward")) {
711 status = REF_STATUS_REJECT_NONFASTFORWARD;
712 free(msg);
713 msg = NULL;
715 else if (!strcmp(msg, "already exists")) {
716 status = REF_STATUS_REJECT_ALREADY_EXISTS;
717 free(msg);
718 msg = NULL;
720 else if (!strcmp(msg, "fetch first")) {
721 status = REF_STATUS_REJECT_FETCH_FIRST;
722 free(msg);
723 msg = NULL;
725 else if (!strcmp(msg, "needs force")) {
726 status = REF_STATUS_REJECT_NEEDS_FORCE;
727 free(msg);
728 msg = NULL;
730 else if (!strcmp(msg, "stale info")) {
731 status = REF_STATUS_REJECT_STALE;
732 free(msg);
733 msg = NULL;
735 else if (!strcmp(msg, "forced update")) {
736 forced = 1;
737 free(msg);
738 msg = NULL;
742 if (*ref)
743 *ref = find_ref_by_name(*ref, refname);
744 if (!*ref)
745 *ref = find_ref_by_name(remote_refs, refname);
746 if (!*ref) {
747 warning("helper reported unexpected status of %s", refname);
748 return 1;
751 if ((*ref)->status != REF_STATUS_NONE) {
753 * Earlier, the ref was marked not to be pushed, so ignore the ref
754 * status reported by the remote helper if the latter is 'no match'.
756 if (status == REF_STATUS_NONE)
757 return 1;
760 (*ref)->status = status;
761 (*ref)->forced_update |= forced;
762 (*ref)->remote_status = msg;
763 return !(status == REF_STATUS_OK);
766 static int push_update_refs_status(struct helper_data *data,
767 struct ref *remote_refs,
768 int flags)
770 struct strbuf buf = STRBUF_INIT;
771 struct ref *ref = remote_refs;
772 int ret = 0;
774 for (;;) {
775 char *private;
777 if (recvline(data, &buf)) {
778 ret = 1;
779 break;
782 if (!buf.len)
783 break;
785 if (push_update_ref_status(&buf, &ref, remote_refs))
786 continue;
788 if (flags & TRANSPORT_PUSH_DRY_RUN || !data->refspecs || data->no_private_update)
789 continue;
791 /* propagate back the update to the remote namespace */
792 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
793 if (!private)
794 continue;
795 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
796 free(private);
798 strbuf_release(&buf);
799 return ret;
802 static int push_refs_with_push(struct transport *transport,
803 struct ref *remote_refs, int flags)
805 int force_all = flags & TRANSPORT_PUSH_FORCE;
806 int mirror = flags & TRANSPORT_PUSH_MIRROR;
807 struct helper_data *data = transport->data;
808 struct strbuf buf = STRBUF_INIT;
809 struct ref *ref;
810 struct string_list cas_options = STRING_LIST_INIT_DUP;
811 struct string_list_item *cas_option;
813 get_helper(transport);
814 if (!data->push)
815 return 1;
817 for (ref = remote_refs; ref; ref = ref->next) {
818 if (!ref->peer_ref && !mirror)
819 continue;
821 /* Check for statuses set by set_ref_status_for_push() */
822 switch (ref->status) {
823 case REF_STATUS_REJECT_NONFASTFORWARD:
824 case REF_STATUS_REJECT_STALE:
825 case REF_STATUS_REJECT_ALREADY_EXISTS:
826 case REF_STATUS_UPTODATE:
827 continue;
828 default:
829 ; /* do nothing */
832 if (force_all)
833 ref->force = 1;
835 strbuf_addstr(&buf, "push ");
836 if (!ref->deletion) {
837 if (ref->force)
838 strbuf_addch(&buf, '+');
839 if (ref->peer_ref)
840 strbuf_addstr(&buf, ref->peer_ref->name);
841 else
842 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
844 strbuf_addch(&buf, ':');
845 strbuf_addstr(&buf, ref->name);
846 strbuf_addch(&buf, '\n');
849 * The "--force-with-lease" options without explicit
850 * values to expect have already been expanded into
851 * the ref->old_sha1_expect[] field; we can ignore
852 * transport->smart_options->cas altogether and instead
853 * can enumerate them from the refs.
855 if (ref->expect_old_sha1) {
856 struct strbuf cas = STRBUF_INIT;
857 strbuf_addf(&cas, "%s:%s",
858 ref->name, sha1_to_hex(ref->old_sha1_expect));
859 string_list_append(&cas_options, strbuf_detach(&cas, NULL));
862 if (buf.len == 0) {
863 string_list_clear(&cas_options, 0);
864 return 0;
867 standard_options(transport);
868 for_each_string_list_item(cas_option, &cas_options)
869 set_helper_option(transport, "cas", cas_option->string);
871 if (flags & TRANSPORT_PUSH_DRY_RUN) {
872 if (set_helper_option(transport, "dry-run", "true") != 0)
873 die("helper %s does not support dry-run", data->name);
876 strbuf_addch(&buf, '\n');
877 sendline(data, &buf);
878 strbuf_release(&buf);
880 return push_update_refs_status(data, remote_refs, flags);
883 static int push_refs_with_export(struct transport *transport,
884 struct ref *remote_refs, int flags)
886 struct ref *ref;
887 struct child_process *helper, exporter;
888 struct helper_data *data = transport->data;
889 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
890 struct strbuf buf = STRBUF_INIT;
892 if (!data->refspecs)
893 die("remote-helper doesn't support push; refspec needed");
895 if (flags & TRANSPORT_PUSH_DRY_RUN) {
896 if (set_helper_option(transport, "dry-run", "true") != 0)
897 die("helper %s does not support dry-run", data->name);
900 if (flags & TRANSPORT_PUSH_FORCE) {
901 if (set_helper_option(transport, "force", "true") != 0)
902 warning("helper %s does not support 'force'", data->name);
905 helper = get_helper(transport);
907 write_constant(helper->in, "export\n");
909 strbuf_reset(&buf);
911 for (ref = remote_refs; ref; ref = ref->next) {
912 char *private;
913 unsigned char sha1[20];
915 if (ref->deletion)
916 die("remote-helpers do not support ref deletion");
918 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
919 if (private && !get_sha1(private, sha1)) {
920 strbuf_addf(&buf, "^%s", private);
921 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
922 hashcpy(ref->old_sha1, sha1);
924 free(private);
926 if (ref->peer_ref) {
927 if (strcmp(ref->peer_ref->name, ref->name))
928 die("remote-helpers do not support old:new syntax");
929 string_list_append(&revlist_args, ref->peer_ref->name);
933 if (get_exporter(transport, &exporter, &revlist_args))
934 die("Couldn't run fast-export");
936 if (finish_command(&exporter))
937 die("Error while running fast-export");
938 check_helper_status(data);
939 if (push_update_refs_status(data, remote_refs, flags))
940 return 1;
942 if (data->export_marks) {
943 strbuf_addf(&buf, "%s.tmp", data->export_marks);
944 rename(buf.buf, data->export_marks);
945 strbuf_release(&buf);
948 return 0;
951 static int push_refs(struct transport *transport,
952 struct ref *remote_refs, int flags)
954 struct helper_data *data = transport->data;
956 if (process_connect(transport, 1)) {
957 do_take_over(transport);
958 return transport->push_refs(transport, remote_refs, flags);
961 if (!remote_refs) {
962 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
963 "Perhaps you should specify a branch such as 'master'.\n");
964 return 0;
967 if (data->push)
968 return push_refs_with_push(transport, remote_refs, flags);
970 if (data->export)
971 return push_refs_with_export(transport, remote_refs, flags);
973 return -1;
977 static int has_attribute(const char *attrs, const char *attr) {
978 int len;
979 if (!attrs)
980 return 0;
982 len = strlen(attr);
983 for (;;) {
984 const char *space = strchrnul(attrs, ' ');
985 if (len == space - attrs && !strncmp(attrs, attr, len))
986 return 1;
987 if (!*space)
988 return 0;
989 attrs = space + 1;
993 static struct ref *get_refs_list(struct transport *transport, int for_push)
995 struct helper_data *data = transport->data;
996 struct child_process *helper;
997 struct ref *ret = NULL;
998 struct ref **tail = &ret;
999 struct ref *posn;
1000 struct strbuf buf = STRBUF_INIT;
1002 helper = get_helper(transport);
1004 if (process_connect(transport, for_push)) {
1005 do_take_over(transport);
1006 return transport->get_refs_list(transport, for_push);
1009 if (data->push && for_push)
1010 write_str_in_full(helper->in, "list for-push\n");
1011 else
1012 write_str_in_full(helper->in, "list\n");
1014 while (1) {
1015 char *eov, *eon;
1016 if (recvline(data, &buf))
1017 exit(128);
1019 if (!*buf.buf)
1020 break;
1022 eov = strchr(buf.buf, ' ');
1023 if (!eov)
1024 die("Malformed response in ref list: %s", buf.buf);
1025 eon = strchr(eov + 1, ' ');
1026 *eov = '\0';
1027 if (eon)
1028 *eon = '\0';
1029 *tail = alloc_ref(eov + 1);
1030 if (buf.buf[0] == '@')
1031 (*tail)->symref = xstrdup(buf.buf + 1);
1032 else if (buf.buf[0] != '?')
1033 get_sha1_hex(buf.buf, (*tail)->old_sha1);
1034 if (eon) {
1035 if (has_attribute(eon + 1, "unchanged")) {
1036 (*tail)->status |= REF_STATUS_UPTODATE;
1037 read_ref((*tail)->name, (*tail)->old_sha1);
1040 tail = &((*tail)->next);
1042 if (debug)
1043 fprintf(stderr, "Debug: Read ref listing.\n");
1044 strbuf_release(&buf);
1046 for (posn = ret; posn; posn = posn->next)
1047 resolve_remote_symref(posn, ret);
1049 return ret;
1052 int transport_helper_init(struct transport *transport, const char *name)
1054 struct helper_data *data = xcalloc(sizeof(*data), 1);
1055 data->name = name;
1057 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1058 debug = 1;
1060 transport->data = data;
1061 transport->set_option = set_helper_option;
1062 transport->get_refs_list = get_refs_list;
1063 transport->fetch = fetch;
1064 transport->push_refs = push_refs;
1065 transport->disconnect = release_helper;
1066 transport->connect = connect_helper;
1067 transport->smart_options = &(data->transport_options);
1068 return 0;
1072 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1073 * buffer less), so attempt reads and writes with up to that size.
1075 #define BUFFERSIZE 65536
1076 /* This should be enough to hold debugging message. */
1077 #define PBUFFERSIZE 8192
1079 /* Print bidirectional transfer loop debug message. */
1080 __attribute__((format (printf, 1, 2)))
1081 static void transfer_debug(const char *fmt, ...)
1083 va_list args;
1084 char msgbuf[PBUFFERSIZE];
1085 static int debug_enabled = -1;
1087 if (debug_enabled < 0)
1088 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1089 if (!debug_enabled)
1090 return;
1092 va_start(args, fmt);
1093 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1094 va_end(args);
1095 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1098 /* Stream state: More data may be coming in this direction. */
1099 #define SSTATE_TRANSFERING 0
1101 * Stream state: No more data coming in this direction, flushing rest of
1102 * data.
1104 #define SSTATE_FLUSHING 1
1105 /* Stream state: Transfer in this direction finished. */
1106 #define SSTATE_FINISHED 2
1108 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1109 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1110 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1112 /* Unidirectional transfer. */
1113 struct unidirectional_transfer {
1114 /* Source */
1115 int src;
1116 /* Destination */
1117 int dest;
1118 /* Is source socket? */
1119 int src_is_sock;
1120 /* Is destination socket? */
1121 int dest_is_sock;
1122 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1123 int state;
1124 /* Buffer. */
1125 char buf[BUFFERSIZE];
1126 /* Buffer used. */
1127 size_t bufuse;
1128 /* Name of source. */
1129 const char *src_name;
1130 /* Name of destination. */
1131 const char *dest_name;
1134 /* Closes the target (for writing) if transfer has finished. */
1135 static void udt_close_if_finished(struct unidirectional_transfer *t)
1137 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1138 t->state = SSTATE_FINISHED;
1139 if (t->dest_is_sock)
1140 shutdown(t->dest, SHUT_WR);
1141 else
1142 close(t->dest);
1143 transfer_debug("Closed %s.", t->dest_name);
1148 * Tries to read read data from source into buffer. If buffer is full,
1149 * no data is read. Returns 0 on success, -1 on error.
1151 static int udt_do_read(struct unidirectional_transfer *t)
1153 ssize_t bytes;
1155 if (t->bufuse == BUFFERSIZE)
1156 return 0; /* No space for more. */
1158 transfer_debug("%s is readable", t->src_name);
1159 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1160 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1161 errno != EINTR) {
1162 error("read(%s) failed: %s", t->src_name, strerror(errno));
1163 return -1;
1164 } else if (bytes == 0) {
1165 transfer_debug("%s EOF (with %i bytes in buffer)",
1166 t->src_name, (int)t->bufuse);
1167 t->state = SSTATE_FLUSHING;
1168 } else if (bytes > 0) {
1169 t->bufuse += bytes;
1170 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1171 (int)bytes, t->src_name, (int)t->bufuse);
1173 return 0;
1176 /* Tries to write data from buffer into destination. If buffer is empty,
1177 * no data is written. Returns 0 on success, -1 on error.
1179 static int udt_do_write(struct unidirectional_transfer *t)
1181 ssize_t bytes;
1183 if (t->bufuse == 0)
1184 return 0; /* Nothing to write. */
1186 transfer_debug("%s is writable", t->dest_name);
1187 bytes = xwrite(t->dest, t->buf, t->bufuse);
1188 if (bytes < 0 && errno != EWOULDBLOCK) {
1189 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1190 return -1;
1191 } else if (bytes > 0) {
1192 t->bufuse -= bytes;
1193 if (t->bufuse)
1194 memmove(t->buf, t->buf + bytes, t->bufuse);
1195 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1196 (int)bytes, t->dest_name, (int)t->bufuse);
1198 return 0;
1202 /* State of bidirectional transfer loop. */
1203 struct bidirectional_transfer_state {
1204 /* Direction from program to git. */
1205 struct unidirectional_transfer ptg;
1206 /* Direction from git to program. */
1207 struct unidirectional_transfer gtp;
1210 static void *udt_copy_task_routine(void *udt)
1212 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1213 while (t->state != SSTATE_FINISHED) {
1214 if (STATE_NEEDS_READING(t->state))
1215 if (udt_do_read(t))
1216 return NULL;
1217 if (STATE_NEEDS_WRITING(t->state))
1218 if (udt_do_write(t))
1219 return NULL;
1220 if (STATE_NEEDS_CLOSING(t->state))
1221 udt_close_if_finished(t);
1223 return udt; /* Just some non-NULL value. */
1226 #ifndef NO_PTHREADS
1229 * Join thread, with appropriate errors on failure. Name is name for the
1230 * thread (for error messages). Returns 0 on success, 1 on failure.
1232 static int tloop_join(pthread_t thread, const char *name)
1234 int err;
1235 void *tret;
1236 err = pthread_join(thread, &tret);
1237 if (!tret) {
1238 error("%s thread failed", name);
1239 return 1;
1241 if (err) {
1242 error("%s thread failed to join: %s", name, strerror(err));
1243 return 1;
1245 return 0;
1249 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1250 * -1 on failure.
1252 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1254 pthread_t gtp_thread;
1255 pthread_t ptg_thread;
1256 int err;
1257 int ret = 0;
1258 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1259 &s->gtp);
1260 if (err)
1261 die("Can't start thread for copying data: %s", strerror(err));
1262 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1263 &s->ptg);
1264 if (err)
1265 die("Can't start thread for copying data: %s", strerror(err));
1267 ret |= tloop_join(gtp_thread, "Git to program copy");
1268 ret |= tloop_join(ptg_thread, "Program to git copy");
1269 return ret;
1271 #else
1273 /* Close the source and target (for writing) for transfer. */
1274 static void udt_kill_transfer(struct unidirectional_transfer *t)
1276 t->state = SSTATE_FINISHED;
1278 * Socket read end left open isn't a disaster if nobody
1279 * attempts to read from it (mingw compat headers do not
1280 * have SHUT_RD)...
1282 * We can't fully close the socket since otherwise gtp
1283 * task would first close the socket it sends data to
1284 * while closing the ptg file descriptors.
1286 if (!t->src_is_sock)
1287 close(t->src);
1288 if (t->dest_is_sock)
1289 shutdown(t->dest, SHUT_WR);
1290 else
1291 close(t->dest);
1295 * Join process, with appropriate errors on failure. Name is name for the
1296 * process (for error messages). Returns 0 on success, 1 on failure.
1298 static int tloop_join(pid_t pid, const char *name)
1300 int tret;
1301 if (waitpid(pid, &tret, 0) < 0) {
1302 error("%s process failed to wait: %s", name, strerror(errno));
1303 return 1;
1305 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1306 error("%s process failed", name);
1307 return 1;
1309 return 0;
1313 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1314 * -1 on failure.
1316 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1318 pid_t pid1, pid2;
1319 int ret = 0;
1321 /* Fork thread #1: git to program. */
1322 pid1 = fork();
1323 if (pid1 < 0)
1324 die_errno("Can't start thread for copying data");
1325 else if (pid1 == 0) {
1326 udt_kill_transfer(&s->ptg);
1327 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1330 /* Fork thread #2: program to git. */
1331 pid2 = fork();
1332 if (pid2 < 0)
1333 die_errno("Can't start thread for copying data");
1334 else if (pid2 == 0) {
1335 udt_kill_transfer(&s->gtp);
1336 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1340 * Close both streams in parent as to not interfere with
1341 * end of file detection and wait for both tasks to finish.
1343 udt_kill_transfer(&s->gtp);
1344 udt_kill_transfer(&s->ptg);
1345 ret |= tloop_join(pid1, "Git to program copy");
1346 ret |= tloop_join(pid2, "Program to git copy");
1347 return ret;
1349 #endif
1352 * Copies data from stdin to output and from input to stdout simultaneously.
1353 * Additionally filtering through given filter. If filter is NULL, uses
1354 * identity filter.
1356 int bidirectional_transfer_loop(int input, int output)
1358 struct bidirectional_transfer_state state;
1360 /* Fill the state fields. */
1361 state.ptg.src = input;
1362 state.ptg.dest = 1;
1363 state.ptg.src_is_sock = (input == output);
1364 state.ptg.dest_is_sock = 0;
1365 state.ptg.state = SSTATE_TRANSFERING;
1366 state.ptg.bufuse = 0;
1367 state.ptg.src_name = "remote input";
1368 state.ptg.dest_name = "stdout";
1370 state.gtp.src = 0;
1371 state.gtp.dest = output;
1372 state.gtp.src_is_sock = 0;
1373 state.gtp.dest_is_sock = (input == output);
1374 state.gtp.state = SSTATE_TRANSFERING;
1375 state.gtp.bufuse = 0;
1376 state.gtp.src_name = "stdin";
1377 state.gtp.dest_name = "remote output";
1379 return tloop_spawnwait_tasks(&state);