compat/terminal: support echoing on windows
[git/dscho.git] / transport-helper.c
blob6d62e971c9bd9f3cd889fdb92e3fcfdfd32982a8
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;
467 * The fast-import stream of a remote helper that advertises
468 * the "refspec" capability writes to the refs named after the
469 * right hand side of the first refspec matching each ref we
470 * were fetching.
472 * (If no "refspec" capability was specified, for historical
473 * reasons we default to *:*.)
475 * Store the result in to_fetch[i].old_sha1. Callers such
476 * as "git fetch" can use the value to write feedback to the
477 * terminal, populate FETCH_HEAD, and determine what new value
478 * should be written to peer_ref if the update is a
479 * fast-forward or this is a forced update.
481 for (i = 0; i < nr_heads; i++) {
482 char *private;
483 posn = to_fetch[i];
484 if (posn->status & REF_STATUS_UPTODATE)
485 continue;
486 if (data->refspecs)
487 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
488 else
489 private = xstrdup(posn->name);
490 if (private) {
491 read_ref(private, posn->old_sha1);
492 free(private);
495 strbuf_release(&buf);
496 if (auto_gc) {
497 const char *argv_gc_auto[] = {
498 "gc", "--auto", "--quiet", NULL,
500 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
502 return 0;
505 static int process_connect_service(struct transport *transport,
506 const char *name, const char *exec)
508 struct helper_data *data = transport->data;
509 struct strbuf cmdbuf = STRBUF_INIT;
510 struct child_process *helper;
511 int r, duped, ret = 0;
512 FILE *input;
514 helper = get_helper(transport);
517 * Yes, dup the pipe another time, as we need unbuffered version
518 * of input pipe as FILE*. fclose() closes the underlying fd and
519 * stream buffering only can be changed before first I/O operation
520 * on it.
522 duped = dup(helper->out);
523 if (duped < 0)
524 die_errno("Can't dup helper output fd");
525 input = xfdopen(duped, "r");
526 setvbuf(input, NULL, _IONBF, 0);
529 * Handle --upload-pack and friends. This is fire and forget...
530 * just warn if it fails.
532 if (strcmp(name, exec)) {
533 r = set_helper_option(transport, "servpath", exec);
534 if (r > 0)
535 warning("Setting remote service path not supported by protocol.");
536 else if (r < 0)
537 warning("Invalid remote service path.");
540 if (data->connect)
541 strbuf_addf(&cmdbuf, "connect %s\n", name);
542 else
543 goto exit;
545 sendline(data, &cmdbuf);
546 recvline_fh(input, &cmdbuf);
547 if (!strcmp(cmdbuf.buf, "")) {
548 data->no_disconnect_req = 1;
549 if (debug)
550 fprintf(stderr, "Debug: Smart transport connection "
551 "ready.\n");
552 ret = 1;
553 } else if (!strcmp(cmdbuf.buf, "fallback")) {
554 if (debug)
555 fprintf(stderr, "Debug: Falling back to dumb "
556 "transport.\n");
557 } else
558 die("Unknown response to connect: %s",
559 cmdbuf.buf);
561 exit:
562 fclose(input);
563 return ret;
566 static int process_connect(struct transport *transport,
567 int for_push)
569 struct helper_data *data = transport->data;
570 const char *name;
571 const char *exec;
573 name = for_push ? "git-receive-pack" : "git-upload-pack";
574 if (for_push)
575 exec = data->transport_options.receivepack;
576 else
577 exec = data->transport_options.uploadpack;
579 return process_connect_service(transport, name, exec);
582 static int connect_helper(struct transport *transport, const char *name,
583 const char *exec, int fd[2])
585 struct helper_data *data = transport->data;
587 /* Get_helper so connect is inited. */
588 get_helper(transport);
589 if (!data->connect)
590 die("Operation not supported by protocol.");
592 if (!process_connect_service(transport, name, exec))
593 die("Can't connect to subservice %s.", name);
595 fd[0] = data->helper->out;
596 fd[1] = data->helper->in;
597 return 0;
600 static int fetch(struct transport *transport,
601 int nr_heads, struct ref **to_fetch)
603 struct helper_data *data = transport->data;
604 int i, count;
606 if (process_connect(transport, 0)) {
607 do_take_over(transport);
608 return transport->fetch(transport, nr_heads, to_fetch);
611 count = 0;
612 for (i = 0; i < nr_heads; i++)
613 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
614 count++;
616 if (!count)
617 return 0;
619 if (data->fetch)
620 return fetch_with_fetch(transport, nr_heads, to_fetch);
622 if (data->import)
623 return fetch_with_import(transport, nr_heads, to_fetch);
625 return -1;
628 static void push_update_ref_status(struct strbuf *buf,
629 struct ref **ref,
630 struct ref *remote_refs)
632 char *refname, *msg;
633 int status;
635 if (!prefixcmp(buf->buf, "ok ")) {
636 status = REF_STATUS_OK;
637 refname = buf->buf + 3;
638 } else if (!prefixcmp(buf->buf, "error ")) {
639 status = REF_STATUS_REMOTE_REJECT;
640 refname = buf->buf + 6;
641 } else
642 die("expected ok/error, helper said '%s'", buf->buf);
644 msg = strchr(refname, ' ');
645 if (msg) {
646 struct strbuf msg_buf = STRBUF_INIT;
647 const char *end;
649 *msg++ = '\0';
650 if (!unquote_c_style(&msg_buf, msg, &end))
651 msg = strbuf_detach(&msg_buf, NULL);
652 else
653 msg = xstrdup(msg);
654 strbuf_release(&msg_buf);
656 if (!strcmp(msg, "no match")) {
657 status = REF_STATUS_NONE;
658 free(msg);
659 msg = NULL;
661 else if (!strcmp(msg, "up to date")) {
662 status = REF_STATUS_UPTODATE;
663 free(msg);
664 msg = NULL;
666 else if (!strcmp(msg, "non-fast forward")) {
667 status = REF_STATUS_REJECT_NONFASTFORWARD;
668 free(msg);
669 msg = NULL;
673 if (*ref)
674 *ref = find_ref_by_name(*ref, refname);
675 if (!*ref)
676 *ref = find_ref_by_name(remote_refs, refname);
677 if (!*ref) {
678 warning("helper reported unexpected status of %s", refname);
679 return;
682 if ((*ref)->status != REF_STATUS_NONE) {
684 * Earlier, the ref was marked not to be pushed, so ignore the ref
685 * status reported by the remote helper if the latter is 'no match'.
687 if (status == REF_STATUS_NONE)
688 return;
691 (*ref)->status = status;
692 (*ref)->remote_status = msg;
695 static void push_update_refs_status(struct helper_data *data,
696 struct ref *remote_refs)
698 struct strbuf buf = STRBUF_INIT;
699 struct ref *ref = remote_refs;
700 for (;;) {
701 recvline(data, &buf);
702 if (!buf.len)
703 break;
705 push_update_ref_status(&buf, &ref, remote_refs);
707 strbuf_release(&buf);
710 static int push_refs_with_push(struct transport *transport,
711 struct ref *remote_refs, int flags)
713 int force_all = flags & TRANSPORT_PUSH_FORCE;
714 int mirror = flags & TRANSPORT_PUSH_MIRROR;
715 struct helper_data *data = transport->data;
716 struct strbuf buf = STRBUF_INIT;
717 struct ref *ref;
719 get_helper(transport);
720 if (!data->push)
721 return 1;
723 for (ref = remote_refs; ref; ref = ref->next) {
724 if (!ref->peer_ref && !mirror)
725 continue;
727 /* Check for statuses set by set_ref_status_for_push() */
728 switch (ref->status) {
729 case REF_STATUS_REJECT_NONFASTFORWARD:
730 case REF_STATUS_UPTODATE:
731 continue;
732 default:
733 ; /* do nothing */
736 if (force_all)
737 ref->force = 1;
739 strbuf_addstr(&buf, "push ");
740 if (!ref->deletion) {
741 if (ref->force)
742 strbuf_addch(&buf, '+');
743 if (ref->peer_ref)
744 strbuf_addstr(&buf, ref->peer_ref->name);
745 else
746 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
748 strbuf_addch(&buf, ':');
749 strbuf_addstr(&buf, ref->name);
750 strbuf_addch(&buf, '\n');
752 if (buf.len == 0)
753 return 0;
755 standard_options(transport);
757 if (flags & TRANSPORT_PUSH_DRY_RUN) {
758 if (set_helper_option(transport, "dry-run", "true") != 0)
759 die("helper %s does not support dry-run", data->name);
762 strbuf_addch(&buf, '\n');
763 sendline(data, &buf);
764 strbuf_release(&buf);
766 push_update_refs_status(data, remote_refs);
767 return 0;
770 static int push_refs_with_export(struct transport *transport,
771 struct ref *remote_refs, int flags)
773 struct ref *ref;
774 struct child_process *helper, exporter;
775 struct helper_data *data = transport->data;
776 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
777 struct strbuf buf = STRBUF_INIT;
779 helper = get_helper(transport);
781 write_constant(helper->in, "export\n");
783 strbuf_reset(&buf);
785 for (ref = remote_refs; ref; ref = ref->next) {
786 char *private;
787 unsigned char sha1[20];
789 if (!data->refspecs)
790 continue;
791 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
792 if (private && !get_sha1(private, sha1)) {
793 strbuf_addf(&buf, "^%s", private);
794 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
796 free(private);
798 if (ref->deletion) {
799 die("remote-helpers do not support ref deletion");
802 if (ref->peer_ref)
803 string_list_append(&revlist_args, ref->peer_ref->name);
807 if (get_exporter(transport, &exporter, &revlist_args))
808 die("Couldn't run fast-export");
810 if (finish_command(&exporter))
811 die("Error while running fast-export");
812 check_helper_status(data);
813 push_update_refs_status(data, remote_refs);
814 return 0;
817 static int push_refs(struct transport *transport,
818 struct ref *remote_refs, int flags)
820 struct helper_data *data = transport->data;
822 if (process_connect(transport, 1)) {
823 do_take_over(transport);
824 return transport->push_refs(transport, remote_refs, flags);
827 if (!remote_refs) {
828 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
829 "Perhaps you should specify a branch such as 'master'.\n");
830 return 0;
833 if (data->push)
834 return push_refs_with_push(transport, remote_refs, flags);
836 if (data->export)
837 return push_refs_with_export(transport, remote_refs, flags);
839 return -1;
843 static int has_attribute(const char *attrs, const char *attr) {
844 int len;
845 if (!attrs)
846 return 0;
848 len = strlen(attr);
849 for (;;) {
850 const char *space = strchrnul(attrs, ' ');
851 if (len == space - attrs && !strncmp(attrs, attr, len))
852 return 1;
853 if (!*space)
854 return 0;
855 attrs = space + 1;
859 static struct ref *get_refs_list(struct transport *transport, int for_push)
861 struct helper_data *data = transport->data;
862 struct child_process *helper;
863 struct ref *ret = NULL;
864 struct ref **tail = &ret;
865 struct ref *posn;
866 struct strbuf buf = STRBUF_INIT;
868 helper = get_helper(transport);
870 if (process_connect(transport, for_push)) {
871 do_take_over(transport);
872 return transport->get_refs_list(transport, for_push);
875 if (data->push && for_push)
876 write_str_in_full(helper->in, "list for-push\n");
877 else
878 write_str_in_full(helper->in, "list\n");
880 while (1) {
881 char *eov, *eon;
882 recvline(data, &buf);
884 if (!*buf.buf)
885 break;
887 eov = strchr(buf.buf, ' ');
888 if (!eov)
889 die("Malformed response in ref list: %s", buf.buf);
890 eon = strchr(eov + 1, ' ');
891 *eov = '\0';
892 if (eon)
893 *eon = '\0';
894 *tail = alloc_ref(eov + 1);
895 if (buf.buf[0] == '@')
896 (*tail)->symref = xstrdup(buf.buf + 1);
897 else if (buf.buf[0] != '?')
898 get_sha1_hex(buf.buf, (*tail)->old_sha1);
899 if (eon) {
900 if (has_attribute(eon + 1, "unchanged")) {
901 (*tail)->status |= REF_STATUS_UPTODATE;
902 read_ref((*tail)->name, (*tail)->old_sha1);
905 tail = &((*tail)->next);
907 if (debug)
908 fprintf(stderr, "Debug: Read ref listing.\n");
909 strbuf_release(&buf);
911 for (posn = ret; posn; posn = posn->next)
912 resolve_remote_symref(posn, ret);
914 return ret;
917 int transport_helper_init(struct transport *transport, const char *name)
919 struct helper_data *data = xcalloc(sizeof(*data), 1);
920 data->name = name;
922 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
923 debug = 1;
925 transport->data = data;
926 transport->set_option = set_helper_option;
927 transport->get_refs_list = get_refs_list;
928 transport->fetch = fetch;
929 transport->push_refs = push_refs;
930 transport->disconnect = release_helper;
931 transport->connect = connect_helper;
932 transport->smart_options = &(data->transport_options);
933 return 0;
937 * Linux pipes can buffer 65536 bytes at once (and most platforms can
938 * buffer less), so attempt reads and writes with up to that size.
940 #define BUFFERSIZE 65536
941 /* This should be enough to hold debugging message. */
942 #define PBUFFERSIZE 8192
944 /* Print bidirectional transfer loop debug message. */
945 static void transfer_debug(const char *fmt, ...)
947 va_list args;
948 char msgbuf[PBUFFERSIZE];
949 static int debug_enabled = -1;
951 if (debug_enabled < 0)
952 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
953 if (!debug_enabled)
954 return;
956 va_start(args, fmt);
957 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
958 va_end(args);
959 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
962 /* Stream state: More data may be coming in this direction. */
963 #define SSTATE_TRANSFERING 0
965 * Stream state: No more data coming in this direction, flushing rest of
966 * data.
968 #define SSTATE_FLUSHING 1
969 /* Stream state: Transfer in this direction finished. */
970 #define SSTATE_FINISHED 2
972 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
973 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
974 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
976 /* Unidirectional transfer. */
977 struct unidirectional_transfer {
978 /* Source */
979 int src;
980 /* Destination */
981 int dest;
982 /* Is source socket? */
983 int src_is_sock;
984 /* Is destination socket? */
985 int dest_is_sock;
986 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
987 int state;
988 /* Buffer. */
989 char buf[BUFFERSIZE];
990 /* Buffer used. */
991 size_t bufuse;
992 /* Name of source. */
993 const char *src_name;
994 /* Name of destination. */
995 const char *dest_name;
998 /* Closes the target (for writing) if transfer has finished. */
999 static void udt_close_if_finished(struct unidirectional_transfer *t)
1001 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1002 t->state = SSTATE_FINISHED;
1003 if (t->dest_is_sock)
1004 shutdown(t->dest, SHUT_WR);
1005 else
1006 close(t->dest);
1007 transfer_debug("Closed %s.", t->dest_name);
1012 * Tries to read read data from source into buffer. If buffer is full,
1013 * no data is read. Returns 0 on success, -1 on error.
1015 static int udt_do_read(struct unidirectional_transfer *t)
1017 ssize_t bytes;
1019 if (t->bufuse == BUFFERSIZE)
1020 return 0; /* No space for more. */
1022 transfer_debug("%s is readable", t->src_name);
1023 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1024 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1025 errno != EINTR) {
1026 error("read(%s) failed: %s", t->src_name, strerror(errno));
1027 return -1;
1028 } else if (bytes == 0) {
1029 transfer_debug("%s EOF (with %i bytes in buffer)",
1030 t->src_name, t->bufuse);
1031 t->state = SSTATE_FLUSHING;
1032 } else if (bytes > 0) {
1033 t->bufuse += bytes;
1034 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1035 (int)bytes, t->src_name, (int)t->bufuse);
1037 return 0;
1040 /* Tries to write data from buffer into destination. If buffer is empty,
1041 * no data is written. Returns 0 on success, -1 on error.
1043 static int udt_do_write(struct unidirectional_transfer *t)
1045 ssize_t bytes;
1047 if (t->bufuse == 0)
1048 return 0; /* Nothing to write. */
1050 transfer_debug("%s is writable", t->dest_name);
1051 bytes = write(t->dest, t->buf, t->bufuse);
1052 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1053 errno != EINTR) {
1054 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1055 return -1;
1056 } else if (bytes > 0) {
1057 t->bufuse -= bytes;
1058 if (t->bufuse)
1059 memmove(t->buf, t->buf + bytes, t->bufuse);
1060 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1061 (int)bytes, t->dest_name, (int)t->bufuse);
1063 return 0;
1067 /* State of bidirectional transfer loop. */
1068 struct bidirectional_transfer_state {
1069 /* Direction from program to git. */
1070 struct unidirectional_transfer ptg;
1071 /* Direction from git to program. */
1072 struct unidirectional_transfer gtp;
1075 static void *udt_copy_task_routine(void *udt)
1077 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1078 while (t->state != SSTATE_FINISHED) {
1079 if (STATE_NEEDS_READING(t->state))
1080 if (udt_do_read(t))
1081 return NULL;
1082 if (STATE_NEEDS_WRITING(t->state))
1083 if (udt_do_write(t))
1084 return NULL;
1085 if (STATE_NEEDS_CLOSING(t->state))
1086 udt_close_if_finished(t);
1088 return udt; /* Just some non-NULL value. */
1091 #ifndef NO_PTHREADS
1094 * Join thread, with apporiate errors on failure. Name is name for the
1095 * thread (for error messages). Returns 0 on success, 1 on failure.
1097 static int tloop_join(pthread_t thread, const char *name)
1099 int err;
1100 void *tret;
1101 err = pthread_join(thread, &tret);
1102 if (!tret) {
1103 error("%s thread failed", name);
1104 return 1;
1106 if (err) {
1107 error("%s thread failed to join: %s", name, strerror(err));
1108 return 1;
1110 return 0;
1114 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1115 * -1 on failure.
1117 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1119 pthread_t gtp_thread;
1120 pthread_t ptg_thread;
1121 int err;
1122 int ret = 0;
1123 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1124 &s->gtp);
1125 if (err)
1126 die("Can't start thread for copying data: %s", strerror(err));
1127 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1128 &s->ptg);
1129 if (err)
1130 die("Can't start thread for copying data: %s", strerror(err));
1132 ret |= tloop_join(gtp_thread, "Git to program copy");
1133 ret |= tloop_join(ptg_thread, "Program to git copy");
1134 return ret;
1136 #else
1138 /* Close the source and target (for writing) for transfer. */
1139 static void udt_kill_transfer(struct unidirectional_transfer *t)
1141 t->state = SSTATE_FINISHED;
1143 * Socket read end left open isn't a disaster if nobody
1144 * attempts to read from it (mingw compat headers do not
1145 * have SHUT_RD)...
1147 * We can't fully close the socket since otherwise gtp
1148 * task would first close the socket it sends data to
1149 * while closing the ptg file descriptors.
1151 if (!t->src_is_sock)
1152 close(t->src);
1153 if (t->dest_is_sock)
1154 shutdown(t->dest, SHUT_WR);
1155 else
1156 close(t->dest);
1160 * Join process, with apporiate errors on failure. Name is name for the
1161 * process (for error messages). Returns 0 on success, 1 on failure.
1163 static int tloop_join(pid_t pid, const char *name)
1165 int tret;
1166 if (waitpid(pid, &tret, 0) < 0) {
1167 error("%s process failed to wait: %s", name, strerror(errno));
1168 return 1;
1170 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1171 error("%s process failed", name);
1172 return 1;
1174 return 0;
1178 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1179 * -1 on failure.
1181 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1183 pid_t pid1, pid2;
1184 int ret = 0;
1186 /* Fork thread #1: git to program. */
1187 pid1 = fork();
1188 if (pid1 < 0)
1189 die_errno("Can't start thread for copying data");
1190 else if (pid1 == 0) {
1191 udt_kill_transfer(&s->ptg);
1192 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1195 /* Fork thread #2: program to git. */
1196 pid2 = fork();
1197 if (pid2 < 0)
1198 die_errno("Can't start thread for copying data");
1199 else if (pid2 == 0) {
1200 udt_kill_transfer(&s->gtp);
1201 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1205 * Close both streams in parent as to not interfere with
1206 * end of file detection and wait for both tasks to finish.
1208 udt_kill_transfer(&s->gtp);
1209 udt_kill_transfer(&s->ptg);
1210 ret |= tloop_join(pid1, "Git to program copy");
1211 ret |= tloop_join(pid2, "Program to git copy");
1212 return ret;
1214 #endif
1217 * Copies data from stdin to output and from input to stdout simultaneously.
1218 * Additionally filtering through given filter. If filter is NULL, uses
1219 * identity filter.
1221 int bidirectional_transfer_loop(int input, int output)
1223 struct bidirectional_transfer_state state;
1225 /* Fill the state fields. */
1226 state.ptg.src = input;
1227 state.ptg.dest = 1;
1228 state.ptg.src_is_sock = (input == output);
1229 state.ptg.dest_is_sock = 0;
1230 state.ptg.state = SSTATE_TRANSFERING;
1231 state.ptg.bufuse = 0;
1232 state.ptg.src_name = "remote input";
1233 state.ptg.dest_name = "stdout";
1235 state.gtp.src = 0;
1236 state.gtp.dest = output;
1237 state.gtp.src_is_sock = 0;
1238 state.gtp.dest_is_sock = (input == output);
1239 state.gtp.state = SSTATE_TRANSFERING;
1240 state.gtp.bufuse = 0;
1241 state.gtp.src_name = "stdin";
1242 state.gtp.dest_name = "remote output";
1244 return tloop_spawnwait_tasks(&state);