Merge branch 'kb/hashmap-v5-minimal' into kb/fscache-v4-t1.8.5
[git/mingw/4msysgit.git] / transport-helper.c
blob80e1ff3ced5e852f03e9b80bfe4d50abae1c849f
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 && !prefixcmp(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 (!prefixcmp(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 (!prefixcmp(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 (!prefixcmp(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 (!prefixcmp(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 for (i = 0; i < nr_heads; i++) {
366 const struct ref *posn = to_fetch[i];
367 if (posn->status & REF_STATUS_UPTODATE)
368 continue;
370 strbuf_addf(&buf, "fetch %s %s\n",
371 sha1_to_hex(posn->old_sha1), posn->name);
374 strbuf_addch(&buf, '\n');
375 sendline(data, &buf);
377 while (1) {
378 recvline(data, &buf);
380 if (!prefixcmp(buf.buf, "lock ")) {
381 const char *name = buf.buf + 5;
382 if (transport->pack_lockfile)
383 warning("%s also locked %s", data->name, name);
384 else
385 transport->pack_lockfile = xstrdup(name);
387 else if (data->check_connectivity &&
388 data->transport_options.check_self_contained_and_connected &&
389 !strcmp(buf.buf, "connectivity-ok"))
390 data->transport_options.self_contained_and_connected = 1;
391 else if (!buf.len)
392 break;
393 else
394 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
396 strbuf_release(&buf);
397 return 0;
400 static int get_importer(struct transport *transport, struct child_process *fastimport)
402 struct child_process *helper = get_helper(transport);
403 struct helper_data *data = transport->data;
404 struct argv_array argv = ARGV_ARRAY_INIT;
405 int cat_blob_fd, code;
406 memset(fastimport, 0, sizeof(*fastimport));
407 fastimport->in = helper->out;
408 argv_array_push(&argv, "fast-import");
409 argv_array_push(&argv, debug ? "--stats" : "--quiet");
411 if (data->bidi_import) {
412 cat_blob_fd = xdup(helper->in);
413 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
415 fastimport->argv = argv.argv;
416 fastimport->git_cmd = 1;
418 code = start_command(fastimport);
419 return code;
422 static int get_exporter(struct transport *transport,
423 struct child_process *fastexport,
424 struct string_list *revlist_args)
426 struct helper_data *data = transport->data;
427 struct child_process *helper = get_helper(transport);
428 int argc = 0, i;
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 fastexport->argv[argc++] = data->export_marks;
441 if (data->import_marks)
442 fastexport->argv[argc++] = data->import_marks;
444 for (i = 0; i < revlist_args->nr; i++)
445 fastexport->argv[argc++] = revlist_args->items[i].string;
447 fastexport->argv[argc++] = "--";
449 fastexport->git_cmd = 1;
450 return start_command(fastexport);
453 static void check_helper_status(struct helper_data *data)
455 int pid, status;
457 pid = waitpid(data->helper->pid, &status, WNOHANG);
458 if (pid < 0)
459 die("Could not retrieve status of remote helper '%s'",
460 data->name);
461 if (pid > 0 && WIFEXITED(status))
462 die("Remote helper '%s' died with %d",
463 data->name, WEXITSTATUS(status));
466 static int fetch_with_import(struct transport *transport,
467 int nr_heads, struct ref **to_fetch)
469 struct child_process fastimport;
470 struct helper_data *data = transport->data;
471 int i;
472 struct ref *posn;
473 struct strbuf buf = STRBUF_INIT;
475 get_helper(transport);
477 if (get_importer(transport, &fastimport))
478 die("Couldn't run fast-import");
480 for (i = 0; i < nr_heads; i++) {
481 posn = to_fetch[i];
482 if (posn->status & REF_STATUS_UPTODATE)
483 continue;
485 strbuf_addf(&buf, "import %s\n", posn->name);
486 sendline(data, &buf);
487 strbuf_reset(&buf);
490 write_constant(data->helper->in, "\n");
492 * remote-helpers that advertise the bidi-import capability are required to
493 * buffer the complete batch of import commands until this newline before
494 * sending data to fast-import.
495 * These helpers read back data from fast-import on their stdin, which could
496 * be mixed with import commands, otherwise.
499 if (finish_command(&fastimport))
500 die("Error while running fast-import");
501 argv_array_free_detached(fastimport.argv);
502 check_helper_status(data);
505 * The fast-import stream of a remote helper that advertises
506 * the "refspec" capability writes to the refs named after the
507 * right hand side of the first refspec matching each ref we
508 * were fetching.
510 * (If no "refspec" capability was specified, for historical
511 * reasons we default to the equivalent of *:*.)
513 * Store the result in to_fetch[i].old_sha1. Callers such
514 * as "git fetch" can use the value to write feedback to the
515 * terminal, populate FETCH_HEAD, and determine what new value
516 * should be written to peer_ref if the update is a
517 * fast-forward or this is a forced update.
519 for (i = 0; i < nr_heads; i++) {
520 char *private;
521 posn = to_fetch[i];
522 if (posn->status & REF_STATUS_UPTODATE)
523 continue;
524 if (data->refspecs)
525 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
526 else
527 private = xstrdup(posn->name);
528 if (private) {
529 read_ref(private, posn->old_sha1);
530 free(private);
533 strbuf_release(&buf);
534 if (auto_gc) {
535 const char *argv_gc_auto[] = {
536 "gc", "--auto", "--quiet", NULL,
538 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
540 return 0;
543 static int process_connect_service(struct transport *transport,
544 const char *name, const char *exec)
546 struct helper_data *data = transport->data;
547 struct strbuf cmdbuf = STRBUF_INIT;
548 struct child_process *helper;
549 int r, duped, ret = 0;
550 FILE *input;
552 helper = get_helper(transport);
555 * Yes, dup the pipe another time, as we need unbuffered version
556 * of input pipe as FILE*. fclose() closes the underlying fd and
557 * stream buffering only can be changed before first I/O operation
558 * on it.
560 duped = dup(helper->out);
561 if (duped < 0)
562 die_errno("Can't dup helper output fd");
563 input = xfdopen(duped, "r");
564 setvbuf(input, NULL, _IONBF, 0);
567 * Handle --upload-pack and friends. This is fire and forget...
568 * just warn if it fails.
570 if (strcmp(name, exec)) {
571 r = set_helper_option(transport, "servpath", exec);
572 if (r > 0)
573 warning("Setting remote service path not supported by protocol.");
574 else if (r < 0)
575 warning("Invalid remote service path.");
578 if (data->connect)
579 strbuf_addf(&cmdbuf, "connect %s\n", name);
580 else
581 goto exit;
583 sendline(data, &cmdbuf);
584 recvline_fh(input, &cmdbuf, name);
585 if (!strcmp(cmdbuf.buf, "")) {
586 data->no_disconnect_req = 1;
587 if (debug)
588 fprintf(stderr, "Debug: Smart transport connection "
589 "ready.\n");
590 ret = 1;
591 } else if (!strcmp(cmdbuf.buf, "fallback")) {
592 if (debug)
593 fprintf(stderr, "Debug: Falling back to dumb "
594 "transport.\n");
595 } else
596 die("Unknown response to connect: %s",
597 cmdbuf.buf);
599 exit:
600 fclose(input);
601 return ret;
604 static int process_connect(struct transport *transport,
605 int for_push)
607 struct helper_data *data = transport->data;
608 const char *name;
609 const char *exec;
611 name = for_push ? "git-receive-pack" : "git-upload-pack";
612 if (for_push)
613 exec = data->transport_options.receivepack;
614 else
615 exec = data->transport_options.uploadpack;
617 return process_connect_service(transport, name, exec);
620 static int connect_helper(struct transport *transport, const char *name,
621 const char *exec, int fd[2])
623 struct helper_data *data = transport->data;
625 /* Get_helper so connect is inited. */
626 get_helper(transport);
627 if (!data->connect)
628 die("Operation not supported by protocol.");
630 if (!process_connect_service(transport, name, exec))
631 die("Can't connect to subservice %s.", name);
633 fd[0] = data->helper->out;
634 fd[1] = data->helper->in;
635 return 0;
638 static int fetch(struct transport *transport,
639 int nr_heads, struct ref **to_fetch)
641 struct helper_data *data = transport->data;
642 int i, count;
644 if (process_connect(transport, 0)) {
645 do_take_over(transport);
646 return transport->fetch(transport, nr_heads, to_fetch);
649 count = 0;
650 for (i = 0; i < nr_heads; i++)
651 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
652 count++;
654 if (!count)
655 return 0;
657 if (data->fetch)
658 return fetch_with_fetch(transport, nr_heads, to_fetch);
660 if (data->import)
661 return fetch_with_import(transport, nr_heads, to_fetch);
663 return -1;
666 static int push_update_ref_status(struct strbuf *buf,
667 struct ref **ref,
668 struct ref *remote_refs)
670 char *refname, *msg;
671 int status;
673 if (!prefixcmp(buf->buf, "ok ")) {
674 status = REF_STATUS_OK;
675 refname = buf->buf + 3;
676 } else if (!prefixcmp(buf->buf, "error ")) {
677 status = REF_STATUS_REMOTE_REJECT;
678 refname = buf->buf + 6;
679 } else
680 die("expected ok/error, helper said '%s'", buf->buf);
682 msg = strchr(refname, ' ');
683 if (msg) {
684 struct strbuf msg_buf = STRBUF_INIT;
685 const char *end;
687 *msg++ = '\0';
688 if (!unquote_c_style(&msg_buf, msg, &end))
689 msg = strbuf_detach(&msg_buf, NULL);
690 else
691 msg = xstrdup(msg);
692 strbuf_release(&msg_buf);
694 if (!strcmp(msg, "no match")) {
695 status = REF_STATUS_NONE;
696 free(msg);
697 msg = NULL;
699 else if (!strcmp(msg, "up to date")) {
700 status = REF_STATUS_UPTODATE;
701 free(msg);
702 msg = NULL;
704 else if (!strcmp(msg, "non-fast forward")) {
705 status = REF_STATUS_REJECT_NONFASTFORWARD;
706 free(msg);
707 msg = NULL;
709 else if (!strcmp(msg, "already exists")) {
710 status = REF_STATUS_REJECT_ALREADY_EXISTS;
711 free(msg);
712 msg = NULL;
714 else if (!strcmp(msg, "fetch first")) {
715 status = REF_STATUS_REJECT_FETCH_FIRST;
716 free(msg);
717 msg = NULL;
719 else if (!strcmp(msg, "needs force")) {
720 status = REF_STATUS_REJECT_NEEDS_FORCE;
721 free(msg);
722 msg = NULL;
724 else if (!strcmp(msg, "stale info")) {
725 status = REF_STATUS_REJECT_STALE;
726 free(msg);
727 msg = NULL;
731 if (*ref)
732 *ref = find_ref_by_name(*ref, refname);
733 if (!*ref)
734 *ref = find_ref_by_name(remote_refs, refname);
735 if (!*ref) {
736 warning("helper reported unexpected status of %s", refname);
737 return 1;
740 if ((*ref)->status != REF_STATUS_NONE) {
742 * Earlier, the ref was marked not to be pushed, so ignore the ref
743 * status reported by the remote helper if the latter is 'no match'.
745 if (status == REF_STATUS_NONE)
746 return 1;
749 (*ref)->status = status;
750 (*ref)->remote_status = msg;
751 return !(status == REF_STATUS_OK);
754 static void push_update_refs_status(struct helper_data *data,
755 struct ref *remote_refs)
757 struct strbuf buf = STRBUF_INIT;
758 struct ref *ref = remote_refs;
759 for (;;) {
760 char *private;
762 recvline(data, &buf);
763 if (!buf.len)
764 break;
766 if (push_update_ref_status(&buf, &ref, remote_refs))
767 continue;
769 if (!data->refspecs || data->no_private_update)
770 continue;
772 /* propagate back the update to the remote namespace */
773 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
774 if (!private)
775 continue;
776 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
777 free(private);
779 strbuf_release(&buf);
782 static int push_refs_with_push(struct transport *transport,
783 struct ref *remote_refs, int flags)
785 int force_all = flags & TRANSPORT_PUSH_FORCE;
786 int mirror = flags & TRANSPORT_PUSH_MIRROR;
787 struct helper_data *data = transport->data;
788 struct strbuf buf = STRBUF_INIT;
789 struct ref *ref;
790 struct string_list cas_options = STRING_LIST_INIT_DUP;
791 struct string_list_item *cas_option;
793 get_helper(transport);
794 if (!data->push)
795 return 1;
797 for (ref = remote_refs; ref; ref = ref->next) {
798 if (!ref->peer_ref && !mirror)
799 continue;
801 /* Check for statuses set by set_ref_status_for_push() */
802 switch (ref->status) {
803 case REF_STATUS_REJECT_NONFASTFORWARD:
804 case REF_STATUS_REJECT_STALE:
805 case REF_STATUS_REJECT_ALREADY_EXISTS:
806 case REF_STATUS_UPTODATE:
807 continue;
808 default:
809 ; /* do nothing */
812 if (force_all)
813 ref->force = 1;
815 strbuf_addstr(&buf, "push ");
816 if (!ref->deletion) {
817 if (ref->force)
818 strbuf_addch(&buf, '+');
819 if (ref->peer_ref)
820 strbuf_addstr(&buf, ref->peer_ref->name);
821 else
822 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
824 strbuf_addch(&buf, ':');
825 strbuf_addstr(&buf, ref->name);
826 strbuf_addch(&buf, '\n');
829 * The "--force-with-lease" options without explicit
830 * values to expect have already been expanded into
831 * the ref->old_sha1_expect[] field; we can ignore
832 * transport->smart_options->cas altogether and instead
833 * can enumerate them from the refs.
835 if (ref->expect_old_sha1) {
836 struct strbuf cas = STRBUF_INIT;
837 strbuf_addf(&cas, "%s:%s",
838 ref->name, sha1_to_hex(ref->old_sha1_expect));
839 string_list_append(&cas_options, strbuf_detach(&cas, NULL));
842 if (buf.len == 0) {
843 string_list_clear(&cas_options, 0);
844 return 0;
847 standard_options(transport);
848 for_each_string_list_item(cas_option, &cas_options)
849 set_helper_option(transport, "cas", cas_option->string);
851 if (flags & TRANSPORT_PUSH_DRY_RUN) {
852 if (set_helper_option(transport, "dry-run", "true") != 0)
853 die("helper %s does not support dry-run", data->name);
856 strbuf_addch(&buf, '\n');
857 sendline(data, &buf);
858 strbuf_release(&buf);
860 push_update_refs_status(data, remote_refs);
861 return 0;
864 static int push_refs_with_export(struct transport *transport,
865 struct ref *remote_refs, int flags)
867 struct ref *ref;
868 struct child_process *helper, exporter;
869 struct helper_data *data = transport->data;
870 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
871 struct strbuf buf = STRBUF_INIT;
873 if (!data->refspecs)
874 die("remote-helper doesn't support push; refspec needed");
876 if (flags & TRANSPORT_PUSH_DRY_RUN) {
877 if (set_helper_option(transport, "dry-run", "true") != 0)
878 die("helper %s does not support dry-run", data->name);
881 helper = get_helper(transport);
883 write_constant(helper->in, "export\n");
885 strbuf_reset(&buf);
887 for (ref = remote_refs; ref; ref = ref->next) {
888 char *private;
889 unsigned char sha1[20];
891 if (ref->deletion)
892 die("remote-helpers do not support ref deletion");
894 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
895 if (private && !get_sha1(private, sha1)) {
896 strbuf_addf(&buf, "^%s", private);
897 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
898 hashcpy(ref->old_sha1, sha1);
900 free(private);
902 if (ref->deletion)
903 die("remote-helpers do not support ref deletion");
905 if (ref->peer_ref) {
906 if (strcmp(ref->peer_ref->name, ref->name))
907 die("remote-helpers do not support old:new syntax");
908 string_list_append(&revlist_args, ref->peer_ref->name);
912 if (get_exporter(transport, &exporter, &revlist_args))
913 die("Couldn't run fast-export");
915 if (finish_command(&exporter))
916 die("Error while running fast-export");
917 check_helper_status(data);
918 push_update_refs_status(data, remote_refs);
919 return 0;
922 static int push_refs(struct transport *transport,
923 struct ref *remote_refs, int flags)
925 struct helper_data *data = transport->data;
927 if (process_connect(transport, 1)) {
928 do_take_over(transport);
929 return transport->push_refs(transport, remote_refs, flags);
932 if (!remote_refs) {
933 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
934 "Perhaps you should specify a branch such as 'master'.\n");
935 return 0;
938 if (data->push)
939 return push_refs_with_push(transport, remote_refs, flags);
941 if (data->export)
942 return push_refs_with_export(transport, remote_refs, flags);
944 return -1;
948 static int has_attribute(const char *attrs, const char *attr) {
949 int len;
950 if (!attrs)
951 return 0;
953 len = strlen(attr);
954 for (;;) {
955 const char *space = strchrnul(attrs, ' ');
956 if (len == space - attrs && !strncmp(attrs, attr, len))
957 return 1;
958 if (!*space)
959 return 0;
960 attrs = space + 1;
964 static struct ref *get_refs_list(struct transport *transport, int for_push)
966 struct helper_data *data = transport->data;
967 struct child_process *helper;
968 struct ref *ret = NULL;
969 struct ref **tail = &ret;
970 struct ref *posn;
971 struct strbuf buf = STRBUF_INIT;
973 helper = get_helper(transport);
975 if (process_connect(transport, for_push)) {
976 do_take_over(transport);
977 return transport->get_refs_list(transport, for_push);
980 if (data->push && for_push)
981 write_str_in_full(helper->in, "list for-push\n");
982 else
983 write_str_in_full(helper->in, "list\n");
985 while (1) {
986 char *eov, *eon;
987 recvline(data, &buf);
989 if (!*buf.buf)
990 break;
992 eov = strchr(buf.buf, ' ');
993 if (!eov)
994 die("Malformed response in ref list: %s", buf.buf);
995 eon = strchr(eov + 1, ' ');
996 *eov = '\0';
997 if (eon)
998 *eon = '\0';
999 *tail = alloc_ref(eov + 1);
1000 if (buf.buf[0] == '@')
1001 (*tail)->symref = xstrdup(buf.buf + 1);
1002 else if (buf.buf[0] != '?')
1003 get_sha1_hex(buf.buf, (*tail)->old_sha1);
1004 if (eon) {
1005 if (has_attribute(eon + 1, "unchanged")) {
1006 (*tail)->status |= REF_STATUS_UPTODATE;
1007 read_ref((*tail)->name, (*tail)->old_sha1);
1010 tail = &((*tail)->next);
1012 if (debug)
1013 fprintf(stderr, "Debug: Read ref listing.\n");
1014 strbuf_release(&buf);
1016 for (posn = ret; posn; posn = posn->next)
1017 resolve_remote_symref(posn, ret);
1019 return ret;
1022 int transport_helper_init(struct transport *transport, const char *name)
1024 struct helper_data *data = xcalloc(sizeof(*data), 1);
1025 data->name = name;
1027 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1028 debug = 1;
1030 transport->data = data;
1031 transport->set_option = set_helper_option;
1032 transport->get_refs_list = get_refs_list;
1033 transport->fetch = fetch;
1034 transport->push_refs = push_refs;
1035 transport->disconnect = release_helper;
1036 transport->connect = connect_helper;
1037 transport->smart_options = &(data->transport_options);
1038 return 0;
1042 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1043 * buffer less), so attempt reads and writes with up to that size.
1045 #define BUFFERSIZE 65536
1046 /* This should be enough to hold debugging message. */
1047 #define PBUFFERSIZE 8192
1049 /* Print bidirectional transfer loop debug message. */
1050 __attribute__((format (printf, 1, 2)))
1051 static void transfer_debug(const char *fmt, ...)
1053 va_list args;
1054 char msgbuf[PBUFFERSIZE];
1055 static int debug_enabled = -1;
1057 if (debug_enabled < 0)
1058 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1059 if (!debug_enabled)
1060 return;
1062 va_start(args, fmt);
1063 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1064 va_end(args);
1065 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1068 /* Stream state: More data may be coming in this direction. */
1069 #define SSTATE_TRANSFERING 0
1071 * Stream state: No more data coming in this direction, flushing rest of
1072 * data.
1074 #define SSTATE_FLUSHING 1
1075 /* Stream state: Transfer in this direction finished. */
1076 #define SSTATE_FINISHED 2
1078 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1079 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1080 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1082 /* Unidirectional transfer. */
1083 struct unidirectional_transfer {
1084 /* Source */
1085 int src;
1086 /* Destination */
1087 int dest;
1088 /* Is source socket? */
1089 int src_is_sock;
1090 /* Is destination socket? */
1091 int dest_is_sock;
1092 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1093 int state;
1094 /* Buffer. */
1095 char buf[BUFFERSIZE];
1096 /* Buffer used. */
1097 size_t bufuse;
1098 /* Name of source. */
1099 const char *src_name;
1100 /* Name of destination. */
1101 const char *dest_name;
1104 /* Closes the target (for writing) if transfer has finished. */
1105 static void udt_close_if_finished(struct unidirectional_transfer *t)
1107 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1108 t->state = SSTATE_FINISHED;
1109 if (t->dest_is_sock)
1110 shutdown(t->dest, SHUT_WR);
1111 else
1112 close(t->dest);
1113 transfer_debug("Closed %s.", t->dest_name);
1118 * Tries to read read data from source into buffer. If buffer is full,
1119 * no data is read. Returns 0 on success, -1 on error.
1121 static int udt_do_read(struct unidirectional_transfer *t)
1123 ssize_t bytes;
1125 if (t->bufuse == BUFFERSIZE)
1126 return 0; /* No space for more. */
1128 transfer_debug("%s is readable", t->src_name);
1129 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1130 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1131 errno != EINTR) {
1132 error("read(%s) failed: %s", t->src_name, strerror(errno));
1133 return -1;
1134 } else if (bytes == 0) {
1135 transfer_debug("%s EOF (with %i bytes in buffer)",
1136 t->src_name, (int)t->bufuse);
1137 t->state = SSTATE_FLUSHING;
1138 } else if (bytes > 0) {
1139 t->bufuse += bytes;
1140 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1141 (int)bytes, t->src_name, (int)t->bufuse);
1143 return 0;
1146 /* Tries to write data from buffer into destination. If buffer is empty,
1147 * no data is written. Returns 0 on success, -1 on error.
1149 static int udt_do_write(struct unidirectional_transfer *t)
1151 ssize_t bytes;
1153 if (t->bufuse == 0)
1154 return 0; /* Nothing to write. */
1156 transfer_debug("%s is writable", t->dest_name);
1157 bytes = write(t->dest, t->buf, t->bufuse);
1158 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1159 errno != EINTR) {
1160 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1161 return -1;
1162 } else if (bytes > 0) {
1163 t->bufuse -= bytes;
1164 if (t->bufuse)
1165 memmove(t->buf, t->buf + bytes, t->bufuse);
1166 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1167 (int)bytes, t->dest_name, (int)t->bufuse);
1169 return 0;
1173 /* State of bidirectional transfer loop. */
1174 struct bidirectional_transfer_state {
1175 /* Direction from program to git. */
1176 struct unidirectional_transfer ptg;
1177 /* Direction from git to program. */
1178 struct unidirectional_transfer gtp;
1181 static void *udt_copy_task_routine(void *udt)
1183 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1184 while (t->state != SSTATE_FINISHED) {
1185 if (STATE_NEEDS_READING(t->state))
1186 if (udt_do_read(t))
1187 return NULL;
1188 if (STATE_NEEDS_WRITING(t->state))
1189 if (udt_do_write(t))
1190 return NULL;
1191 if (STATE_NEEDS_CLOSING(t->state))
1192 udt_close_if_finished(t);
1194 return udt; /* Just some non-NULL value. */
1197 #ifndef NO_PTHREADS
1200 * Join thread, with appropriate errors on failure. Name is name for the
1201 * thread (for error messages). Returns 0 on success, 1 on failure.
1203 static int tloop_join(pthread_t thread, const char *name)
1205 int err;
1206 void *tret;
1207 err = pthread_join(thread, &tret);
1208 if (!tret) {
1209 error("%s thread failed", name);
1210 return 1;
1212 if (err) {
1213 error("%s thread failed to join: %s", name, strerror(err));
1214 return 1;
1216 return 0;
1220 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1221 * -1 on failure.
1223 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1225 pthread_t gtp_thread;
1226 pthread_t ptg_thread;
1227 int err;
1228 int ret = 0;
1229 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1230 &s->gtp);
1231 if (err)
1232 die("Can't start thread for copying data: %s", strerror(err));
1233 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1234 &s->ptg);
1235 if (err)
1236 die("Can't start thread for copying data: %s", strerror(err));
1238 ret |= tloop_join(gtp_thread, "Git to program copy");
1239 ret |= tloop_join(ptg_thread, "Program to git copy");
1240 return ret;
1242 #else
1244 /* Close the source and target (for writing) for transfer. */
1245 static void udt_kill_transfer(struct unidirectional_transfer *t)
1247 t->state = SSTATE_FINISHED;
1249 * Socket read end left open isn't a disaster if nobody
1250 * attempts to read from it (mingw compat headers do not
1251 * have SHUT_RD)...
1253 * We can't fully close the socket since otherwise gtp
1254 * task would first close the socket it sends data to
1255 * while closing the ptg file descriptors.
1257 if (!t->src_is_sock)
1258 close(t->src);
1259 if (t->dest_is_sock)
1260 shutdown(t->dest, SHUT_WR);
1261 else
1262 close(t->dest);
1266 * Join process, with appropriate errors on failure. Name is name for the
1267 * process (for error messages). Returns 0 on success, 1 on failure.
1269 static int tloop_join(pid_t pid, const char *name)
1271 int tret;
1272 if (waitpid(pid, &tret, 0) < 0) {
1273 error("%s process failed to wait: %s", name, strerror(errno));
1274 return 1;
1276 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1277 error("%s process failed", name);
1278 return 1;
1280 return 0;
1284 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1285 * -1 on failure.
1287 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1289 pid_t pid1, pid2;
1290 int ret = 0;
1292 /* Fork thread #1: git to program. */
1293 pid1 = fork();
1294 if (pid1 < 0)
1295 die_errno("Can't start thread for copying data");
1296 else if (pid1 == 0) {
1297 udt_kill_transfer(&s->ptg);
1298 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1301 /* Fork thread #2: program to git. */
1302 pid2 = fork();
1303 if (pid2 < 0)
1304 die_errno("Can't start thread for copying data");
1305 else if (pid2 == 0) {
1306 udt_kill_transfer(&s->gtp);
1307 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1311 * Close both streams in parent as to not interfere with
1312 * end of file detection and wait for both tasks to finish.
1314 udt_kill_transfer(&s->gtp);
1315 udt_kill_transfer(&s->ptg);
1316 ret |= tloop_join(pid1, "Git to program copy");
1317 ret |= tloop_join(pid2, "Program to git copy");
1318 return ret;
1320 #endif
1323 * Copies data from stdin to output and from input to stdout simultaneously.
1324 * Additionally filtering through given filter. If filter is NULL, uses
1325 * identity filter.
1327 int bidirectional_transfer_loop(int input, int output)
1329 struct bidirectional_transfer_state state;
1331 /* Fill the state fields. */
1332 state.ptg.src = input;
1333 state.ptg.dest = 1;
1334 state.ptg.src_is_sock = (input == output);
1335 state.ptg.dest_is_sock = 0;
1336 state.ptg.state = SSTATE_TRANSFERING;
1337 state.ptg.bufuse = 0;
1338 state.ptg.src_name = "remote input";
1339 state.ptg.dest_name = "stdout";
1341 state.gtp.src = 0;
1342 state.gtp.dest = output;
1343 state.gtp.src_is_sock = 0;
1344 state.gtp.dest_is_sock = (input == output);
1345 state.gtp.state = SSTATE_TRANSFERING;
1346 state.gtp.bufuse = 0;
1347 state.gtp.src_name = "stdin";
1348 state.gtp.dest_name = "remote output";
1350 return tloop_spawnwait_tasks(&state);