fast-import: leakfix for 'ls' of dirty trees
[git/mjg.git] / transport-helper.c
blob4e4754c32bd53f28f9335c2a4529f5804f3086f2
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"
13 static int debug;
15 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 /* These go from remote name (as in "list") to private name */
28 struct refspec *refspecs;
29 int refspec_nr;
30 /* Transport options for fetch-pack/send-pack (should one of
31 * those be invoked).
33 struct git_transport_options transport_options;
36 static void sendline(struct helper_data *helper, struct strbuf *buffer)
38 if (debug)
39 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
40 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
41 != buffer->len)
42 die_errno("Full write to remote helper failed");
45 static int recvline_fh(FILE *helper, struct strbuf *buffer)
47 strbuf_reset(buffer);
48 if (debug)
49 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
50 if (strbuf_getline(buffer, helper, '\n') == EOF) {
51 if (debug)
52 fprintf(stderr, "Debug: Remote helper quit.\n");
53 exit(128);
56 if (debug)
57 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
58 return 0;
61 static int recvline(struct helper_data *helper, struct strbuf *buffer)
63 return recvline_fh(helper->out, buffer);
66 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
68 sendline(helper, buffer);
69 recvline(helper, buffer);
72 static void write_constant(int fd, const char *str)
74 if (debug)
75 fprintf(stderr, "Debug: Remote helper: -> %s", str);
76 if (write_in_full(fd, str, strlen(str)) != strlen(str))
77 die_errno("Full write to remote helper failed");
80 const char *remove_ext_force(const char *url)
82 if (url) {
83 const char *colon = strchr(url, ':');
84 if (colon && colon[1] == ':')
85 return colon + 2;
87 return url;
90 static void do_take_over(struct transport *transport)
92 struct helper_data *data;
93 data = (struct helper_data *)transport->data;
94 transport_take_over(transport, data->helper);
95 fclose(data->out);
96 free(data);
99 static struct child_process *get_helper(struct transport *transport)
101 struct helper_data *data = transport->data;
102 struct strbuf buf = STRBUF_INIT;
103 struct child_process *helper;
104 const char **refspecs = NULL;
105 int refspec_nr = 0;
106 int refspec_alloc = 0;
107 int duped;
108 int code;
110 if (data->helper)
111 return data->helper;
113 helper = xcalloc(1, sizeof(*helper));
114 helper->in = -1;
115 helper->out = -1;
116 helper->err = 0;
117 helper->argv = xcalloc(4, sizeof(*helper->argv));
118 strbuf_addf(&buf, "git-remote-%s", data->name);
119 helper->argv[0] = strbuf_detach(&buf, NULL);
120 helper->argv[1] = transport->remote->name;
121 helper->argv[2] = remove_ext_force(transport->url);
122 helper->git_cmd = 0;
123 helper->silent_exec_failure = 1;
124 code = start_command(helper);
125 if (code < 0 && errno == ENOENT)
126 die("Unable to find remote helper for '%s'", data->name);
127 else if (code != 0)
128 exit(code);
130 data->helper = helper;
131 data->no_disconnect_req = 0;
134 * Open the output as FILE* so strbuf_getline() can be used.
135 * Do this with duped fd because fclose() will close the fd,
136 * and stuff like taking over will require the fd to remain.
138 duped = dup(helper->out);
139 if (duped < 0)
140 die_errno("Can't dup helper output fd");
141 data->out = xfdopen(duped, "r");
143 write_constant(helper->in, "capabilities\n");
145 while (1) {
146 const char *capname;
147 int mandatory = 0;
148 recvline(data, &buf);
150 if (!*buf.buf)
151 break;
153 if (*buf.buf == '*') {
154 capname = buf.buf + 1;
155 mandatory = 1;
156 } else
157 capname = buf.buf;
159 if (debug)
160 fprintf(stderr, "Debug: Got cap %s\n", capname);
161 if (!strcmp(capname, "fetch"))
162 data->fetch = 1;
163 else if (!strcmp(capname, "option"))
164 data->option = 1;
165 else if (!strcmp(capname, "push"))
166 data->push = 1;
167 else if (!strcmp(capname, "import"))
168 data->import = 1;
169 else if (!strcmp(capname, "export"))
170 data->export = 1;
171 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
172 ALLOC_GROW(refspecs,
173 refspec_nr + 1,
174 refspec_alloc);
175 refspecs[refspec_nr++] = strdup(buf.buf + strlen("refspec "));
176 } else if (!strcmp(capname, "connect")) {
177 data->connect = 1;
178 } else if (!strcmp(buf.buf, "gitdir")) {
179 struct strbuf gitdir = STRBUF_INIT;
180 strbuf_addf(&gitdir, "gitdir %s\n", get_git_dir());
181 sendline(data, &gitdir);
182 strbuf_release(&gitdir);
183 } else if (mandatory) {
184 die("Unknown mandatory capability %s. This remote "
185 "helper probably needs newer version of Git.\n",
186 capname);
189 if (refspecs) {
190 int i;
191 data->refspec_nr = refspec_nr;
192 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
193 for (i = 0; i < refspec_nr; i++) {
194 free((char *)refspecs[i]);
196 free(refspecs);
198 strbuf_release(&buf);
199 if (debug)
200 fprintf(stderr, "Debug: Capabilities complete.\n");
201 return data->helper;
204 static int disconnect_helper(struct transport *transport)
206 struct helper_data *data = transport->data;
207 struct strbuf buf = STRBUF_INIT;
209 if (data->helper) {
210 if (debug)
211 fprintf(stderr, "Debug: Disconnecting.\n");
212 if (!data->no_disconnect_req) {
213 strbuf_addf(&buf, "\n");
214 sendline(data, &buf);
216 close(data->helper->in);
217 close(data->helper->out);
218 fclose(data->out);
219 finish_command(data->helper);
220 free((char *)data->helper->argv[0]);
221 free(data->helper->argv);
222 free(data->helper);
223 data->helper = NULL;
225 return 0;
228 static const char *unsupported_options[] = {
229 TRANS_OPT_UPLOADPACK,
230 TRANS_OPT_RECEIVEPACK,
231 TRANS_OPT_THIN,
232 TRANS_OPT_KEEP
234 static const char *boolean_options[] = {
235 TRANS_OPT_THIN,
236 TRANS_OPT_KEEP,
237 TRANS_OPT_FOLLOWTAGS
240 static int set_helper_option(struct transport *transport,
241 const char *name, const char *value)
243 struct helper_data *data = transport->data;
244 struct strbuf buf = STRBUF_INIT;
245 int i, ret, is_bool = 0;
247 get_helper(transport);
249 if (!data->option)
250 return 1;
252 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
253 if (!strcmp(name, unsupported_options[i]))
254 return 1;
257 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
258 if (!strcmp(name, boolean_options[i])) {
259 is_bool = 1;
260 break;
264 strbuf_addf(&buf, "option %s ", name);
265 if (is_bool)
266 strbuf_addstr(&buf, value ? "true" : "false");
267 else
268 quote_c_style(value, &buf, NULL, 0);
269 strbuf_addch(&buf, '\n');
271 xchgline(data, &buf);
273 if (!strcmp(buf.buf, "ok"))
274 ret = 0;
275 else if (!prefixcmp(buf.buf, "error")) {
276 ret = -1;
277 } else if (!strcmp(buf.buf, "unsupported"))
278 ret = 1;
279 else {
280 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
281 ret = 1;
283 strbuf_release(&buf);
284 return ret;
287 static void standard_options(struct transport *t)
289 char buf[16];
290 int n;
291 int v = t->verbose;
293 set_helper_option(t, "progress", t->progress ? "true" : "false");
295 n = snprintf(buf, sizeof(buf), "%d", v + 1);
296 if (n >= sizeof(buf))
297 die("impossibly large verbosity value");
298 set_helper_option(t, "verbosity", buf);
301 static int release_helper(struct transport *transport)
303 struct helper_data *data = transport->data;
304 free_refspec(data->refspec_nr, data->refspecs);
305 data->refspecs = NULL;
306 disconnect_helper(transport);
307 free(transport->data);
308 return 0;
311 static int fetch_with_fetch(struct transport *transport,
312 int nr_heads, struct ref **to_fetch)
314 struct helper_data *data = transport->data;
315 int i;
316 struct strbuf buf = STRBUF_INIT;
318 standard_options(transport);
320 for (i = 0; i < nr_heads; i++) {
321 const struct ref *posn = to_fetch[i];
322 if (posn->status & REF_STATUS_UPTODATE)
323 continue;
325 strbuf_addf(&buf, "fetch %s %s\n",
326 sha1_to_hex(posn->old_sha1), posn->name);
329 strbuf_addch(&buf, '\n');
330 sendline(data, &buf);
332 while (1) {
333 recvline(data, &buf);
335 if (!prefixcmp(buf.buf, "lock ")) {
336 const char *name = buf.buf + 5;
337 if (transport->pack_lockfile)
338 warning("%s also locked %s", data->name, name);
339 else
340 transport->pack_lockfile = xstrdup(name);
342 else if (!buf.len)
343 break;
344 else
345 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
347 strbuf_release(&buf);
348 return 0;
351 static int get_importer(struct transport *transport, struct child_process *fastimport)
353 struct child_process *helper = get_helper(transport);
354 memset(fastimport, 0, sizeof(*fastimport));
355 fastimport->in = helper->out;
356 fastimport->argv = xcalloc(5, sizeof(*fastimport->argv));
357 fastimport->argv[0] = "fast-import";
358 fastimport->argv[1] = "--quiet";
360 fastimport->git_cmd = 1;
361 return start_command(fastimport);
364 static int get_exporter(struct transport *transport,
365 struct child_process *fastexport,
366 const char *export_marks,
367 const char *import_marks,
368 struct string_list *revlist_args)
370 struct child_process *helper = get_helper(transport);
371 int argc = 0, i;
372 memset(fastexport, 0, sizeof(*fastexport));
374 /* we need to duplicate helper->in because we want to use it after
375 * fastexport is done with it. */
376 fastexport->out = dup(helper->in);
377 fastexport->argv = xcalloc(4 + revlist_args->nr, sizeof(*fastexport->argv));
378 fastexport->argv[argc++] = "fast-export";
379 if (export_marks)
380 fastexport->argv[argc++] = export_marks;
381 if (import_marks)
382 fastexport->argv[argc++] = import_marks;
384 for (i = 0; i < revlist_args->nr; i++)
385 fastexport->argv[argc++] = revlist_args->items[i].string;
387 fastexport->git_cmd = 1;
388 return start_command(fastexport);
391 static int fetch_with_import(struct transport *transport,
392 int nr_heads, struct ref **to_fetch)
394 struct child_process fastimport;
395 struct helper_data *data = transport->data;
396 int i;
397 struct ref *posn;
398 struct strbuf buf = STRBUF_INIT;
400 get_helper(transport);
402 if (get_importer(transport, &fastimport))
403 die("Couldn't run fast-import");
405 for (i = 0; i < nr_heads; i++) {
406 posn = to_fetch[i];
407 if (posn->status & REF_STATUS_UPTODATE)
408 continue;
410 strbuf_addf(&buf, "import %s\n", posn->name);
411 sendline(data, &buf);
412 strbuf_reset(&buf);
414 disconnect_helper(transport);
415 finish_command(&fastimport);
416 free(fastimport.argv);
417 fastimport.argv = NULL;
419 for (i = 0; i < nr_heads; i++) {
420 char *private;
421 posn = to_fetch[i];
422 if (posn->status & REF_STATUS_UPTODATE)
423 continue;
424 if (data->refspecs)
425 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
426 else
427 private = strdup(posn->name);
428 read_ref(private, posn->old_sha1);
429 free(private);
431 strbuf_release(&buf);
432 return 0;
435 static int process_connect_service(struct transport *transport,
436 const char *name, const char *exec)
438 struct helper_data *data = transport->data;
439 struct strbuf cmdbuf = STRBUF_INIT;
440 struct child_process *helper;
441 int r, duped, ret = 0;
442 FILE *input;
444 helper = get_helper(transport);
447 * Yes, dup the pipe another time, as we need unbuffered version
448 * of input pipe as FILE*. fclose() closes the underlying fd and
449 * stream buffering only can be changed before first I/O operation
450 * on it.
452 duped = dup(helper->out);
453 if (duped < 0)
454 die_errno("Can't dup helper output fd");
455 input = xfdopen(duped, "r");
456 setvbuf(input, NULL, _IONBF, 0);
459 * Handle --upload-pack and friends. This is fire and forget...
460 * just warn if it fails.
462 if (strcmp(name, exec)) {
463 r = set_helper_option(transport, "servpath", exec);
464 if (r > 0)
465 warning("Setting remote service path not supported by protocol.");
466 else if (r < 0)
467 warning("Invalid remote service path.");
470 if (data->connect)
471 strbuf_addf(&cmdbuf, "connect %s\n", name);
472 else
473 goto exit;
475 sendline(data, &cmdbuf);
476 recvline_fh(input, &cmdbuf);
477 if (!strcmp(cmdbuf.buf, "")) {
478 data->no_disconnect_req = 1;
479 if (debug)
480 fprintf(stderr, "Debug: Smart transport connection "
481 "ready.\n");
482 ret = 1;
483 } else if (!strcmp(cmdbuf.buf, "fallback")) {
484 if (debug)
485 fprintf(stderr, "Debug: Falling back to dumb "
486 "transport.\n");
487 } else
488 die("Unknown response to connect: %s",
489 cmdbuf.buf);
491 exit:
492 fclose(input);
493 return ret;
496 static int process_connect(struct transport *transport,
497 int for_push)
499 struct helper_data *data = transport->data;
500 const char *name;
501 const char *exec;
503 name = for_push ? "git-receive-pack" : "git-upload-pack";
504 if (for_push)
505 exec = data->transport_options.receivepack;
506 else
507 exec = data->transport_options.uploadpack;
509 return process_connect_service(transport, name, exec);
512 static int connect_helper(struct transport *transport, const char *name,
513 const char *exec, int fd[2])
515 struct helper_data *data = transport->data;
517 /* Get_helper so connect is inited. */
518 get_helper(transport);
519 if (!data->connect)
520 die("Operation not supported by protocol.");
522 if (!process_connect_service(transport, name, exec))
523 die("Can't connect to subservice %s.", name);
525 fd[0] = data->helper->out;
526 fd[1] = data->helper->in;
527 return 0;
530 static int fetch(struct transport *transport,
531 int nr_heads, struct ref **to_fetch)
533 struct helper_data *data = transport->data;
534 int i, count;
536 if (process_connect(transport, 0)) {
537 do_take_over(transport);
538 return transport->fetch(transport, nr_heads, to_fetch);
541 count = 0;
542 for (i = 0; i < nr_heads; i++)
543 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
544 count++;
546 if (!count)
547 return 0;
549 if (data->fetch)
550 return fetch_with_fetch(transport, nr_heads, to_fetch);
552 if (data->import)
553 return fetch_with_import(transport, nr_heads, to_fetch);
555 return -1;
558 static int push_refs_with_push(struct transport *transport,
559 struct ref *remote_refs, int flags)
561 int force_all = flags & TRANSPORT_PUSH_FORCE;
562 int mirror = flags & TRANSPORT_PUSH_MIRROR;
563 struct helper_data *data = transport->data;
564 struct strbuf buf = STRBUF_INIT;
565 struct child_process *helper;
566 struct ref *ref;
568 helper = get_helper(transport);
569 if (!data->push)
570 return 1;
572 for (ref = remote_refs; ref; ref = ref->next) {
573 if (!ref->peer_ref && !mirror)
574 continue;
576 /* Check for statuses set by set_ref_status_for_push() */
577 switch (ref->status) {
578 case REF_STATUS_REJECT_NONFASTFORWARD:
579 case REF_STATUS_UPTODATE:
580 continue;
581 default:
582 ; /* do nothing */
585 if (force_all)
586 ref->force = 1;
588 strbuf_addstr(&buf, "push ");
589 if (!ref->deletion) {
590 if (ref->force)
591 strbuf_addch(&buf, '+');
592 if (ref->peer_ref)
593 strbuf_addstr(&buf, ref->peer_ref->name);
594 else
595 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
597 strbuf_addch(&buf, ':');
598 strbuf_addstr(&buf, ref->name);
599 strbuf_addch(&buf, '\n');
601 if (buf.len == 0)
602 return 0;
604 standard_options(transport);
606 if (flags & TRANSPORT_PUSH_DRY_RUN) {
607 if (set_helper_option(transport, "dry-run", "true") != 0)
608 die("helper %s does not support dry-run", data->name);
611 strbuf_addch(&buf, '\n');
612 sendline(data, &buf);
614 ref = remote_refs;
615 while (1) {
616 char *refname, *msg;
617 int status;
619 recvline(data, &buf);
620 if (!buf.len)
621 break;
623 if (!prefixcmp(buf.buf, "ok ")) {
624 status = REF_STATUS_OK;
625 refname = buf.buf + 3;
626 } else if (!prefixcmp(buf.buf, "error ")) {
627 status = REF_STATUS_REMOTE_REJECT;
628 refname = buf.buf + 6;
629 } else
630 die("expected ok/error, helper said '%s'\n", buf.buf);
632 msg = strchr(refname, ' ');
633 if (msg) {
634 struct strbuf msg_buf = STRBUF_INIT;
635 const char *end;
637 *msg++ = '\0';
638 if (!unquote_c_style(&msg_buf, msg, &end))
639 msg = strbuf_detach(&msg_buf, NULL);
640 else
641 msg = xstrdup(msg);
642 strbuf_release(&msg_buf);
644 if (!strcmp(msg, "no match")) {
645 status = REF_STATUS_NONE;
646 free(msg);
647 msg = NULL;
649 else if (!strcmp(msg, "up to date")) {
650 status = REF_STATUS_UPTODATE;
651 free(msg);
652 msg = NULL;
654 else if (!strcmp(msg, "non-fast forward")) {
655 status = REF_STATUS_REJECT_NONFASTFORWARD;
656 free(msg);
657 msg = NULL;
661 if (ref)
662 ref = find_ref_by_name(ref, refname);
663 if (!ref)
664 ref = find_ref_by_name(remote_refs, refname);
665 if (!ref) {
666 warning("helper reported unexpected status of %s", refname);
667 continue;
670 if (ref->status != REF_STATUS_NONE) {
672 * Earlier, the ref was marked not to be pushed, so ignore the ref
673 * status reported by the remote helper if the latter is 'no match'.
675 if (status == REF_STATUS_NONE)
676 continue;
679 ref->status = status;
680 ref->remote_status = msg;
682 strbuf_release(&buf);
683 return 0;
686 static int push_refs_with_export(struct transport *transport,
687 struct ref *remote_refs, int flags)
689 struct ref *ref;
690 struct child_process *helper, exporter;
691 struct helper_data *data = transport->data;
692 char *export_marks = NULL, *import_marks = NULL;
693 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
694 struct strbuf buf = STRBUF_INIT;
696 helper = get_helper(transport);
698 write_constant(helper->in, "export\n");
700 recvline(data, &buf);
701 if (debug)
702 fprintf(stderr, "Debug: Got export_marks '%s'\n", buf.buf);
703 if (buf.len) {
704 struct strbuf arg = STRBUF_INIT;
705 strbuf_addstr(&arg, "--export-marks=");
706 strbuf_addbuf(&arg, &buf);
707 export_marks = strbuf_detach(&arg, NULL);
710 recvline(data, &buf);
711 if (debug)
712 fprintf(stderr, "Debug: Got import_marks '%s'\n", buf.buf);
713 if (buf.len) {
714 struct strbuf arg = STRBUF_INIT;
715 strbuf_addstr(&arg, "--import-marks=");
716 strbuf_addbuf(&arg, &buf);
717 import_marks = strbuf_detach(&arg, NULL);
720 strbuf_reset(&buf);
722 for (ref = remote_refs; ref; ref = ref->next) {
723 char *private;
724 unsigned char sha1[20];
726 if (!data->refspecs)
727 continue;
728 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
729 if (private && !get_sha1(private, sha1)) {
730 strbuf_addf(&buf, "^%s", private);
731 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
734 string_list_append(&revlist_args, ref->name);
738 if (get_exporter(transport, &exporter,
739 export_marks, import_marks, &revlist_args))
740 die("Couldn't run fast-export");
742 data->no_disconnect_req = 1;
743 finish_command(&exporter);
744 disconnect_helper(transport);
745 return 0;
748 static int push_refs(struct transport *transport,
749 struct ref *remote_refs, int flags)
751 struct helper_data *data = transport->data;
753 if (process_connect(transport, 1)) {
754 do_take_over(transport);
755 return transport->push_refs(transport, remote_refs, flags);
758 if (!remote_refs) {
759 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
760 "Perhaps you should specify a branch such as 'master'.\n");
761 return 0;
764 if (data->push)
765 return push_refs_with_push(transport, remote_refs, flags);
767 if (data->export)
768 return push_refs_with_export(transport, remote_refs, flags);
770 return -1;
774 static int has_attribute(const char *attrs, const char *attr) {
775 int len;
776 if (!attrs)
777 return 0;
779 len = strlen(attr);
780 for (;;) {
781 const char *space = strchrnul(attrs, ' ');
782 if (len == space - attrs && !strncmp(attrs, attr, len))
783 return 1;
784 if (!*space)
785 return 0;
786 attrs = space + 1;
790 static struct ref *get_refs_list(struct transport *transport, int for_push)
792 struct helper_data *data = transport->data;
793 struct child_process *helper;
794 struct ref *ret = NULL;
795 struct ref **tail = &ret;
796 struct ref *posn;
797 struct strbuf buf = STRBUF_INIT;
799 helper = get_helper(transport);
801 if (process_connect(transport, for_push)) {
802 do_take_over(transport);
803 return transport->get_refs_list(transport, for_push);
806 if (data->push && for_push)
807 write_str_in_full(helper->in, "list for-push\n");
808 else
809 write_str_in_full(helper->in, "list\n");
811 while (1) {
812 char *eov, *eon;
813 recvline(data, &buf);
815 if (!*buf.buf)
816 break;
818 eov = strchr(buf.buf, ' ');
819 if (!eov)
820 die("Malformed response in ref list: %s", buf.buf);
821 eon = strchr(eov + 1, ' ');
822 *eov = '\0';
823 if (eon)
824 *eon = '\0';
825 *tail = alloc_ref(eov + 1);
826 if (buf.buf[0] == '@')
827 (*tail)->symref = xstrdup(buf.buf + 1);
828 else if (buf.buf[0] != '?')
829 get_sha1_hex(buf.buf, (*tail)->old_sha1);
830 if (eon) {
831 if (has_attribute(eon + 1, "unchanged")) {
832 (*tail)->status |= REF_STATUS_UPTODATE;
833 read_ref((*tail)->name, (*tail)->old_sha1);
836 tail = &((*tail)->next);
838 if (debug)
839 fprintf(stderr, "Debug: Read ref listing.\n");
840 strbuf_release(&buf);
842 for (posn = ret; posn; posn = posn->next)
843 resolve_remote_symref(posn, ret);
845 return ret;
848 int transport_helper_init(struct transport *transport, const char *name)
850 struct helper_data *data = xcalloc(sizeof(*data), 1);
851 data->name = name;
853 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
854 debug = 1;
856 transport->data = data;
857 transport->set_option = set_helper_option;
858 transport->get_refs_list = get_refs_list;
859 transport->fetch = fetch;
860 transport->push_refs = push_refs;
861 transport->disconnect = release_helper;
862 transport->connect = connect_helper;
863 transport->smart_options = &(data->transport_options);
864 return 0;
868 * Linux pipes can buffer 65536 bytes at once (and most platforms can
869 * buffer less), so attempt reads and writes with up to that size.
871 #define BUFFERSIZE 65536
872 /* This should be enough to hold debugging message. */
873 #define PBUFFERSIZE 8192
875 /* Print bidirectional transfer loop debug message. */
876 static void transfer_debug(const char *fmt, ...)
878 va_list args;
879 char msgbuf[PBUFFERSIZE];
880 static int debug_enabled = -1;
882 if (debug_enabled < 0)
883 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
884 if (!debug_enabled)
885 return;
887 va_start(args, fmt);
888 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
889 va_end(args);
890 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
893 /* Stream state: More data may be coming in this direction. */
894 #define SSTATE_TRANSFERING 0
896 * Stream state: No more data coming in this direction, flushing rest of
897 * data.
899 #define SSTATE_FLUSHING 1
900 /* Stream state: Transfer in this direction finished. */
901 #define SSTATE_FINISHED 2
903 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
904 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
905 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
907 /* Unidirectional transfer. */
908 struct unidirectional_transfer {
909 /* Source */
910 int src;
911 /* Destination */
912 int dest;
913 /* Is source socket? */
914 int src_is_sock;
915 /* Is destination socket? */
916 int dest_is_sock;
917 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
918 int state;
919 /* Buffer. */
920 char buf[BUFFERSIZE];
921 /* Buffer used. */
922 size_t bufuse;
923 /* Name of source. */
924 const char *src_name;
925 /* Name of destination. */
926 const char *dest_name;
929 /* Closes the target (for writing) if transfer has finished. */
930 static void udt_close_if_finished(struct unidirectional_transfer *t)
932 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
933 t->state = SSTATE_FINISHED;
934 if (t->dest_is_sock)
935 shutdown(t->dest, SHUT_WR);
936 else
937 close(t->dest);
938 transfer_debug("Closed %s.", t->dest_name);
943 * Tries to read read data from source into buffer. If buffer is full,
944 * no data is read. Returns 0 on success, -1 on error.
946 static int udt_do_read(struct unidirectional_transfer *t)
948 ssize_t bytes;
950 if (t->bufuse == BUFFERSIZE)
951 return 0; /* No space for more. */
953 transfer_debug("%s is readable", t->src_name);
954 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
955 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
956 errno != EINTR) {
957 error("read(%s) failed: %s", t->src_name, strerror(errno));
958 return -1;
959 } else if (bytes == 0) {
960 transfer_debug("%s EOF (with %i bytes in buffer)",
961 t->src_name, t->bufuse);
962 t->state = SSTATE_FLUSHING;
963 } else if (bytes > 0) {
964 t->bufuse += bytes;
965 transfer_debug("Read %i bytes from %s (buffer now at %i)",
966 (int)bytes, t->src_name, (int)t->bufuse);
968 return 0;
971 /* Tries to write data from buffer into destination. If buffer is empty,
972 * no data is written. Returns 0 on success, -1 on error.
974 static int udt_do_write(struct unidirectional_transfer *t)
976 size_t bytes;
978 if (t->bufuse == 0)
979 return 0; /* Nothing to write. */
981 transfer_debug("%s is writable", t->dest_name);
982 bytes = write(t->dest, t->buf, t->bufuse);
983 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
984 errno != EINTR) {
985 error("write(%s) failed: %s", t->dest_name, strerror(errno));
986 return -1;
987 } else if (bytes > 0) {
988 t->bufuse -= bytes;
989 if (t->bufuse)
990 memmove(t->buf, t->buf + bytes, t->bufuse);
991 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
992 (int)bytes, t->dest_name, (int)t->bufuse);
994 return 0;
998 /* State of bidirectional transfer loop. */
999 struct bidirectional_transfer_state {
1000 /* Direction from program to git. */
1001 struct unidirectional_transfer ptg;
1002 /* Direction from git to program. */
1003 struct unidirectional_transfer gtp;
1006 static void *udt_copy_task_routine(void *udt)
1008 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1009 while (t->state != SSTATE_FINISHED) {
1010 if (STATE_NEEDS_READING(t->state))
1011 if (udt_do_read(t))
1012 return NULL;
1013 if (STATE_NEEDS_WRITING(t->state))
1014 if (udt_do_write(t))
1015 return NULL;
1016 if (STATE_NEEDS_CLOSING(t->state))
1017 udt_close_if_finished(t);
1019 return udt; /* Just some non-NULL value. */
1022 #ifndef NO_PTHREADS
1025 * Join thread, with apporiate errors on failure. Name is name for the
1026 * thread (for error messages). Returns 0 on success, 1 on failure.
1028 static int tloop_join(pthread_t thread, const char *name)
1030 int err;
1031 void *tret;
1032 err = pthread_join(thread, &tret);
1033 if (!tret) {
1034 error("%s thread failed", name);
1035 return 1;
1037 if (err) {
1038 error("%s thread failed to join: %s", name, strerror(err));
1039 return 1;
1041 return 0;
1045 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1046 * -1 on failure.
1048 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1050 pthread_t gtp_thread;
1051 pthread_t ptg_thread;
1052 int err;
1053 int ret = 0;
1054 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1055 &s->gtp);
1056 if (err)
1057 die("Can't start thread for copying data: %s", strerror(err));
1058 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1059 &s->ptg);
1060 if (err)
1061 die("Can't start thread for copying data: %s", strerror(err));
1063 ret |= tloop_join(gtp_thread, "Git to program copy");
1064 ret |= tloop_join(ptg_thread, "Program to git copy");
1065 return ret;
1067 #else
1069 /* Close the source and target (for writing) for transfer. */
1070 static void udt_kill_transfer(struct unidirectional_transfer *t)
1072 t->state = SSTATE_FINISHED;
1074 * Socket read end left open isn't a disaster if nobody
1075 * attempts to read from it (mingw compat headers do not
1076 * have SHUT_RD)...
1078 * We can't fully close the socket since otherwise gtp
1079 * task would first close the socket it sends data to
1080 * while closing the ptg file descriptors.
1082 if (!t->src_is_sock)
1083 close(t->src);
1084 if (t->dest_is_sock)
1085 shutdown(t->dest, SHUT_WR);
1086 else
1087 close(t->dest);
1091 * Join process, with apporiate errors on failure. Name is name for the
1092 * process (for error messages). Returns 0 on success, 1 on failure.
1094 static int tloop_join(pid_t pid, const char *name)
1096 int tret;
1097 if (waitpid(pid, &tret, 0) < 0) {
1098 error("%s process failed to wait: %s", name, strerror(errno));
1099 return 1;
1101 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1102 error("%s process failed", name);
1103 return 1;
1105 return 0;
1109 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1110 * -1 on failure.
1112 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1114 pid_t pid1, pid2;
1115 int ret = 0;
1117 /* Fork thread #1: git to program. */
1118 pid1 = fork();
1119 if (pid1 < 0)
1120 die_errno("Can't start thread for copying data");
1121 else if (pid1 == 0) {
1122 udt_kill_transfer(&s->ptg);
1123 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1126 /* Fork thread #2: program to git. */
1127 pid2 = fork();
1128 if (pid2 < 0)
1129 die_errno("Can't start thread for copying data");
1130 else if (pid2 == 0) {
1131 udt_kill_transfer(&s->gtp);
1132 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1136 * Close both streams in parent as to not interfere with
1137 * end of file detection and wait for both tasks to finish.
1139 udt_kill_transfer(&s->gtp);
1140 udt_kill_transfer(&s->ptg);
1141 ret |= tloop_join(pid1, "Git to program copy");
1142 ret |= tloop_join(pid2, "Program to git copy");
1143 return ret;
1145 #endif
1148 * Copies data from stdin to output and from input to stdout simultaneously.
1149 * Additionally filtering through given filter. If filter is NULL, uses
1150 * identity filter.
1152 int bidirectional_transfer_loop(int input, int output)
1154 struct bidirectional_transfer_state state;
1156 /* Fill the state fields. */
1157 state.ptg.src = input;
1158 state.ptg.dest = 1;
1159 state.ptg.src_is_sock = (input == output);
1160 state.ptg.dest_is_sock = 0;
1161 state.ptg.state = SSTATE_TRANSFERING;
1162 state.ptg.bufuse = 0;
1163 state.ptg.src_name = "remote input";
1164 state.ptg.dest_name = "stdout";
1166 state.gtp.src = 0;
1167 state.gtp.dest = output;
1168 state.gtp.src_is_sock = 0;
1169 state.gtp.dest_is_sock = (input == output);
1170 state.gtp.state = SSTATE_TRANSFERING;
1171 state.gtp.bufuse = 0;
1172 state.gtp.src_name = "stdin";
1173 state.gtp.dest_name = "remote output";
1175 return tloop_spawnwait_tasks(&state);