Merge 'install-wincred' into HEAD
[git/mingw/4msysgit.git] / transport-helper.c
blobece3f3c1e899ae3ec93a3e2f2396b8e526328fb4
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 exit(128);
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 xchgline(struct helper_data *helper, struct strbuf *buffer)
78 sendline(helper, buffer);
79 recvline(helper, buffer);
82 static void write_constant(int fd, const char *str)
84 if (debug)
85 fprintf(stderr, "Debug: Remote helper: -> %s", str);
86 if (write_in_full(fd, str, strlen(str)) != strlen(str))
87 die_errno("Full write to remote helper failed");
90 static const char *remove_ext_force(const char *url)
92 if (url) {
93 const char *colon = strchr(url, ':');
94 if (colon && colon[1] == ':')
95 return colon + 2;
97 return url;
100 static void do_take_over(struct transport *transport)
102 struct helper_data *data;
103 data = (struct helper_data *)transport->data;
104 transport_take_over(transport, data->helper);
105 fclose(data->out);
106 free(data);
109 static struct child_process *get_helper(struct transport *transport)
111 struct helper_data *data = transport->data;
112 struct argv_array argv = ARGV_ARRAY_INIT;
113 struct strbuf buf = STRBUF_INIT;
114 struct child_process *helper;
115 const char **refspecs = NULL;
116 int refspec_nr = 0;
117 int refspec_alloc = 0;
118 int duped;
119 int code;
120 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
121 const char *helper_env[] = {
122 git_dir_buf,
123 NULL
127 if (data->helper)
128 return data->helper;
130 helper = xcalloc(1, sizeof(*helper));
131 helper->in = -1;
132 helper->out = -1;
133 helper->err = 0;
134 argv_array_pushf(&argv, "git-remote-%s", data->name);
135 argv_array_push(&argv, transport->remote->name);
136 argv_array_push(&argv, remove_ext_force(transport->url));
137 helper->argv = argv_array_detach(&argv, NULL);
138 helper->git_cmd = 0;
139 helper->silent_exec_failure = 1;
141 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
142 helper->env = helper_env;
144 code = start_command(helper);
145 if (code < 0 && errno == ENOENT)
146 die("Unable to find remote helper for '%s'", data->name);
147 else if (code != 0)
148 exit(code);
150 data->helper = helper;
151 data->no_disconnect_req = 0;
154 * Open the output as FILE* so strbuf_getline() 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;
167 int mandatory = 0;
168 recvline(data, &buf);
170 if (!*buf.buf)
171 break;
173 if (*buf.buf == '*') {
174 capname = buf.buf + 1;
175 mandatory = 1;
176 } else
177 capname = buf.buf;
179 if (debug)
180 fprintf(stderr, "Debug: Got cap %s\n", capname);
181 if (!strcmp(capname, "fetch"))
182 data->fetch = 1;
183 else if (!strcmp(capname, "option"))
184 data->option = 1;
185 else if (!strcmp(capname, "push"))
186 data->push = 1;
187 else if (!strcmp(capname, "import"))
188 data->import = 1;
189 else if (!strcmp(capname, "bidi-import"))
190 data->bidi_import = 1;
191 else if (!strcmp(capname, "export"))
192 data->export = 1;
193 else if (!strcmp(capname, "check-connectivity"))
194 data->check_connectivity = 1;
195 else if (!data->refspecs && starts_with(capname, "refspec ")) {
196 ALLOC_GROW(refspecs,
197 refspec_nr + 1,
198 refspec_alloc);
199 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
200 } else if (!strcmp(capname, "connect")) {
201 data->connect = 1;
202 } else if (!strcmp(capname, "signed-tags")) {
203 data->signed_tags = 1;
204 } else if (starts_with(capname, "export-marks ")) {
205 struct strbuf arg = STRBUF_INIT;
206 strbuf_addstr(&arg, "--export-marks=");
207 strbuf_addstr(&arg, capname + strlen("export-marks "));
208 data->export_marks = strbuf_detach(&arg, NULL);
209 } else if (starts_with(capname, "import-marks")) {
210 struct strbuf arg = STRBUF_INIT;
211 strbuf_addstr(&arg, "--import-marks=");
212 strbuf_addstr(&arg, capname + strlen("import-marks "));
213 data->import_marks = strbuf_detach(&arg, NULL);
214 } else if (starts_with(capname, "no-private-update")) {
215 data->no_private_update = 1;
216 } else if (mandatory) {
217 die("Unknown mandatory capability %s. This remote "
218 "helper probably needs newer version of Git.",
219 capname);
222 if (refspecs) {
223 int i;
224 data->refspec_nr = refspec_nr;
225 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
226 for (i = 0; i < refspec_nr; i++)
227 free((char *)refspecs[i]);
228 free(refspecs);
229 } else if (data->import || data->bidi_import || data->export) {
230 warning("This remote helper should implement refspec capability.");
232 strbuf_release(&buf);
233 if (debug)
234 fprintf(stderr, "Debug: Capabilities complete.\n");
235 return data->helper;
238 static int disconnect_helper(struct transport *transport)
240 struct helper_data *data = transport->data;
241 int res = 0;
243 if (data->helper) {
244 if (debug)
245 fprintf(stderr, "Debug: Disconnecting.\n");
246 if (!data->no_disconnect_req) {
248 * Ignore write errors; there's nothing we can do,
249 * since we're about to close the pipe anyway. And the
250 * most likely error is EPIPE due to the helper dying
251 * to report an error itself.
253 sigchain_push(SIGPIPE, SIG_IGN);
254 xwrite(data->helper->in, "\n", 1);
255 sigchain_pop(SIGPIPE);
257 close(data->helper->in);
258 close(data->helper->out);
259 fclose(data->out);
260 res = finish_command(data->helper);
261 argv_array_free_detached(data->helper->argv);
262 free(data->helper);
263 data->helper = NULL;
265 return res;
268 static const char *unsupported_options[] = {
269 TRANS_OPT_UPLOADPACK,
270 TRANS_OPT_RECEIVEPACK,
271 TRANS_OPT_THIN,
272 TRANS_OPT_KEEP
275 static const char *boolean_options[] = {
276 TRANS_OPT_THIN,
277 TRANS_OPT_KEEP,
278 TRANS_OPT_FOLLOWTAGS
281 static int set_helper_option(struct transport *transport,
282 const char *name, const char *value)
284 struct helper_data *data = transport->data;
285 struct strbuf buf = STRBUF_INIT;
286 int i, ret, is_bool = 0;
288 get_helper(transport);
290 if (!data->option)
291 return 1;
293 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
294 if (!strcmp(name, unsupported_options[i]))
295 return 1;
298 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
299 if (!strcmp(name, boolean_options[i])) {
300 is_bool = 1;
301 break;
305 strbuf_addf(&buf, "option %s ", name);
306 if (is_bool)
307 strbuf_addstr(&buf, value ? "true" : "false");
308 else
309 quote_c_style(value, &buf, NULL, 0);
310 strbuf_addch(&buf, '\n');
312 xchgline(data, &buf);
314 if (!strcmp(buf.buf, "ok"))
315 ret = 0;
316 else if (starts_with(buf.buf, "error")) {
317 ret = -1;
318 } else if (!strcmp(buf.buf, "unsupported"))
319 ret = 1;
320 else {
321 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
322 ret = 1;
324 strbuf_release(&buf);
325 return ret;
328 static void standard_options(struct transport *t)
330 char buf[16];
331 int n;
332 int v = t->verbose;
334 set_helper_option(t, "progress", t->progress ? "true" : "false");
336 n = snprintf(buf, sizeof(buf), "%d", v + 1);
337 if (n >= sizeof(buf))
338 die("impossibly large verbosity value");
339 set_helper_option(t, "verbosity", buf);
342 static int release_helper(struct transport *transport)
344 int res = 0;
345 struct helper_data *data = transport->data;
346 free_refspec(data->refspec_nr, data->refspecs);
347 data->refspecs = NULL;
348 res = disconnect_helper(transport);
349 free(transport->data);
350 return res;
353 static int fetch_with_fetch(struct transport *transport,
354 int nr_heads, struct ref **to_fetch)
356 struct helper_data *data = transport->data;
357 int i;
358 struct strbuf buf = STRBUF_INIT;
360 standard_options(transport);
361 if (data->check_connectivity &&
362 data->transport_options.check_self_contained_and_connected)
363 set_helper_option(transport, "check-connectivity", "true");
365 if (transport->cloning)
366 set_helper_option(transport, "cloning", "true");
368 if (data->transport_options.update_shallow)
369 set_helper_option(transport, "update-shallow", "true");
371 for (i = 0; i < nr_heads; i++) {
372 const struct ref *posn = to_fetch[i];
373 if (posn->status & REF_STATUS_UPTODATE)
374 continue;
376 strbuf_addf(&buf, "fetch %s %s\n",
377 sha1_to_hex(posn->old_sha1), posn->name);
380 strbuf_addch(&buf, '\n');
381 sendline(data, &buf);
383 while (1) {
384 recvline(data, &buf);
386 if (starts_with(buf.buf, "lock ")) {
387 const char *name = buf.buf + 5;
388 if (transport->pack_lockfile)
389 warning("%s also locked %s", data->name, name);
390 else
391 transport->pack_lockfile = xstrdup(name);
393 else if (data->check_connectivity &&
394 data->transport_options.check_self_contained_and_connected &&
395 !strcmp(buf.buf, "connectivity-ok"))
396 data->transport_options.self_contained_and_connected = 1;
397 else if (!buf.len)
398 break;
399 else
400 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
402 strbuf_release(&buf);
403 return 0;
406 static int get_importer(struct transport *transport, struct child_process *fastimport)
408 struct child_process *helper = get_helper(transport);
409 struct helper_data *data = transport->data;
410 struct argv_array argv = ARGV_ARRAY_INIT;
411 int cat_blob_fd, code;
412 memset(fastimport, 0, sizeof(*fastimport));
413 fastimport->in = helper->out;
414 argv_array_push(&argv, "fast-import");
415 argv_array_push(&argv, debug ? "--stats" : "--quiet");
417 if (data->bidi_import) {
418 cat_blob_fd = xdup(helper->in);
419 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
421 fastimport->argv = argv.argv;
422 fastimport->git_cmd = 1;
424 code = start_command(fastimport);
425 return code;
428 static int get_exporter(struct transport *transport,
429 struct child_process *fastexport,
430 struct string_list *revlist_args)
432 struct helper_data *data = transport->data;
433 struct child_process *helper = get_helper(transport);
434 int argc = 0, i;
435 memset(fastexport, 0, sizeof(*fastexport));
437 /* we need to duplicate helper->in because we want to use it after
438 * fastexport is done with it. */
439 fastexport->out = dup(helper->in);
440 fastexport->argv = xcalloc(7 + revlist_args->nr, sizeof(*fastexport->argv));
441 fastexport->argv[argc++] = "fast-export";
442 fastexport->argv[argc++] = "--use-done-feature";
443 fastexport->argv[argc++] = data->signed_tags ?
444 "--signed-tags=verbatim" : "--signed-tags=warn-strip";
445 if (data->export_marks)
446 fastexport->argv[argc++] = data->export_marks;
447 if (data->import_marks)
448 fastexport->argv[argc++] = data->import_marks;
450 for (i = 0; i < revlist_args->nr; i++)
451 fastexport->argv[argc++] = revlist_args->items[i].string;
453 fastexport->argv[argc++] = "--";
455 fastexport->git_cmd = 1;
456 return start_command(fastexport);
459 static void check_helper_status(struct helper_data *data)
461 int pid, status;
463 pid = waitpid(data->helper->pid, &status, WNOHANG);
464 if (pid < 0)
465 die("Could not retrieve status of remote helper '%s'",
466 data->name);
467 if (pid > 0 && WIFEXITED(status))
468 die("Remote helper '%s' died with %d",
469 data->name, WEXITSTATUS(status));
472 static int fetch_with_import(struct transport *transport,
473 int nr_heads, struct ref **to_fetch)
475 struct child_process fastimport;
476 struct helper_data *data = transport->data;
477 int i;
478 struct ref *posn;
479 struct strbuf buf = STRBUF_INIT;
481 get_helper(transport);
483 if (get_importer(transport, &fastimport))
484 die("Couldn't run fast-import");
486 for (i = 0; i < nr_heads; i++) {
487 posn = to_fetch[i];
488 if (posn->status & REF_STATUS_UPTODATE)
489 continue;
491 strbuf_addf(&buf, "import %s\n", posn->name);
492 sendline(data, &buf);
493 strbuf_reset(&buf);
496 write_constant(data->helper->in, "\n");
498 * remote-helpers that advertise the bidi-import capability are required to
499 * buffer the complete batch of import commands until this newline before
500 * sending data to fast-import.
501 * These helpers read back data from fast-import on their stdin, which could
502 * be mixed with import commands, otherwise.
505 if (finish_command(&fastimport))
506 die("Error while running fast-import");
507 argv_array_free_detached(fastimport.argv);
508 check_helper_status(data);
511 * The fast-import stream of a remote helper that advertises
512 * the "refspec" capability writes to the refs named after the
513 * right hand side of the first refspec matching each ref we
514 * were fetching.
516 * (If no "refspec" capability was specified, for historical
517 * reasons we default to the equivalent of *:*.)
519 * Store the result in to_fetch[i].old_sha1. Callers such
520 * as "git fetch" can use the value to write feedback to the
521 * terminal, populate FETCH_HEAD, and determine what new value
522 * should be written to peer_ref if the update is a
523 * fast-forward or this is a forced update.
525 for (i = 0; i < nr_heads; i++) {
526 char *private;
527 posn = to_fetch[i];
528 if (posn->status & REF_STATUS_UPTODATE)
529 continue;
530 if (data->refspecs)
531 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
532 else
533 private = xstrdup(posn->name);
534 if (private) {
535 read_ref(private, posn->old_sha1);
536 free(private);
539 strbuf_release(&buf);
540 if (auto_gc) {
541 const char *argv_gc_auto[] = {
542 "gc", "--auto", "--quiet", NULL,
544 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
546 return 0;
549 static int process_connect_service(struct transport *transport,
550 const char *name, const char *exec)
552 struct helper_data *data = transport->data;
553 struct strbuf cmdbuf = STRBUF_INIT;
554 struct child_process *helper;
555 int r, duped, ret = 0;
556 FILE *input;
558 helper = get_helper(transport);
561 * Yes, dup the pipe another time, as we need unbuffered version
562 * of input pipe as FILE*. fclose() closes the underlying fd and
563 * stream buffering only can be changed before first I/O operation
564 * on it.
566 duped = dup(helper->out);
567 if (duped < 0)
568 die_errno("Can't dup helper output fd");
569 input = xfdopen(duped, "r");
570 setvbuf(input, NULL, _IONBF, 0);
573 * Handle --upload-pack and friends. This is fire and forget...
574 * just warn if it fails.
576 if (strcmp(name, exec)) {
577 r = set_helper_option(transport, "servpath", exec);
578 if (r > 0)
579 warning("Setting remote service path not supported by protocol.");
580 else if (r < 0)
581 warning("Invalid remote service path.");
584 if (data->connect)
585 strbuf_addf(&cmdbuf, "connect %s\n", name);
586 else
587 goto exit;
589 sendline(data, &cmdbuf);
590 recvline_fh(input, &cmdbuf, name);
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;
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;
737 if (*ref)
738 *ref = find_ref_by_name(*ref, refname);
739 if (!*ref)
740 *ref = find_ref_by_name(remote_refs, refname);
741 if (!*ref) {
742 warning("helper reported unexpected status of %s", refname);
743 return 1;
746 if ((*ref)->status != REF_STATUS_NONE) {
748 * Earlier, the ref was marked not to be pushed, so ignore the ref
749 * status reported by the remote helper if the latter is 'no match'.
751 if (status == REF_STATUS_NONE)
752 return 1;
755 (*ref)->status = status;
756 (*ref)->remote_status = msg;
757 return !(status == REF_STATUS_OK);
760 static void push_update_refs_status(struct helper_data *data,
761 struct ref *remote_refs)
763 struct strbuf buf = STRBUF_INIT;
764 struct ref *ref = remote_refs;
765 for (;;) {
766 char *private;
768 recvline(data, &buf);
769 if (!buf.len)
770 break;
772 if (push_update_ref_status(&buf, &ref, remote_refs))
773 continue;
775 if (!data->refspecs || data->no_private_update)
776 continue;
778 /* propagate back the update to the remote namespace */
779 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
780 if (!private)
781 continue;
782 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
783 free(private);
785 strbuf_release(&buf);
788 static int push_refs_with_push(struct transport *transport,
789 struct ref *remote_refs, int flags)
791 int force_all = flags & TRANSPORT_PUSH_FORCE;
792 int mirror = flags & TRANSPORT_PUSH_MIRROR;
793 struct helper_data *data = transport->data;
794 struct strbuf buf = STRBUF_INIT;
795 struct ref *ref;
796 struct string_list cas_options = STRING_LIST_INIT_DUP;
797 struct string_list_item *cas_option;
799 get_helper(transport);
800 if (!data->push)
801 return 1;
803 for (ref = remote_refs; ref; ref = ref->next) {
804 if (!ref->peer_ref && !mirror)
805 continue;
807 /* Check for statuses set by set_ref_status_for_push() */
808 switch (ref->status) {
809 case REF_STATUS_REJECT_NONFASTFORWARD:
810 case REF_STATUS_REJECT_STALE:
811 case REF_STATUS_REJECT_ALREADY_EXISTS:
812 case REF_STATUS_UPTODATE:
813 continue;
814 default:
815 ; /* do nothing */
818 if (force_all)
819 ref->force = 1;
821 strbuf_addstr(&buf, "push ");
822 if (!ref->deletion) {
823 if (ref->force)
824 strbuf_addch(&buf, '+');
825 if (ref->peer_ref)
826 strbuf_addstr(&buf, ref->peer_ref->name);
827 else
828 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
830 strbuf_addch(&buf, ':');
831 strbuf_addstr(&buf, ref->name);
832 strbuf_addch(&buf, '\n');
835 * The "--force-with-lease" options without explicit
836 * values to expect have already been expanded into
837 * the ref->old_sha1_expect[] field; we can ignore
838 * transport->smart_options->cas altogether and instead
839 * can enumerate them from the refs.
841 if (ref->expect_old_sha1) {
842 struct strbuf cas = STRBUF_INIT;
843 strbuf_addf(&cas, "%s:%s",
844 ref->name, sha1_to_hex(ref->old_sha1_expect));
845 string_list_append(&cas_options, strbuf_detach(&cas, NULL));
848 if (buf.len == 0) {
849 string_list_clear(&cas_options, 0);
850 return 0;
853 standard_options(transport);
854 for_each_string_list_item(cas_option, &cas_options)
855 set_helper_option(transport, "cas", cas_option->string);
857 if (flags & TRANSPORT_PUSH_DRY_RUN) {
858 if (set_helper_option(transport, "dry-run", "true") != 0)
859 die("helper %s does not support dry-run", data->name);
862 strbuf_addch(&buf, '\n');
863 sendline(data, &buf);
864 strbuf_release(&buf);
866 push_update_refs_status(data, remote_refs);
867 return 0;
870 static int push_refs_with_export(struct transport *transport,
871 struct ref *remote_refs, int flags)
873 struct ref *ref;
874 struct child_process *helper, exporter;
875 struct helper_data *data = transport->data;
876 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
877 struct strbuf buf = STRBUF_INIT;
879 if (!data->refspecs)
880 die("remote-helper doesn't support push; refspec needed");
882 if (flags & TRANSPORT_PUSH_DRY_RUN) {
883 if (set_helper_option(transport, "dry-run", "true") != 0)
884 die("helper %s does not support dry-run", data->name);
887 helper = get_helper(transport);
889 write_constant(helper->in, "export\n");
891 strbuf_reset(&buf);
893 for (ref = remote_refs; ref; ref = ref->next) {
894 char *private;
895 unsigned char sha1[20];
897 if (ref->deletion)
898 die("remote-helpers do not support ref deletion");
900 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
901 if (private && !get_sha1(private, sha1)) {
902 strbuf_addf(&buf, "^%s", private);
903 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
904 hashcpy(ref->old_sha1, sha1);
906 free(private);
908 if (ref->deletion)
909 die("remote-helpers do not support ref deletion");
911 if (ref->peer_ref) {
912 if (strcmp(ref->peer_ref->name, ref->name))
913 die("remote-helpers do not support old:new syntax");
914 string_list_append(&revlist_args, ref->peer_ref->name);
918 if (get_exporter(transport, &exporter, &revlist_args))
919 die("Couldn't run fast-export");
921 if (finish_command(&exporter))
922 die("Error while running fast-export");
923 check_helper_status(data);
924 push_update_refs_status(data, remote_refs);
925 return 0;
928 static int push_refs(struct transport *transport,
929 struct ref *remote_refs, int flags)
931 struct helper_data *data = transport->data;
933 if (process_connect(transport, 1)) {
934 do_take_over(transport);
935 return transport->push_refs(transport, remote_refs, flags);
938 if (!remote_refs) {
939 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
940 "Perhaps you should specify a branch such as 'master'.\n");
941 return 0;
944 if (data->push)
945 return push_refs_with_push(transport, remote_refs, flags);
947 if (data->export)
948 return push_refs_with_export(transport, remote_refs, flags);
950 return -1;
954 static int has_attribute(const char *attrs, const char *attr) {
955 int len;
956 if (!attrs)
957 return 0;
959 len = strlen(attr);
960 for (;;) {
961 const char *space = strchrnul(attrs, ' ');
962 if (len == space - attrs && !strncmp(attrs, attr, len))
963 return 1;
964 if (!*space)
965 return 0;
966 attrs = space + 1;
970 static struct ref *get_refs_list(struct transport *transport, int for_push)
972 struct helper_data *data = transport->data;
973 struct child_process *helper;
974 struct ref *ret = NULL;
975 struct ref **tail = &ret;
976 struct ref *posn;
977 struct strbuf buf = STRBUF_INIT;
979 helper = get_helper(transport);
981 if (process_connect(transport, for_push)) {
982 do_take_over(transport);
983 return transport->get_refs_list(transport, for_push);
986 if (data->push && for_push)
987 write_str_in_full(helper->in, "list for-push\n");
988 else
989 write_str_in_full(helper->in, "list\n");
991 while (1) {
992 char *eov, *eon;
993 recvline(data, &buf);
995 if (!*buf.buf)
996 break;
998 eov = strchr(buf.buf, ' ');
999 if (!eov)
1000 die("Malformed response in ref list: %s", buf.buf);
1001 eon = strchr(eov + 1, ' ');
1002 *eov = '\0';
1003 if (eon)
1004 *eon = '\0';
1005 *tail = alloc_ref(eov + 1);
1006 if (buf.buf[0] == '@')
1007 (*tail)->symref = xstrdup(buf.buf + 1);
1008 else if (buf.buf[0] != '?')
1009 get_sha1_hex(buf.buf, (*tail)->old_sha1);
1010 if (eon) {
1011 if (has_attribute(eon + 1, "unchanged")) {
1012 (*tail)->status |= REF_STATUS_UPTODATE;
1013 read_ref((*tail)->name, (*tail)->old_sha1);
1016 tail = &((*tail)->next);
1018 if (debug)
1019 fprintf(stderr, "Debug: Read ref listing.\n");
1020 strbuf_release(&buf);
1022 for (posn = ret; posn; posn = posn->next)
1023 resolve_remote_symref(posn, ret);
1025 return ret;
1028 int transport_helper_init(struct transport *transport, const char *name)
1030 struct helper_data *data = xcalloc(sizeof(*data), 1);
1031 data->name = name;
1033 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1034 debug = 1;
1036 transport->data = data;
1037 transport->set_option = set_helper_option;
1038 transport->get_refs_list = get_refs_list;
1039 transport->fetch = fetch;
1040 transport->push_refs = push_refs;
1041 transport->disconnect = release_helper;
1042 transport->connect = connect_helper;
1043 transport->smart_options = &(data->transport_options);
1044 return 0;
1048 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1049 * buffer less), so attempt reads and writes with up to that size.
1051 #define BUFFERSIZE 65536
1052 /* This should be enough to hold debugging message. */
1053 #define PBUFFERSIZE 8192
1055 /* Print bidirectional transfer loop debug message. */
1056 __attribute__((format (printf, 1, 2)))
1057 static void transfer_debug(const char *fmt, ...)
1059 va_list args;
1060 char msgbuf[PBUFFERSIZE];
1061 static int debug_enabled = -1;
1063 if (debug_enabled < 0)
1064 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1065 if (!debug_enabled)
1066 return;
1068 va_start(args, fmt);
1069 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1070 va_end(args);
1071 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1074 /* Stream state: More data may be coming in this direction. */
1075 #define SSTATE_TRANSFERING 0
1077 * Stream state: No more data coming in this direction, flushing rest of
1078 * data.
1080 #define SSTATE_FLUSHING 1
1081 /* Stream state: Transfer in this direction finished. */
1082 #define SSTATE_FINISHED 2
1084 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1085 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1086 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1088 /* Unidirectional transfer. */
1089 struct unidirectional_transfer {
1090 /* Source */
1091 int src;
1092 /* Destination */
1093 int dest;
1094 /* Is source socket? */
1095 int src_is_sock;
1096 /* Is destination socket? */
1097 int dest_is_sock;
1098 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1099 int state;
1100 /* Buffer. */
1101 char buf[BUFFERSIZE];
1102 /* Buffer used. */
1103 size_t bufuse;
1104 /* Name of source. */
1105 const char *src_name;
1106 /* Name of destination. */
1107 const char *dest_name;
1110 /* Closes the target (for writing) if transfer has finished. */
1111 static void udt_close_if_finished(struct unidirectional_transfer *t)
1113 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1114 t->state = SSTATE_FINISHED;
1115 if (t->dest_is_sock)
1116 shutdown(t->dest, SHUT_WR);
1117 else
1118 close(t->dest);
1119 transfer_debug("Closed %s.", t->dest_name);
1124 * Tries to read read data from source into buffer. If buffer is full,
1125 * no data is read. Returns 0 on success, -1 on error.
1127 static int udt_do_read(struct unidirectional_transfer *t)
1129 ssize_t bytes;
1131 if (t->bufuse == BUFFERSIZE)
1132 return 0; /* No space for more. */
1134 transfer_debug("%s is readable", t->src_name);
1135 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1136 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1137 errno != EINTR) {
1138 error("read(%s) failed: %s", t->src_name, strerror(errno));
1139 return -1;
1140 } else if (bytes == 0) {
1141 transfer_debug("%s EOF (with %i bytes in buffer)",
1142 t->src_name, (int)t->bufuse);
1143 t->state = SSTATE_FLUSHING;
1144 } else if (bytes > 0) {
1145 t->bufuse += bytes;
1146 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1147 (int)bytes, t->src_name, (int)t->bufuse);
1149 return 0;
1152 /* Tries to write data from buffer into destination. If buffer is empty,
1153 * no data is written. Returns 0 on success, -1 on error.
1155 static int udt_do_write(struct unidirectional_transfer *t)
1157 ssize_t bytes;
1159 if (t->bufuse == 0)
1160 return 0; /* Nothing to write. */
1162 transfer_debug("%s is writable", t->dest_name);
1163 bytes = xwrite(t->dest, t->buf, t->bufuse);
1164 if (bytes < 0 && errno != EWOULDBLOCK) {
1165 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1166 return -1;
1167 } else if (bytes > 0) {
1168 t->bufuse -= bytes;
1169 if (t->bufuse)
1170 memmove(t->buf, t->buf + bytes, t->bufuse);
1171 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1172 (int)bytes, t->dest_name, (int)t->bufuse);
1174 return 0;
1178 /* State of bidirectional transfer loop. */
1179 struct bidirectional_transfer_state {
1180 /* Direction from program to git. */
1181 struct unidirectional_transfer ptg;
1182 /* Direction from git to program. */
1183 struct unidirectional_transfer gtp;
1186 static void *udt_copy_task_routine(void *udt)
1188 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1189 while (t->state != SSTATE_FINISHED) {
1190 if (STATE_NEEDS_READING(t->state))
1191 if (udt_do_read(t))
1192 return NULL;
1193 if (STATE_NEEDS_WRITING(t->state))
1194 if (udt_do_write(t))
1195 return NULL;
1196 if (STATE_NEEDS_CLOSING(t->state))
1197 udt_close_if_finished(t);
1199 return udt; /* Just some non-NULL value. */
1202 #ifndef NO_PTHREADS
1205 * Join thread, with appropriate errors on failure. Name is name for the
1206 * thread (for error messages). Returns 0 on success, 1 on failure.
1208 static int tloop_join(pthread_t thread, const char *name)
1210 int err;
1211 void *tret;
1212 err = pthread_join(thread, &tret);
1213 if (!tret) {
1214 error("%s thread failed", name);
1215 return 1;
1217 if (err) {
1218 error("%s thread failed to join: %s", name, strerror(err));
1219 return 1;
1221 return 0;
1225 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1226 * -1 on failure.
1228 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1230 pthread_t gtp_thread;
1231 pthread_t ptg_thread;
1232 int err;
1233 int ret = 0;
1234 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1235 &s->gtp);
1236 if (err)
1237 die("Can't start thread for copying data: %s", strerror(err));
1238 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1239 &s->ptg);
1240 if (err)
1241 die("Can't start thread for copying data: %s", strerror(err));
1243 ret |= tloop_join(gtp_thread, "Git to program copy");
1244 ret |= tloop_join(ptg_thread, "Program to git copy");
1245 return ret;
1247 #else
1249 /* Close the source and target (for writing) for transfer. */
1250 static void udt_kill_transfer(struct unidirectional_transfer *t)
1252 t->state = SSTATE_FINISHED;
1254 * Socket read end left open isn't a disaster if nobody
1255 * attempts to read from it (mingw compat headers do not
1256 * have SHUT_RD)...
1258 * We can't fully close the socket since otherwise gtp
1259 * task would first close the socket it sends data to
1260 * while closing the ptg file descriptors.
1262 if (!t->src_is_sock)
1263 close(t->src);
1264 if (t->dest_is_sock)
1265 shutdown(t->dest, SHUT_WR);
1266 else
1267 close(t->dest);
1271 * Join process, with appropriate errors on failure. Name is name for the
1272 * process (for error messages). Returns 0 on success, 1 on failure.
1274 static int tloop_join(pid_t pid, const char *name)
1276 int tret;
1277 if (waitpid(pid, &tret, 0) < 0) {
1278 error("%s process failed to wait: %s", name, strerror(errno));
1279 return 1;
1281 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1282 error("%s process failed", name);
1283 return 1;
1285 return 0;
1289 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1290 * -1 on failure.
1292 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1294 pid_t pid1, pid2;
1295 int ret = 0;
1297 /* Fork thread #1: git to program. */
1298 pid1 = fork();
1299 if (pid1 < 0)
1300 die_errno("Can't start thread for copying data");
1301 else if (pid1 == 0) {
1302 udt_kill_transfer(&s->ptg);
1303 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1306 /* Fork thread #2: program to git. */
1307 pid2 = fork();
1308 if (pid2 < 0)
1309 die_errno("Can't start thread for copying data");
1310 else if (pid2 == 0) {
1311 udt_kill_transfer(&s->gtp);
1312 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1316 * Close both streams in parent as to not interfere with
1317 * end of file detection and wait for both tasks to finish.
1319 udt_kill_transfer(&s->gtp);
1320 udt_kill_transfer(&s->ptg);
1321 ret |= tloop_join(pid1, "Git to program copy");
1322 ret |= tloop_join(pid2, "Program to git copy");
1323 return ret;
1325 #endif
1328 * Copies data from stdin to output and from input to stdout simultaneously.
1329 * Additionally filtering through given filter. If filter is NULL, uses
1330 * identity filter.
1332 int bidirectional_transfer_loop(int input, int output)
1334 struct bidirectional_transfer_state state;
1336 /* Fill the state fields. */
1337 state.ptg.src = input;
1338 state.ptg.dest = 1;
1339 state.ptg.src_is_sock = (input == output);
1340 state.ptg.dest_is_sock = 0;
1341 state.ptg.state = SSTATE_TRANSFERING;
1342 state.ptg.bufuse = 0;
1343 state.ptg.src_name = "remote input";
1344 state.ptg.dest_name = "stdout";
1346 state.gtp.src = 0;
1347 state.gtp.dest = output;
1348 state.gtp.src_is_sock = 0;
1349 state.gtp.dest_is_sock = (input == output);
1350 state.gtp.state = SSTATE_TRANSFERING;
1351 state.gtp.bufuse = 0;
1352 state.gtp.src_name = "stdin";
1353 state.gtp.dest_name = "remote output";
1355 return tloop_spawnwait_tasks(&state);