Merge branch 'master' into next
[git/mingw/4msysgit.git] / transport-helper.c
blob3a50856318798c14824bb628d7d463cd61b77213
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"
12 #ifndef NO_PTHREADS
13 #include <pthread.h>
14 #include "thread-utils.h"
15 #endif
17 static int debug;
19 struct helper_data
21 const char *name;
22 struct child_process *helper;
23 FILE *out;
24 unsigned fetch : 1,
25 import : 1,
26 export : 1,
27 option : 1,
28 push : 1,
29 connect : 1,
30 no_disconnect_req : 1;
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 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;
114 if (data->helper)
115 return data->helper;
117 helper = xcalloc(1, sizeof(*helper));
118 helper->in = -1;
119 helper->out = -1;
120 helper->err = 0;
121 helper->argv = xcalloc(4, sizeof(*helper->argv));
122 strbuf_addf(&buf, "git-remote-%s", data->name);
123 helper->argv[0] = strbuf_detach(&buf, NULL);
124 helper->argv[1] = transport->remote->name;
125 helper->argv[2] = remove_ext_force(transport->url);
126 helper->git_cmd = 0;
127 helper->silent_exec_failure = 1;
128 code = start_command(helper);
129 if (code < 0 && errno == ENOENT)
130 die("Unable to find remote helper for '%s'", data->name);
131 else if (code != 0)
132 exit(code);
134 data->helper = helper;
135 data->no_disconnect_req = 0;
138 * Open the output as FILE* so strbuf_getline() can be used.
139 * Do this with duped fd because fclose() will close the fd,
140 * and stuff like taking over will require the fd to remain.
142 duped = dup(helper->out);
143 if (duped < 0)
144 die_errno("Can't dup helper output fd");
145 data->out = xfdopen(duped, "r");
147 write_constant(helper->in, "capabilities\n");
149 while (1) {
150 const char *capname;
151 int mandatory = 0;
152 recvline(data, &buf);
154 if (!*buf.buf)
155 break;
157 if (*buf.buf == '*') {
158 capname = buf.buf + 1;
159 mandatory = 1;
160 } else
161 capname = buf.buf;
163 if (debug)
164 fprintf(stderr, "Debug: Got cap %s\n", capname);
165 if (!strcmp(capname, "fetch"))
166 data->fetch = 1;
167 else if (!strcmp(capname, "option"))
168 data->option = 1;
169 else if (!strcmp(capname, "push"))
170 data->push = 1;
171 else if (!strcmp(capname, "import"))
172 data->import = 1;
173 else if (!strcmp(capname, "export"))
174 data->export = 1;
175 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
176 ALLOC_GROW(refspecs,
177 refspec_nr + 1,
178 refspec_alloc);
179 refspecs[refspec_nr++] = strdup(buf.buf + strlen("refspec "));
180 } else if (!strcmp(capname, "connect")) {
181 data->connect = 1;
182 } else if (!strcmp(buf.buf, "gitdir")) {
183 struct strbuf gitdir = STRBUF_INIT;
184 strbuf_addf(&gitdir, "gitdir %s\n", get_git_dir());
185 sendline(data, &gitdir);
186 strbuf_release(&gitdir);
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 child_process *helper;
570 struct ref *ref;
572 helper = get_helper(transport);
573 if (!data->push)
574 return 1;
576 for (ref = remote_refs; ref; ref = ref->next) {
577 if (!ref->peer_ref && !mirror)
578 continue;
580 /* Check for statuses set by set_ref_status_for_push() */
581 switch (ref->status) {
582 case REF_STATUS_REJECT_NONFASTFORWARD:
583 case REF_STATUS_UPTODATE:
584 continue;
585 default:
586 ; /* do nothing */
589 if (force_all)
590 ref->force = 1;
592 strbuf_addstr(&buf, "push ");
593 if (!ref->deletion) {
594 if (ref->force)
595 strbuf_addch(&buf, '+');
596 if (ref->peer_ref)
597 strbuf_addstr(&buf, ref->peer_ref->name);
598 else
599 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
601 strbuf_addch(&buf, ':');
602 strbuf_addstr(&buf, ref->name);
603 strbuf_addch(&buf, '\n');
605 if (buf.len == 0)
606 return 0;
608 standard_options(transport);
610 if (flags & TRANSPORT_PUSH_DRY_RUN) {
611 if (set_helper_option(transport, "dry-run", "true") != 0)
612 die("helper %s does not support dry-run", data->name);
615 strbuf_addch(&buf, '\n');
616 sendline(data, &buf);
618 ref = remote_refs;
619 while (1) {
620 char *refname, *msg;
621 int status;
623 recvline(data, &buf);
624 if (!buf.len)
625 break;
627 if (!prefixcmp(buf.buf, "ok ")) {
628 status = REF_STATUS_OK;
629 refname = buf.buf + 3;
630 } else if (!prefixcmp(buf.buf, "error ")) {
631 status = REF_STATUS_REMOTE_REJECT;
632 refname = buf.buf + 6;
633 } else
634 die("expected ok/error, helper said '%s'\n", buf.buf);
636 msg = strchr(refname, ' ');
637 if (msg) {
638 struct strbuf msg_buf = STRBUF_INIT;
639 const char *end;
641 *msg++ = '\0';
642 if (!unquote_c_style(&msg_buf, msg, &end))
643 msg = strbuf_detach(&msg_buf, NULL);
644 else
645 msg = xstrdup(msg);
646 strbuf_release(&msg_buf);
648 if (!strcmp(msg, "no match")) {
649 status = REF_STATUS_NONE;
650 free(msg);
651 msg = NULL;
653 else if (!strcmp(msg, "up to date")) {
654 status = REF_STATUS_UPTODATE;
655 free(msg);
656 msg = NULL;
658 else if (!strcmp(msg, "non-fast forward")) {
659 status = REF_STATUS_REJECT_NONFASTFORWARD;
660 free(msg);
661 msg = NULL;
665 if (ref)
666 ref = find_ref_by_name(ref, refname);
667 if (!ref)
668 ref = find_ref_by_name(remote_refs, refname);
669 if (!ref) {
670 warning("helper reported unexpected status of %s", refname);
671 continue;
674 if (ref->status != REF_STATUS_NONE) {
676 * Earlier, the ref was marked not to be pushed, so ignore the ref
677 * status reported by the remote helper if the latter is 'no match'.
679 if (status == REF_STATUS_NONE)
680 continue;
683 ref->status = status;
684 ref->remote_status = msg;
686 strbuf_release(&buf);
687 return 0;
690 static int push_refs_with_export(struct transport *transport,
691 struct ref *remote_refs, int flags)
693 struct ref *ref;
694 struct child_process *helper, exporter;
695 struct helper_data *data = transport->data;
696 char *export_marks = NULL, *import_marks = NULL;
697 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
698 struct strbuf buf = STRBUF_INIT;
700 helper = get_helper(transport);
702 write_constant(helper->in, "export\n");
704 recvline(data, &buf);
705 if (debug)
706 fprintf(stderr, "Debug: Got export_marks '%s'\n", buf.buf);
707 if (buf.len) {
708 struct strbuf arg = STRBUF_INIT;
709 strbuf_addstr(&arg, "--export-marks=");
710 strbuf_addbuf(&arg, &buf);
711 export_marks = strbuf_detach(&arg, NULL);
714 recvline(data, &buf);
715 if (debug)
716 fprintf(stderr, "Debug: Got import_marks '%s'\n", buf.buf);
717 if (buf.len) {
718 struct strbuf arg = STRBUF_INIT;
719 strbuf_addstr(&arg, "--import-marks=");
720 strbuf_addbuf(&arg, &buf);
721 import_marks = strbuf_detach(&arg, NULL);
724 strbuf_reset(&buf);
726 for (ref = remote_refs; ref; ref = ref->next) {
727 char *private;
728 unsigned char sha1[20];
730 if (!data->refspecs)
731 continue;
732 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
733 if (private && !get_sha1(private, sha1)) {
734 strbuf_addf(&buf, "^%s", private);
735 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
738 string_list_append(&revlist_args, ref->name);
742 if (get_exporter(transport, &exporter,
743 export_marks, import_marks, &revlist_args))
744 die("Couldn't run fast-export");
746 data->no_disconnect_req = 1;
747 finish_command(&exporter);
748 disconnect_helper(transport);
749 return 0;
752 static int push_refs(struct transport *transport,
753 struct ref *remote_refs, int flags)
755 struct helper_data *data = transport->data;
757 if (process_connect(transport, 1)) {
758 do_take_over(transport);
759 return transport->push_refs(transport, remote_refs, flags);
762 if (!remote_refs) {
763 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
764 "Perhaps you should specify a branch such as 'master'.\n");
765 return 0;
768 if (data->push)
769 return push_refs_with_push(transport, remote_refs, flags);
771 if (data->export)
772 return push_refs_with_export(transport, remote_refs, flags);
774 return -1;
778 static int has_attribute(const char *attrs, const char *attr) {
779 int len;
780 if (!attrs)
781 return 0;
783 len = strlen(attr);
784 for (;;) {
785 const char *space = strchrnul(attrs, ' ');
786 if (len == space - attrs && !strncmp(attrs, attr, len))
787 return 1;
788 if (!*space)
789 return 0;
790 attrs = space + 1;
794 static struct ref *get_refs_list(struct transport *transport, int for_push)
796 struct helper_data *data = transport->data;
797 struct child_process *helper;
798 struct ref *ret = NULL;
799 struct ref **tail = &ret;
800 struct ref *posn;
801 struct strbuf buf = STRBUF_INIT;
803 helper = get_helper(transport);
805 if (process_connect(transport, for_push)) {
806 do_take_over(transport);
807 return transport->get_refs_list(transport, for_push);
810 if (data->push && for_push)
811 write_str_in_full(helper->in, "list for-push\n");
812 else
813 write_str_in_full(helper->in, "list\n");
815 while (1) {
816 char *eov, *eon;
817 recvline(data, &buf);
819 if (!*buf.buf)
820 break;
822 eov = strchr(buf.buf, ' ');
823 if (!eov)
824 die("Malformed response in ref list: %s", buf.buf);
825 eon = strchr(eov + 1, ' ');
826 *eov = '\0';
827 if (eon)
828 *eon = '\0';
829 *tail = alloc_ref(eov + 1);
830 if (buf.buf[0] == '@')
831 (*tail)->symref = xstrdup(buf.buf + 1);
832 else if (buf.buf[0] != '?')
833 get_sha1_hex(buf.buf, (*tail)->old_sha1);
834 if (eon) {
835 if (has_attribute(eon + 1, "unchanged")) {
836 (*tail)->status |= REF_STATUS_UPTODATE;
837 read_ref((*tail)->name, (*tail)->old_sha1);
840 tail = &((*tail)->next);
842 if (debug)
843 fprintf(stderr, "Debug: Read ref listing.\n");
844 strbuf_release(&buf);
846 for (posn = ret; posn; posn = posn->next)
847 resolve_remote_symref(posn, ret);
849 return ret;
852 int transport_helper_init(struct transport *transport, const char *name)
854 struct helper_data *data = xcalloc(sizeof(*data), 1);
855 data->name = name;
857 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
858 debug = 1;
860 transport->data = data;
861 transport->set_option = set_helper_option;
862 transport->get_refs_list = get_refs_list;
863 transport->fetch = fetch;
864 transport->push_refs = push_refs;
865 transport->disconnect = release_helper;
866 transport->connect = connect_helper;
867 transport->smart_options = &(data->transport_options);
868 return 0;
872 * Linux pipes can buffer 65536 bytes at once (and most platforms can
873 * buffer less), so attempt reads and writes with up to that size.
875 #define BUFFERSIZE 65536
876 /* This should be enough to hold debugging message. */
877 #define PBUFFERSIZE 8192
879 /* Print bidirectional transfer loop debug message. */
880 static void transfer_debug(const char *fmt, ...)
882 va_list args;
883 char msgbuf[PBUFFERSIZE];
884 static int debug_enabled = -1;
886 if (debug_enabled < 0)
887 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
888 if (!debug_enabled)
889 return;
891 va_start(args, fmt);
892 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
893 va_end(args);
894 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
897 /* Stream state: More data may be coming in this direction. */
898 #define SSTATE_TRANSFERING 0
900 * Stream state: No more data coming in this direction, flushing rest of
901 * data.
903 #define SSTATE_FLUSHING 1
904 /* Stream state: Transfer in this direction finished. */
905 #define SSTATE_FINISHED 2
907 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
908 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
909 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
911 /* Unidirectional transfer. */
912 struct unidirectional_transfer {
913 /* Source */
914 int src;
915 /* Destination */
916 int dest;
917 /* Is source socket? */
918 int src_is_sock;
919 /* Is destination socket? */
920 int dest_is_sock;
921 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
922 int state;
923 /* Buffer. */
924 char buf[BUFFERSIZE];
925 /* Buffer used. */
926 size_t bufuse;
927 /* Name of source. */
928 const char *src_name;
929 /* Name of destination. */
930 const char *dest_name;
933 /* Closes the target (for writing) if transfer has finished. */
934 static void udt_close_if_finished(struct unidirectional_transfer *t)
936 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
937 t->state = SSTATE_FINISHED;
938 if (t->dest_is_sock)
939 shutdown(t->dest, SHUT_WR);
940 else
941 close(t->dest);
942 transfer_debug("Closed %s.", t->dest_name);
947 * Tries to read read data from source into buffer. If buffer is full,
948 * no data is read. Returns 0 on success, -1 on error.
950 static int udt_do_read(struct unidirectional_transfer *t)
952 ssize_t bytes;
954 if (t->bufuse == BUFFERSIZE)
955 return 0; /* No space for more. */
957 transfer_debug("%s is readable", t->src_name);
958 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
959 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
960 errno != EINTR) {
961 error("read(%s) failed: %s", t->src_name, strerror(errno));
962 return -1;
963 } else if (bytes == 0) {
964 transfer_debug("%s EOF (with %i bytes in buffer)",
965 t->src_name, t->bufuse);
966 t->state = SSTATE_FLUSHING;
967 } else if (bytes > 0) {
968 t->bufuse += bytes;
969 transfer_debug("Read %i bytes from %s (buffer now at %i)",
970 (int)bytes, t->src_name, (int)t->bufuse);
972 return 0;
975 /* Tries to write data from buffer into destination. If buffer is empty,
976 * no data is written. Returns 0 on success, -1 on error.
978 static int udt_do_write(struct unidirectional_transfer *t)
980 size_t bytes;
982 if (t->bufuse == 0)
983 return 0; /* Nothing to write. */
985 transfer_debug("%s is writable", t->dest_name);
986 bytes = write(t->dest, t->buf, t->bufuse);
987 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
988 errno != EINTR) {
989 error("write(%s) failed: %s", t->dest_name, strerror(errno));
990 return -1;
991 } else if (bytes > 0) {
992 t->bufuse -= bytes;
993 if (t->bufuse)
994 memmove(t->buf, t->buf + bytes, t->bufuse);
995 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
996 (int)bytes, t->dest_name, (int)t->bufuse);
998 return 0;
1002 /* State of bidirectional transfer loop. */
1003 struct bidirectional_transfer_state {
1004 /* Direction from program to git. */
1005 struct unidirectional_transfer ptg;
1006 /* Direction from git to program. */
1007 struct unidirectional_transfer gtp;
1010 static void *udt_copy_task_routine(void *udt)
1012 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1013 while (t->state != SSTATE_FINISHED) {
1014 if (STATE_NEEDS_READING(t->state))
1015 if (udt_do_read(t))
1016 return NULL;
1017 if (STATE_NEEDS_WRITING(t->state))
1018 if (udt_do_write(t))
1019 return NULL;
1020 if (STATE_NEEDS_CLOSING(t->state))
1021 udt_close_if_finished(t);
1023 return udt; /* Just some non-NULL value. */
1026 #ifndef NO_PTHREADS
1029 * Join thread, with apporiate errors on failure. Name is name for the
1030 * thread (for error messages). Returns 0 on success, 1 on failure.
1032 static int tloop_join(pthread_t thread, const char *name)
1034 int err;
1035 void *tret;
1036 err = pthread_join(thread, &tret);
1037 if (!tret) {
1038 error("%s thread failed", name);
1039 return 1;
1041 if (err) {
1042 error("%s thread failed to join: %s", name, strerror(err));
1043 return 1;
1045 return 0;
1049 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1050 * -1 on failure.
1052 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1054 pthread_t gtp_thread;
1055 pthread_t ptg_thread;
1056 int err;
1057 int ret = 0;
1058 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1059 &s->gtp);
1060 if (err)
1061 die("Can't start thread for copying data: %s", strerror(err));
1062 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1063 &s->ptg);
1064 if (err)
1065 die("Can't start thread for copying data: %s", strerror(err));
1067 ret |= tloop_join(gtp_thread, "Git to program copy");
1068 ret |= tloop_join(ptg_thread, "Program to git copy");
1069 return ret;
1071 #else
1073 /* Close the source and target (for writing) for transfer. */
1074 static void udt_kill_transfer(struct unidirectional_transfer *t)
1076 t->state = SSTATE_FINISHED;
1078 * Socket read end left open isn't a disaster if nobody
1079 * attempts to read from it (mingw compat headers do not
1080 * have SHUT_RD)...
1082 * We can't fully close the socket since otherwise gtp
1083 * task would first close the socket it sends data to
1084 * while closing the ptg file descriptors.
1086 if (!t->src_is_sock)
1087 close(t->src);
1088 if (t->dest_is_sock)
1089 shutdown(t->dest, SHUT_WR);
1090 else
1091 close(t->dest);
1095 * Join process, with apporiate errors on failure. Name is name for the
1096 * process (for error messages). Returns 0 on success, 1 on failure.
1098 static int tloop_join(pid_t pid, const char *name)
1100 int tret;
1101 if (waitpid(pid, &tret, 0) < 0) {
1102 error("%s process failed to wait: %s", name, strerror(errno));
1103 return 1;
1105 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1106 error("%s process failed", name);
1107 return 1;
1109 return 0;
1113 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1114 * -1 on failure.
1116 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1118 pid_t pid1, pid2;
1119 int ret = 0;
1121 /* Fork thread #1: git to program. */
1122 pid1 = fork();
1123 if (pid1 < 0)
1124 die_errno("Can't start thread for copying data");
1125 else if (pid1 == 0) {
1126 udt_kill_transfer(&s->ptg);
1127 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1130 /* Fork thread #2: program to git. */
1131 pid2 = fork();
1132 if (pid2 < 0)
1133 die_errno("Can't start thread for copying data");
1134 else if (pid2 == 0) {
1135 udt_kill_transfer(&s->gtp);
1136 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1140 * Close both streams in parent as to not interfere with
1141 * end of file detection and wait for both tasks to finish.
1143 udt_kill_transfer(&s->gtp);
1144 udt_kill_transfer(&s->ptg);
1145 ret |= tloop_join(pid1, "Git to program copy");
1146 ret |= tloop_join(pid2, "Program to git copy");
1147 return ret;
1149 #endif
1152 * Copies data from stdin to output and from input to stdout simultaneously.
1153 * Additionally filtering through given filter. If filter is NULL, uses
1154 * identity filter.
1156 int bidirectional_transfer_loop(int input, int output)
1158 struct bidirectional_transfer_state state;
1160 /* Fill the state fields. */
1161 state.ptg.src = input;
1162 state.ptg.dest = 1;
1163 state.ptg.src_is_sock = (input == output);
1164 state.ptg.dest_is_sock = 0;
1165 state.ptg.state = SSTATE_TRANSFERING;
1166 state.ptg.bufuse = 0;
1167 state.ptg.src_name = "remote input";
1168 state.ptg.dest_name = "stdout";
1170 state.gtp.src = 0;
1171 state.gtp.dest = output;
1172 state.gtp.src_is_sock = 0;
1173 state.gtp.dest_is_sock = (input == output);
1174 state.gtp.state = SSTATE_TRANSFERING;
1175 state.gtp.bufuse = 0;
1176 state.gtp.src_name = "stdin";
1177 state.gtp.dest_name = "remote output";
1179 return tloop_spawnwait_tasks(&state);