transport-helper: add trailing --
[git/dscho.git] / transport-helper.c
blob57069432ab7adaa8a5f0d8b98a8b8178043098a5
1 #include "cache.h"
2 #include "transport.h"
3 #include "quote.h"
4 #include "run-command.h"
5 #include "commit.h"
6 #include "diff.h"
7 #include "revision.h"
8 #include "quote.h"
9 #include "remote.h"
10 #include "string-list.h"
11 #include "thread-utils.h"
12 #include "sigchain.h"
14 static int debug;
16 struct helper_data {
17 const char *name;
18 struct child_process *helper;
19 FILE *out;
20 unsigned fetch : 1,
21 import : 1,
22 export : 1,
23 option : 1,
24 push : 1,
25 connect : 1,
26 no_disconnect_req : 1;
27 char *export_marks;
28 char *import_marks;
29 /* These go from remote name (as in "list") to private name */
30 struct refspec *refspecs;
31 int refspec_nr;
32 /* Transport options for fetch-pack/send-pack (should one of
33 * those be invoked).
35 struct git_transport_options transport_options;
38 static void sendline(struct helper_data *helper, struct strbuf *buffer)
40 if (debug)
41 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
42 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
43 != buffer->len)
44 die_errno("Full write to remote helper failed");
47 static int recvline_fh(FILE *helper, struct strbuf *buffer)
49 strbuf_reset(buffer);
50 if (debug)
51 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
52 if (strbuf_getline(buffer, helper, '\n') == EOF) {
53 if (debug)
54 fprintf(stderr, "Debug: Remote helper quit.\n");
55 exit(128);
58 if (debug)
59 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
60 return 0;
63 static int recvline(struct helper_data *helper, struct strbuf *buffer)
65 return recvline_fh(helper->out, buffer);
68 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
70 sendline(helper, buffer);
71 recvline(helper, buffer);
74 static void write_constant(int fd, const char *str)
76 if (debug)
77 fprintf(stderr, "Debug: Remote helper: -> %s", str);
78 if (write_in_full(fd, str, strlen(str)) != strlen(str))
79 die_errno("Full write to remote helper failed");
82 static const char *remove_ext_force(const char *url)
84 if (url) {
85 const char *colon = strchr(url, ':');
86 if (colon && colon[1] == ':')
87 return colon + 2;
89 return url;
92 static void do_take_over(struct transport *transport)
94 struct helper_data *data;
95 data = (struct helper_data *)transport->data;
96 transport_take_over(transport, data->helper);
97 fclose(data->out);
98 free(data);
101 static struct child_process *get_helper(struct transport *transport)
103 struct helper_data *data = transport->data;
104 struct strbuf buf = STRBUF_INIT;
105 struct child_process *helper;
106 const char **refspecs = NULL;
107 int refspec_nr = 0;
108 int refspec_alloc = 0;
109 int duped;
110 int code;
111 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
112 const char *helper_env[] = {
113 git_dir_buf,
114 NULL
118 if (data->helper)
119 return data->helper;
121 helper = xcalloc(1, sizeof(*helper));
122 helper->in = -1;
123 helper->out = -1;
124 helper->err = 0;
125 helper->argv = xcalloc(4, sizeof(*helper->argv));
126 strbuf_addf(&buf, "git-remote-%s", data->name);
127 helper->argv[0] = strbuf_detach(&buf, NULL);
128 helper->argv[1] = transport->remote->name;
129 helper->argv[2] = remove_ext_force(transport->url);
130 helper->git_cmd = 0;
131 helper->silent_exec_failure = 1;
133 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
134 helper->env = helper_env;
136 code = start_command(helper);
137 if (code < 0 && errno == ENOENT)
138 die("Unable to find remote helper for '%s'", data->name);
139 else if (code != 0)
140 exit(code);
142 data->helper = helper;
143 data->no_disconnect_req = 0;
146 * Open the output as FILE* so strbuf_getline() can be used.
147 * Do this with duped fd because fclose() will close the fd,
148 * and stuff like taking over will require the fd to remain.
150 duped = dup(helper->out);
151 if (duped < 0)
152 die_errno("Can't dup helper output fd");
153 data->out = xfdopen(duped, "r");
155 write_constant(helper->in, "capabilities\n");
157 while (1) {
158 const char *capname;
159 int mandatory = 0;
160 recvline(data, &buf);
162 if (!*buf.buf)
163 break;
165 if (*buf.buf == '*') {
166 capname = buf.buf + 1;
167 mandatory = 1;
168 } else
169 capname = buf.buf;
171 if (debug)
172 fprintf(stderr, "Debug: Got cap %s\n", capname);
173 if (!strcmp(capname, "fetch"))
174 data->fetch = 1;
175 else if (!strcmp(capname, "option"))
176 data->option = 1;
177 else if (!strcmp(capname, "push"))
178 data->push = 1;
179 else if (!strcmp(capname, "import"))
180 data->import = 1;
181 else if (!strcmp(capname, "export"))
182 data->export = 1;
183 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
184 ALLOC_GROW(refspecs,
185 refspec_nr + 1,
186 refspec_alloc);
187 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
188 } else if (!strcmp(capname, "connect")) {
189 data->connect = 1;
190 } else if (!prefixcmp(capname, "export-marks ")) {
191 struct strbuf arg = STRBUF_INIT;
192 strbuf_addstr(&arg, "--export-marks=");
193 strbuf_addstr(&arg, capname + strlen("export-marks "));
194 data->export_marks = strbuf_detach(&arg, NULL);
195 } else if (!prefixcmp(capname, "import-marks")) {
196 struct strbuf arg = STRBUF_INIT;
197 strbuf_addstr(&arg, "--import-marks=");
198 strbuf_addstr(&arg, capname + strlen("import-marks "));
199 data->import_marks = strbuf_detach(&arg, NULL);
200 } else if (mandatory) {
201 die("Unknown mandatory capability %s. This remote "
202 "helper probably needs newer version of Git.",
203 capname);
206 if (refspecs) {
207 int i;
208 data->refspec_nr = refspec_nr;
209 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
210 for (i = 0; i < refspec_nr; i++) {
211 free((char *)refspecs[i]);
213 free(refspecs);
215 strbuf_release(&buf);
216 if (debug)
217 fprintf(stderr, "Debug: Capabilities complete.\n");
218 return data->helper;
221 static int disconnect_helper(struct transport *transport)
223 struct helper_data *data = transport->data;
224 int res = 0;
226 if (data->helper) {
227 if (debug)
228 fprintf(stderr, "Debug: Disconnecting.\n");
229 if (!data->no_disconnect_req) {
231 * Ignore write errors; there's nothing we can do,
232 * since we're about to close the pipe anyway. And the
233 * most likely error is EPIPE due to the helper dying
234 * to report an error itself.
236 sigchain_push(SIGPIPE, SIG_IGN);
237 xwrite(data->helper->in, "\n", 1);
238 sigchain_pop(SIGPIPE);
240 close(data->helper->in);
241 close(data->helper->out);
242 fclose(data->out);
243 res = finish_command(data->helper);
244 free((char *)data->helper->argv[0]);
245 free(data->helper->argv);
246 free(data->helper);
247 data->helper = NULL;
249 return res;
252 static const char *unsupported_options[] = {
253 TRANS_OPT_UPLOADPACK,
254 TRANS_OPT_RECEIVEPACK,
255 TRANS_OPT_THIN,
256 TRANS_OPT_KEEP
258 static const char *boolean_options[] = {
259 TRANS_OPT_THIN,
260 TRANS_OPT_KEEP,
261 TRANS_OPT_FOLLOWTAGS
264 static int set_helper_option(struct transport *transport,
265 const char *name, const char *value)
267 struct helper_data *data = transport->data;
268 struct strbuf buf = STRBUF_INIT;
269 int i, ret, is_bool = 0;
271 get_helper(transport);
273 if (!data->option)
274 return 1;
276 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
277 if (!strcmp(name, unsupported_options[i]))
278 return 1;
281 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
282 if (!strcmp(name, boolean_options[i])) {
283 is_bool = 1;
284 break;
288 strbuf_addf(&buf, "option %s ", name);
289 if (is_bool)
290 strbuf_addstr(&buf, value ? "true" : "false");
291 else
292 quote_c_style(value, &buf, NULL, 0);
293 strbuf_addch(&buf, '\n');
295 xchgline(data, &buf);
297 if (!strcmp(buf.buf, "ok"))
298 ret = 0;
299 else if (!prefixcmp(buf.buf, "error")) {
300 ret = -1;
301 } else if (!strcmp(buf.buf, "unsupported"))
302 ret = 1;
303 else {
304 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
305 ret = 1;
307 strbuf_release(&buf);
308 return ret;
311 static void standard_options(struct transport *t)
313 char buf[16];
314 int n;
315 int v = t->verbose;
317 set_helper_option(t, "progress", t->progress ? "true" : "false");
319 n = snprintf(buf, sizeof(buf), "%d", v + 1);
320 if (n >= sizeof(buf))
321 die("impossibly large verbosity value");
322 set_helper_option(t, "verbosity", buf);
325 static int release_helper(struct transport *transport)
327 int res = 0;
328 struct helper_data *data = transport->data;
329 free_refspec(data->refspec_nr, data->refspecs);
330 data->refspecs = NULL;
331 res = disconnect_helper(transport);
332 free(transport->data);
333 return res;
336 static int fetch_with_fetch(struct transport *transport,
337 int nr_heads, struct ref **to_fetch)
339 struct helper_data *data = transport->data;
340 int i;
341 struct strbuf buf = STRBUF_INIT;
343 standard_options(transport);
345 for (i = 0; i < nr_heads; i++) {
346 const struct ref *posn = to_fetch[i];
347 if (posn->status & REF_STATUS_UPTODATE)
348 continue;
350 strbuf_addf(&buf, "fetch %s %s\n",
351 sha1_to_hex(posn->old_sha1), posn->name);
354 strbuf_addch(&buf, '\n');
355 sendline(data, &buf);
357 while (1) {
358 recvline(data, &buf);
360 if (!prefixcmp(buf.buf, "lock ")) {
361 const char *name = buf.buf + 5;
362 if (transport->pack_lockfile)
363 warning("%s also locked %s", data->name, name);
364 else
365 transport->pack_lockfile = xstrdup(name);
367 else if (!buf.len)
368 break;
369 else
370 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
372 strbuf_release(&buf);
373 return 0;
376 static int get_importer(struct transport *transport, struct child_process *fastimport)
378 struct child_process *helper = get_helper(transport);
379 memset(fastimport, 0, sizeof(*fastimport));
380 fastimport->in = helper->out;
381 fastimport->argv = xcalloc(5, sizeof(*fastimport->argv));
382 fastimport->argv[0] = "fast-import";
383 fastimport->argv[1] = "--quiet";
385 fastimport->git_cmd = 1;
386 return start_command(fastimport);
389 static int get_exporter(struct transport *transport,
390 struct child_process *fastexport,
391 struct string_list *revlist_args)
393 struct helper_data *data = transport->data;
394 struct child_process *helper = get_helper(transport);
395 int argc = 0, i;
396 memset(fastexport, 0, sizeof(*fastexport));
398 /* we need to duplicate helper->in because we want to use it after
399 * fastexport is done with it. */
400 fastexport->out = dup(helper->in);
401 fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
402 fastexport->argv[argc++] = "fast-export";
403 fastexport->argv[argc++] = "--use-done-feature";
404 if (data->export_marks)
405 fastexport->argv[argc++] = data->export_marks;
406 if (data->import_marks)
407 fastexport->argv[argc++] = data->import_marks;
409 for (i = 0; i < revlist_args->nr; i++)
410 fastexport->argv[argc++] = revlist_args->items[i].string;
412 fastexport->argv[argc++] = "--";
414 fastexport->git_cmd = 1;
415 return start_command(fastexport);
418 static int fetch_with_import(struct transport *transport,
419 int nr_heads, struct ref **to_fetch)
421 struct child_process fastimport;
422 struct helper_data *data = transport->data;
423 int i;
424 struct ref *posn;
425 struct strbuf buf = STRBUF_INIT;
427 get_helper(transport);
429 if (get_importer(transport, &fastimport))
430 die("Couldn't run fast-import");
432 for (i = 0; i < nr_heads; i++) {
433 posn = to_fetch[i];
434 if (posn->status & REF_STATUS_UPTODATE)
435 continue;
437 strbuf_addf(&buf, "import %s\n", posn->name);
438 sendline(data, &buf);
439 strbuf_reset(&buf);
442 write_constant(data->helper->in, "\n");
444 if (finish_command(&fastimport))
445 die("Error while running fast-import");
446 free(fastimport.argv);
447 fastimport.argv = NULL;
449 for (i = 0; i < nr_heads; i++) {
450 char *private;
451 posn = to_fetch[i];
452 if (posn->status & REF_STATUS_UPTODATE)
453 continue;
454 if (data->refspecs)
455 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
456 else
457 private = xstrdup(posn->name);
458 if (private) {
459 read_ref(private, posn->old_sha1);
460 free(private);
463 strbuf_release(&buf);
464 return 0;
467 static int process_connect_service(struct transport *transport,
468 const char *name, const char *exec)
470 struct helper_data *data = transport->data;
471 struct strbuf cmdbuf = STRBUF_INIT;
472 struct child_process *helper;
473 int r, duped, ret = 0;
474 FILE *input;
476 helper = get_helper(transport);
479 * Yes, dup the pipe another time, as we need unbuffered version
480 * of input pipe as FILE*. fclose() closes the underlying fd and
481 * stream buffering only can be changed before first I/O operation
482 * on it.
484 duped = dup(helper->out);
485 if (duped < 0)
486 die_errno("Can't dup helper output fd");
487 input = xfdopen(duped, "r");
488 setvbuf(input, NULL, _IONBF, 0);
491 * Handle --upload-pack and friends. This is fire and forget...
492 * just warn if it fails.
494 if (strcmp(name, exec)) {
495 r = set_helper_option(transport, "servpath", exec);
496 if (r > 0)
497 warning("Setting remote service path not supported by protocol.");
498 else if (r < 0)
499 warning("Invalid remote service path.");
502 if (data->connect)
503 strbuf_addf(&cmdbuf, "connect %s\n", name);
504 else
505 goto exit;
507 sendline(data, &cmdbuf);
508 recvline_fh(input, &cmdbuf);
509 if (!strcmp(cmdbuf.buf, "")) {
510 data->no_disconnect_req = 1;
511 if (debug)
512 fprintf(stderr, "Debug: Smart transport connection "
513 "ready.\n");
514 ret = 1;
515 } else if (!strcmp(cmdbuf.buf, "fallback")) {
516 if (debug)
517 fprintf(stderr, "Debug: Falling back to dumb "
518 "transport.\n");
519 } else
520 die("Unknown response to connect: %s",
521 cmdbuf.buf);
523 exit:
524 fclose(input);
525 return ret;
528 static int process_connect(struct transport *transport,
529 int for_push)
531 struct helper_data *data = transport->data;
532 const char *name;
533 const char *exec;
535 name = for_push ? "git-receive-pack" : "git-upload-pack";
536 if (for_push)
537 exec = data->transport_options.receivepack;
538 else
539 exec = data->transport_options.uploadpack;
541 return process_connect_service(transport, name, exec);
544 static int connect_helper(struct transport *transport, const char *name,
545 const char *exec, int fd[2])
547 struct helper_data *data = transport->data;
549 /* Get_helper so connect is inited. */
550 get_helper(transport);
551 if (!data->connect)
552 die("Operation not supported by protocol.");
554 if (!process_connect_service(transport, name, exec))
555 die("Can't connect to subservice %s.", name);
557 fd[0] = data->helper->out;
558 fd[1] = data->helper->in;
559 return 0;
562 static int fetch(struct transport *transport,
563 int nr_heads, struct ref **to_fetch)
565 struct helper_data *data = transport->data;
566 int i, count;
568 if (process_connect(transport, 0)) {
569 do_take_over(transport);
570 return transport->fetch(transport, nr_heads, to_fetch);
573 count = 0;
574 for (i = 0; i < nr_heads; i++)
575 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
576 count++;
578 if (!count)
579 return 0;
581 if (data->fetch)
582 return fetch_with_fetch(transport, nr_heads, to_fetch);
584 if (data->import)
585 return fetch_with_import(transport, nr_heads, to_fetch);
587 return -1;
590 static void push_update_ref_status(struct strbuf *buf,
591 struct ref **ref,
592 struct ref *remote_refs)
594 char *refname, *msg;
595 int status;
597 if (!prefixcmp(buf->buf, "ok ")) {
598 status = REF_STATUS_OK;
599 refname = buf->buf + 3;
600 } else if (!prefixcmp(buf->buf, "error ")) {
601 status = REF_STATUS_REMOTE_REJECT;
602 refname = buf->buf + 6;
603 } else
604 die("expected ok/error, helper said '%s'", buf->buf);
606 msg = strchr(refname, ' ');
607 if (msg) {
608 struct strbuf msg_buf = STRBUF_INIT;
609 const char *end;
611 *msg++ = '\0';
612 if (!unquote_c_style(&msg_buf, msg, &end))
613 msg = strbuf_detach(&msg_buf, NULL);
614 else
615 msg = xstrdup(msg);
616 strbuf_release(&msg_buf);
618 if (!strcmp(msg, "no match")) {
619 status = REF_STATUS_NONE;
620 free(msg);
621 msg = NULL;
623 else if (!strcmp(msg, "up to date")) {
624 status = REF_STATUS_UPTODATE;
625 free(msg);
626 msg = NULL;
628 else if (!strcmp(msg, "non-fast forward")) {
629 status = REF_STATUS_REJECT_NONFASTFORWARD;
630 free(msg);
631 msg = NULL;
635 if (*ref)
636 *ref = find_ref_by_name(*ref, refname);
637 if (!*ref)
638 *ref = find_ref_by_name(remote_refs, refname);
639 if (!*ref) {
640 warning("helper reported unexpected status of %s", refname);
641 return;
644 if ((*ref)->status != REF_STATUS_NONE) {
646 * Earlier, the ref was marked not to be pushed, so ignore the ref
647 * status reported by the remote helper if the latter is 'no match'.
649 if (status == REF_STATUS_NONE)
650 return;
653 (*ref)->status = status;
654 (*ref)->remote_status = msg;
657 static void push_update_refs_status(struct helper_data *data,
658 struct ref *remote_refs)
660 struct strbuf buf = STRBUF_INIT;
661 struct ref *ref = remote_refs;
662 for (;;) {
663 recvline(data, &buf);
664 if (!buf.len)
665 break;
667 push_update_ref_status(&buf, &ref, remote_refs);
669 strbuf_release(&buf);
672 static int push_refs_with_push(struct transport *transport,
673 struct ref *remote_refs, int flags)
675 int force_all = flags & TRANSPORT_PUSH_FORCE;
676 int mirror = flags & TRANSPORT_PUSH_MIRROR;
677 struct helper_data *data = transport->data;
678 struct strbuf buf = STRBUF_INIT;
679 struct ref *ref;
681 get_helper(transport);
682 if (!data->push)
683 return 1;
685 for (ref = remote_refs; ref; ref = ref->next) {
686 if (!ref->peer_ref && !mirror)
687 continue;
689 /* Check for statuses set by set_ref_status_for_push() */
690 switch (ref->status) {
691 case REF_STATUS_REJECT_NONFASTFORWARD:
692 case REF_STATUS_UPTODATE:
693 continue;
694 default:
695 ; /* do nothing */
698 if (force_all)
699 ref->force = 1;
701 strbuf_addstr(&buf, "push ");
702 if (!ref->deletion) {
703 if (ref->force)
704 strbuf_addch(&buf, '+');
705 if (ref->peer_ref)
706 strbuf_addstr(&buf, ref->peer_ref->name);
707 else
708 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
710 strbuf_addch(&buf, ':');
711 strbuf_addstr(&buf, ref->name);
712 strbuf_addch(&buf, '\n');
714 if (buf.len == 0)
715 return 0;
717 standard_options(transport);
719 if (flags & TRANSPORT_PUSH_DRY_RUN) {
720 if (set_helper_option(transport, "dry-run", "true") != 0)
721 die("helper %s does not support dry-run", data->name);
724 strbuf_addch(&buf, '\n');
725 sendline(data, &buf);
726 strbuf_release(&buf);
728 push_update_refs_status(data, remote_refs);
729 return 0;
732 static int push_refs_with_export(struct transport *transport,
733 struct ref *remote_refs, int flags)
735 struct ref *ref;
736 struct child_process *helper, exporter;
737 struct helper_data *data = transport->data;
738 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
739 struct strbuf buf = STRBUF_INIT;
741 helper = get_helper(transport);
743 write_constant(helper->in, "export\n");
745 strbuf_reset(&buf);
747 for (ref = remote_refs; ref; ref = ref->next) {
748 char *private;
749 unsigned char sha1[20];
751 if (!data->refspecs)
752 continue;
753 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
754 if (private && !get_sha1(private, sha1)) {
755 strbuf_addf(&buf, "^%s", private);
756 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
758 free(private);
760 if (ref->deletion) {
761 die("remote-helpers do not support ref deletion");
764 if (ref->peer_ref)
765 string_list_append(&revlist_args, ref->peer_ref->name);
769 if (get_exporter(transport, &exporter, &revlist_args))
770 die("Couldn't run fast-export");
772 if (finish_command(&exporter))
773 die("Error while running fast-export");
774 push_update_refs_status(data, remote_refs);
775 return 0;
778 static int push_refs(struct transport *transport,
779 struct ref *remote_refs, int flags)
781 struct helper_data *data = transport->data;
783 if (process_connect(transport, 1)) {
784 do_take_over(transport);
785 return transport->push_refs(transport, remote_refs, flags);
788 if (!remote_refs) {
789 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
790 "Perhaps you should specify a branch such as 'master'.\n");
791 return 0;
794 if (data->push)
795 return push_refs_with_push(transport, remote_refs, flags);
797 if (data->export)
798 return push_refs_with_export(transport, remote_refs, flags);
800 return -1;
804 static int has_attribute(const char *attrs, const char *attr) {
805 int len;
806 if (!attrs)
807 return 0;
809 len = strlen(attr);
810 for (;;) {
811 const char *space = strchrnul(attrs, ' ');
812 if (len == space - attrs && !strncmp(attrs, attr, len))
813 return 1;
814 if (!*space)
815 return 0;
816 attrs = space + 1;
820 static struct ref *get_refs_list(struct transport *transport, int for_push)
822 struct helper_data *data = transport->data;
823 struct child_process *helper;
824 struct ref *ret = NULL;
825 struct ref **tail = &ret;
826 struct ref *posn;
827 struct strbuf buf = STRBUF_INIT;
829 helper = get_helper(transport);
831 if (process_connect(transport, for_push)) {
832 do_take_over(transport);
833 return transport->get_refs_list(transport, for_push);
836 if (data->push && for_push)
837 write_str_in_full(helper->in, "list for-push\n");
838 else
839 write_str_in_full(helper->in, "list\n");
841 while (1) {
842 char *eov, *eon;
843 recvline(data, &buf);
845 if (!*buf.buf)
846 break;
848 eov = strchr(buf.buf, ' ');
849 if (!eov)
850 die("Malformed response in ref list: %s", buf.buf);
851 eon = strchr(eov + 1, ' ');
852 *eov = '\0';
853 if (eon)
854 *eon = '\0';
855 *tail = alloc_ref(eov + 1);
856 if (buf.buf[0] == '@')
857 (*tail)->symref = xstrdup(buf.buf + 1);
858 else if (buf.buf[0] != '?')
859 get_sha1_hex(buf.buf, (*tail)->old_sha1);
860 if (eon) {
861 if (has_attribute(eon + 1, "unchanged")) {
862 (*tail)->status |= REF_STATUS_UPTODATE;
863 read_ref((*tail)->name, (*tail)->old_sha1);
866 tail = &((*tail)->next);
868 if (debug)
869 fprintf(stderr, "Debug: Read ref listing.\n");
870 strbuf_release(&buf);
872 for (posn = ret; posn; posn = posn->next)
873 resolve_remote_symref(posn, ret);
875 return ret;
878 int transport_helper_init(struct transport *transport, const char *name)
880 struct helper_data *data = xcalloc(sizeof(*data), 1);
881 data->name = name;
883 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
884 debug = 1;
886 transport->data = data;
887 transport->set_option = set_helper_option;
888 transport->get_refs_list = get_refs_list;
889 transport->fetch = fetch;
890 transport->push_refs = push_refs;
891 transport->disconnect = release_helper;
892 transport->connect = connect_helper;
893 transport->smart_options = &(data->transport_options);
894 return 0;
898 * Linux pipes can buffer 65536 bytes at once (and most platforms can
899 * buffer less), so attempt reads and writes with up to that size.
901 #define BUFFERSIZE 65536
902 /* This should be enough to hold debugging message. */
903 #define PBUFFERSIZE 8192
905 /* Print bidirectional transfer loop debug message. */
906 static void transfer_debug(const char *fmt, ...)
908 va_list args;
909 char msgbuf[PBUFFERSIZE];
910 static int debug_enabled = -1;
912 if (debug_enabled < 0)
913 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
914 if (!debug_enabled)
915 return;
917 va_start(args, fmt);
918 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
919 va_end(args);
920 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
923 /* Stream state: More data may be coming in this direction. */
924 #define SSTATE_TRANSFERING 0
926 * Stream state: No more data coming in this direction, flushing rest of
927 * data.
929 #define SSTATE_FLUSHING 1
930 /* Stream state: Transfer in this direction finished. */
931 #define SSTATE_FINISHED 2
933 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
934 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
935 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
937 /* Unidirectional transfer. */
938 struct unidirectional_transfer {
939 /* Source */
940 int src;
941 /* Destination */
942 int dest;
943 /* Is source socket? */
944 int src_is_sock;
945 /* Is destination socket? */
946 int dest_is_sock;
947 /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
948 int state;
949 /* Buffer. */
950 char buf[BUFFERSIZE];
951 /* Buffer used. */
952 size_t bufuse;
953 /* Name of source. */
954 const char *src_name;
955 /* Name of destination. */
956 const char *dest_name;
959 /* Closes the target (for writing) if transfer has finished. */
960 static void udt_close_if_finished(struct unidirectional_transfer *t)
962 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
963 t->state = SSTATE_FINISHED;
964 if (t->dest_is_sock)
965 shutdown(t->dest, SHUT_WR);
966 else
967 close(t->dest);
968 transfer_debug("Closed %s.", t->dest_name);
973 * Tries to read read data from source into buffer. If buffer is full,
974 * no data is read. Returns 0 on success, -1 on error.
976 static int udt_do_read(struct unidirectional_transfer *t)
978 ssize_t bytes;
980 if (t->bufuse == BUFFERSIZE)
981 return 0; /* No space for more. */
983 transfer_debug("%s is readable", t->src_name);
984 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
985 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
986 errno != EINTR) {
987 error("read(%s) failed: %s", t->src_name, strerror(errno));
988 return -1;
989 } else if (bytes == 0) {
990 transfer_debug("%s EOF (with %i bytes in buffer)",
991 t->src_name, t->bufuse);
992 t->state = SSTATE_FLUSHING;
993 } else if (bytes > 0) {
994 t->bufuse += bytes;
995 transfer_debug("Read %i bytes from %s (buffer now at %i)",
996 (int)bytes, t->src_name, (int)t->bufuse);
998 return 0;
1001 /* Tries to write data from buffer into destination. If buffer is empty,
1002 * no data is written. Returns 0 on success, -1 on error.
1004 static int udt_do_write(struct unidirectional_transfer *t)
1006 ssize_t bytes;
1008 if (t->bufuse == 0)
1009 return 0; /* Nothing to write. */
1011 transfer_debug("%s is writable", t->dest_name);
1012 bytes = write(t->dest, t->buf, t->bufuse);
1013 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1014 errno != EINTR) {
1015 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1016 return -1;
1017 } else if (bytes > 0) {
1018 t->bufuse -= bytes;
1019 if (t->bufuse)
1020 memmove(t->buf, t->buf + bytes, t->bufuse);
1021 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1022 (int)bytes, t->dest_name, (int)t->bufuse);
1024 return 0;
1028 /* State of bidirectional transfer loop. */
1029 struct bidirectional_transfer_state {
1030 /* Direction from program to git. */
1031 struct unidirectional_transfer ptg;
1032 /* Direction from git to program. */
1033 struct unidirectional_transfer gtp;
1036 static void *udt_copy_task_routine(void *udt)
1038 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1039 while (t->state != SSTATE_FINISHED) {
1040 if (STATE_NEEDS_READING(t->state))
1041 if (udt_do_read(t))
1042 return NULL;
1043 if (STATE_NEEDS_WRITING(t->state))
1044 if (udt_do_write(t))
1045 return NULL;
1046 if (STATE_NEEDS_CLOSING(t->state))
1047 udt_close_if_finished(t);
1049 return udt; /* Just some non-NULL value. */
1052 #ifndef NO_PTHREADS
1055 * Join thread, with apporiate errors on failure. Name is name for the
1056 * thread (for error messages). Returns 0 on success, 1 on failure.
1058 static int tloop_join(pthread_t thread, const char *name)
1060 int err;
1061 void *tret;
1062 err = pthread_join(thread, &tret);
1063 if (!tret) {
1064 error("%s thread failed", name);
1065 return 1;
1067 if (err) {
1068 error("%s thread failed to join: %s", name, strerror(err));
1069 return 1;
1071 return 0;
1075 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1076 * -1 on failure.
1078 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1080 pthread_t gtp_thread;
1081 pthread_t ptg_thread;
1082 int err;
1083 int ret = 0;
1084 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1085 &s->gtp);
1086 if (err)
1087 die("Can't start thread for copying data: %s", strerror(err));
1088 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1089 &s->ptg);
1090 if (err)
1091 die("Can't start thread for copying data: %s", strerror(err));
1093 ret |= tloop_join(gtp_thread, "Git to program copy");
1094 ret |= tloop_join(ptg_thread, "Program to git copy");
1095 return ret;
1097 #else
1099 /* Close the source and target (for writing) for transfer. */
1100 static void udt_kill_transfer(struct unidirectional_transfer *t)
1102 t->state = SSTATE_FINISHED;
1104 * Socket read end left open isn't a disaster if nobody
1105 * attempts to read from it (mingw compat headers do not
1106 * have SHUT_RD)...
1108 * We can't fully close the socket since otherwise gtp
1109 * task would first close the socket it sends data to
1110 * while closing the ptg file descriptors.
1112 if (!t->src_is_sock)
1113 close(t->src);
1114 if (t->dest_is_sock)
1115 shutdown(t->dest, SHUT_WR);
1116 else
1117 close(t->dest);
1121 * Join process, with apporiate errors on failure. Name is name for the
1122 * process (for error messages). Returns 0 on success, 1 on failure.
1124 static int tloop_join(pid_t pid, const char *name)
1126 int tret;
1127 if (waitpid(pid, &tret, 0) < 0) {
1128 error("%s process failed to wait: %s", name, strerror(errno));
1129 return 1;
1131 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1132 error("%s process failed", name);
1133 return 1;
1135 return 0;
1139 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1140 * -1 on failure.
1142 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1144 pid_t pid1, pid2;
1145 int ret = 0;
1147 /* Fork thread #1: git to program. */
1148 pid1 = fork();
1149 if (pid1 < 0)
1150 die_errno("Can't start thread for copying data");
1151 else if (pid1 == 0) {
1152 udt_kill_transfer(&s->ptg);
1153 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1156 /* Fork thread #2: program to git. */
1157 pid2 = fork();
1158 if (pid2 < 0)
1159 die_errno("Can't start thread for copying data");
1160 else if (pid2 == 0) {
1161 udt_kill_transfer(&s->gtp);
1162 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1166 * Close both streams in parent as to not interfere with
1167 * end of file detection and wait for both tasks to finish.
1169 udt_kill_transfer(&s->gtp);
1170 udt_kill_transfer(&s->ptg);
1171 ret |= tloop_join(pid1, "Git to program copy");
1172 ret |= tloop_join(pid2, "Program to git copy");
1173 return ret;
1175 #endif
1178 * Copies data from stdin to output and from input to stdout simultaneously.
1179 * Additionally filtering through given filter. If filter is NULL, uses
1180 * identity filter.
1182 int bidirectional_transfer_loop(int input, int output)
1184 struct bidirectional_transfer_state state;
1186 /* Fill the state fields. */
1187 state.ptg.src = input;
1188 state.ptg.dest = 1;
1189 state.ptg.src_is_sock = (input == output);
1190 state.ptg.dest_is_sock = 0;
1191 state.ptg.state = SSTATE_TRANSFERING;
1192 state.ptg.bufuse = 0;
1193 state.ptg.src_name = "remote input";
1194 state.ptg.dest_name = "stdout";
1196 state.gtp.src = 0;
1197 state.gtp.dest = output;
1198 state.gtp.src_is_sock = 0;
1199 state.gtp.dest_is_sock = (input == output);
1200 state.gtp.state = SSTATE_TRANSFERING;
1201 state.gtp.bufuse = 0;
1202 state.gtp.src_name = "stdin";
1203 state.gtp.dest_name = "remote output";
1205 return tloop_spawnwait_tasks(&state);