Always auto-gc after calling a fast-import transport
[git/dscho.git] / transport-helper.c
blob5ff0e44a6d0d5316a5915e5ac4b435415d14ffd1
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"
14 static int debug;
15 /* TODO: put somewhere sensible, e.g. git_transport_options? */
16 static int auto_gc = 1;
18 struct helper_data {
19 const char *name;
20 struct child_process *helper;
21 FILE *out;
22 unsigned fetch : 1,
23 import : 1,
24 export : 1,
25 option : 1,
26 push : 1,
27 connect : 1,
28 no_disconnect_req : 1;
29 char *export_marks;
30 char *import_marks;
31 /* These go from remote name (as in "list") to private name */
32 struct refspec *refspecs;
33 int refspec_nr;
34 /* Transport options for fetch-pack/send-pack (should one of
35 * those be invoked).
37 struct git_transport_options transport_options;
40 static void sendline(struct helper_data *helper, struct strbuf *buffer)
42 if (debug)
43 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
44 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
45 != buffer->len)
46 die_errno("Full write to remote helper failed");
49 static int recvline_fh(FILE *helper, struct strbuf *buffer)
51 strbuf_reset(buffer);
52 if (debug)
53 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
54 if (strbuf_getline(buffer, helper, '\n') == EOF) {
55 if (debug)
56 fprintf(stderr, "Debug: Remote helper quit.\n");
57 exit(128);
60 if (debug)
61 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
62 return 0;
65 static int recvline(struct helper_data *helper, struct strbuf *buffer)
67 return recvline_fh(helper->out, buffer);
70 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
72 sendline(helper, buffer);
73 recvline(helper, buffer);
76 static void write_constant(int fd, const char *str)
78 if (debug)
79 fprintf(stderr, "Debug: Remote helper: -> %s", str);
80 if (write_in_full(fd, str, strlen(str)) != strlen(str))
81 die_errno("Full write to remote helper failed");
84 static const char *remove_ext_force(const char *url)
86 if (url) {
87 const char *colon = strchr(url, ':');
88 if (colon && colon[1] == ':')
89 return colon + 2;
91 return url;
94 static void do_take_over(struct transport *transport)
96 struct helper_data *data;
97 data = (struct helper_data *)transport->data;
98 transport_take_over(transport, data->helper);
99 fclose(data->out);
100 free(data);
103 static struct child_process *get_helper(struct transport *transport)
105 struct helper_data *data = transport->data;
106 struct strbuf buf = STRBUF_INIT;
107 struct child_process *helper;
108 const char **refspecs = NULL;
109 int refspec_nr = 0;
110 int refspec_alloc = 0;
111 int duped;
112 int code;
113 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
114 const char *helper_env[] = {
115 git_dir_buf,
116 NULL
120 if (data->helper)
121 return data->helper;
123 helper = xcalloc(1, sizeof(*helper));
124 helper->in = -1;
125 helper->out = -1;
126 helper->err = 0;
127 helper->argv = xcalloc(4, sizeof(*helper->argv));
128 strbuf_addf(&buf, "git-remote-%s", data->name);
129 helper->argv[0] = strbuf_detach(&buf, NULL);
130 helper->argv[1] = transport->remote->name;
131 helper->argv[2] = remove_ext_force(transport->url);
132 helper->git_cmd = 0;
133 helper->silent_exec_failure = 1;
135 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
136 helper->env = helper_env;
138 code = start_command(helper);
139 if (code < 0 && errno == ENOENT)
140 die("Unable to find remote helper for '%s'", data->name);
141 else if (code != 0)
142 exit(code);
144 data->helper = helper;
145 data->no_disconnect_req = 0;
148 * Open the output as FILE* so strbuf_getline() can be used.
149 * Do this with duped fd because fclose() will close the fd,
150 * and stuff like taking over will require the fd to remain.
152 duped = dup(helper->out);
153 if (duped < 0)
154 die_errno("Can't dup helper output fd");
155 data->out = xfdopen(duped, "r");
157 write_constant(helper->in, "capabilities\n");
159 while (1) {
160 const char *capname;
161 int mandatory = 0;
162 recvline(data, &buf);
164 if (!*buf.buf)
165 break;
167 if (*buf.buf == '*') {
168 capname = buf.buf + 1;
169 mandatory = 1;
170 } else
171 capname = buf.buf;
173 if (debug)
174 fprintf(stderr, "Debug: Got cap %s\n", capname);
175 if (!strcmp(capname, "fetch"))
176 data->fetch = 1;
177 else if (!strcmp(capname, "option"))
178 data->option = 1;
179 else if (!strcmp(capname, "push"))
180 data->push = 1;
181 else if (!strcmp(capname, "import"))
182 data->import = 1;
183 else if (!strcmp(capname, "export"))
184 data->export = 1;
185 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
186 ALLOC_GROW(refspecs,
187 refspec_nr + 1,
188 refspec_alloc);
189 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
190 } else if (!strcmp(capname, "connect")) {
191 data->connect = 1;
192 } else if (!prefixcmp(capname, "export-marks ")) {
193 struct strbuf arg = STRBUF_INIT;
194 strbuf_addstr(&arg, "--export-marks=");
195 strbuf_addstr(&arg, capname + strlen("export-marks "));
196 data->export_marks = strbuf_detach(&arg, NULL);
197 } else if (!prefixcmp(capname, "import-marks")) {
198 struct strbuf arg = STRBUF_INIT;
199 strbuf_addstr(&arg, "--import-marks=");
200 strbuf_addstr(&arg, capname + strlen("import-marks "));
201 data->import_marks = strbuf_detach(&arg, NULL);
202 } else if (mandatory) {
203 die("Unknown mandatory capability %s. This remote "
204 "helper probably needs newer version of Git.",
205 capname);
208 if (refspecs) {
209 int i;
210 data->refspec_nr = refspec_nr;
211 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
212 for (i = 0; i < refspec_nr; i++) {
213 free((char *)refspecs[i]);
215 free(refspecs);
217 strbuf_release(&buf);
218 if (debug)
219 fprintf(stderr, "Debug: Capabilities complete.\n");
220 return data->helper;
223 static int disconnect_helper(struct transport *transport)
225 struct helper_data *data = transport->data;
226 int res = 0;
228 if (data->helper) {
229 if (debug)
230 fprintf(stderr, "Debug: Disconnecting.\n");
231 if (!data->no_disconnect_req) {
233 * Ignore write errors; there's nothing we can do,
234 * since we're about to close the pipe anyway. And the
235 * most likely error is EPIPE due to the helper dying
236 * to report an error itself.
238 sigchain_push(SIGPIPE, SIG_IGN);
239 xwrite(data->helper->in, "\n", 1);
240 sigchain_pop(SIGPIPE);
242 close(data->helper->in);
243 close(data->helper->out);
244 fclose(data->out);
245 res = finish_command(data->helper);
246 free((char *)data->helper->argv[0]);
247 free(data->helper->argv);
248 free(data->helper);
249 data->helper = NULL;
251 return res;
254 static const char *unsupported_options[] = {
255 TRANS_OPT_UPLOADPACK,
256 TRANS_OPT_RECEIVEPACK,
257 TRANS_OPT_THIN,
258 TRANS_OPT_KEEP
260 static const char *boolean_options[] = {
261 TRANS_OPT_THIN,
262 TRANS_OPT_KEEP,
263 TRANS_OPT_FOLLOWTAGS
266 static int set_helper_option(struct transport *transport,
267 const char *name, const char *value)
269 struct helper_data *data = transport->data;
270 struct strbuf buf = STRBUF_INIT;
271 int i, ret, is_bool = 0;
273 get_helper(transport);
275 if (!data->option)
276 return 1;
278 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
279 if (!strcmp(name, unsupported_options[i]))
280 return 1;
283 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
284 if (!strcmp(name, boolean_options[i])) {
285 is_bool = 1;
286 break;
290 strbuf_addf(&buf, "option %s ", name);
291 if (is_bool)
292 strbuf_addstr(&buf, value ? "true" : "false");
293 else
294 quote_c_style(value, &buf, NULL, 0);
295 strbuf_addch(&buf, '\n');
297 xchgline(data, &buf);
299 if (!strcmp(buf.buf, "ok"))
300 ret = 0;
301 else if (!prefixcmp(buf.buf, "error")) {
302 ret = -1;
303 } else if (!strcmp(buf.buf, "unsupported"))
304 ret = 1;
305 else {
306 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
307 ret = 1;
309 strbuf_release(&buf);
310 return ret;
313 static void standard_options(struct transport *t)
315 char buf[16];
316 int n;
317 int v = t->verbose;
319 set_helper_option(t, "progress", t->progress ? "true" : "false");
321 n = snprintf(buf, sizeof(buf), "%d", v + 1);
322 if (n >= sizeof(buf))
323 die("impossibly large verbosity value");
324 set_helper_option(t, "verbosity", buf);
327 static int release_helper(struct transport *transport)
329 int res = 0;
330 struct helper_data *data = transport->data;
331 free_refspec(data->refspec_nr, data->refspecs);
332 data->refspecs = NULL;
333 res = disconnect_helper(transport);
334 free(transport->data);
335 return res;
338 static int fetch_with_fetch(struct transport *transport,
339 int nr_heads, struct ref **to_fetch)
341 struct helper_data *data = transport->data;
342 int i;
343 struct strbuf buf = STRBUF_INIT;
345 standard_options(transport);
347 for (i = 0; i < nr_heads; i++) {
348 const struct ref *posn = to_fetch[i];
349 if (posn->status & REF_STATUS_UPTODATE)
350 continue;
352 strbuf_addf(&buf, "fetch %s %s\n",
353 sha1_to_hex(posn->old_sha1), posn->name);
356 strbuf_addch(&buf, '\n');
357 sendline(data, &buf);
359 while (1) {
360 recvline(data, &buf);
362 if (!prefixcmp(buf.buf, "lock ")) {
363 const char *name = buf.buf + 5;
364 if (transport->pack_lockfile)
365 warning("%s also locked %s", data->name, name);
366 else
367 transport->pack_lockfile = xstrdup(name);
369 else if (!buf.len)
370 break;
371 else
372 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
374 strbuf_release(&buf);
375 return 0;
378 static int get_importer(struct transport *transport, struct child_process *fastimport)
380 struct child_process *helper = get_helper(transport);
381 memset(fastimport, 0, sizeof(*fastimport));
382 fastimport->in = helper->out;
383 fastimport->argv = xcalloc(5, sizeof(*fastimport->argv));
384 fastimport->argv[0] = "fast-import";
385 fastimport->argv[1] = "--quiet";
387 fastimport->git_cmd = 1;
388 return start_command(fastimport);
391 static int get_exporter(struct transport *transport,
392 struct child_process *fastexport,
393 struct string_list *revlist_args)
395 struct helper_data *data = transport->data;
396 struct child_process *helper = get_helper(transport);
397 int argc = 0, i;
398 memset(fastexport, 0, sizeof(*fastexport));
400 /* we need to duplicate helper->in because we want to use it after
401 * fastexport is done with it. */
402 fastexport->out = dup(helper->in);
403 fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
404 fastexport->argv[argc++] = "fast-export";
405 fastexport->argv[argc++] = "--use-done-feature";
406 if (data->export_marks)
407 fastexport->argv[argc++] = data->export_marks;
408 if (data->import_marks)
409 fastexport->argv[argc++] = data->import_marks;
411 for (i = 0; i < revlist_args->nr; i++)
412 fastexport->argv[argc++] = revlist_args->items[i].string;
414 fastexport->argv[argc++] = "--";
416 fastexport->git_cmd = 1;
417 return start_command(fastexport);
420 static void check_helper_status(struct helper_data *data)
422 int pid, status;
424 pid = waitpid(data->helper->pid, &status, WNOHANG);
425 if (pid < 0)
426 die("Could not retrieve status of remote helper '%s'",
427 data->name);
428 if (pid > 0 && WIFEXITED(status))
429 die("Remote helper '%s' died with %d",
430 data->name, WEXITSTATUS(status));
433 static int fetch_with_import(struct transport *transport,
434 int nr_heads, struct ref **to_fetch)
436 struct child_process fastimport;
437 struct helper_data *data = transport->data;
438 int i;
439 struct ref *posn;
440 struct strbuf buf = STRBUF_INIT;
442 get_helper(transport);
444 if (get_importer(transport, &fastimport))
445 die("Couldn't run fast-import");
447 for (i = 0; i < nr_heads; i++) {
448 posn = to_fetch[i];
449 if (posn->status & REF_STATUS_UPTODATE)
450 continue;
452 strbuf_addf(&buf, "import %s\n", posn->name);
453 sendline(data, &buf);
454 strbuf_reset(&buf);
457 write_constant(data->helper->in, "\n");
459 if (finish_command(&fastimport))
460 die("Error while running fast-import");
461 check_helper_status(data);
463 free(fastimport.argv);
464 fastimport.argv = NULL;
466 for (i = 0; i < nr_heads; i++) {
467 char *private;
468 posn = to_fetch[i];
469 if (posn->status & REF_STATUS_UPTODATE)
470 continue;
471 if (data->refspecs)
472 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
473 else
474 private = xstrdup(posn->name);
475 if (private) {
476 read_ref(private, posn->old_sha1);
477 free(private);
480 strbuf_release(&buf);
481 if (auto_gc) {
482 const char *argv_gc_auto[] = {
483 "gc", "--auto", "--quiet", NULL,
485 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
487 return 0;
490 static int process_connect_service(struct transport *transport,
491 const char *name, const char *exec)
493 struct helper_data *data = transport->data;
494 struct strbuf cmdbuf = STRBUF_INIT;
495 struct child_process *helper;
496 int r, duped, ret = 0;
497 FILE *input;
499 helper = get_helper(transport);
502 * Yes, dup the pipe another time, as we need unbuffered version
503 * of input pipe as FILE*. fclose() closes the underlying fd and
504 * stream buffering only can be changed before first I/O operation
505 * on it.
507 duped = dup(helper->out);
508 if (duped < 0)
509 die_errno("Can't dup helper output fd");
510 input = xfdopen(duped, "r");
511 setvbuf(input, NULL, _IONBF, 0);
514 * Handle --upload-pack and friends. This is fire and forget...
515 * just warn if it fails.
517 if (strcmp(name, exec)) {
518 r = set_helper_option(transport, "servpath", exec);
519 if (r > 0)
520 warning("Setting remote service path not supported by protocol.");
521 else if (r < 0)
522 warning("Invalid remote service path.");
525 if (data->connect)
526 strbuf_addf(&cmdbuf, "connect %s\n", name);
527 else
528 goto exit;
530 sendline(data, &cmdbuf);
531 recvline_fh(input, &cmdbuf);
532 if (!strcmp(cmdbuf.buf, "")) {
533 data->no_disconnect_req = 1;
534 if (debug)
535 fprintf(stderr, "Debug: Smart transport connection "
536 "ready.\n");
537 ret = 1;
538 } else if (!strcmp(cmdbuf.buf, "fallback")) {
539 if (debug)
540 fprintf(stderr, "Debug: Falling back to dumb "
541 "transport.\n");
542 } else
543 die("Unknown response to connect: %s",
544 cmdbuf.buf);
546 exit:
547 fclose(input);
548 return ret;
551 static int process_connect(struct transport *transport,
552 int for_push)
554 struct helper_data *data = transport->data;
555 const char *name;
556 const char *exec;
558 name = for_push ? "git-receive-pack" : "git-upload-pack";
559 if (for_push)
560 exec = data->transport_options.receivepack;
561 else
562 exec = data->transport_options.uploadpack;
564 return process_connect_service(transport, name, exec);
567 static int connect_helper(struct transport *transport, const char *name,
568 const char *exec, int fd[2])
570 struct helper_data *data = transport->data;
572 /* Get_helper so connect is inited. */
573 get_helper(transport);
574 if (!data->connect)
575 die("Operation not supported by protocol.");
577 if (!process_connect_service(transport, name, exec))
578 die("Can't connect to subservice %s.", name);
580 fd[0] = data->helper->out;
581 fd[1] = data->helper->in;
582 return 0;
585 static int fetch(struct transport *transport,
586 int nr_heads, struct ref **to_fetch)
588 struct helper_data *data = transport->data;
589 int i, count;
591 if (process_connect(transport, 0)) {
592 do_take_over(transport);
593 return transport->fetch(transport, nr_heads, to_fetch);
596 count = 0;
597 for (i = 0; i < nr_heads; i++)
598 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
599 count++;
601 if (!count)
602 return 0;
604 if (data->fetch)
605 return fetch_with_fetch(transport, nr_heads, to_fetch);
607 if (data->import)
608 return fetch_with_import(transport, nr_heads, to_fetch);
610 return -1;
613 static void push_update_ref_status(struct strbuf *buf,
614 struct ref **ref,
615 struct ref *remote_refs)
617 char *refname, *msg;
618 int status;
620 if (!prefixcmp(buf->buf, "ok ")) {
621 status = REF_STATUS_OK;
622 refname = buf->buf + 3;
623 } else if (!prefixcmp(buf->buf, "error ")) {
624 status = REF_STATUS_REMOTE_REJECT;
625 refname = buf->buf + 6;
626 } else
627 die("expected ok/error, helper said '%s'", buf->buf);
629 msg = strchr(refname, ' ');
630 if (msg) {
631 struct strbuf msg_buf = STRBUF_INIT;
632 const char *end;
634 *msg++ = '\0';
635 if (!unquote_c_style(&msg_buf, msg, &end))
636 msg = strbuf_detach(&msg_buf, NULL);
637 else
638 msg = xstrdup(msg);
639 strbuf_release(&msg_buf);
641 if (!strcmp(msg, "no match")) {
642 status = REF_STATUS_NONE;
643 free(msg);
644 msg = NULL;
646 else if (!strcmp(msg, "up to date")) {
647 status = REF_STATUS_UPTODATE;
648 free(msg);
649 msg = NULL;
651 else if (!strcmp(msg, "non-fast forward")) {
652 status = REF_STATUS_REJECT_NONFASTFORWARD;
653 free(msg);
654 msg = NULL;
658 if (*ref)
659 *ref = find_ref_by_name(*ref, refname);
660 if (!*ref)
661 *ref = find_ref_by_name(remote_refs, refname);
662 if (!*ref) {
663 warning("helper reported unexpected status of %s", refname);
664 return;
667 if ((*ref)->status != REF_STATUS_NONE) {
669 * Earlier, the ref was marked not to be pushed, so ignore the ref
670 * status reported by the remote helper if the latter is 'no match'.
672 if (status == REF_STATUS_NONE)
673 return;
676 (*ref)->status = status;
677 (*ref)->remote_status = msg;
680 static void push_update_refs_status(struct helper_data *data,
681 struct ref *remote_refs)
683 struct strbuf buf = STRBUF_INIT;
684 struct ref *ref = remote_refs;
685 for (;;) {
686 recvline(data, &buf);
687 if (!buf.len)
688 break;
690 push_update_ref_status(&buf, &ref, remote_refs);
692 strbuf_release(&buf);
695 static int push_refs_with_push(struct transport *transport,
696 struct ref *remote_refs, int flags)
698 int force_all = flags & TRANSPORT_PUSH_FORCE;
699 int mirror = flags & TRANSPORT_PUSH_MIRROR;
700 struct helper_data *data = transport->data;
701 struct strbuf buf = STRBUF_INIT;
702 struct ref *ref;
704 get_helper(transport);
705 if (!data->push)
706 return 1;
708 for (ref = remote_refs; ref; ref = ref->next) {
709 if (!ref->peer_ref && !mirror)
710 continue;
712 /* Check for statuses set by set_ref_status_for_push() */
713 switch (ref->status) {
714 case REF_STATUS_REJECT_NONFASTFORWARD:
715 case REF_STATUS_UPTODATE:
716 continue;
717 default:
718 ; /* do nothing */
721 if (force_all)
722 ref->force = 1;
724 strbuf_addstr(&buf, "push ");
725 if (!ref->deletion) {
726 if (ref->force)
727 strbuf_addch(&buf, '+');
728 if (ref->peer_ref)
729 strbuf_addstr(&buf, ref->peer_ref->name);
730 else
731 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
733 strbuf_addch(&buf, ':');
734 strbuf_addstr(&buf, ref->name);
735 strbuf_addch(&buf, '\n');
737 if (buf.len == 0)
738 return 0;
740 standard_options(transport);
742 if (flags & TRANSPORT_PUSH_DRY_RUN) {
743 if (set_helper_option(transport, "dry-run", "true") != 0)
744 die("helper %s does not support dry-run", data->name);
747 strbuf_addch(&buf, '\n');
748 sendline(data, &buf);
749 strbuf_release(&buf);
751 push_update_refs_status(data, remote_refs);
752 return 0;
755 static int push_refs_with_export(struct transport *transport,
756 struct ref *remote_refs, int flags)
758 struct ref *ref;
759 struct child_process *helper, exporter;
760 struct helper_data *data = transport->data;
761 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
762 struct strbuf buf = STRBUF_INIT;
764 helper = get_helper(transport);
766 write_constant(helper->in, "export\n");
768 strbuf_reset(&buf);
770 for (ref = remote_refs; ref; ref = ref->next) {
771 char *private;
772 unsigned char sha1[20];
774 if (!data->refspecs)
775 continue;
776 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
777 if (private && !get_sha1(private, sha1)) {
778 strbuf_addf(&buf, "^%s", private);
779 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
781 free(private);
783 if (ref->deletion) {
784 die("remote-helpers do not support ref deletion");
787 if (ref->peer_ref)
788 string_list_append(&revlist_args, ref->peer_ref->name);
792 if (get_exporter(transport, &exporter, &revlist_args))
793 die("Couldn't run fast-export");
795 if (finish_command(&exporter))
796 die("Error while running fast-export");
797 check_helper_status(data);
798 push_update_refs_status(data, remote_refs);
799 return 0;
802 static int push_refs(struct transport *transport,
803 struct ref *remote_refs, int flags)
805 struct helper_data *data = transport->data;
807 if (process_connect(transport, 1)) {
808 do_take_over(transport);
809 return transport->push_refs(transport, remote_refs, flags);
812 if (!remote_refs) {
813 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
814 "Perhaps you should specify a branch such as 'master'.\n");
815 return 0;
818 if (data->push)
819 return push_refs_with_push(transport, remote_refs, flags);
821 if (data->export)
822 return push_refs_with_export(transport, remote_refs, flags);
824 return -1;
828 static int has_attribute(const char *attrs, const char *attr) {
829 int len;
830 if (!attrs)
831 return 0;
833 len = strlen(attr);
834 for (;;) {
835 const char *space = strchrnul(attrs, ' ');
836 if (len == space - attrs && !strncmp(attrs, attr, len))
837 return 1;
838 if (!*space)
839 return 0;
840 attrs = space + 1;
844 static struct ref *get_refs_list(struct transport *transport, int for_push)
846 struct helper_data *data = transport->data;
847 struct child_process *helper;
848 struct ref *ret = NULL;
849 struct ref **tail = &ret;
850 struct ref *posn;
851 struct strbuf buf = STRBUF_INIT;
853 helper = get_helper(transport);
855 if (process_connect(transport, for_push)) {
856 do_take_over(transport);
857 return transport->get_refs_list(transport, for_push);
860 if (data->push && for_push)
861 write_str_in_full(helper->in, "list for-push\n");
862 else
863 write_str_in_full(helper->in, "list\n");
865 while (1) {
866 char *eov, *eon;
867 recvline(data, &buf);
869 if (!*buf.buf)
870 break;
872 eov = strchr(buf.buf, ' ');
873 if (!eov)
874 die("Malformed response in ref list: %s", buf.buf);
875 eon = strchr(eov + 1, ' ');
876 *eov = '\0';
877 if (eon)
878 *eon = '\0';
879 *tail = alloc_ref(eov + 1);
880 if (buf.buf[0] == '@')
881 (*tail)->symref = xstrdup(buf.buf + 1);
882 else if (buf.buf[0] != '?')
883 get_sha1_hex(buf.buf, (*tail)->old_sha1);
884 if (eon) {
885 if (has_attribute(eon + 1, "unchanged")) {
886 (*tail)->status |= REF_STATUS_UPTODATE;
887 read_ref((*tail)->name, (*tail)->old_sha1);
890 tail = &((*tail)->next);
892 if (debug)
893 fprintf(stderr, "Debug: Read ref listing.\n");
894 strbuf_release(&buf);
896 for (posn = ret; posn; posn = posn->next)
897 resolve_remote_symref(posn, ret);
899 return ret;
902 int transport_helper_init(struct transport *transport, const char *name)
904 struct helper_data *data = xcalloc(sizeof(*data), 1);
905 data->name = name;
907 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
908 debug = 1;
910 transport->data = data;
911 transport->set_option = set_helper_option;
912 transport->get_refs_list = get_refs_list;
913 transport->fetch = fetch;
914 transport->push_refs = push_refs;
915 transport->disconnect = release_helper;
916 transport->connect = connect_helper;
917 transport->smart_options = &(data->transport_options);
918 return 0;
922 * Linux pipes can buffer 65536 bytes at once (and most platforms can
923 * buffer less), so attempt reads and writes with up to that size.
925 #define BUFFERSIZE 65536
926 /* This should be enough to hold debugging message. */
927 #define PBUFFERSIZE 8192
929 /* Print bidirectional transfer loop debug message. */
930 static void transfer_debug(const char *fmt, ...)
932 va_list args;
933 char msgbuf[PBUFFERSIZE];
934 static int debug_enabled = -1;
936 if (debug_enabled < 0)
937 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
938 if (!debug_enabled)
939 return;
941 va_start(args, fmt);
942 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
943 va_end(args);
944 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
947 /* Stream state: More data may be coming in this direction. */
948 #define SSTATE_TRANSFERING 0
950 * Stream state: No more data coming in this direction, flushing rest of
951 * data.
953 #define SSTATE_FLUSHING 1
954 /* Stream state: Transfer in this direction finished. */
955 #define SSTATE_FINISHED 2
957 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
958 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
959 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
961 /* Unidirectional transfer. */
962 struct unidirectional_transfer {
963 /* Source */
964 int src;
965 /* Destination */
966 int dest;
967 /* Is source socket? */
968 int src_is_sock;
969 /* Is destination socket? */
970 int dest_is_sock;
971 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
972 int state;
973 /* Buffer. */
974 char buf[BUFFERSIZE];
975 /* Buffer used. */
976 size_t bufuse;
977 /* Name of source. */
978 const char *src_name;
979 /* Name of destination. */
980 const char *dest_name;
983 /* Closes the target (for writing) if transfer has finished. */
984 static void udt_close_if_finished(struct unidirectional_transfer *t)
986 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
987 t->state = SSTATE_FINISHED;
988 if (t->dest_is_sock)
989 shutdown(t->dest, SHUT_WR);
990 else
991 close(t->dest);
992 transfer_debug("Closed %s.", t->dest_name);
997 * Tries to read read data from source into buffer. If buffer is full,
998 * no data is read. Returns 0 on success, -1 on error.
1000 static int udt_do_read(struct unidirectional_transfer *t)
1002 ssize_t bytes;
1004 if (t->bufuse == BUFFERSIZE)
1005 return 0; /* No space for more. */
1007 transfer_debug("%s is readable", t->src_name);
1008 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1009 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1010 errno != EINTR) {
1011 error("read(%s) failed: %s", t->src_name, strerror(errno));
1012 return -1;
1013 } else if (bytes == 0) {
1014 transfer_debug("%s EOF (with %i bytes in buffer)",
1015 t->src_name, t->bufuse);
1016 t->state = SSTATE_FLUSHING;
1017 } else if (bytes > 0) {
1018 t->bufuse += bytes;
1019 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1020 (int)bytes, t->src_name, (int)t->bufuse);
1022 return 0;
1025 /* Tries to write data from buffer into destination. If buffer is empty,
1026 * no data is written. Returns 0 on success, -1 on error.
1028 static int udt_do_write(struct unidirectional_transfer *t)
1030 ssize_t bytes;
1032 if (t->bufuse == 0)
1033 return 0; /* Nothing to write. */
1035 transfer_debug("%s is writable", t->dest_name);
1036 bytes = write(t->dest, t->buf, t->bufuse);
1037 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1038 errno != EINTR) {
1039 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1040 return -1;
1041 } else if (bytes > 0) {
1042 t->bufuse -= bytes;
1043 if (t->bufuse)
1044 memmove(t->buf, t->buf + bytes, t->bufuse);
1045 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1046 (int)bytes, t->dest_name, (int)t->bufuse);
1048 return 0;
1052 /* State of bidirectional transfer loop. */
1053 struct bidirectional_transfer_state {
1054 /* Direction from program to git. */
1055 struct unidirectional_transfer ptg;
1056 /* Direction from git to program. */
1057 struct unidirectional_transfer gtp;
1060 static void *udt_copy_task_routine(void *udt)
1062 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1063 while (t->state != SSTATE_FINISHED) {
1064 if (STATE_NEEDS_READING(t->state))
1065 if (udt_do_read(t))
1066 return NULL;
1067 if (STATE_NEEDS_WRITING(t->state))
1068 if (udt_do_write(t))
1069 return NULL;
1070 if (STATE_NEEDS_CLOSING(t->state))
1071 udt_close_if_finished(t);
1073 return udt; /* Just some non-NULL value. */
1076 #ifndef NO_PTHREADS
1079 * Join thread, with apporiate errors on failure. Name is name for the
1080 * thread (for error messages). Returns 0 on success, 1 on failure.
1082 static int tloop_join(pthread_t thread, const char *name)
1084 int err;
1085 void *tret;
1086 err = pthread_join(thread, &tret);
1087 if (!tret) {
1088 error("%s thread failed", name);
1089 return 1;
1091 if (err) {
1092 error("%s thread failed to join: %s", name, strerror(err));
1093 return 1;
1095 return 0;
1099 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1100 * -1 on failure.
1102 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1104 pthread_t gtp_thread;
1105 pthread_t ptg_thread;
1106 int err;
1107 int ret = 0;
1108 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1109 &s->gtp);
1110 if (err)
1111 die("Can't start thread for copying data: %s", strerror(err));
1112 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1113 &s->ptg);
1114 if (err)
1115 die("Can't start thread for copying data: %s", strerror(err));
1117 ret |= tloop_join(gtp_thread, "Git to program copy");
1118 ret |= tloop_join(ptg_thread, "Program to git copy");
1119 return ret;
1121 #else
1123 /* Close the source and target (for writing) for transfer. */
1124 static void udt_kill_transfer(struct unidirectional_transfer *t)
1126 t->state = SSTATE_FINISHED;
1128 * Socket read end left open isn't a disaster if nobody
1129 * attempts to read from it (mingw compat headers do not
1130 * have SHUT_RD)...
1132 * We can't fully close the socket since otherwise gtp
1133 * task would first close the socket it sends data to
1134 * while closing the ptg file descriptors.
1136 if (!t->src_is_sock)
1137 close(t->src);
1138 if (t->dest_is_sock)
1139 shutdown(t->dest, SHUT_WR);
1140 else
1141 close(t->dest);
1145 * Join process, with apporiate errors on failure. Name is name for the
1146 * process (for error messages). Returns 0 on success, 1 on failure.
1148 static int tloop_join(pid_t pid, const char *name)
1150 int tret;
1151 if (waitpid(pid, &tret, 0) < 0) {
1152 error("%s process failed to wait: %s", name, strerror(errno));
1153 return 1;
1155 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1156 error("%s process failed", name);
1157 return 1;
1159 return 0;
1163 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1164 * -1 on failure.
1166 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1168 pid_t pid1, pid2;
1169 int ret = 0;
1171 /* Fork thread #1: git to program. */
1172 pid1 = fork();
1173 if (pid1 < 0)
1174 die_errno("Can't start thread for copying data");
1175 else if (pid1 == 0) {
1176 udt_kill_transfer(&s->ptg);
1177 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1180 /* Fork thread #2: program to git. */
1181 pid2 = fork();
1182 if (pid2 < 0)
1183 die_errno("Can't start thread for copying data");
1184 else if (pid2 == 0) {
1185 udt_kill_transfer(&s->gtp);
1186 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1190 * Close both streams in parent as to not interfere with
1191 * end of file detection and wait for both tasks to finish.
1193 udt_kill_transfer(&s->gtp);
1194 udt_kill_transfer(&s->ptg);
1195 ret |= tloop_join(pid1, "Git to program copy");
1196 ret |= tloop_join(pid2, "Program to git copy");
1197 return ret;
1199 #endif
1202 * Copies data from stdin to output and from input to stdout simultaneously.
1203 * Additionally filtering through given filter. If filter is NULL, uses
1204 * identity filter.
1206 int bidirectional_transfer_loop(int input, int output)
1208 struct bidirectional_transfer_state state;
1210 /* Fill the state fields. */
1211 state.ptg.src = input;
1212 state.ptg.dest = 1;
1213 state.ptg.src_is_sock = (input == output);
1214 state.ptg.dest_is_sock = 0;
1215 state.ptg.state = SSTATE_TRANSFERING;
1216 state.ptg.bufuse = 0;
1217 state.ptg.src_name = "remote input";
1218 state.ptg.dest_name = "stdout";
1220 state.gtp.src = 0;
1221 state.gtp.dest = output;
1222 state.gtp.src_is_sock = 0;
1223 state.gtp.dest_is_sock = (input == output);
1224 state.gtp.state = SSTATE_TRANSFERING;
1225 state.gtp.bufuse = 0;
1226 state.gtp.src_name = "stdin";
1227 state.gtp.dest_name = "remote output";
1229 return tloop_spawnwait_tasks(&state);