transport-helper: add trailing --
[git/dscho.git] / transport-helper.c
blob1e03609729186f81a8466d003048a2c696cb4f09
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;
16 struct helper_data {
17 const char *name;
18 struct child_process *helper;
19 FILE *out;
20 unsigned fetch : 1,
21 import : 1,
22 export : 1,
23 option : 1,
24 push : 1,
25 connect : 1,
26 no_disconnect_req : 1;
27 char *export_marks;
28 char *import_marks;
29 /* These go from remote name (as in "list") to private name */
30 struct refspec *refspecs;
31 int refspec_nr;
32 /* Transport options for fetch-pack/send-pack (should one of
33 * those be invoked).
35 struct git_transport_options transport_options;
38 static void sendline(struct helper_data *helper, struct strbuf *buffer)
40 if (debug)
41 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
42 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
43 != buffer->len)
44 die_errno("Full write to remote helper failed");
47 static int recvline_fh(FILE *helper, struct strbuf *buffer)
49 strbuf_reset(buffer);
50 if (debug)
51 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
52 if (strbuf_getline(buffer, helper, '\n') == EOF) {
53 if (debug)
54 fprintf(stderr, "Debug: Remote helper quit.\n");
55 exit(128);
58 if (debug)
59 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
60 return 0;
63 static int recvline(struct helper_data *helper, struct strbuf *buffer)
65 return recvline_fh(helper->out, buffer);
68 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
70 sendline(helper, buffer);
71 recvline(helper, buffer);
74 static void write_constant(int fd, const char *str)
76 if (debug)
77 fprintf(stderr, "Debug: Remote helper: -> %s", str);
78 if (write_in_full(fd, str, strlen(str)) != strlen(str))
79 die_errno("Full write to remote helper failed");
82 static const char *remove_ext_force(const char *url)
84 if (url) {
85 const char *colon = strchr(url, ':');
86 if (colon && colon[1] == ':')
87 return colon + 2;
89 return url;
92 static void do_take_over(struct transport *transport)
94 struct helper_data *data;
95 data = (struct helper_data *)transport->data;
96 transport_take_over(transport, data->helper);
97 fclose(data->out);
98 free(data);
101 static struct child_process *get_helper(struct transport *transport)
103 struct helper_data *data = transport->data;
104 struct strbuf buf = STRBUF_INIT;
105 struct child_process *helper;
106 const char **refspecs = NULL;
107 int refspec_nr = 0;
108 int refspec_alloc = 0;
109 int duped;
110 int code;
111 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
112 const char *helper_env[] = {
113 git_dir_buf,
114 NULL
118 if (data->helper)
119 return data->helper;
121 helper = xcalloc(1, sizeof(*helper));
122 helper->in = -1;
123 helper->out = -1;
124 helper->err = 0;
125 helper->argv = xcalloc(4, sizeof(*helper->argv));
126 strbuf_addf(&buf, "git-remote-%s", data->name);
127 helper->argv[0] = strbuf_detach(&buf, NULL);
128 helper->argv[1] = transport->remote->name;
129 helper->argv[2] = remove_ext_force(transport->url);
130 helper->git_cmd = 0;
131 helper->silent_exec_failure = 1;
133 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
134 helper->env = helper_env;
136 code = start_command(helper);
137 if (code < 0 && errno == ENOENT)
138 die("Unable to find remote helper for '%s'", data->name);
139 else if (code != 0)
140 exit(code);
142 data->helper = helper;
143 data->no_disconnect_req = 0;
146 * Open the output as FILE* so strbuf_getline() can be used.
147 * Do this with duped fd because fclose() will close the fd,
148 * and stuff like taking over will require the fd to remain.
150 duped = dup(helper->out);
151 if (duped < 0)
152 die_errno("Can't dup helper output fd");
153 data->out = xfdopen(duped, "r");
155 write_constant(helper->in, "capabilities\n");
157 while (1) {
158 const char *capname;
159 int mandatory = 0;
160 recvline(data, &buf);
162 if (!*buf.buf)
163 break;
165 if (*buf.buf == '*') {
166 capname = buf.buf + 1;
167 mandatory = 1;
168 } else
169 capname = buf.buf;
171 if (debug)
172 fprintf(stderr, "Debug: Got cap %s\n", capname);
173 if (!strcmp(capname, "fetch"))
174 data->fetch = 1;
175 else if (!strcmp(capname, "option"))
176 data->option = 1;
177 else if (!strcmp(capname, "push"))
178 data->push = 1;
179 else if (!strcmp(capname, "import"))
180 data->import = 1;
181 else if (!strcmp(capname, "export"))
182 data->export = 1;
183 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
184 ALLOC_GROW(refspecs,
185 refspec_nr + 1,
186 refspec_alloc);
187 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
188 } else if (!strcmp(capname, "connect")) {
189 data->connect = 1;
190 } else if (!prefixcmp(capname, "export-marks ")) {
191 struct strbuf arg = STRBUF_INIT;
192 strbuf_addstr(&arg, "--export-marks=");
193 strbuf_addstr(&arg, capname + strlen("export-marks "));
194 data->export_marks = strbuf_detach(&arg, NULL);
195 } else if (!prefixcmp(capname, "import-marks")) {
196 struct strbuf arg = STRBUF_INIT;
197 strbuf_addstr(&arg, "--import-marks=");
198 strbuf_addstr(&arg, capname + strlen("import-marks "));
199 data->import_marks = strbuf_detach(&arg, NULL);
200 } else if (mandatory) {
201 die("Unknown mandatory capability %s. This remote "
202 "helper probably needs newer version of Git.",
203 capname);
206 if (refspecs) {
207 int i;
208 data->refspec_nr = refspec_nr;
209 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
210 for (i = 0; i < refspec_nr; i++) {
211 free((char *)refspecs[i]);
213 free(refspecs);
215 strbuf_release(&buf);
216 if (debug)
217 fprintf(stderr, "Debug: Capabilities complete.\n");
218 return data->helper;
221 static int disconnect_helper(struct transport *transport)
223 struct helper_data *data = transport->data;
224 int res = 0;
226 if (data->helper) {
227 if (debug)
228 fprintf(stderr, "Debug: Disconnecting.\n");
229 if (!data->no_disconnect_req) {
231 * Ignore write errors; there's nothing we can do,
232 * since we're about to close the pipe anyway. And the
233 * most likely error is EPIPE due to the helper dying
234 * to report an error itself.
236 sigchain_push(SIGPIPE, SIG_IGN);
237 xwrite(data->helper->in, "\n", 1);
238 sigchain_pop(SIGPIPE);
240 close(data->helper->in);
241 close(data->helper->out);
242 fclose(data->out);
243 res = finish_command(data->helper);
244 free((char *)data->helper->argv[0]);
245 free(data->helper->argv);
246 free(data->helper);
247 data->helper = NULL;
249 return res;
252 static const char *unsupported_options[] = {
253 TRANS_OPT_UPLOADPACK,
254 TRANS_OPT_RECEIVEPACK,
255 TRANS_OPT_THIN,
256 TRANS_OPT_KEEP
258 static const char *boolean_options[] = {
259 TRANS_OPT_THIN,
260 TRANS_OPT_KEEP,
261 TRANS_OPT_FOLLOWTAGS
264 static int set_helper_option(struct transport *transport,
265 const char *name, const char *value)
267 struct helper_data *data = transport->data;
268 struct strbuf buf = STRBUF_INIT;
269 int i, ret, is_bool = 0;
271 get_helper(transport);
273 if (!data->option)
274 return 1;
276 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
277 if (!strcmp(name, unsupported_options[i]))
278 return 1;
281 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
282 if (!strcmp(name, boolean_options[i])) {
283 is_bool = 1;
284 break;
288 strbuf_addf(&buf, "option %s ", name);
289 if (is_bool)
290 strbuf_addstr(&buf, value ? "true" : "false");
291 else
292 quote_c_style(value, &buf, NULL, 0);
293 strbuf_addch(&buf, '\n');
295 xchgline(data, &buf);
297 if (!strcmp(buf.buf, "ok"))
298 ret = 0;
299 else if (!prefixcmp(buf.buf, "error")) {
300 ret = -1;
301 } else if (!strcmp(buf.buf, "unsupported"))
302 ret = 1;
303 else {
304 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
305 ret = 1;
307 strbuf_release(&buf);
308 return ret;
311 static void standard_options(struct transport *t)
313 char buf[16];
314 int n;
315 int v = t->verbose;
317 set_helper_option(t, "progress", t->progress ? "true" : "false");
319 n = snprintf(buf, sizeof(buf), "%d", v + 1);
320 if (n >= sizeof(buf))
321 die("impossibly large verbosity value");
322 set_helper_option(t, "verbosity", buf);
325 static int release_helper(struct transport *transport)
327 int res = 0;
328 struct helper_data *data = transport->data;
329 free_refspec(data->refspec_nr, data->refspecs);
330 data->refspecs = NULL;
331 res = disconnect_helper(transport);
332 free(transport->data);
333 return res;
336 static int fetch_with_fetch(struct transport *transport,
337 int nr_heads, struct ref **to_fetch)
339 struct helper_data *data = transport->data;
340 int i;
341 struct strbuf buf = STRBUF_INIT;
343 standard_options(transport);
345 for (i = 0; i < nr_heads; i++) {
346 const struct ref *posn = to_fetch[i];
347 if (posn->status & REF_STATUS_UPTODATE)
348 continue;
350 strbuf_addf(&buf, "fetch %s %s\n",
351 sha1_to_hex(posn->old_sha1), posn->name);
354 strbuf_addch(&buf, '\n');
355 sendline(data, &buf);
357 while (1) {
358 recvline(data, &buf);
360 if (!prefixcmp(buf.buf, "lock ")) {
361 const char *name = buf.buf + 5;
362 if (transport->pack_lockfile)
363 warning("%s also locked %s", data->name, name);
364 else
365 transport->pack_lockfile = xstrdup(name);
367 else if (!buf.len)
368 break;
369 else
370 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
372 strbuf_release(&buf);
373 return 0;
376 static int get_importer(struct transport *transport, struct child_process *fastimport)
378 struct child_process *helper = get_helper(transport);
379 memset(fastimport, 0, sizeof(*fastimport));
380 fastimport->in = helper->out;
381 fastimport->argv = xcalloc(5, sizeof(*fastimport->argv));
382 fastimport->argv[0] = "fast-import";
383 fastimport->argv[1] = "--quiet";
385 fastimport->git_cmd = 1;
386 return start_command(fastimport);
389 static int get_exporter(struct transport *transport,
390 struct child_process *fastexport,
391 struct string_list *revlist_args)
393 struct helper_data *data = transport->data;
394 struct child_process *helper = get_helper(transport);
395 int argc = 0, i;
396 memset(fastexport, 0, sizeof(*fastexport));
398 /* we need to duplicate helper->in because we want to use it after
399 * fastexport is done with it. */
400 fastexport->out = dup(helper->in);
401 fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
402 fastexport->argv[argc++] = "fast-export";
403 fastexport->argv[argc++] = "--use-done-feature";
404 if (data->export_marks)
405 fastexport->argv[argc++] = data->export_marks;
406 if (data->import_marks)
407 fastexport->argv[argc++] = data->import_marks;
409 for (i = 0; i < revlist_args->nr; i++)
410 fastexport->argv[argc++] = revlist_args->items[i].string;
412 fastexport->argv[argc++] = "--";
414 fastexport->git_cmd = 1;
415 return start_command(fastexport);
418 static int fetch_with_import(struct transport *transport,
419 int nr_heads, struct ref **to_fetch)
421 struct child_process fastimport;
422 struct helper_data *data = transport->data;
423 int i;
424 struct ref *posn;
425 struct strbuf buf = STRBUF_INIT;
427 get_helper(transport);
429 if (get_importer(transport, &fastimport))
430 die("Couldn't run fast-import");
432 for (i = 0; i < nr_heads; i++) {
433 posn = to_fetch[i];
434 if (posn->status & REF_STATUS_UPTODATE)
435 continue;
437 strbuf_addf(&buf, "import %s\n", posn->name);
438 sendline(data, &buf);
439 strbuf_reset(&buf);
442 write_constant(data->helper->in, "\n");
444 if (finish_command(&fastimport))
445 die("Error while running fast-import");
446 free(fastimport.argv);
447 fastimport.argv = NULL;
450 * The fast-import stream of a remote helper that advertises
451 * the "refspec" capability writes to the refs named after the
452 * right hand side of the first refspec matching each ref we
453 * were fetching.
455 * (If no "refspec" capability was specified, for historical
456 * reasons we default to *:*.)
458 * Store the result in to_fetch[i].old_sha1. Callers such
459 * as "git fetch" can use the value to write feedback to the
460 * terminal, populate FETCH_HEAD, and determine what new value
461 * should be written to peer_ref if the update is a
462 * fast-forward or this is a forced update.
464 for (i = 0; i < nr_heads; i++) {
465 char *private;
466 posn = to_fetch[i];
467 if (posn->status & REF_STATUS_UPTODATE)
468 continue;
469 if (data->refspecs)
470 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
471 else
472 private = xstrdup(posn->name);
473 if (private) {
474 read_ref(private, posn->old_sha1);
475 free(private);
478 strbuf_release(&buf);
479 return 0;
482 static int process_connect_service(struct transport *transport,
483 const char *name, const char *exec)
485 struct helper_data *data = transport->data;
486 struct strbuf cmdbuf = STRBUF_INIT;
487 struct child_process *helper;
488 int r, duped, ret = 0;
489 FILE *input;
491 helper = get_helper(transport);
494 * Yes, dup the pipe another time, as we need unbuffered version
495 * of input pipe as FILE*. fclose() closes the underlying fd and
496 * stream buffering only can be changed before first I/O operation
497 * on it.
499 duped = dup(helper->out);
500 if (duped < 0)
501 die_errno("Can't dup helper output fd");
502 input = xfdopen(duped, "r");
503 setvbuf(input, NULL, _IONBF, 0);
506 * Handle --upload-pack and friends. This is fire and forget...
507 * just warn if it fails.
509 if (strcmp(name, exec)) {
510 r = set_helper_option(transport, "servpath", exec);
511 if (r > 0)
512 warning("Setting remote service path not supported by protocol.");
513 else if (r < 0)
514 warning("Invalid remote service path.");
517 if (data->connect)
518 strbuf_addf(&cmdbuf, "connect %s\n", name);
519 else
520 goto exit;
522 sendline(data, &cmdbuf);
523 recvline_fh(input, &cmdbuf);
524 if (!strcmp(cmdbuf.buf, "")) {
525 data->no_disconnect_req = 1;
526 if (debug)
527 fprintf(stderr, "Debug: Smart transport connection "
528 "ready.\n");
529 ret = 1;
530 } else if (!strcmp(cmdbuf.buf, "fallback")) {
531 if (debug)
532 fprintf(stderr, "Debug: Falling back to dumb "
533 "transport.\n");
534 } else
535 die("Unknown response to connect: %s",
536 cmdbuf.buf);
538 exit:
539 fclose(input);
540 return ret;
543 static int process_connect(struct transport *transport,
544 int for_push)
546 struct helper_data *data = transport->data;
547 const char *name;
548 const char *exec;
550 name = for_push ? "git-receive-pack" : "git-upload-pack";
551 if (for_push)
552 exec = data->transport_options.receivepack;
553 else
554 exec = data->transport_options.uploadpack;
556 return process_connect_service(transport, name, exec);
559 static int connect_helper(struct transport *transport, const char *name,
560 const char *exec, int fd[2])
562 struct helper_data *data = transport->data;
564 /* Get_helper so connect is inited. */
565 get_helper(transport);
566 if (!data->connect)
567 die("Operation not supported by protocol.");
569 if (!process_connect_service(transport, name, exec))
570 die("Can't connect to subservice %s.", name);
572 fd[0] = data->helper->out;
573 fd[1] = data->helper->in;
574 return 0;
577 static int fetch(struct transport *transport,
578 int nr_heads, struct ref **to_fetch)
580 struct helper_data *data = transport->data;
581 int i, count;
583 if (process_connect(transport, 0)) {
584 do_take_over(transport);
585 return transport->fetch(transport, nr_heads, to_fetch);
588 count = 0;
589 for (i = 0; i < nr_heads; i++)
590 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
591 count++;
593 if (!count)
594 return 0;
596 if (data->fetch)
597 return fetch_with_fetch(transport, nr_heads, to_fetch);
599 if (data->import)
600 return fetch_with_import(transport, nr_heads, to_fetch);
602 return -1;
605 static void push_update_ref_status(struct strbuf *buf,
606 struct ref **ref,
607 struct ref *remote_refs)
609 char *refname, *msg;
610 int status;
612 if (!prefixcmp(buf->buf, "ok ")) {
613 status = REF_STATUS_OK;
614 refname = buf->buf + 3;
615 } else if (!prefixcmp(buf->buf, "error ")) {
616 status = REF_STATUS_REMOTE_REJECT;
617 refname = buf->buf + 6;
618 } else
619 die("expected ok/error, helper said '%s'", buf->buf);
621 msg = strchr(refname, ' ');
622 if (msg) {
623 struct strbuf msg_buf = STRBUF_INIT;
624 const char *end;
626 *msg++ = '\0';
627 if (!unquote_c_style(&msg_buf, msg, &end))
628 msg = strbuf_detach(&msg_buf, NULL);
629 else
630 msg = xstrdup(msg);
631 strbuf_release(&msg_buf);
633 if (!strcmp(msg, "no match")) {
634 status = REF_STATUS_NONE;
635 free(msg);
636 msg = NULL;
638 else if (!strcmp(msg, "up to date")) {
639 status = REF_STATUS_UPTODATE;
640 free(msg);
641 msg = NULL;
643 else if (!strcmp(msg, "non-fast forward")) {
644 status = REF_STATUS_REJECT_NONFASTFORWARD;
645 free(msg);
646 msg = NULL;
650 if (*ref)
651 *ref = find_ref_by_name(*ref, refname);
652 if (!*ref)
653 *ref = find_ref_by_name(remote_refs, refname);
654 if (!*ref) {
655 warning("helper reported unexpected status of %s", refname);
656 return;
659 if ((*ref)->status != REF_STATUS_NONE) {
661 * Earlier, the ref was marked not to be pushed, so ignore the ref
662 * status reported by the remote helper if the latter is 'no match'.
664 if (status == REF_STATUS_NONE)
665 return;
668 (*ref)->status = status;
669 (*ref)->remote_status = msg;
672 static void push_update_refs_status(struct helper_data *data,
673 struct ref *remote_refs)
675 struct strbuf buf = STRBUF_INIT;
676 struct ref *ref = remote_refs;
677 for (;;) {
678 recvline(data, &buf);
679 if (!buf.len)
680 break;
682 push_update_ref_status(&buf, &ref, remote_refs);
684 strbuf_release(&buf);
687 static int push_refs_with_push(struct transport *transport,
688 struct ref *remote_refs, int flags)
690 int force_all = flags & TRANSPORT_PUSH_FORCE;
691 int mirror = flags & TRANSPORT_PUSH_MIRROR;
692 struct helper_data *data = transport->data;
693 struct strbuf buf = STRBUF_INIT;
694 struct ref *ref;
696 get_helper(transport);
697 if (!data->push)
698 return 1;
700 for (ref = remote_refs; ref; ref = ref->next) {
701 if (!ref->peer_ref && !mirror)
702 continue;
704 /* Check for statuses set by set_ref_status_for_push() */
705 switch (ref->status) {
706 case REF_STATUS_REJECT_NONFASTFORWARD:
707 case REF_STATUS_UPTODATE:
708 continue;
709 default:
710 ; /* do nothing */
713 if (force_all)
714 ref->force = 1;
716 strbuf_addstr(&buf, "push ");
717 if (!ref->deletion) {
718 if (ref->force)
719 strbuf_addch(&buf, '+');
720 if (ref->peer_ref)
721 strbuf_addstr(&buf, ref->peer_ref->name);
722 else
723 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
725 strbuf_addch(&buf, ':');
726 strbuf_addstr(&buf, ref->name);
727 strbuf_addch(&buf, '\n');
729 if (buf.len == 0)
730 return 0;
732 standard_options(transport);
734 if (flags & TRANSPORT_PUSH_DRY_RUN) {
735 if (set_helper_option(transport, "dry-run", "true") != 0)
736 die("helper %s does not support dry-run", data->name);
739 strbuf_addch(&buf, '\n');
740 sendline(data, &buf);
741 strbuf_release(&buf);
743 push_update_refs_status(data, remote_refs);
744 return 0;
747 static int push_refs_with_export(struct transport *transport,
748 struct ref *remote_refs, int flags)
750 struct ref *ref;
751 struct child_process *helper, exporter;
752 struct helper_data *data = transport->data;
753 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
754 struct strbuf buf = STRBUF_INIT;
756 helper = get_helper(transport);
758 write_constant(helper->in, "export\n");
760 strbuf_reset(&buf);
762 for (ref = remote_refs; ref; ref = ref->next) {
763 char *private;
764 unsigned char sha1[20];
766 if (!data->refspecs)
767 continue;
768 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
769 if (private && !get_sha1(private, sha1)) {
770 strbuf_addf(&buf, "^%s", private);
771 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
773 free(private);
775 if (ref->deletion) {
776 die("remote-helpers do not support ref deletion");
779 if (ref->peer_ref)
780 string_list_append(&revlist_args, ref->peer_ref->name);
784 if (get_exporter(transport, &exporter, &revlist_args))
785 die("Couldn't run fast-export");
787 if (finish_command(&exporter))
788 die("Error while running fast-export");
789 push_update_refs_status(data, remote_refs);
790 return 0;
793 static int push_refs(struct transport *transport,
794 struct ref *remote_refs, int flags)
796 struct helper_data *data = transport->data;
798 if (process_connect(transport, 1)) {
799 do_take_over(transport);
800 return transport->push_refs(transport, remote_refs, flags);
803 if (!remote_refs) {
804 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
805 "Perhaps you should specify a branch such as 'master'.\n");
806 return 0;
809 if (data->push)
810 return push_refs_with_push(transport, remote_refs, flags);
812 if (data->export)
813 return push_refs_with_export(transport, remote_refs, flags);
815 return -1;
819 static int has_attribute(const char *attrs, const char *attr) {
820 int len;
821 if (!attrs)
822 return 0;
824 len = strlen(attr);
825 for (;;) {
826 const char *space = strchrnul(attrs, ' ');
827 if (len == space - attrs && !strncmp(attrs, attr, len))
828 return 1;
829 if (!*space)
830 return 0;
831 attrs = space + 1;
835 static struct ref *get_refs_list(struct transport *transport, int for_push)
837 struct helper_data *data = transport->data;
838 struct child_process *helper;
839 struct ref *ret = NULL;
840 struct ref **tail = &ret;
841 struct ref *posn;
842 struct strbuf buf = STRBUF_INIT;
844 helper = get_helper(transport);
846 if (process_connect(transport, for_push)) {
847 do_take_over(transport);
848 return transport->get_refs_list(transport, for_push);
851 if (data->push && for_push)
852 write_str_in_full(helper->in, "list for-push\n");
853 else
854 write_str_in_full(helper->in, "list\n");
856 while (1) {
857 char *eov, *eon;
858 recvline(data, &buf);
860 if (!*buf.buf)
861 break;
863 eov = strchr(buf.buf, ' ');
864 if (!eov)
865 die("Malformed response in ref list: %s", buf.buf);
866 eon = strchr(eov + 1, ' ');
867 *eov = '\0';
868 if (eon)
869 *eon = '\0';
870 *tail = alloc_ref(eov + 1);
871 if (buf.buf[0] == '@')
872 (*tail)->symref = xstrdup(buf.buf + 1);
873 else if (buf.buf[0] != '?')
874 get_sha1_hex(buf.buf, (*tail)->old_sha1);
875 if (eon) {
876 if (has_attribute(eon + 1, "unchanged")) {
877 (*tail)->status |= REF_STATUS_UPTODATE;
878 read_ref((*tail)->name, (*tail)->old_sha1);
881 tail = &((*tail)->next);
883 if (debug)
884 fprintf(stderr, "Debug: Read ref listing.\n");
885 strbuf_release(&buf);
887 for (posn = ret; posn; posn = posn->next)
888 resolve_remote_symref(posn, ret);
890 return ret;
893 int transport_helper_init(struct transport *transport, const char *name)
895 struct helper_data *data = xcalloc(sizeof(*data), 1);
896 data->name = name;
898 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
899 debug = 1;
901 transport->data = data;
902 transport->set_option = set_helper_option;
903 transport->get_refs_list = get_refs_list;
904 transport->fetch = fetch;
905 transport->push_refs = push_refs;
906 transport->disconnect = release_helper;
907 transport->connect = connect_helper;
908 transport->smart_options = &(data->transport_options);
909 return 0;
913 * Linux pipes can buffer 65536 bytes at once (and most platforms can
914 * buffer less), so attempt reads and writes with up to that size.
916 #define BUFFERSIZE 65536
917 /* This should be enough to hold debugging message. */
918 #define PBUFFERSIZE 8192
920 /* Print bidirectional transfer loop debug message. */
921 static void transfer_debug(const char *fmt, ...)
923 va_list args;
924 char msgbuf[PBUFFERSIZE];
925 static int debug_enabled = -1;
927 if (debug_enabled < 0)
928 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
929 if (!debug_enabled)
930 return;
932 va_start(args, fmt);
933 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
934 va_end(args);
935 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
938 /* Stream state: More data may be coming in this direction. */
939 #define SSTATE_TRANSFERING 0
941 * Stream state: No more data coming in this direction, flushing rest of
942 * data.
944 #define SSTATE_FLUSHING 1
945 /* Stream state: Transfer in this direction finished. */
946 #define SSTATE_FINISHED 2
948 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
949 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
950 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
952 /* Unidirectional transfer. */
953 struct unidirectional_transfer {
954 /* Source */
955 int src;
956 /* Destination */
957 int dest;
958 /* Is source socket? */
959 int src_is_sock;
960 /* Is destination socket? */
961 int dest_is_sock;
962 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
963 int state;
964 /* Buffer. */
965 char buf[BUFFERSIZE];
966 /* Buffer used. */
967 size_t bufuse;
968 /* Name of source. */
969 const char *src_name;
970 /* Name of destination. */
971 const char *dest_name;
974 /* Closes the target (for writing) if transfer has finished. */
975 static void udt_close_if_finished(struct unidirectional_transfer *t)
977 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
978 t->state = SSTATE_FINISHED;
979 if (t->dest_is_sock)
980 shutdown(t->dest, SHUT_WR);
981 else
982 close(t->dest);
983 transfer_debug("Closed %s.", t->dest_name);
988 * Tries to read read data from source into buffer. If buffer is full,
989 * no data is read. Returns 0 on success, -1 on error.
991 static int udt_do_read(struct unidirectional_transfer *t)
993 ssize_t bytes;
995 if (t->bufuse == BUFFERSIZE)
996 return 0; /* No space for more. */
998 transfer_debug("%s is readable", t->src_name);
999 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1000 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1001 errno != EINTR) {
1002 error("read(%s) failed: %s", t->src_name, strerror(errno));
1003 return -1;
1004 } else if (bytes == 0) {
1005 transfer_debug("%s EOF (with %i bytes in buffer)",
1006 t->src_name, t->bufuse);
1007 t->state = SSTATE_FLUSHING;
1008 } else if (bytes > 0) {
1009 t->bufuse += bytes;
1010 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1011 (int)bytes, t->src_name, (int)t->bufuse);
1013 return 0;
1016 /* Tries to write data from buffer into destination. If buffer is empty,
1017 * no data is written. Returns 0 on success, -1 on error.
1019 static int udt_do_write(struct unidirectional_transfer *t)
1021 ssize_t bytes;
1023 if (t->bufuse == 0)
1024 return 0; /* Nothing to write. */
1026 transfer_debug("%s is writable", t->dest_name);
1027 bytes = write(t->dest, t->buf, t->bufuse);
1028 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1029 errno != EINTR) {
1030 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1031 return -1;
1032 } else if (bytes > 0) {
1033 t->bufuse -= bytes;
1034 if (t->bufuse)
1035 memmove(t->buf, t->buf + bytes, t->bufuse);
1036 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1037 (int)bytes, t->dest_name, (int)t->bufuse);
1039 return 0;
1043 /* State of bidirectional transfer loop. */
1044 struct bidirectional_transfer_state {
1045 /* Direction from program to git. */
1046 struct unidirectional_transfer ptg;
1047 /* Direction from git to program. */
1048 struct unidirectional_transfer gtp;
1051 static void *udt_copy_task_routine(void *udt)
1053 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1054 while (t->state != SSTATE_FINISHED) {
1055 if (STATE_NEEDS_READING(t->state))
1056 if (udt_do_read(t))
1057 return NULL;
1058 if (STATE_NEEDS_WRITING(t->state))
1059 if (udt_do_write(t))
1060 return NULL;
1061 if (STATE_NEEDS_CLOSING(t->state))
1062 udt_close_if_finished(t);
1064 return udt; /* Just some non-NULL value. */
1067 #ifndef NO_PTHREADS
1070 * Join thread, with apporiate errors on failure. Name is name for the
1071 * thread (for error messages). Returns 0 on success, 1 on failure.
1073 static int tloop_join(pthread_t thread, const char *name)
1075 int err;
1076 void *tret;
1077 err = pthread_join(thread, &tret);
1078 if (!tret) {
1079 error("%s thread failed", name);
1080 return 1;
1082 if (err) {
1083 error("%s thread failed to join: %s", name, strerror(err));
1084 return 1;
1086 return 0;
1090 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1091 * -1 on failure.
1093 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1095 pthread_t gtp_thread;
1096 pthread_t ptg_thread;
1097 int err;
1098 int ret = 0;
1099 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1100 &s->gtp);
1101 if (err)
1102 die("Can't start thread for copying data: %s", strerror(err));
1103 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1104 &s->ptg);
1105 if (err)
1106 die("Can't start thread for copying data: %s", strerror(err));
1108 ret |= tloop_join(gtp_thread, "Git to program copy");
1109 ret |= tloop_join(ptg_thread, "Program to git copy");
1110 return ret;
1112 #else
1114 /* Close the source and target (for writing) for transfer. */
1115 static void udt_kill_transfer(struct unidirectional_transfer *t)
1117 t->state = SSTATE_FINISHED;
1119 * Socket read end left open isn't a disaster if nobody
1120 * attempts to read from it (mingw compat headers do not
1121 * have SHUT_RD)...
1123 * We can't fully close the socket since otherwise gtp
1124 * task would first close the socket it sends data to
1125 * while closing the ptg file descriptors.
1127 if (!t->src_is_sock)
1128 close(t->src);
1129 if (t->dest_is_sock)
1130 shutdown(t->dest, SHUT_WR);
1131 else
1132 close(t->dest);
1136 * Join process, with apporiate errors on failure. Name is name for the
1137 * process (for error messages). Returns 0 on success, 1 on failure.
1139 static int tloop_join(pid_t pid, const char *name)
1141 int tret;
1142 if (waitpid(pid, &tret, 0) < 0) {
1143 error("%s process failed to wait: %s", name, strerror(errno));
1144 return 1;
1146 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1147 error("%s process failed", name);
1148 return 1;
1150 return 0;
1154 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1155 * -1 on failure.
1157 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1159 pid_t pid1, pid2;
1160 int ret = 0;
1162 /* Fork thread #1: git to program. */
1163 pid1 = fork();
1164 if (pid1 < 0)
1165 die_errno("Can't start thread for copying data");
1166 else if (pid1 == 0) {
1167 udt_kill_transfer(&s->ptg);
1168 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1171 /* Fork thread #2: program to git. */
1172 pid2 = fork();
1173 if (pid2 < 0)
1174 die_errno("Can't start thread for copying data");
1175 else if (pid2 == 0) {
1176 udt_kill_transfer(&s->gtp);
1177 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1181 * Close both streams in parent as to not interfere with
1182 * end of file detection and wait for both tasks to finish.
1184 udt_kill_transfer(&s->gtp);
1185 udt_kill_transfer(&s->ptg);
1186 ret |= tloop_join(pid1, "Git to program copy");
1187 ret |= tloop_join(pid2, "Program to git copy");
1188 return ret;
1190 #endif
1193 * Copies data from stdin to output and from input to stdout simultaneously.
1194 * Additionally filtering through given filter. If filter is NULL, uses
1195 * identity filter.
1197 int bidirectional_transfer_loop(int input, int output)
1199 struct bidirectional_transfer_state state;
1201 /* Fill the state fields. */
1202 state.ptg.src = input;
1203 state.ptg.dest = 1;
1204 state.ptg.src_is_sock = (input == output);
1205 state.ptg.dest_is_sock = 0;
1206 state.ptg.state = SSTATE_TRANSFERING;
1207 state.ptg.bufuse = 0;
1208 state.ptg.src_name = "remote input";
1209 state.ptg.dest_name = "stdout";
1211 state.gtp.src = 0;
1212 state.gtp.dest = output;
1213 state.gtp.src_is_sock = 0;
1214 state.gtp.dest_is_sock = (input == output);
1215 state.gtp.state = SSTATE_TRANSFERING;
1216 state.gtp.bufuse = 0;
1217 state.gtp.src_name = "stdin";
1218 state.gtp.dest_name = "remote output";
1220 return tloop_spawnwait_tasks(&state);