Sleep 1 millisecond in poll() to avoid busy wait
[git/mingw/4msysgit.git] / transport-helper.c
blobbc03ba0ecdee605ea408b5a1566230720d074e1b
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"
15 static int debug;
16 /* TODO: put somewhere sensible, e.g. git_transport_options? */
17 static int auto_gc = 1;
19 struct helper_data {
20 const char *name;
21 struct child_process *helper;
22 FILE *out;
23 unsigned fetch : 1,
24 import : 1,
25 bidi_import : 1,
26 export : 1,
27 option : 1,
28 push : 1,
29 connect : 1,
30 no_disconnect_req : 1;
31 char *export_marks;
32 char *import_marks;
33 /* These go from remote name (as in "list") to private name */
34 struct refspec *refspecs;
35 int refspec_nr;
36 /* Transport options for fetch-pack/send-pack (should one of
37 * those be invoked).
39 struct git_transport_options transport_options;
42 static void sendline(struct helper_data *helper, struct strbuf *buffer)
44 if (debug)
45 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
46 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
47 != buffer->len)
48 die_errno("Full write to remote helper failed");
51 static int recvline_fh(FILE *helper, struct strbuf *buffer)
53 strbuf_reset(buffer);
54 if (debug)
55 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
56 if (strbuf_getline(buffer, helper, '\n') == EOF) {
57 if (debug)
58 fprintf(stderr, "Debug: Remote helper quit.\n");
59 exit(128);
62 if (debug)
63 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
64 return 0;
67 static int recvline(struct helper_data *helper, struct strbuf *buffer)
69 return recvline_fh(helper->out, buffer);
72 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
74 sendline(helper, buffer);
75 recvline(helper, buffer);
78 static void write_constant(int fd, const char *str)
80 if (debug)
81 fprintf(stderr, "Debug: Remote helper: -> %s", str);
82 if (write_in_full(fd, str, strlen(str)) != strlen(str))
83 die_errno("Full write to remote helper failed");
86 static const char *remove_ext_force(const char *url)
88 if (url) {
89 const char *colon = strchr(url, ':');
90 if (colon && colon[1] == ':')
91 return colon + 2;
93 return url;
96 static void do_take_over(struct transport *transport)
98 struct helper_data *data;
99 data = (struct helper_data *)transport->data;
100 transport_take_over(transport, data->helper);
101 fclose(data->out);
102 free(data);
105 static struct child_process *get_helper(struct transport *transport)
107 struct helper_data *data = transport->data;
108 struct argv_array argv = ARGV_ARRAY_INIT;
109 struct strbuf buf = STRBUF_INIT;
110 struct child_process *helper;
111 const char **refspecs = NULL;
112 int refspec_nr = 0;
113 int refspec_alloc = 0;
114 int duped;
115 int code;
116 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
117 const char *helper_env[] = {
118 git_dir_buf,
119 NULL
123 if (data->helper)
124 return data->helper;
126 helper = xcalloc(1, sizeof(*helper));
127 helper->in = -1;
128 helper->out = -1;
129 helper->err = 0;
130 argv_array_pushf(&argv, "git-remote-%s", data->name);
131 argv_array_push(&argv, transport->remote->name);
132 argv_array_push(&argv, remove_ext_force(transport->url));
133 helper->argv = argv_array_detach(&argv, NULL);
134 helper->git_cmd = 0;
135 helper->silent_exec_failure = 1;
137 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
138 helper->env = helper_env;
140 code = start_command(helper);
141 if (code < 0 && errno == ENOENT)
142 die("Unable to find remote helper for '%s'", data->name);
143 else if (code != 0)
144 exit(code);
146 data->helper = helper;
147 data->no_disconnect_req = 0;
150 * Open the output as FILE* so strbuf_getline() can be used.
151 * Do this with duped fd because fclose() will close the fd,
152 * and stuff like taking over will require the fd to remain.
154 duped = dup(helper->out);
155 if (duped < 0)
156 die_errno("Can't dup helper output fd");
157 data->out = xfdopen(duped, "r");
159 write_constant(helper->in, "capabilities\n");
161 while (1) {
162 const char *capname;
163 int mandatory = 0;
164 recvline(data, &buf);
166 if (!*buf.buf)
167 break;
169 if (*buf.buf == '*') {
170 capname = buf.buf + 1;
171 mandatory = 1;
172 } else
173 capname = buf.buf;
175 if (debug)
176 fprintf(stderr, "Debug: Got cap %s\n", capname);
177 if (!strcmp(capname, "fetch"))
178 data->fetch = 1;
179 else if (!strcmp(capname, "option"))
180 data->option = 1;
181 else if (!strcmp(capname, "push"))
182 data->push = 1;
183 else if (!strcmp(capname, "import"))
184 data->import = 1;
185 else if (!strcmp(capname, "bidi-import"))
186 data->bidi_import = 1;
187 else if (!strcmp(capname, "export"))
188 data->export = 1;
189 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
190 ALLOC_GROW(refspecs,
191 refspec_nr + 1,
192 refspec_alloc);
193 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
194 } else if (!strcmp(capname, "connect")) {
195 data->connect = 1;
196 } else if (!prefixcmp(capname, "export-marks ")) {
197 struct strbuf arg = STRBUF_INIT;
198 strbuf_addstr(&arg, "--export-marks=");
199 strbuf_addstr(&arg, capname + strlen("export-marks "));
200 data->export_marks = strbuf_detach(&arg, NULL);
201 } else if (!prefixcmp(capname, "import-marks")) {
202 struct strbuf arg = STRBUF_INIT;
203 strbuf_addstr(&arg, "--import-marks=");
204 strbuf_addstr(&arg, capname + strlen("import-marks "));
205 data->import_marks = strbuf_detach(&arg, NULL);
206 } else if (mandatory) {
207 die("Unknown mandatory capability %s. This remote "
208 "helper probably needs newer version of Git.",
209 capname);
212 if (refspecs) {
213 int i;
214 data->refspec_nr = refspec_nr;
215 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
216 for (i = 0; i < refspec_nr; i++) {
217 free((char *)refspecs[i]);
219 free(refspecs);
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
263 static const char *boolean_options[] = {
264 TRANS_OPT_THIN,
265 TRANS_OPT_KEEP,
266 TRANS_OPT_FOLLOWTAGS
269 static int set_helper_option(struct transport *transport,
270 const char *name, const char *value)
272 struct helper_data *data = transport->data;
273 struct strbuf buf = STRBUF_INIT;
274 int i, ret, is_bool = 0;
276 get_helper(transport);
278 if (!data->option)
279 return 1;
281 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
282 if (!strcmp(name, unsupported_options[i]))
283 return 1;
286 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
287 if (!strcmp(name, boolean_options[i])) {
288 is_bool = 1;
289 break;
293 strbuf_addf(&buf, "option %s ", name);
294 if (is_bool)
295 strbuf_addstr(&buf, value ? "true" : "false");
296 else
297 quote_c_style(value, &buf, NULL, 0);
298 strbuf_addch(&buf, '\n');
300 xchgline(data, &buf);
302 if (!strcmp(buf.buf, "ok"))
303 ret = 0;
304 else if (!prefixcmp(buf.buf, "error")) {
305 ret = -1;
306 } else if (!strcmp(buf.buf, "unsupported"))
307 ret = 1;
308 else {
309 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
310 ret = 1;
312 strbuf_release(&buf);
313 return ret;
316 static void standard_options(struct transport *t)
318 char buf[16];
319 int n;
320 int v = t->verbose;
322 set_helper_option(t, "progress", t->progress ? "true" : "false");
324 n = snprintf(buf, sizeof(buf), "%d", v + 1);
325 if (n >= sizeof(buf))
326 die("impossibly large verbosity value");
327 set_helper_option(t, "verbosity", buf);
330 static int release_helper(struct transport *transport)
332 int res = 0;
333 struct helper_data *data = transport->data;
334 free_refspec(data->refspec_nr, data->refspecs);
335 data->refspecs = NULL;
336 res = disconnect_helper(transport);
337 free(transport->data);
338 return res;
341 static int fetch_with_fetch(struct transport *transport,
342 int nr_heads, struct ref **to_fetch)
344 struct helper_data *data = transport->data;
345 int i;
346 struct strbuf buf = STRBUF_INIT;
348 standard_options(transport);
350 for (i = 0; i < nr_heads; i++) {
351 const struct ref *posn = to_fetch[i];
352 if (posn->status & REF_STATUS_UPTODATE)
353 continue;
355 strbuf_addf(&buf, "fetch %s %s\n",
356 sha1_to_hex(posn->old_sha1), posn->name);
359 strbuf_addch(&buf, '\n');
360 sendline(data, &buf);
362 while (1) {
363 recvline(data, &buf);
365 if (!prefixcmp(buf.buf, "lock ")) {
366 const char *name = buf.buf + 5;
367 if (transport->pack_lockfile)
368 warning("%s also locked %s", data->name, name);
369 else
370 transport->pack_lockfile = xstrdup(name);
372 else if (!buf.len)
373 break;
374 else
375 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
377 strbuf_release(&buf);
378 return 0;
381 static int get_importer(struct transport *transport, struct child_process *fastimport)
383 struct child_process *helper = get_helper(transport);
384 struct helper_data *data = transport->data;
385 struct argv_array argv = ARGV_ARRAY_INIT;
386 int cat_blob_fd, code;
387 memset(fastimport, 0, sizeof(*fastimport));
388 fastimport->in = helper->out;
389 argv_array_push(&argv, "fast-import");
390 argv_array_push(&argv, debug ? "--stats" : "--quiet");
392 if (data->bidi_import) {
393 cat_blob_fd = xdup(helper->in);
394 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
396 fastimport->argv = argv.argv;
397 fastimport->git_cmd = 1;
399 code = start_command(fastimport);
400 return code;
403 static int get_exporter(struct transport *transport,
404 struct child_process *fastexport,
405 struct string_list *revlist_args)
407 struct helper_data *data = transport->data;
408 struct child_process *helper = get_helper(transport);
409 int argc = 0, i;
410 memset(fastexport, 0, sizeof(*fastexport));
412 /* we need to duplicate helper->in because we want to use it after
413 * fastexport is done with it. */
414 fastexport->out = dup(helper->in);
415 fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
416 fastexport->argv[argc++] = "fast-export";
417 fastexport->argv[argc++] = "--use-done-feature";
418 if (data->export_marks)
419 fastexport->argv[argc++] = data->export_marks;
420 if (data->import_marks)
421 fastexport->argv[argc++] = data->import_marks;
423 for (i = 0; i < revlist_args->nr; i++)
424 fastexport->argv[argc++] = revlist_args->items[i].string;
426 fastexport->argv[argc++] = "--";
428 fastexport->git_cmd = 1;
429 return start_command(fastexport);
432 static void check_helper_status(struct helper_data *data)
434 int pid, status;
436 pid = waitpid(data->helper->pid, &status, WNOHANG);
437 if (pid < 0)
438 die("Could not retrieve status of remote helper '%s'",
439 data->name);
440 if (pid > 0 && WIFEXITED(status))
441 die("Remote helper '%s' died with %d",
442 data->name, WEXITSTATUS(status));
445 static int fetch_with_import(struct transport *transport,
446 int nr_heads, struct ref **to_fetch)
448 struct child_process fastimport;
449 struct helper_data *data = transport->data;
450 int i;
451 struct ref *posn;
452 struct strbuf buf = STRBUF_INIT;
454 get_helper(transport);
456 if (get_importer(transport, &fastimport))
457 die("Couldn't run fast-import");
459 for (i = 0; i < nr_heads; i++) {
460 posn = to_fetch[i];
461 if (posn->status & REF_STATUS_UPTODATE)
462 continue;
464 strbuf_addf(&buf, "import %s\n", posn->name);
465 sendline(data, &buf);
466 strbuf_reset(&buf);
469 write_constant(data->helper->in, "\n");
471 * remote-helpers that advertise the bidi-import capability are required to
472 * buffer the complete batch of import commands until this newline before
473 * sending data to fast-import.
474 * These helpers read back data from fast-import on their stdin, which could
475 * be mixed with import commands, otherwise.
478 if (finish_command(&fastimport))
479 die("Error while running fast-import");
480 argv_array_free_detached(fastimport.argv);
481 check_helper_status(data);
484 * The fast-import stream of a remote helper that advertises
485 * the "refspec" capability writes to the refs named after the
486 * right hand side of the first refspec matching each ref we
487 * were fetching.
489 * (If no "refspec" capability was specified, for historical
490 * reasons we default to *:*.)
492 * Store the result in to_fetch[i].old_sha1. Callers such
493 * as "git fetch" can use the value to write feedback to the
494 * terminal, populate FETCH_HEAD, and determine what new value
495 * should be written to peer_ref if the update is a
496 * fast-forward or this is a forced update.
498 for (i = 0; i < nr_heads; i++) {
499 char *private;
500 posn = to_fetch[i];
501 if (posn->status & REF_STATUS_UPTODATE)
502 continue;
503 if (data->refspecs)
504 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
505 else
506 private = xstrdup(posn->name);
507 if (private) {
508 read_ref(private, posn->old_sha1);
509 free(private);
512 strbuf_release(&buf);
513 if (auto_gc) {
514 const char *argv_gc_auto[] = {
515 "gc", "--auto", "--quiet", NULL,
517 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
519 return 0;
522 static int process_connect_service(struct transport *transport,
523 const char *name, const char *exec)
525 struct helper_data *data = transport->data;
526 struct strbuf cmdbuf = STRBUF_INIT;
527 struct child_process *helper;
528 int r, duped, ret = 0;
529 FILE *input;
531 helper = get_helper(transport);
534 * Yes, dup the pipe another time, as we need unbuffered version
535 * of input pipe as FILE*. fclose() closes the underlying fd and
536 * stream buffering only can be changed before first I/O operation
537 * on it.
539 duped = dup(helper->out);
540 if (duped < 0)
541 die_errno("Can't dup helper output fd");
542 input = xfdopen(duped, "r");
543 setvbuf(input, NULL, _IONBF, 0);
546 * Handle --upload-pack and friends. This is fire and forget...
547 * just warn if it fails.
549 if (strcmp(name, exec)) {
550 r = set_helper_option(transport, "servpath", exec);
551 if (r > 0)
552 warning("Setting remote service path not supported by protocol.");
553 else if (r < 0)
554 warning("Invalid remote service path.");
557 if (data->connect)
558 strbuf_addf(&cmdbuf, "connect %s\n", name);
559 else
560 goto exit;
562 sendline(data, &cmdbuf);
563 recvline_fh(input, &cmdbuf);
564 if (!strcmp(cmdbuf.buf, "")) {
565 data->no_disconnect_req = 1;
566 if (debug)
567 fprintf(stderr, "Debug: Smart transport connection "
568 "ready.\n");
569 ret = 1;
570 } else if (!strcmp(cmdbuf.buf, "fallback")) {
571 if (debug)
572 fprintf(stderr, "Debug: Falling back to dumb "
573 "transport.\n");
574 } else
575 die("Unknown response to connect: %s",
576 cmdbuf.buf);
578 exit:
579 fclose(input);
580 return ret;
583 static int process_connect(struct transport *transport,
584 int for_push)
586 struct helper_data *data = transport->data;
587 const char *name;
588 const char *exec;
590 name = for_push ? "git-receive-pack" : "git-upload-pack";
591 if (for_push)
592 exec = data->transport_options.receivepack;
593 else
594 exec = data->transport_options.uploadpack;
596 return process_connect_service(transport, name, exec);
599 static int connect_helper(struct transport *transport, const char *name,
600 const char *exec, int fd[2])
602 struct helper_data *data = transport->data;
604 /* Get_helper so connect is inited. */
605 get_helper(transport);
606 if (!data->connect)
607 die("Operation not supported by protocol.");
609 if (!process_connect_service(transport, name, exec))
610 die("Can't connect to subservice %s.", name);
612 fd[0] = data->helper->out;
613 fd[1] = data->helper->in;
614 return 0;
617 static int fetch(struct transport *transport,
618 int nr_heads, struct ref **to_fetch)
620 struct helper_data *data = transport->data;
621 int i, count;
623 if (process_connect(transport, 0)) {
624 do_take_over(transport);
625 return transport->fetch(transport, nr_heads, to_fetch);
628 count = 0;
629 for (i = 0; i < nr_heads; i++)
630 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
631 count++;
633 if (!count)
634 return 0;
636 if (data->fetch)
637 return fetch_with_fetch(transport, nr_heads, to_fetch);
639 if (data->import)
640 return fetch_with_import(transport, nr_heads, to_fetch);
642 return -1;
645 static void push_update_ref_status(struct strbuf *buf,
646 struct ref **ref,
647 struct ref *remote_refs)
649 char *refname, *msg;
650 int status;
652 if (!prefixcmp(buf->buf, "ok ")) {
653 status = REF_STATUS_OK;
654 refname = buf->buf + 3;
655 } else if (!prefixcmp(buf->buf, "error ")) {
656 status = REF_STATUS_REMOTE_REJECT;
657 refname = buf->buf + 6;
658 } else
659 die("expected ok/error, helper said '%s'", buf->buf);
661 msg = strchr(refname, ' ');
662 if (msg) {
663 struct strbuf msg_buf = STRBUF_INIT;
664 const char *end;
666 *msg++ = '\0';
667 if (!unquote_c_style(&msg_buf, msg, &end))
668 msg = strbuf_detach(&msg_buf, NULL);
669 else
670 msg = xstrdup(msg);
671 strbuf_release(&msg_buf);
673 if (!strcmp(msg, "no match")) {
674 status = REF_STATUS_NONE;
675 free(msg);
676 msg = NULL;
678 else if (!strcmp(msg, "up to date")) {
679 status = REF_STATUS_UPTODATE;
680 free(msg);
681 msg = NULL;
683 else if (!strcmp(msg, "non-fast forward")) {
684 status = REF_STATUS_REJECT_NONFASTFORWARD;
685 free(msg);
686 msg = NULL;
690 if (*ref)
691 *ref = find_ref_by_name(*ref, refname);
692 if (!*ref)
693 *ref = find_ref_by_name(remote_refs, refname);
694 if (!*ref) {
695 warning("helper reported unexpected status of %s", refname);
696 return;
699 if ((*ref)->status != REF_STATUS_NONE) {
701 * Earlier, the ref was marked not to be pushed, so ignore the ref
702 * status reported by the remote helper if the latter is 'no match'.
704 if (status == REF_STATUS_NONE)
705 return;
708 (*ref)->status = status;
709 (*ref)->remote_status = msg;
712 static void push_update_refs_status(struct helper_data *data,
713 struct ref *remote_refs)
715 struct strbuf buf = STRBUF_INIT;
716 struct ref *ref = remote_refs;
717 for (;;) {
718 recvline(data, &buf);
719 if (!buf.len)
720 break;
722 push_update_ref_status(&buf, &ref, remote_refs);
724 strbuf_release(&buf);
727 static int push_refs_with_push(struct transport *transport,
728 struct ref *remote_refs, int flags)
730 int force_all = flags & TRANSPORT_PUSH_FORCE;
731 int mirror = flags & TRANSPORT_PUSH_MIRROR;
732 struct helper_data *data = transport->data;
733 struct strbuf buf = STRBUF_INIT;
734 struct ref *ref;
736 get_helper(transport);
737 if (!data->push)
738 return 1;
740 for (ref = remote_refs; ref; ref = ref->next) {
741 if (!ref->peer_ref && !mirror)
742 continue;
744 /* Check for statuses set by set_ref_status_for_push() */
745 switch (ref->status) {
746 case REF_STATUS_REJECT_NONFASTFORWARD:
747 case REF_STATUS_UPTODATE:
748 continue;
749 default:
750 ; /* do nothing */
753 if (force_all)
754 ref->force = 1;
756 strbuf_addstr(&buf, "push ");
757 if (!ref->deletion) {
758 if (ref->force)
759 strbuf_addch(&buf, '+');
760 if (ref->peer_ref)
761 strbuf_addstr(&buf, ref->peer_ref->name);
762 else
763 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
765 strbuf_addch(&buf, ':');
766 strbuf_addstr(&buf, ref->name);
767 strbuf_addch(&buf, '\n');
769 if (buf.len == 0)
770 return 0;
772 standard_options(transport);
774 if (flags & TRANSPORT_PUSH_DRY_RUN) {
775 if (set_helper_option(transport, "dry-run", "true") != 0)
776 die("helper %s does not support dry-run", data->name);
779 strbuf_addch(&buf, '\n');
780 sendline(data, &buf);
781 strbuf_release(&buf);
783 push_update_refs_status(data, remote_refs);
784 return 0;
787 static int push_refs_with_export(struct transport *transport,
788 struct ref *remote_refs, int flags)
790 struct ref *ref;
791 struct child_process *helper, exporter;
792 struct helper_data *data = transport->data;
793 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
794 struct strbuf buf = STRBUF_INIT;
796 helper = get_helper(transport);
798 write_constant(helper->in, "export\n");
800 strbuf_reset(&buf);
802 for (ref = remote_refs; ref; ref = ref->next) {
803 char *private;
804 unsigned char sha1[20];
806 if (!data->refspecs)
807 continue;
808 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
809 if (private && !get_sha1(private, sha1)) {
810 strbuf_addf(&buf, "^%s", private);
811 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
813 free(private);
815 if (ref->deletion) {
816 die("remote-helpers do not support ref deletion");
819 if (ref->peer_ref)
820 string_list_append(&revlist_args, ref->peer_ref->name);
824 if (get_exporter(transport, &exporter, &revlist_args))
825 die("Couldn't run fast-export");
827 if (finish_command(&exporter))
828 die("Error while running fast-export");
829 check_helper_status(data);
830 push_update_refs_status(data, remote_refs);
831 return 0;
834 static int push_refs(struct transport *transport,
835 struct ref *remote_refs, int flags)
837 struct helper_data *data = transport->data;
839 if (process_connect(transport, 1)) {
840 do_take_over(transport);
841 return transport->push_refs(transport, remote_refs, flags);
844 if (!remote_refs) {
845 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
846 "Perhaps you should specify a branch such as 'master'.\n");
847 return 0;
850 if (data->push)
851 return push_refs_with_push(transport, remote_refs, flags);
853 if (data->export)
854 return push_refs_with_export(transport, remote_refs, flags);
856 return -1;
860 static int has_attribute(const char *attrs, const char *attr) {
861 int len;
862 if (!attrs)
863 return 0;
865 len = strlen(attr);
866 for (;;) {
867 const char *space = strchrnul(attrs, ' ');
868 if (len == space - attrs && !strncmp(attrs, attr, len))
869 return 1;
870 if (!*space)
871 return 0;
872 attrs = space + 1;
876 static struct ref *get_refs_list(struct transport *transport, int for_push)
878 struct helper_data *data = transport->data;
879 struct child_process *helper;
880 struct ref *ret = NULL;
881 struct ref **tail = &ret;
882 struct ref *posn;
883 struct strbuf buf = STRBUF_INIT;
885 helper = get_helper(transport);
887 if (process_connect(transport, for_push)) {
888 do_take_over(transport);
889 return transport->get_refs_list(transport, for_push);
892 if (data->push && for_push)
893 write_str_in_full(helper->in, "list for-push\n");
894 else
895 write_str_in_full(helper->in, "list\n");
897 while (1) {
898 char *eov, *eon;
899 recvline(data, &buf);
901 if (!*buf.buf)
902 break;
904 eov = strchr(buf.buf, ' ');
905 if (!eov)
906 die("Malformed response in ref list: %s", buf.buf);
907 eon = strchr(eov + 1, ' ');
908 *eov = '\0';
909 if (eon)
910 *eon = '\0';
911 *tail = alloc_ref(eov + 1);
912 if (buf.buf[0] == '@')
913 (*tail)->symref = xstrdup(buf.buf + 1);
914 else if (buf.buf[0] != '?')
915 get_sha1_hex(buf.buf, (*tail)->old_sha1);
916 if (eon) {
917 if (has_attribute(eon + 1, "unchanged")) {
918 (*tail)->status |= REF_STATUS_UPTODATE;
919 read_ref((*tail)->name, (*tail)->old_sha1);
922 tail = &((*tail)->next);
924 if (debug)
925 fprintf(stderr, "Debug: Read ref listing.\n");
926 strbuf_release(&buf);
928 for (posn = ret; posn; posn = posn->next)
929 resolve_remote_symref(posn, ret);
931 return ret;
934 int transport_helper_init(struct transport *transport, const char *name)
936 struct helper_data *data = xcalloc(sizeof(*data), 1);
937 data->name = name;
939 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
940 debug = 1;
942 transport->data = data;
943 transport->set_option = set_helper_option;
944 transport->get_refs_list = get_refs_list;
945 transport->fetch = fetch;
946 transport->push_refs = push_refs;
947 transport->disconnect = release_helper;
948 transport->connect = connect_helper;
949 transport->smart_options = &(data->transport_options);
950 return 0;
954 * Linux pipes can buffer 65536 bytes at once (and most platforms can
955 * buffer less), so attempt reads and writes with up to that size.
957 #define BUFFERSIZE 65536
958 /* This should be enough to hold debugging message. */
959 #define PBUFFERSIZE 8192
961 /* Print bidirectional transfer loop debug message. */
962 static void transfer_debug(const char *fmt, ...)
964 va_list args;
965 char msgbuf[PBUFFERSIZE];
966 static int debug_enabled = -1;
968 if (debug_enabled < 0)
969 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
970 if (!debug_enabled)
971 return;
973 va_start(args, fmt);
974 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
975 va_end(args);
976 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
979 /* Stream state: More data may be coming in this direction. */
980 #define SSTATE_TRANSFERING 0
982 * Stream state: No more data coming in this direction, flushing rest of
983 * data.
985 #define SSTATE_FLUSHING 1
986 /* Stream state: Transfer in this direction finished. */
987 #define SSTATE_FINISHED 2
989 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
990 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
991 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
993 /* Unidirectional transfer. */
994 struct unidirectional_transfer {
995 /* Source */
996 int src;
997 /* Destination */
998 int dest;
999 /* Is source socket? */
1000 int src_is_sock;
1001 /* Is destination socket? */
1002 int dest_is_sock;
1003 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
1004 int state;
1005 /* Buffer. */
1006 char buf[BUFFERSIZE];
1007 /* Buffer used. */
1008 size_t bufuse;
1009 /* Name of source. */
1010 const char *src_name;
1011 /* Name of destination. */
1012 const char *dest_name;
1015 /* Closes the target (for writing) if transfer has finished. */
1016 static void udt_close_if_finished(struct unidirectional_transfer *t)
1018 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1019 t->state = SSTATE_FINISHED;
1020 if (t->dest_is_sock)
1021 shutdown(t->dest, SHUT_WR);
1022 else
1023 close(t->dest);
1024 transfer_debug("Closed %s.", t->dest_name);
1029 * Tries to read read data from source into buffer. If buffer is full,
1030 * no data is read. Returns 0 on success, -1 on error.
1032 static int udt_do_read(struct unidirectional_transfer *t)
1034 ssize_t bytes;
1036 if (t->bufuse == BUFFERSIZE)
1037 return 0; /* No space for more. */
1039 transfer_debug("%s is readable", t->src_name);
1040 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1041 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1042 errno != EINTR) {
1043 error("read(%s) failed: %s", t->src_name, strerror(errno));
1044 return -1;
1045 } else if (bytes == 0) {
1046 transfer_debug("%s EOF (with %i bytes in buffer)",
1047 t->src_name, t->bufuse);
1048 t->state = SSTATE_FLUSHING;
1049 } else if (bytes > 0) {
1050 t->bufuse += bytes;
1051 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1052 (int)bytes, t->src_name, (int)t->bufuse);
1054 return 0;
1057 /* Tries to write data from buffer into destination. If buffer is empty,
1058 * no data is written. Returns 0 on success, -1 on error.
1060 static int udt_do_write(struct unidirectional_transfer *t)
1062 ssize_t bytes;
1064 if (t->bufuse == 0)
1065 return 0; /* Nothing to write. */
1067 transfer_debug("%s is writable", t->dest_name);
1068 bytes = write(t->dest, t->buf, t->bufuse);
1069 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1070 errno != EINTR) {
1071 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1072 return -1;
1073 } else if (bytes > 0) {
1074 t->bufuse -= bytes;
1075 if (t->bufuse)
1076 memmove(t->buf, t->buf + bytes, t->bufuse);
1077 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1078 (int)bytes, t->dest_name, (int)t->bufuse);
1080 return 0;
1084 /* State of bidirectional transfer loop. */
1085 struct bidirectional_transfer_state {
1086 /* Direction from program to git. */
1087 struct unidirectional_transfer ptg;
1088 /* Direction from git to program. */
1089 struct unidirectional_transfer gtp;
1092 static void *udt_copy_task_routine(void *udt)
1094 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1095 while (t->state != SSTATE_FINISHED) {
1096 if (STATE_NEEDS_READING(t->state))
1097 if (udt_do_read(t))
1098 return NULL;
1099 if (STATE_NEEDS_WRITING(t->state))
1100 if (udt_do_write(t))
1101 return NULL;
1102 if (STATE_NEEDS_CLOSING(t->state))
1103 udt_close_if_finished(t);
1105 return udt; /* Just some non-NULL value. */
1108 #ifndef NO_PTHREADS
1111 * Join thread, with apporiate errors on failure. Name is name for the
1112 * thread (for error messages). Returns 0 on success, 1 on failure.
1114 static int tloop_join(pthread_t thread, const char *name)
1116 int err;
1117 void *tret;
1118 err = pthread_join(thread, &tret);
1119 if (!tret) {
1120 error("%s thread failed", name);
1121 return 1;
1123 if (err) {
1124 error("%s thread failed to join: %s", name, strerror(err));
1125 return 1;
1127 return 0;
1131 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1132 * -1 on failure.
1134 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1136 pthread_t gtp_thread;
1137 pthread_t ptg_thread;
1138 int err;
1139 int ret = 0;
1140 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1141 &s->gtp);
1142 if (err)
1143 die("Can't start thread for copying data: %s", strerror(err));
1144 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1145 &s->ptg);
1146 if (err)
1147 die("Can't start thread for copying data: %s", strerror(err));
1149 ret |= tloop_join(gtp_thread, "Git to program copy");
1150 ret |= tloop_join(ptg_thread, "Program to git copy");
1151 return ret;
1153 #else
1155 /* Close the source and target (for writing) for transfer. */
1156 static void udt_kill_transfer(struct unidirectional_transfer *t)
1158 t->state = SSTATE_FINISHED;
1160 * Socket read end left open isn't a disaster if nobody
1161 * attempts to read from it (mingw compat headers do not
1162 * have SHUT_RD)...
1164 * We can't fully close the socket since otherwise gtp
1165 * task would first close the socket it sends data to
1166 * while closing the ptg file descriptors.
1168 if (!t->src_is_sock)
1169 close(t->src);
1170 if (t->dest_is_sock)
1171 shutdown(t->dest, SHUT_WR);
1172 else
1173 close(t->dest);
1177 * Join process, with apporiate errors on failure. Name is name for the
1178 * process (for error messages). Returns 0 on success, 1 on failure.
1180 static int tloop_join(pid_t pid, const char *name)
1182 int tret;
1183 if (waitpid(pid, &tret, 0) < 0) {
1184 error("%s process failed to wait: %s", name, strerror(errno));
1185 return 1;
1187 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1188 error("%s process failed", name);
1189 return 1;
1191 return 0;
1195 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1196 * -1 on failure.
1198 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1200 pid_t pid1, pid2;
1201 int ret = 0;
1203 /* Fork thread #1: git to program. */
1204 pid1 = fork();
1205 if (pid1 < 0)
1206 die_errno("Can't start thread for copying data");
1207 else if (pid1 == 0) {
1208 udt_kill_transfer(&s->ptg);
1209 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1212 /* Fork thread #2: program to git. */
1213 pid2 = fork();
1214 if (pid2 < 0)
1215 die_errno("Can't start thread for copying data");
1216 else if (pid2 == 0) {
1217 udt_kill_transfer(&s->gtp);
1218 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1222 * Close both streams in parent as to not interfere with
1223 * end of file detection and wait for both tasks to finish.
1225 udt_kill_transfer(&s->gtp);
1226 udt_kill_transfer(&s->ptg);
1227 ret |= tloop_join(pid1, "Git to program copy");
1228 ret |= tloop_join(pid2, "Program to git copy");
1229 return ret;
1231 #endif
1234 * Copies data from stdin to output and from input to stdout simultaneously.
1235 * Additionally filtering through given filter. If filter is NULL, uses
1236 * identity filter.
1238 int bidirectional_transfer_loop(int input, int output)
1240 struct bidirectional_transfer_state state;
1242 /* Fill the state fields. */
1243 state.ptg.src = input;
1244 state.ptg.dest = 1;
1245 state.ptg.src_is_sock = (input == output);
1246 state.ptg.dest_is_sock = 0;
1247 state.ptg.state = SSTATE_TRANSFERING;
1248 state.ptg.bufuse = 0;
1249 state.ptg.src_name = "remote input";
1250 state.ptg.dest_name = "stdout";
1252 state.gtp.src = 0;
1253 state.gtp.dest = output;
1254 state.gtp.src_is_sock = 0;
1255 state.gtp.dest_is_sock = (input == output);
1256 state.gtp.state = SSTATE_TRANSFERING;
1257 state.gtp.bufuse = 0;
1258 state.gtp.src_name = "stdin";
1259 state.gtp.dest_name = "remote output";
1261 return tloop_spawnwait_tasks(&state);