transport-helper: change import semantics
[alt-git.git] / transport-helper.c
blob0c00be9dc7a12645242008a3ad869c0cb3f63caf
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;
212 int res = 0;
214 if (data->helper) {
215 if (debug)
216 fprintf(stderr, "Debug: Disconnecting.\n");
217 if (!data->no_disconnect_req) {
218 strbuf_addf(&buf, "\n");
219 sendline(data, &buf);
221 close(data->helper->in);
222 close(data->helper->out);
223 fclose(data->out);
224 res = finish_command(data->helper);
225 free((char *)data->helper->argv[0]);
226 free(data->helper->argv);
227 free(data->helper);
228 data->helper = NULL;
230 return res;
233 static const char *unsupported_options[] = {
234 TRANS_OPT_UPLOADPACK,
235 TRANS_OPT_RECEIVEPACK,
236 TRANS_OPT_THIN,
237 TRANS_OPT_KEEP
239 static const char *boolean_options[] = {
240 TRANS_OPT_THIN,
241 TRANS_OPT_KEEP,
242 TRANS_OPT_FOLLOWTAGS
245 static int set_helper_option(struct transport *transport,
246 const char *name, const char *value)
248 struct helper_data *data = transport->data;
249 struct strbuf buf = STRBUF_INIT;
250 int i, ret, is_bool = 0;
252 get_helper(transport);
254 if (!data->option)
255 return 1;
257 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
258 if (!strcmp(name, unsupported_options[i]))
259 return 1;
262 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
263 if (!strcmp(name, boolean_options[i])) {
264 is_bool = 1;
265 break;
269 strbuf_addf(&buf, "option %s ", name);
270 if (is_bool)
271 strbuf_addstr(&buf, value ? "true" : "false");
272 else
273 quote_c_style(value, &buf, NULL, 0);
274 strbuf_addch(&buf, '\n');
276 xchgline(data, &buf);
278 if (!strcmp(buf.buf, "ok"))
279 ret = 0;
280 else if (!prefixcmp(buf.buf, "error")) {
281 ret = -1;
282 } else if (!strcmp(buf.buf, "unsupported"))
283 ret = 1;
284 else {
285 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
286 ret = 1;
288 strbuf_release(&buf);
289 return ret;
292 static void standard_options(struct transport *t)
294 char buf[16];
295 int n;
296 int v = t->verbose;
298 set_helper_option(t, "progress", t->progress ? "true" : "false");
300 n = snprintf(buf, sizeof(buf), "%d", v + 1);
301 if (n >= sizeof(buf))
302 die("impossibly large verbosity value");
303 set_helper_option(t, "verbosity", buf);
306 static int release_helper(struct transport *transport)
308 int res = 0;
309 struct helper_data *data = transport->data;
310 free_refspec(data->refspec_nr, data->refspecs);
311 data->refspecs = NULL;
312 res = disconnect_helper(transport);
313 free(transport->data);
314 return res;
317 static int fetch_with_fetch(struct transport *transport,
318 int nr_heads, struct ref **to_fetch)
320 struct helper_data *data = transport->data;
321 int i;
322 struct strbuf buf = STRBUF_INIT;
324 standard_options(transport);
326 for (i = 0; i < nr_heads; i++) {
327 const struct ref *posn = to_fetch[i];
328 if (posn->status & REF_STATUS_UPTODATE)
329 continue;
331 strbuf_addf(&buf, "fetch %s %s\n",
332 sha1_to_hex(posn->old_sha1), posn->name);
335 strbuf_addch(&buf, '\n');
336 sendline(data, &buf);
338 while (1) {
339 recvline(data, &buf);
341 if (!prefixcmp(buf.buf, "lock ")) {
342 const char *name = buf.buf + 5;
343 if (transport->pack_lockfile)
344 warning("%s also locked %s", data->name, name);
345 else
346 transport->pack_lockfile = xstrdup(name);
348 else if (!buf.len)
349 break;
350 else
351 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
353 strbuf_release(&buf);
354 return 0;
357 static int get_importer(struct transport *transport, struct child_process *fastimport)
359 struct child_process *helper = get_helper(transport);
360 memset(fastimport, 0, sizeof(*fastimport));
361 fastimport->in = helper->out;
362 fastimport->argv = xcalloc(5, sizeof(*fastimport->argv));
363 fastimport->argv[0] = "fast-import";
364 fastimport->argv[1] = "--quiet";
366 fastimport->git_cmd = 1;
367 return start_command(fastimport);
370 static int get_exporter(struct transport *transport,
371 struct child_process *fastexport,
372 const char *export_marks,
373 const char *import_marks,
374 struct string_list *revlist_args)
376 struct child_process *helper = get_helper(transport);
377 int argc = 0, i;
378 memset(fastexport, 0, sizeof(*fastexport));
380 /* we need to duplicate helper->in because we want to use it after
381 * fastexport is done with it. */
382 fastexport->out = dup(helper->in);
383 fastexport->argv = xcalloc(5 + revlist_args->nr, sizeof(*fastexport->argv));
384 fastexport->argv[argc++] = "fast-export";
385 fastexport->argv[argc++] = "--use-done-feature";
386 if (export_marks)
387 fastexport->argv[argc++] = export_marks;
388 if (import_marks)
389 fastexport->argv[argc++] = import_marks;
391 for (i = 0; i < revlist_args->nr; i++)
392 fastexport->argv[argc++] = revlist_args->items[i].string;
394 fastexport->git_cmd = 1;
395 return start_command(fastexport);
398 static int fetch_with_import(struct transport *transport,
399 int nr_heads, struct ref **to_fetch)
401 struct child_process fastimport;
402 struct helper_data *data = transport->data;
403 int i;
404 struct ref *posn;
405 struct strbuf buf = STRBUF_INIT;
407 get_helper(transport);
409 if (get_importer(transport, &fastimport))
410 die("Couldn't run fast-import");
412 for (i = 0; i < nr_heads; i++) {
413 posn = to_fetch[i];
414 if (posn->status & REF_STATUS_UPTODATE)
415 continue;
417 strbuf_addf(&buf, "import %s\n", posn->name);
418 sendline(data, &buf);
419 strbuf_reset(&buf);
422 write_constant(data->helper->in, "\n");
424 if (finish_command(&fastimport))
425 die("Error while running fast-import");
426 free(fastimport.argv);
427 fastimport.argv = NULL;
429 for (i = 0; i < nr_heads; i++) {
430 char *private;
431 posn = to_fetch[i];
432 if (posn->status & REF_STATUS_UPTODATE)
433 continue;
434 if (data->refspecs)
435 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
436 else
437 private = strdup(posn->name);
438 read_ref(private, posn->old_sha1);
439 free(private);
441 strbuf_release(&buf);
442 return 0;
445 static int process_connect_service(struct transport *transport,
446 const char *name, const char *exec)
448 struct helper_data *data = transport->data;
449 struct strbuf cmdbuf = STRBUF_INIT;
450 struct child_process *helper;
451 int r, duped, ret = 0;
452 FILE *input;
454 helper = get_helper(transport);
457 * Yes, dup the pipe another time, as we need unbuffered version
458 * of input pipe as FILE*. fclose() closes the underlying fd and
459 * stream buffering only can be changed before first I/O operation
460 * on it.
462 duped = dup(helper->out);
463 if (duped < 0)
464 die_errno("Can't dup helper output fd");
465 input = xfdopen(duped, "r");
466 setvbuf(input, NULL, _IONBF, 0);
469 * Handle --upload-pack and friends. This is fire and forget...
470 * just warn if it fails.
472 if (strcmp(name, exec)) {
473 r = set_helper_option(transport, "servpath", exec);
474 if (r > 0)
475 warning("Setting remote service path not supported by protocol.");
476 else if (r < 0)
477 warning("Invalid remote service path.");
480 if (data->connect)
481 strbuf_addf(&cmdbuf, "connect %s\n", name);
482 else
483 goto exit;
485 sendline(data, &cmdbuf);
486 recvline_fh(input, &cmdbuf);
487 if (!strcmp(cmdbuf.buf, "")) {
488 data->no_disconnect_req = 1;
489 if (debug)
490 fprintf(stderr, "Debug: Smart transport connection "
491 "ready.\n");
492 ret = 1;
493 } else if (!strcmp(cmdbuf.buf, "fallback")) {
494 if (debug)
495 fprintf(stderr, "Debug: Falling back to dumb "
496 "transport.\n");
497 } else
498 die("Unknown response to connect: %s",
499 cmdbuf.buf);
501 exit:
502 fclose(input);
503 return ret;
506 static int process_connect(struct transport *transport,
507 int for_push)
509 struct helper_data *data = transport->data;
510 const char *name;
511 const char *exec;
513 name = for_push ? "git-receive-pack" : "git-upload-pack";
514 if (for_push)
515 exec = data->transport_options.receivepack;
516 else
517 exec = data->transport_options.uploadpack;
519 return process_connect_service(transport, name, exec);
522 static int connect_helper(struct transport *transport, const char *name,
523 const char *exec, int fd[2])
525 struct helper_data *data = transport->data;
527 /* Get_helper so connect is inited. */
528 get_helper(transport);
529 if (!data->connect)
530 die("Operation not supported by protocol.");
532 if (!process_connect_service(transport, name, exec))
533 die("Can't connect to subservice %s.", name);
535 fd[0] = data->helper->out;
536 fd[1] = data->helper->in;
537 return 0;
540 static int fetch(struct transport *transport,
541 int nr_heads, struct ref **to_fetch)
543 struct helper_data *data = transport->data;
544 int i, count;
546 if (process_connect(transport, 0)) {
547 do_take_over(transport);
548 return transport->fetch(transport, nr_heads, to_fetch);
551 count = 0;
552 for (i = 0; i < nr_heads; i++)
553 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
554 count++;
556 if (!count)
557 return 0;
559 if (data->fetch)
560 return fetch_with_fetch(transport, nr_heads, to_fetch);
562 if (data->import)
563 return fetch_with_import(transport, nr_heads, to_fetch);
565 return -1;
568 static void push_update_ref_status(struct strbuf *buf,
569 struct ref **ref,
570 struct ref *remote_refs)
572 char *refname, *msg;
573 int status;
575 if (!prefixcmp(buf->buf, "ok ")) {
576 status = REF_STATUS_OK;
577 refname = buf->buf + 3;
578 } else if (!prefixcmp(buf->buf, "error ")) {
579 status = REF_STATUS_REMOTE_REJECT;
580 refname = buf->buf + 6;
581 } else
582 die("expected ok/error, helper said '%s'\n", buf->buf);
584 msg = strchr(refname, ' ');
585 if (msg) {
586 struct strbuf msg_buf = STRBUF_INIT;
587 const char *end;
589 *msg++ = '\0';
590 if (!unquote_c_style(&msg_buf, msg, &end))
591 msg = strbuf_detach(&msg_buf, NULL);
592 else
593 msg = xstrdup(msg);
594 strbuf_release(&msg_buf);
596 if (!strcmp(msg, "no match")) {
597 status = REF_STATUS_NONE;
598 free(msg);
599 msg = NULL;
601 else if (!strcmp(msg, "up to date")) {
602 status = REF_STATUS_UPTODATE;
603 free(msg);
604 msg = NULL;
606 else if (!strcmp(msg, "non-fast forward")) {
607 status = REF_STATUS_REJECT_NONFASTFORWARD;
608 free(msg);
609 msg = NULL;
613 if (*ref)
614 *ref = find_ref_by_name(*ref, refname);
615 if (!*ref)
616 *ref = find_ref_by_name(remote_refs, refname);
617 if (!*ref) {
618 warning("helper reported unexpected status of %s", refname);
619 return;
622 if ((*ref)->status != REF_STATUS_NONE) {
624 * Earlier, the ref was marked not to be pushed, so ignore the ref
625 * status reported by the remote helper if the latter is 'no match'.
627 if (status == REF_STATUS_NONE)
628 return;
631 (*ref)->status = status;
632 (*ref)->remote_status = msg;
635 static void push_update_refs_status(struct helper_data *data,
636 struct ref *remote_refs)
638 struct strbuf buf = STRBUF_INIT;
639 struct ref *ref = remote_refs;
640 for (;;) {
641 recvline(data, &buf);
642 if (!buf.len)
643 break;
645 push_update_ref_status(&buf, &ref, remote_refs);
647 strbuf_release(&buf);
650 static int push_refs_with_push(struct transport *transport,
651 struct ref *remote_refs, int flags)
653 int force_all = flags & TRANSPORT_PUSH_FORCE;
654 int mirror = flags & TRANSPORT_PUSH_MIRROR;
655 struct helper_data *data = transport->data;
656 struct strbuf buf = STRBUF_INIT;
657 struct ref *ref;
659 get_helper(transport);
660 if (!data->push)
661 return 1;
663 for (ref = remote_refs; ref; ref = ref->next) {
664 if (!ref->peer_ref && !mirror)
665 continue;
667 /* Check for statuses set by set_ref_status_for_push() */
668 switch (ref->status) {
669 case REF_STATUS_REJECT_NONFASTFORWARD:
670 case REF_STATUS_UPTODATE:
671 continue;
672 default:
673 ; /* do nothing */
676 if (force_all)
677 ref->force = 1;
679 strbuf_addstr(&buf, "push ");
680 if (!ref->deletion) {
681 if (ref->force)
682 strbuf_addch(&buf, '+');
683 if (ref->peer_ref)
684 strbuf_addstr(&buf, ref->peer_ref->name);
685 else
686 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
688 strbuf_addch(&buf, ':');
689 strbuf_addstr(&buf, ref->name);
690 strbuf_addch(&buf, '\n');
692 if (buf.len == 0)
693 return 0;
695 standard_options(transport);
697 if (flags & TRANSPORT_PUSH_DRY_RUN) {
698 if (set_helper_option(transport, "dry-run", "true") != 0)
699 die("helper %s does not support dry-run", data->name);
702 strbuf_addch(&buf, '\n');
703 sendline(data, &buf);
704 strbuf_release(&buf);
706 push_update_refs_status(data, remote_refs);
707 return 0;
710 static int push_refs_with_export(struct transport *transport,
711 struct ref *remote_refs, int flags)
713 struct ref *ref;
714 struct child_process *helper, exporter;
715 struct helper_data *data = transport->data;
716 char *export_marks = NULL, *import_marks = NULL;
717 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
718 struct strbuf buf = STRBUF_INIT;
720 helper = get_helper(transport);
722 write_constant(helper->in, "export\n");
724 recvline(data, &buf);
725 if (debug)
726 fprintf(stderr, "Debug: Got export_marks '%s'\n", buf.buf);
727 if (buf.len) {
728 struct strbuf arg = STRBUF_INIT;
729 strbuf_addstr(&arg, "--export-marks=");
730 strbuf_addbuf(&arg, &buf);
731 export_marks = strbuf_detach(&arg, NULL);
734 recvline(data, &buf);
735 if (debug)
736 fprintf(stderr, "Debug: Got import_marks '%s'\n", buf.buf);
737 if (buf.len) {
738 struct strbuf arg = STRBUF_INIT;
739 strbuf_addstr(&arg, "--import-marks=");
740 strbuf_addbuf(&arg, &buf);
741 import_marks = strbuf_detach(&arg, NULL);
744 strbuf_reset(&buf);
746 for (ref = remote_refs; ref; ref = ref->next) {
747 char *private;
748 unsigned char sha1[20];
750 if (!data->refspecs)
751 continue;
752 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
753 if (private && !get_sha1(private, sha1)) {
754 strbuf_addf(&buf, "^%s", private);
755 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
757 free(private);
759 if (ref->peer_ref)
760 string_list_append(&revlist_args, ref->peer_ref->name);
764 if (get_exporter(transport, &exporter,
765 export_marks, import_marks, &revlist_args))
766 die("Couldn't run fast-export");
768 if (finish_command(&exporter))
769 die("Error while running fast-export");
770 push_update_refs_status(data, remote_refs);
771 return 0;
774 static int push_refs(struct transport *transport,
775 struct ref *remote_refs, int flags)
777 struct helper_data *data = transport->data;
779 if (process_connect(transport, 1)) {
780 do_take_over(transport);
781 return transport->push_refs(transport, remote_refs, flags);
784 if (!remote_refs) {
785 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
786 "Perhaps you should specify a branch such as 'master'.\n");
787 return 0;
790 if (data->push)
791 return push_refs_with_push(transport, remote_refs, flags);
793 if (data->export)
794 return push_refs_with_export(transport, remote_refs, flags);
796 return -1;
800 static int has_attribute(const char *attrs, const char *attr) {
801 int len;
802 if (!attrs)
803 return 0;
805 len = strlen(attr);
806 for (;;) {
807 const char *space = strchrnul(attrs, ' ');
808 if (len == space - attrs && !strncmp(attrs, attr, len))
809 return 1;
810 if (!*space)
811 return 0;
812 attrs = space + 1;
816 static struct ref *get_refs_list(struct transport *transport, int for_push)
818 struct helper_data *data = transport->data;
819 struct child_process *helper;
820 struct ref *ret = NULL;
821 struct ref **tail = &ret;
822 struct ref *posn;
823 struct strbuf buf = STRBUF_INIT;
825 helper = get_helper(transport);
827 if (process_connect(transport, for_push)) {
828 do_take_over(transport);
829 return transport->get_refs_list(transport, for_push);
832 if (data->push && for_push)
833 write_str_in_full(helper->in, "list for-push\n");
834 else
835 write_str_in_full(helper->in, "list\n");
837 while (1) {
838 char *eov, *eon;
839 recvline(data, &buf);
841 if (!*buf.buf)
842 break;
844 eov = strchr(buf.buf, ' ');
845 if (!eov)
846 die("Malformed response in ref list: %s", buf.buf);
847 eon = strchr(eov + 1, ' ');
848 *eov = '\0';
849 if (eon)
850 *eon = '\0';
851 *tail = alloc_ref(eov + 1);
852 if (buf.buf[0] == '@')
853 (*tail)->symref = xstrdup(buf.buf + 1);
854 else if (buf.buf[0] != '?')
855 get_sha1_hex(buf.buf, (*tail)->old_sha1);
856 if (eon) {
857 if (has_attribute(eon + 1, "unchanged")) {
858 (*tail)->status |= REF_STATUS_UPTODATE;
859 read_ref((*tail)->name, (*tail)->old_sha1);
862 tail = &((*tail)->next);
864 if (debug)
865 fprintf(stderr, "Debug: Read ref listing.\n");
866 strbuf_release(&buf);
868 for (posn = ret; posn; posn = posn->next)
869 resolve_remote_symref(posn, ret);
871 return ret;
874 int transport_helper_init(struct transport *transport, const char *name)
876 struct helper_data *data = xcalloc(sizeof(*data), 1);
877 data->name = name;
879 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
880 debug = 1;
882 transport->data = data;
883 transport->set_option = set_helper_option;
884 transport->get_refs_list = get_refs_list;
885 transport->fetch = fetch;
886 transport->push_refs = push_refs;
887 transport->disconnect = release_helper;
888 transport->connect = connect_helper;
889 transport->smart_options = &(data->transport_options);
890 return 0;
894 * Linux pipes can buffer 65536 bytes at once (and most platforms can
895 * buffer less), so attempt reads and writes with up to that size.
897 #define BUFFERSIZE 65536
898 /* This should be enough to hold debugging message. */
899 #define PBUFFERSIZE 8192
901 /* Print bidirectional transfer loop debug message. */
902 static void transfer_debug(const char *fmt, ...)
904 va_list args;
905 char msgbuf[PBUFFERSIZE];
906 static int debug_enabled = -1;
908 if (debug_enabled < 0)
909 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
910 if (!debug_enabled)
911 return;
913 va_start(args, fmt);
914 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
915 va_end(args);
916 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
919 /* Stream state: More data may be coming in this direction. */
920 #define SSTATE_TRANSFERING 0
922 * Stream state: No more data coming in this direction, flushing rest of
923 * data.
925 #define SSTATE_FLUSHING 1
926 /* Stream state: Transfer in this direction finished. */
927 #define SSTATE_FINISHED 2
929 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
930 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
931 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
933 /* Unidirectional transfer. */
934 struct unidirectional_transfer {
935 /* Source */
936 int src;
937 /* Destination */
938 int dest;
939 /* Is source socket? */
940 int src_is_sock;
941 /* Is destination socket? */
942 int dest_is_sock;
943 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
944 int state;
945 /* Buffer. */
946 char buf[BUFFERSIZE];
947 /* Buffer used. */
948 size_t bufuse;
949 /* Name of source. */
950 const char *src_name;
951 /* Name of destination. */
952 const char *dest_name;
955 /* Closes the target (for writing) if transfer has finished. */
956 static void udt_close_if_finished(struct unidirectional_transfer *t)
958 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
959 t->state = SSTATE_FINISHED;
960 if (t->dest_is_sock)
961 shutdown(t->dest, SHUT_WR);
962 else
963 close(t->dest);
964 transfer_debug("Closed %s.", t->dest_name);
969 * Tries to read read data from source into buffer. If buffer is full,
970 * no data is read. Returns 0 on success, -1 on error.
972 static int udt_do_read(struct unidirectional_transfer *t)
974 ssize_t bytes;
976 if (t->bufuse == BUFFERSIZE)
977 return 0; /* No space for more. */
979 transfer_debug("%s is readable", t->src_name);
980 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
981 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
982 errno != EINTR) {
983 error("read(%s) failed: %s", t->src_name, strerror(errno));
984 return -1;
985 } else if (bytes == 0) {
986 transfer_debug("%s EOF (with %i bytes in buffer)",
987 t->src_name, t->bufuse);
988 t->state = SSTATE_FLUSHING;
989 } else if (bytes > 0) {
990 t->bufuse += bytes;
991 transfer_debug("Read %i bytes from %s (buffer now at %i)",
992 (int)bytes, t->src_name, (int)t->bufuse);
994 return 0;
997 /* Tries to write data from buffer into destination. If buffer is empty,
998 * no data is written. Returns 0 on success, -1 on error.
1000 static int udt_do_write(struct unidirectional_transfer *t)
1002 ssize_t bytes;
1004 if (t->bufuse == 0)
1005 return 0; /* Nothing to write. */
1007 transfer_debug("%s is writable", t->dest_name);
1008 bytes = write(t->dest, t->buf, t->bufuse);
1009 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1010 errno != EINTR) {
1011 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1012 return -1;
1013 } else if (bytes > 0) {
1014 t->bufuse -= bytes;
1015 if (t->bufuse)
1016 memmove(t->buf, t->buf + bytes, t->bufuse);
1017 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1018 (int)bytes, t->dest_name, (int)t->bufuse);
1020 return 0;
1024 /* State of bidirectional transfer loop. */
1025 struct bidirectional_transfer_state {
1026 /* Direction from program to git. */
1027 struct unidirectional_transfer ptg;
1028 /* Direction from git to program. */
1029 struct unidirectional_transfer gtp;
1032 static void *udt_copy_task_routine(void *udt)
1034 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1035 while (t->state != SSTATE_FINISHED) {
1036 if (STATE_NEEDS_READING(t->state))
1037 if (udt_do_read(t))
1038 return NULL;
1039 if (STATE_NEEDS_WRITING(t->state))
1040 if (udt_do_write(t))
1041 return NULL;
1042 if (STATE_NEEDS_CLOSING(t->state))
1043 udt_close_if_finished(t);
1045 return udt; /* Just some non-NULL value. */
1048 #ifndef NO_PTHREADS
1051 * Join thread, with apporiate errors on failure. Name is name for the
1052 * thread (for error messages). Returns 0 on success, 1 on failure.
1054 static int tloop_join(pthread_t thread, const char *name)
1056 int err;
1057 void *tret;
1058 err = pthread_join(thread, &tret);
1059 if (!tret) {
1060 error("%s thread failed", name);
1061 return 1;
1063 if (err) {
1064 error("%s thread failed to join: %s", name, strerror(err));
1065 return 1;
1067 return 0;
1071 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1072 * -1 on failure.
1074 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1076 pthread_t gtp_thread;
1077 pthread_t ptg_thread;
1078 int err;
1079 int ret = 0;
1080 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1081 &s->gtp);
1082 if (err)
1083 die("Can't start thread for copying data: %s", strerror(err));
1084 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1085 &s->ptg);
1086 if (err)
1087 die("Can't start thread for copying data: %s", strerror(err));
1089 ret |= tloop_join(gtp_thread, "Git to program copy");
1090 ret |= tloop_join(ptg_thread, "Program to git copy");
1091 return ret;
1093 #else
1095 /* Close the source and target (for writing) for transfer. */
1096 static void udt_kill_transfer(struct unidirectional_transfer *t)
1098 t->state = SSTATE_FINISHED;
1100 * Socket read end left open isn't a disaster if nobody
1101 * attempts to read from it (mingw compat headers do not
1102 * have SHUT_RD)...
1104 * We can't fully close the socket since otherwise gtp
1105 * task would first close the socket it sends data to
1106 * while closing the ptg file descriptors.
1108 if (!t->src_is_sock)
1109 close(t->src);
1110 if (t->dest_is_sock)
1111 shutdown(t->dest, SHUT_WR);
1112 else
1113 close(t->dest);
1117 * Join process, with apporiate errors on failure. Name is name for the
1118 * process (for error messages). Returns 0 on success, 1 on failure.
1120 static int tloop_join(pid_t pid, const char *name)
1122 int tret;
1123 if (waitpid(pid, &tret, 0) < 0) {
1124 error("%s process failed to wait: %s", name, strerror(errno));
1125 return 1;
1127 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1128 error("%s process failed", name);
1129 return 1;
1131 return 0;
1135 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1136 * -1 on failure.
1138 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1140 pid_t pid1, pid2;
1141 int ret = 0;
1143 /* Fork thread #1: git to program. */
1144 pid1 = fork();
1145 if (pid1 < 0)
1146 die_errno("Can't start thread for copying data");
1147 else if (pid1 == 0) {
1148 udt_kill_transfer(&s->ptg);
1149 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1152 /* Fork thread #2: program to git. */
1153 pid2 = fork();
1154 if (pid2 < 0)
1155 die_errno("Can't start thread for copying data");
1156 else if (pid2 == 0) {
1157 udt_kill_transfer(&s->gtp);
1158 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1162 * Close both streams in parent as to not interfere with
1163 * end of file detection and wait for both tasks to finish.
1165 udt_kill_transfer(&s->gtp);
1166 udt_kill_transfer(&s->ptg);
1167 ret |= tloop_join(pid1, "Git to program copy");
1168 ret |= tloop_join(pid2, "Program to git copy");
1169 return ret;
1171 #endif
1174 * Copies data from stdin to output and from input to stdout simultaneously.
1175 * Additionally filtering through given filter. If filter is NULL, uses
1176 * identity filter.
1178 int bidirectional_transfer_loop(int input, int output)
1180 struct bidirectional_transfer_state state;
1182 /* Fill the state fields. */
1183 state.ptg.src = input;
1184 state.ptg.dest = 1;
1185 state.ptg.src_is_sock = (input == output);
1186 state.ptg.dest_is_sock = 0;
1187 state.ptg.state = SSTATE_TRANSFERING;
1188 state.ptg.bufuse = 0;
1189 state.ptg.src_name = "remote input";
1190 state.ptg.dest_name = "stdout";
1192 state.gtp.src = 0;
1193 state.gtp.dest = output;
1194 state.gtp.src_is_sock = 0;
1195 state.gtp.dest_is_sock = (input == output);
1196 state.gtp.state = SSTATE_TRANSFERING;
1197 state.gtp.bufuse = 0;
1198 state.gtp.src_name = "stdin";
1199 state.gtp.dest_name = "remote output";
1201 return tloop_spawnwait_tasks(&state);