git-fast-import(1): reorganise options
[git/debian/pape.git] / transport-helper.c
blob6cccb20f8db98bdd040698e674dd3cec01021d65
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 {
16 const char *name;
17 struct child_process *helper;
18 FILE *out;
19 unsigned fetch : 1,
20 import : 1,
21 export : 1,
22 option : 1,
23 push : 1,
24 connect : 1,
25 no_disconnect_req : 1;
26 /* These go from remote name (as in "list") to private name */
27 struct refspec *refspecs;
28 int refspec_nr;
29 /* Transport options for fetch-pack/send-pack (should one of
30 * those be invoked).
32 struct git_transport_options transport_options;
35 static void sendline(struct helper_data *helper, struct strbuf *buffer)
37 if (debug)
38 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
39 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
40 != buffer->len)
41 die_errno("Full write to remote helper failed");
44 static int recvline_fh(FILE *helper, struct strbuf *buffer)
46 strbuf_reset(buffer);
47 if (debug)
48 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
49 if (strbuf_getline(buffer, helper, '\n') == EOF) {
50 if (debug)
51 fprintf(stderr, "Debug: Remote helper quit.\n");
52 exit(128);
55 if (debug)
56 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
57 return 0;
60 static int recvline(struct helper_data *helper, struct strbuf *buffer)
62 return recvline_fh(helper->out, buffer);
65 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
67 sendline(helper, buffer);
68 recvline(helper, buffer);
71 static void write_constant(int fd, const char *str)
73 if (debug)
74 fprintf(stderr, "Debug: Remote helper: -> %s", str);
75 if (write_in_full(fd, str, strlen(str)) != strlen(str))
76 die_errno("Full write to remote helper failed");
79 static const char *remove_ext_force(const char *url)
81 if (url) {
82 const char *colon = strchr(url, ':');
83 if (colon && colon[1] == ':')
84 return colon + 2;
86 return url;
89 static void do_take_over(struct transport *transport)
91 struct helper_data *data;
92 data = (struct helper_data *)transport->data;
93 transport_take_over(transport, data->helper);
94 fclose(data->out);
95 free(data);
98 static struct child_process *get_helper(struct transport *transport)
100 struct helper_data *data = transport->data;
101 struct strbuf buf = STRBUF_INIT;
102 struct child_process *helper;
103 const char **refspecs = NULL;
104 int refspec_nr = 0;
105 int refspec_alloc = 0;
106 int duped;
107 int code;
108 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
109 const char *helper_env[] = {
110 git_dir_buf,
111 NULL
115 if (data->helper)
116 return data->helper;
118 helper = xcalloc(1, sizeof(*helper));
119 helper->in = -1;
120 helper->out = -1;
121 helper->err = 0;
122 helper->argv = xcalloc(4, sizeof(*helper->argv));
123 strbuf_addf(&buf, "git-remote-%s", data->name);
124 helper->argv[0] = strbuf_detach(&buf, NULL);
125 helper->argv[1] = transport->remote->name;
126 helper->argv[2] = remove_ext_force(transport->url);
127 helper->git_cmd = 0;
128 helper->silent_exec_failure = 1;
130 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
131 helper->env = helper_env;
133 code = start_command(helper);
134 if (code < 0 && errno == ENOENT)
135 die("Unable to find remote helper for '%s'", data->name);
136 else if (code != 0)
137 exit(code);
139 data->helper = helper;
140 data->no_disconnect_req = 0;
143 * Open the output as FILE* so strbuf_getline() can be used.
144 * Do this with duped fd because fclose() will close the fd,
145 * and stuff like taking over will require the fd to remain.
147 duped = dup(helper->out);
148 if (duped < 0)
149 die_errno("Can't dup helper output fd");
150 data->out = xfdopen(duped, "r");
152 write_constant(helper->in, "capabilities\n");
154 while (1) {
155 const char *capname;
156 int mandatory = 0;
157 recvline(data, &buf);
159 if (!*buf.buf)
160 break;
162 if (*buf.buf == '*') {
163 capname = buf.buf + 1;
164 mandatory = 1;
165 } else
166 capname = buf.buf;
168 if (debug)
169 fprintf(stderr, "Debug: Got cap %s\n", capname);
170 if (!strcmp(capname, "fetch"))
171 data->fetch = 1;
172 else if (!strcmp(capname, "option"))
173 data->option = 1;
174 else if (!strcmp(capname, "push"))
175 data->push = 1;
176 else if (!strcmp(capname, "import"))
177 data->import = 1;
178 else if (!strcmp(capname, "export"))
179 data->export = 1;
180 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
181 ALLOC_GROW(refspecs,
182 refspec_nr + 1,
183 refspec_alloc);
184 refspecs[refspec_nr++] = strdup(buf.buf + strlen("refspec "));
185 } else if (!strcmp(capname, "connect")) {
186 data->connect = 1;
187 } else if (mandatory) {
188 die("Unknown mandatory capability %s. This remote "
189 "helper probably needs newer version of Git.\n",
190 capname);
193 if (refspecs) {
194 int i;
195 data->refspec_nr = refspec_nr;
196 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
197 for (i = 0; i < refspec_nr; i++) {
198 free((char *)refspecs[i]);
200 free(refspecs);
202 strbuf_release(&buf);
203 if (debug)
204 fprintf(stderr, "Debug: Capabilities complete.\n");
205 return data->helper;
208 static int disconnect_helper(struct transport *transport)
210 struct helper_data *data = transport->data;
211 struct strbuf buf = STRBUF_INIT;
213 if (data->helper) {
214 if (debug)
215 fprintf(stderr, "Debug: Disconnecting.\n");
216 if (!data->no_disconnect_req) {
217 strbuf_addf(&buf, "\n");
218 sendline(data, &buf);
220 close(data->helper->in);
221 close(data->helper->out);
222 fclose(data->out);
223 finish_command(data->helper);
224 free((char *)data->helper->argv[0]);
225 free(data->helper->argv);
226 free(data->helper);
227 data->helper = NULL;
229 return 0;
232 static const char *unsupported_options[] = {
233 TRANS_OPT_UPLOADPACK,
234 TRANS_OPT_RECEIVEPACK,
235 TRANS_OPT_THIN,
236 TRANS_OPT_KEEP
238 static const char *boolean_options[] = {
239 TRANS_OPT_THIN,
240 TRANS_OPT_KEEP,
241 TRANS_OPT_FOLLOWTAGS
244 static int set_helper_option(struct transport *transport,
245 const char *name, const char *value)
247 struct helper_data *data = transport->data;
248 struct strbuf buf = STRBUF_INIT;
249 int i, ret, is_bool = 0;
251 get_helper(transport);
253 if (!data->option)
254 return 1;
256 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
257 if (!strcmp(name, unsupported_options[i]))
258 return 1;
261 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
262 if (!strcmp(name, boolean_options[i])) {
263 is_bool = 1;
264 break;
268 strbuf_addf(&buf, "option %s ", name);
269 if (is_bool)
270 strbuf_addstr(&buf, value ? "true" : "false");
271 else
272 quote_c_style(value, &buf, NULL, 0);
273 strbuf_addch(&buf, '\n');
275 xchgline(data, &buf);
277 if (!strcmp(buf.buf, "ok"))
278 ret = 0;
279 else if (!prefixcmp(buf.buf, "error")) {
280 ret = -1;
281 } else if (!strcmp(buf.buf, "unsupported"))
282 ret = 1;
283 else {
284 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
285 ret = 1;
287 strbuf_release(&buf);
288 return ret;
291 static void standard_options(struct transport *t)
293 char buf[16];
294 int n;
295 int v = t->verbose;
297 set_helper_option(t, "progress", t->progress ? "true" : "false");
299 n = snprintf(buf, sizeof(buf), "%d", v + 1);
300 if (n >= sizeof(buf))
301 die("impossibly large verbosity value");
302 set_helper_option(t, "verbosity", buf);
305 static int release_helper(struct transport *transport)
307 struct helper_data *data = transport->data;
308 free_refspec(data->refspec_nr, data->refspecs);
309 data->refspecs = NULL;
310 disconnect_helper(transport);
311 free(transport->data);
312 return 0;
315 static int fetch_with_fetch(struct transport *transport,
316 int nr_heads, struct ref **to_fetch)
318 struct helper_data *data = transport->data;
319 int i;
320 struct strbuf buf = STRBUF_INIT;
322 standard_options(transport);
324 for (i = 0; i < nr_heads; i++) {
325 const struct ref *posn = to_fetch[i];
326 if (posn->status & REF_STATUS_UPTODATE)
327 continue;
329 strbuf_addf(&buf, "fetch %s %s\n",
330 sha1_to_hex(posn->old_sha1), posn->name);
333 strbuf_addch(&buf, '\n');
334 sendline(data, &buf);
336 while (1) {
337 recvline(data, &buf);
339 if (!prefixcmp(buf.buf, "lock ")) {
340 const char *name = buf.buf + 5;
341 if (transport->pack_lockfile)
342 warning("%s also locked %s", data->name, name);
343 else
344 transport->pack_lockfile = xstrdup(name);
346 else if (!buf.len)
347 break;
348 else
349 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
351 strbuf_release(&buf);
352 return 0;
355 static int get_importer(struct transport *transport, struct child_process *fastimport)
357 struct child_process *helper = get_helper(transport);
358 memset(fastimport, 0, sizeof(*fastimport));
359 fastimport->in = helper->out;
360 fastimport->argv = xcalloc(5, sizeof(*fastimport->argv));
361 fastimport->argv[0] = "fast-import";
362 fastimport->argv[1] = "--quiet";
364 fastimport->git_cmd = 1;
365 return start_command(fastimport);
368 static int get_exporter(struct transport *transport,
369 struct child_process *fastexport,
370 const char *export_marks,
371 const char *import_marks,
372 struct string_list *revlist_args)
374 struct child_process *helper = get_helper(transport);
375 int argc = 0, i;
376 memset(fastexport, 0, sizeof(*fastexport));
378 /* we need to duplicate helper->in because we want to use it after
379 * fastexport is done with it. */
380 fastexport->out = dup(helper->in);
381 fastexport->argv = xcalloc(4 + revlist_args->nr, sizeof(*fastexport->argv));
382 fastexport->argv[argc++] = "fast-export";
383 if (export_marks)
384 fastexport->argv[argc++] = export_marks;
385 if (import_marks)
386 fastexport->argv[argc++] = import_marks;
388 for (i = 0; i < revlist_args->nr; i++)
389 fastexport->argv[argc++] = revlist_args->items[i].string;
391 fastexport->git_cmd = 1;
392 return start_command(fastexport);
395 static int fetch_with_import(struct transport *transport,
396 int nr_heads, struct ref **to_fetch)
398 struct child_process fastimport;
399 struct helper_data *data = transport->data;
400 int i;
401 struct ref *posn;
402 struct strbuf buf = STRBUF_INIT;
404 get_helper(transport);
406 if (get_importer(transport, &fastimport))
407 die("Couldn't run fast-import");
409 for (i = 0; i < nr_heads; i++) {
410 posn = to_fetch[i];
411 if (posn->status & REF_STATUS_UPTODATE)
412 continue;
414 strbuf_addf(&buf, "import %s\n", posn->name);
415 sendline(data, &buf);
416 strbuf_reset(&buf);
418 disconnect_helper(transport);
419 finish_command(&fastimport);
420 free(fastimport.argv);
421 fastimport.argv = NULL;
423 for (i = 0; i < nr_heads; i++) {
424 char *private;
425 posn = to_fetch[i];
426 if (posn->status & REF_STATUS_UPTODATE)
427 continue;
428 if (data->refspecs)
429 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
430 else
431 private = strdup(posn->name);
432 read_ref(private, posn->old_sha1);
433 free(private);
435 strbuf_release(&buf);
436 return 0;
439 static int process_connect_service(struct transport *transport,
440 const char *name, const char *exec)
442 struct helper_data *data = transport->data;
443 struct strbuf cmdbuf = STRBUF_INIT;
444 struct child_process *helper;
445 int r, duped, ret = 0;
446 FILE *input;
448 helper = get_helper(transport);
451 * Yes, dup the pipe another time, as we need unbuffered version
452 * of input pipe as FILE*. fclose() closes the underlying fd and
453 * stream buffering only can be changed before first I/O operation
454 * on it.
456 duped = dup(helper->out);
457 if (duped < 0)
458 die_errno("Can't dup helper output fd");
459 input = xfdopen(duped, "r");
460 setvbuf(input, NULL, _IONBF, 0);
463 * Handle --upload-pack and friends. This is fire and forget...
464 * just warn if it fails.
466 if (strcmp(name, exec)) {
467 r = set_helper_option(transport, "servpath", exec);
468 if (r > 0)
469 warning("Setting remote service path not supported by protocol.");
470 else if (r < 0)
471 warning("Invalid remote service path.");
474 if (data->connect)
475 strbuf_addf(&cmdbuf, "connect %s\n", name);
476 else
477 goto exit;
479 sendline(data, &cmdbuf);
480 recvline_fh(input, &cmdbuf);
481 if (!strcmp(cmdbuf.buf, "")) {
482 data->no_disconnect_req = 1;
483 if (debug)
484 fprintf(stderr, "Debug: Smart transport connection "
485 "ready.\n");
486 ret = 1;
487 } else if (!strcmp(cmdbuf.buf, "fallback")) {
488 if (debug)
489 fprintf(stderr, "Debug: Falling back to dumb "
490 "transport.\n");
491 } else
492 die("Unknown response to connect: %s",
493 cmdbuf.buf);
495 exit:
496 fclose(input);
497 return ret;
500 static int process_connect(struct transport *transport,
501 int for_push)
503 struct helper_data *data = transport->data;
504 const char *name;
505 const char *exec;
507 name = for_push ? "git-receive-pack" : "git-upload-pack";
508 if (for_push)
509 exec = data->transport_options.receivepack;
510 else
511 exec = data->transport_options.uploadpack;
513 return process_connect_service(transport, name, exec);
516 static int connect_helper(struct transport *transport, const char *name,
517 const char *exec, int fd[2])
519 struct helper_data *data = transport->data;
521 /* Get_helper so connect is inited. */
522 get_helper(transport);
523 if (!data->connect)
524 die("Operation not supported by protocol.");
526 if (!process_connect_service(transport, name, exec))
527 die("Can't connect to subservice %s.", name);
529 fd[0] = data->helper->out;
530 fd[1] = data->helper->in;
531 return 0;
534 static int fetch(struct transport *transport,
535 int nr_heads, struct ref **to_fetch)
537 struct helper_data *data = transport->data;
538 int i, count;
540 if (process_connect(transport, 0)) {
541 do_take_over(transport);
542 return transport->fetch(transport, nr_heads, to_fetch);
545 count = 0;
546 for (i = 0; i < nr_heads; i++)
547 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
548 count++;
550 if (!count)
551 return 0;
553 if (data->fetch)
554 return fetch_with_fetch(transport, nr_heads, to_fetch);
556 if (data->import)
557 return fetch_with_import(transport, nr_heads, to_fetch);
559 return -1;
562 static int push_refs_with_push(struct transport *transport,
563 struct ref *remote_refs, int flags)
565 int force_all = flags & TRANSPORT_PUSH_FORCE;
566 int mirror = flags & TRANSPORT_PUSH_MIRROR;
567 struct helper_data *data = transport->data;
568 struct strbuf buf = STRBUF_INIT;
569 struct ref *ref;
571 get_helper(transport);
572 if (!data->push)
573 return 1;
575 for (ref = remote_refs; ref; ref = ref->next) {
576 if (!ref->peer_ref && !mirror)
577 continue;
579 /* Check for statuses set by set_ref_status_for_push() */
580 switch (ref->status) {
581 case REF_STATUS_REJECT_NONFASTFORWARD:
582 case REF_STATUS_UPTODATE:
583 continue;
584 default:
585 ; /* do nothing */
588 if (force_all)
589 ref->force = 1;
591 strbuf_addstr(&buf, "push ");
592 if (!ref->deletion) {
593 if (ref->force)
594 strbuf_addch(&buf, '+');
595 if (ref->peer_ref)
596 strbuf_addstr(&buf, ref->peer_ref->name);
597 else
598 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
600 strbuf_addch(&buf, ':');
601 strbuf_addstr(&buf, ref->name);
602 strbuf_addch(&buf, '\n');
604 if (buf.len == 0)
605 return 0;
607 standard_options(transport);
609 if (flags & TRANSPORT_PUSH_DRY_RUN) {
610 if (set_helper_option(transport, "dry-run", "true") != 0)
611 die("helper %s does not support dry-run", data->name);
614 strbuf_addch(&buf, '\n');
615 sendline(data, &buf);
617 ref = remote_refs;
618 while (1) {
619 char *refname, *msg;
620 int status;
622 recvline(data, &buf);
623 if (!buf.len)
624 break;
626 if (!prefixcmp(buf.buf, "ok ")) {
627 status = REF_STATUS_OK;
628 refname = buf.buf + 3;
629 } else if (!prefixcmp(buf.buf, "error ")) {
630 status = REF_STATUS_REMOTE_REJECT;
631 refname = buf.buf + 6;
632 } else
633 die("expected ok/error, helper said '%s'\n", buf.buf);
635 msg = strchr(refname, ' ');
636 if (msg) {
637 struct strbuf msg_buf = STRBUF_INIT;
638 const char *end;
640 *msg++ = '\0';
641 if (!unquote_c_style(&msg_buf, msg, &end))
642 msg = strbuf_detach(&msg_buf, NULL);
643 else
644 msg = xstrdup(msg);
645 strbuf_release(&msg_buf);
647 if (!strcmp(msg, "no match")) {
648 status = REF_STATUS_NONE;
649 free(msg);
650 msg = NULL;
652 else if (!strcmp(msg, "up to date")) {
653 status = REF_STATUS_UPTODATE;
654 free(msg);
655 msg = NULL;
657 else if (!strcmp(msg, "non-fast forward")) {
658 status = REF_STATUS_REJECT_NONFASTFORWARD;
659 free(msg);
660 msg = NULL;
664 if (ref)
665 ref = find_ref_by_name(ref, refname);
666 if (!ref)
667 ref = find_ref_by_name(remote_refs, refname);
668 if (!ref) {
669 warning("helper reported unexpected status of %s", refname);
670 continue;
673 if (ref->status != REF_STATUS_NONE) {
675 * Earlier, the ref was marked not to be pushed, so ignore the ref
676 * status reported by the remote helper if the latter is 'no match'.
678 if (status == REF_STATUS_NONE)
679 continue;
682 ref->status = status;
683 ref->remote_status = msg;
685 strbuf_release(&buf);
686 return 0;
689 static int push_refs_with_export(struct transport *transport,
690 struct ref *remote_refs, int flags)
692 struct ref *ref;
693 struct child_process *helper, exporter;
694 struct helper_data *data = transport->data;
695 char *export_marks = NULL, *import_marks = NULL;
696 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
697 struct strbuf buf = STRBUF_INIT;
699 helper = get_helper(transport);
701 write_constant(helper->in, "export\n");
703 recvline(data, &buf);
704 if (debug)
705 fprintf(stderr, "Debug: Got export_marks '%s'\n", buf.buf);
706 if (buf.len) {
707 struct strbuf arg = STRBUF_INIT;
708 strbuf_addstr(&arg, "--export-marks=");
709 strbuf_addbuf(&arg, &buf);
710 export_marks = strbuf_detach(&arg, NULL);
713 recvline(data, &buf);
714 if (debug)
715 fprintf(stderr, "Debug: Got import_marks '%s'\n", buf.buf);
716 if (buf.len) {
717 struct strbuf arg = STRBUF_INIT;
718 strbuf_addstr(&arg, "--import-marks=");
719 strbuf_addbuf(&arg, &buf);
720 import_marks = strbuf_detach(&arg, NULL);
723 strbuf_reset(&buf);
725 for (ref = remote_refs; ref; ref = ref->next) {
726 char *private;
727 unsigned char sha1[20];
729 if (!data->refspecs)
730 continue;
731 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
732 if (private && !get_sha1(private, sha1)) {
733 strbuf_addf(&buf, "^%s", private);
734 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
736 free(private);
738 if (ref->peer_ref)
739 string_list_append(&revlist_args, ref->peer_ref->name);
743 if (get_exporter(transport, &exporter,
744 export_marks, import_marks, &revlist_args))
745 die("Couldn't run fast-export");
747 data->no_disconnect_req = 1;
748 finish_command(&exporter);
749 disconnect_helper(transport);
750 return 0;
753 static int push_refs(struct transport *transport,
754 struct ref *remote_refs, int flags)
756 struct helper_data *data = transport->data;
758 if (process_connect(transport, 1)) {
759 do_take_over(transport);
760 return transport->push_refs(transport, remote_refs, flags);
763 if (!remote_refs) {
764 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
765 "Perhaps you should specify a branch such as 'master'.\n");
766 return 0;
769 if (data->push)
770 return push_refs_with_push(transport, remote_refs, flags);
772 if (data->export)
773 return push_refs_with_export(transport, remote_refs, flags);
775 return -1;
779 static int has_attribute(const char *attrs, const char *attr) {
780 int len;
781 if (!attrs)
782 return 0;
784 len = strlen(attr);
785 for (;;) {
786 const char *space = strchrnul(attrs, ' ');
787 if (len == space - attrs && !strncmp(attrs, attr, len))
788 return 1;
789 if (!*space)
790 return 0;
791 attrs = space + 1;
795 static struct ref *get_refs_list(struct transport *transport, int for_push)
797 struct helper_data *data = transport->data;
798 struct child_process *helper;
799 struct ref *ret = NULL;
800 struct ref **tail = &ret;
801 struct ref *posn;
802 struct strbuf buf = STRBUF_INIT;
804 helper = get_helper(transport);
806 if (process_connect(transport, for_push)) {
807 do_take_over(transport);
808 return transport->get_refs_list(transport, for_push);
811 if (data->push && for_push)
812 write_str_in_full(helper->in, "list for-push\n");
813 else
814 write_str_in_full(helper->in, "list\n");
816 while (1) {
817 char *eov, *eon;
818 recvline(data, &buf);
820 if (!*buf.buf)
821 break;
823 eov = strchr(buf.buf, ' ');
824 if (!eov)
825 die("Malformed response in ref list: %s", buf.buf);
826 eon = strchr(eov + 1, ' ');
827 *eov = '\0';
828 if (eon)
829 *eon = '\0';
830 *tail = alloc_ref(eov + 1);
831 if (buf.buf[0] == '@')
832 (*tail)->symref = xstrdup(buf.buf + 1);
833 else if (buf.buf[0] != '?')
834 get_sha1_hex(buf.buf, (*tail)->old_sha1);
835 if (eon) {
836 if (has_attribute(eon + 1, "unchanged")) {
837 (*tail)->status |= REF_STATUS_UPTODATE;
838 read_ref((*tail)->name, (*tail)->old_sha1);
841 tail = &((*tail)->next);
843 if (debug)
844 fprintf(stderr, "Debug: Read ref listing.\n");
845 strbuf_release(&buf);
847 for (posn = ret; posn; posn = posn->next)
848 resolve_remote_symref(posn, ret);
850 return ret;
853 int transport_helper_init(struct transport *transport, const char *name)
855 struct helper_data *data = xcalloc(sizeof(*data), 1);
856 data->name = name;
858 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
859 debug = 1;
861 transport->data = data;
862 transport->set_option = set_helper_option;
863 transport->get_refs_list = get_refs_list;
864 transport->fetch = fetch;
865 transport->push_refs = push_refs;
866 transport->disconnect = release_helper;
867 transport->connect = connect_helper;
868 transport->smart_options = &(data->transport_options);
869 return 0;
873 * Linux pipes can buffer 65536 bytes at once (and most platforms can
874 * buffer less), so attempt reads and writes with up to that size.
876 #define BUFFERSIZE 65536
877 /* This should be enough to hold debugging message. */
878 #define PBUFFERSIZE 8192
880 /* Print bidirectional transfer loop debug message. */
881 static void transfer_debug(const char *fmt, ...)
883 va_list args;
884 char msgbuf[PBUFFERSIZE];
885 static int debug_enabled = -1;
887 if (debug_enabled < 0)
888 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
889 if (!debug_enabled)
890 return;
892 va_start(args, fmt);
893 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
894 va_end(args);
895 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
898 /* Stream state: More data may be coming in this direction. */
899 #define SSTATE_TRANSFERING 0
901 * Stream state: No more data coming in this direction, flushing rest of
902 * data.
904 #define SSTATE_FLUSHING 1
905 /* Stream state: Transfer in this direction finished. */
906 #define SSTATE_FINISHED 2
908 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
909 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
910 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
912 /* Unidirectional transfer. */
913 struct unidirectional_transfer {
914 /* Source */
915 int src;
916 /* Destination */
917 int dest;
918 /* Is source socket? */
919 int src_is_sock;
920 /* Is destination socket? */
921 int dest_is_sock;
922 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
923 int state;
924 /* Buffer. */
925 char buf[BUFFERSIZE];
926 /* Buffer used. */
927 size_t bufuse;
928 /* Name of source. */
929 const char *src_name;
930 /* Name of destination. */
931 const char *dest_name;
934 /* Closes the target (for writing) if transfer has finished. */
935 static void udt_close_if_finished(struct unidirectional_transfer *t)
937 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
938 t->state = SSTATE_FINISHED;
939 if (t->dest_is_sock)
940 shutdown(t->dest, SHUT_WR);
941 else
942 close(t->dest);
943 transfer_debug("Closed %s.", t->dest_name);
948 * Tries to read read data from source into buffer. If buffer is full,
949 * no data is read. Returns 0 on success, -1 on error.
951 static int udt_do_read(struct unidirectional_transfer *t)
953 ssize_t bytes;
955 if (t->bufuse == BUFFERSIZE)
956 return 0; /* No space for more. */
958 transfer_debug("%s is readable", t->src_name);
959 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
960 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
961 errno != EINTR) {
962 error("read(%s) failed: %s", t->src_name, strerror(errno));
963 return -1;
964 } else if (bytes == 0) {
965 transfer_debug("%s EOF (with %i bytes in buffer)",
966 t->src_name, t->bufuse);
967 t->state = SSTATE_FLUSHING;
968 } else if (bytes > 0) {
969 t->bufuse += bytes;
970 transfer_debug("Read %i bytes from %s (buffer now at %i)",
971 (int)bytes, t->src_name, (int)t->bufuse);
973 return 0;
976 /* Tries to write data from buffer into destination. If buffer is empty,
977 * no data is written. Returns 0 on success, -1 on error.
979 static int udt_do_write(struct unidirectional_transfer *t)
981 ssize_t bytes;
983 if (t->bufuse == 0)
984 return 0; /* Nothing to write. */
986 transfer_debug("%s is writable", t->dest_name);
987 bytes = write(t->dest, t->buf, t->bufuse);
988 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
989 errno != EINTR) {
990 error("write(%s) failed: %s", t->dest_name, strerror(errno));
991 return -1;
992 } else if (bytes > 0) {
993 t->bufuse -= bytes;
994 if (t->bufuse)
995 memmove(t->buf, t->buf + bytes, t->bufuse);
996 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
997 (int)bytes, t->dest_name, (int)t->bufuse);
999 return 0;
1003 /* State of bidirectional transfer loop. */
1004 struct bidirectional_transfer_state {
1005 /* Direction from program to git. */
1006 struct unidirectional_transfer ptg;
1007 /* Direction from git to program. */
1008 struct unidirectional_transfer gtp;
1011 static void *udt_copy_task_routine(void *udt)
1013 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1014 while (t->state != SSTATE_FINISHED) {
1015 if (STATE_NEEDS_READING(t->state))
1016 if (udt_do_read(t))
1017 return NULL;
1018 if (STATE_NEEDS_WRITING(t->state))
1019 if (udt_do_write(t))
1020 return NULL;
1021 if (STATE_NEEDS_CLOSING(t->state))
1022 udt_close_if_finished(t);
1024 return udt; /* Just some non-NULL value. */
1027 #ifndef NO_PTHREADS
1030 * Join thread, with apporiate errors on failure. Name is name for the
1031 * thread (for error messages). Returns 0 on success, 1 on failure.
1033 static int tloop_join(pthread_t thread, const char *name)
1035 int err;
1036 void *tret;
1037 err = pthread_join(thread, &tret);
1038 if (!tret) {
1039 error("%s thread failed", name);
1040 return 1;
1042 if (err) {
1043 error("%s thread failed to join: %s", name, strerror(err));
1044 return 1;
1046 return 0;
1050 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1051 * -1 on failure.
1053 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1055 pthread_t gtp_thread;
1056 pthread_t ptg_thread;
1057 int err;
1058 int ret = 0;
1059 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1060 &s->gtp);
1061 if (err)
1062 die("Can't start thread for copying data: %s", strerror(err));
1063 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1064 &s->ptg);
1065 if (err)
1066 die("Can't start thread for copying data: %s", strerror(err));
1068 ret |= tloop_join(gtp_thread, "Git to program copy");
1069 ret |= tloop_join(ptg_thread, "Program to git copy");
1070 return ret;
1072 #else
1074 /* Close the source and target (for writing) for transfer. */
1075 static void udt_kill_transfer(struct unidirectional_transfer *t)
1077 t->state = SSTATE_FINISHED;
1079 * Socket read end left open isn't a disaster if nobody
1080 * attempts to read from it (mingw compat headers do not
1081 * have SHUT_RD)...
1083 * We can't fully close the socket since otherwise gtp
1084 * task would first close the socket it sends data to
1085 * while closing the ptg file descriptors.
1087 if (!t->src_is_sock)
1088 close(t->src);
1089 if (t->dest_is_sock)
1090 shutdown(t->dest, SHUT_WR);
1091 else
1092 close(t->dest);
1096 * Join process, with apporiate errors on failure. Name is name for the
1097 * process (for error messages). Returns 0 on success, 1 on failure.
1099 static int tloop_join(pid_t pid, const char *name)
1101 int tret;
1102 if (waitpid(pid, &tret, 0) < 0) {
1103 error("%s process failed to wait: %s", name, strerror(errno));
1104 return 1;
1106 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1107 error("%s process failed", name);
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 pid_t pid1, pid2;
1120 int ret = 0;
1122 /* Fork thread #1: git to program. */
1123 pid1 = fork();
1124 if (pid1 < 0)
1125 die_errno("Can't start thread for copying data");
1126 else if (pid1 == 0) {
1127 udt_kill_transfer(&s->ptg);
1128 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1131 /* Fork thread #2: program to git. */
1132 pid2 = fork();
1133 if (pid2 < 0)
1134 die_errno("Can't start thread for copying data");
1135 else if (pid2 == 0) {
1136 udt_kill_transfer(&s->gtp);
1137 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1141 * Close both streams in parent as to not interfere with
1142 * end of file detection and wait for both tasks to finish.
1144 udt_kill_transfer(&s->gtp);
1145 udt_kill_transfer(&s->ptg);
1146 ret |= tloop_join(pid1, "Git to program copy");
1147 ret |= tloop_join(pid2, "Program to git copy");
1148 return ret;
1150 #endif
1153 * Copies data from stdin to output and from input to stdout simultaneously.
1154 * Additionally filtering through given filter. If filter is NULL, uses
1155 * identity filter.
1157 int bidirectional_transfer_loop(int input, int output)
1159 struct bidirectional_transfer_state state;
1161 /* Fill the state fields. */
1162 state.ptg.src = input;
1163 state.ptg.dest = 1;
1164 state.ptg.src_is_sock = (input == output);
1165 state.ptg.dest_is_sock = 0;
1166 state.ptg.state = SSTATE_TRANSFERING;
1167 state.ptg.bufuse = 0;
1168 state.ptg.src_name = "remote input";
1169 state.ptg.dest_name = "stdout";
1171 state.gtp.src = 0;
1172 state.gtp.dest = output;
1173 state.gtp.src_is_sock = 0;
1174 state.gtp.dest_is_sock = (input == output);
1175 state.gtp.state = SSTATE_TRANSFERING;
1176 state.gtp.bufuse = 0;
1177 state.gtp.src_name = "stdin";
1178 state.gtp.dest_name = "remote output";
1180 return tloop_spawnwait_tasks(&state);