git-remote-mediawiki: use no-private-update capability on dumb push
[git/raj.git] / transport-helper.c
blob3328394a9bb54d659747030729e2b5e86e7194a0
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"
13 #include "argv-array.h"
14 #include "refs.h"
16 static int debug;
18 struct helper_data {
19 const char *name;
20 struct child_process *helper;
21 FILE *out;
22 unsigned fetch : 1,
23 import : 1,
24 bidi_import : 1,
25 export : 1,
26 option : 1,
27 push : 1,
28 connect : 1,
29 signed_tags : 1,
30 no_disconnect_req : 1,
31 no_private_update : 1;
32 char *export_marks;
33 char *import_marks;
34 /* These go from remote name (as in "list") to private name */
35 struct refspec *refspecs;
36 int refspec_nr;
37 /* Transport options for fetch-pack/send-pack (should one of
38 * those be invoked).
40 struct git_transport_options transport_options;
43 static void sendline(struct helper_data *helper, struct strbuf *buffer)
45 if (debug)
46 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
47 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
48 != buffer->len)
49 die_errno("Full write to remote helper failed");
52 static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
54 strbuf_reset(buffer);
55 if (debug)
56 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
57 if (strbuf_getline(buffer, helper, '\n') == EOF) {
58 if (debug)
59 fprintf(stderr, "Debug: Remote helper quit.\n");
60 exit(128);
63 if (debug)
64 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
65 return 0;
68 static int recvline(struct helper_data *helper, struct strbuf *buffer)
70 return recvline_fh(helper->out, buffer, helper->name);
73 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
75 sendline(helper, buffer);
76 recvline(helper, buffer);
79 static void write_constant(int fd, const char *str)
81 if (debug)
82 fprintf(stderr, "Debug: Remote helper: -> %s", str);
83 if (write_in_full(fd, str, strlen(str)) != strlen(str))
84 die_errno("Full write to remote helper failed");
87 static const char *remove_ext_force(const char *url)
89 if (url) {
90 const char *colon = strchr(url, ':');
91 if (colon && colon[1] == ':')
92 return colon + 2;
94 return url;
97 static void do_take_over(struct transport *transport)
99 struct helper_data *data;
100 data = (struct helper_data *)transport->data;
101 transport_take_over(transport, data->helper);
102 fclose(data->out);
103 free(data);
106 static struct child_process *get_helper(struct transport *transport)
108 struct helper_data *data = transport->data;
109 struct argv_array argv = ARGV_ARRAY_INIT;
110 struct strbuf buf = STRBUF_INIT;
111 struct child_process *helper;
112 const char **refspecs = NULL;
113 int refspec_nr = 0;
114 int refspec_alloc = 0;
115 int duped;
116 int code;
117 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
118 const char *helper_env[] = {
119 git_dir_buf,
120 NULL
124 if (data->helper)
125 return data->helper;
127 helper = xcalloc(1, sizeof(*helper));
128 helper->in = -1;
129 helper->out = -1;
130 helper->err = 0;
131 argv_array_pushf(&argv, "git-remote-%s", data->name);
132 argv_array_push(&argv, transport->remote->name);
133 argv_array_push(&argv, remove_ext_force(transport->url));
134 helper->argv = argv_array_detach(&argv, NULL);
135 helper->git_cmd = 0;
136 helper->silent_exec_failure = 1;
138 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
139 helper->env = helper_env;
141 code = start_command(helper);
142 if (code < 0 && errno == ENOENT)
143 die("Unable to find remote helper for '%s'", data->name);
144 else if (code != 0)
145 exit(code);
147 data->helper = helper;
148 data->no_disconnect_req = 0;
151 * Open the output as FILE* so strbuf_getline() can be used.
152 * Do this with duped fd because fclose() will close the fd,
153 * and stuff like taking over will require the fd to remain.
155 duped = dup(helper->out);
156 if (duped < 0)
157 die_errno("Can't dup helper output fd");
158 data->out = xfdopen(duped, "r");
160 write_constant(helper->in, "capabilities\n");
162 while (1) {
163 const char *capname;
164 int mandatory = 0;
165 recvline(data, &buf);
167 if (!*buf.buf)
168 break;
170 if (*buf.buf == '*') {
171 capname = buf.buf + 1;
172 mandatory = 1;
173 } else
174 capname = buf.buf;
176 if (debug)
177 fprintf(stderr, "Debug: Got cap %s\n", capname);
178 if (!strcmp(capname, "fetch"))
179 data->fetch = 1;
180 else if (!strcmp(capname, "option"))
181 data->option = 1;
182 else if (!strcmp(capname, "push"))
183 data->push = 1;
184 else if (!strcmp(capname, "import"))
185 data->import = 1;
186 else if (!strcmp(capname, "bidi-import"))
187 data->bidi_import = 1;
188 else if (!strcmp(capname, "export"))
189 data->export = 1;
190 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
191 ALLOC_GROW(refspecs,
192 refspec_nr + 1,
193 refspec_alloc);
194 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
195 } else if (!strcmp(capname, "connect")) {
196 data->connect = 1;
197 } else if (!strcmp(capname, "signed-tags")) {
198 data->signed_tags = 1;
199 } else if (!prefixcmp(capname, "export-marks ")) {
200 struct strbuf arg = STRBUF_INIT;
201 strbuf_addstr(&arg, "--export-marks=");
202 strbuf_addstr(&arg, capname + strlen("export-marks "));
203 data->export_marks = strbuf_detach(&arg, NULL);
204 } else if (!prefixcmp(capname, "import-marks")) {
205 struct strbuf arg = STRBUF_INIT;
206 strbuf_addstr(&arg, "--import-marks=");
207 strbuf_addstr(&arg, capname + strlen("import-marks "));
208 data->import_marks = strbuf_detach(&arg, NULL);
209 } else if (!prefixcmp(capname, "no-private-update")) {
210 data->no_private_update = 1;
211 } else if (mandatory) {
212 die("Unknown mandatory capability %s. This remote "
213 "helper probably needs newer version of Git.",
214 capname);
217 if (refspecs) {
218 int i;
219 data->refspec_nr = refspec_nr;
220 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
221 for (i = 0; i < refspec_nr; i++)
222 free((char *)refspecs[i]);
223 free(refspecs);
224 } else if (data->import || data->bidi_import || data->export) {
225 warning("This remote helper should implement refspec capability.");
227 strbuf_release(&buf);
228 if (debug)
229 fprintf(stderr, "Debug: Capabilities complete.\n");
230 return data->helper;
233 static int disconnect_helper(struct transport *transport)
235 struct helper_data *data = transport->data;
236 int res = 0;
238 if (data->helper) {
239 if (debug)
240 fprintf(stderr, "Debug: Disconnecting.\n");
241 if (!data->no_disconnect_req) {
243 * Ignore write errors; there's nothing we can do,
244 * since we're about to close the pipe anyway. And the
245 * most likely error is EPIPE due to the helper dying
246 * to report an error itself.
248 sigchain_push(SIGPIPE, SIG_IGN);
249 xwrite(data->helper->in, "\n", 1);
250 sigchain_pop(SIGPIPE);
252 close(data->helper->in);
253 close(data->helper->out);
254 fclose(data->out);
255 res = finish_command(data->helper);
256 argv_array_free_detached(data->helper->argv);
257 free(data->helper);
258 data->helper = NULL;
260 return res;
263 static const char *unsupported_options[] = {
264 TRANS_OPT_UPLOADPACK,
265 TRANS_OPT_RECEIVEPACK,
266 TRANS_OPT_THIN,
267 TRANS_OPT_KEEP
269 static const char *boolean_options[] = {
270 TRANS_OPT_THIN,
271 TRANS_OPT_KEEP,
272 TRANS_OPT_FOLLOWTAGS
275 static int set_helper_option(struct transport *transport,
276 const char *name, const char *value)
278 struct helper_data *data = transport->data;
279 struct strbuf buf = STRBUF_INIT;
280 int i, ret, is_bool = 0;
282 get_helper(transport);
284 if (!data->option)
285 return 1;
287 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
288 if (!strcmp(name, unsupported_options[i]))
289 return 1;
292 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
293 if (!strcmp(name, boolean_options[i])) {
294 is_bool = 1;
295 break;
299 strbuf_addf(&buf, "option %s ", name);
300 if (is_bool)
301 strbuf_addstr(&buf, value ? "true" : "false");
302 else
303 quote_c_style(value, &buf, NULL, 0);
304 strbuf_addch(&buf, '\n');
306 xchgline(data, &buf);
308 if (!strcmp(buf.buf, "ok"))
309 ret = 0;
310 else if (!prefixcmp(buf.buf, "error")) {
311 ret = -1;
312 } else if (!strcmp(buf.buf, "unsupported"))
313 ret = 1;
314 else {
315 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
316 ret = 1;
318 strbuf_release(&buf);
319 return ret;
322 static void standard_options(struct transport *t)
324 char buf[16];
325 int n;
326 int v = t->verbose;
328 set_helper_option(t, "progress", t->progress ? "true" : "false");
330 n = snprintf(buf, sizeof(buf), "%d", v + 1);
331 if (n >= sizeof(buf))
332 die("impossibly large verbosity value");
333 set_helper_option(t, "verbosity", buf);
336 static int release_helper(struct transport *transport)
338 int res = 0;
339 struct helper_data *data = transport->data;
340 free_refspec(data->refspec_nr, data->refspecs);
341 data->refspecs = NULL;
342 res = disconnect_helper(transport);
343 free(transport->data);
344 return res;
347 static int fetch_with_fetch(struct transport *transport,
348 int nr_heads, struct ref **to_fetch)
350 struct helper_data *data = transport->data;
351 int i;
352 struct strbuf buf = STRBUF_INIT;
354 standard_options(transport);
356 for (i = 0; i < nr_heads; i++) {
357 const struct ref *posn = to_fetch[i];
358 if (posn->status & REF_STATUS_UPTODATE)
359 continue;
361 strbuf_addf(&buf, "fetch %s %s\n",
362 sha1_to_hex(posn->old_sha1), posn->name);
365 strbuf_addch(&buf, '\n');
366 sendline(data, &buf);
368 while (1) {
369 recvline(data, &buf);
371 if (!prefixcmp(buf.buf, "lock ")) {
372 const char *name = buf.buf + 5;
373 if (transport->pack_lockfile)
374 warning("%s also locked %s", data->name, name);
375 else
376 transport->pack_lockfile = xstrdup(name);
378 else if (!buf.len)
379 break;
380 else
381 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
383 strbuf_release(&buf);
384 return 0;
387 static int get_importer(struct transport *transport, struct child_process *fastimport)
389 struct child_process *helper = get_helper(transport);
390 struct helper_data *data = transport->data;
391 struct argv_array argv = ARGV_ARRAY_INIT;
392 int cat_blob_fd, code;
393 memset(fastimport, 0, sizeof(*fastimport));
394 fastimport->in = helper->out;
395 argv_array_push(&argv, "fast-import");
396 argv_array_push(&argv, debug ? "--stats" : "--quiet");
398 if (data->bidi_import) {
399 cat_blob_fd = xdup(helper->in);
400 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
402 fastimport->argv = argv.argv;
403 fastimport->git_cmd = 1;
405 code = start_command(fastimport);
406 return code;
409 static int get_exporter(struct transport *transport,
410 struct child_process *fastexport,
411 struct string_list *revlist_args)
413 struct helper_data *data = transport->data;
414 struct child_process *helper = get_helper(transport);
415 int argc = 0, i;
416 memset(fastexport, 0, sizeof(*fastexport));
418 /* we need to duplicate helper->in because we want to use it after
419 * fastexport is done with it. */
420 fastexport->out = dup(helper->in);
421 fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
422 fastexport->argv[argc++] = "fast-export";
423 fastexport->argv[argc++] = "--use-done-feature";
424 fastexport->argv[argc++] = data->signed_tags ?
425 "--signed-tags=verbatim" : "--signed-tags=warn-strip";
426 if (data->export_marks)
427 fastexport->argv[argc++] = data->export_marks;
428 if (data->import_marks)
429 fastexport->argv[argc++] = data->import_marks;
431 for (i = 0; i < revlist_args->nr; i++)
432 fastexport->argv[argc++] = revlist_args->items[i].string;
434 fastexport->git_cmd = 1;
435 return start_command(fastexport);
438 static int fetch_with_import(struct transport *transport,
439 int nr_heads, struct ref **to_fetch)
441 struct child_process fastimport;
442 struct helper_data *data = transport->data;
443 int i;
444 struct ref *posn;
445 struct strbuf buf = STRBUF_INIT;
447 get_helper(transport);
449 if (get_importer(transport, &fastimport))
450 die("Couldn't run fast-import");
452 for (i = 0; i < nr_heads; i++) {
453 posn = to_fetch[i];
454 if (posn->status & REF_STATUS_UPTODATE)
455 continue;
457 strbuf_addf(&buf, "import %s\n", posn->name);
458 sendline(data, &buf);
459 strbuf_reset(&buf);
462 write_constant(data->helper->in, "\n");
464 * remote-helpers that advertise the bidi-import capability are required to
465 * buffer the complete batch of import commands until this newline before
466 * sending data to fast-import.
467 * These helpers read back data from fast-import on their stdin, which could
468 * be mixed with import commands, otherwise.
471 if (finish_command(&fastimport))
472 die("Error while running fast-import");
473 argv_array_free_detached(fastimport.argv);
476 * The fast-import stream of a remote helper that advertises
477 * the "refspec" capability writes to the refs named after the
478 * right hand side of the first refspec matching each ref we
479 * were fetching.
481 * (If no "refspec" capability was specified, for historical
482 * reasons we default to the equivalent of *:*.)
484 * Store the result in to_fetch[i].old_sha1. Callers such
485 * as "git fetch" can use the value to write feedback to the
486 * terminal, populate FETCH_HEAD, and determine what new value
487 * should be written to peer_ref if the update is a
488 * fast-forward or this is a forced update.
490 for (i = 0; i < nr_heads; i++) {
491 char *private;
492 posn = to_fetch[i];
493 if (posn->status & REF_STATUS_UPTODATE)
494 continue;
495 if (data->refspecs)
496 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
497 else
498 private = xstrdup(posn->name);
499 if (private) {
500 read_ref(private, posn->old_sha1);
501 free(private);
504 strbuf_release(&buf);
505 return 0;
508 static int process_connect_service(struct transport *transport,
509 const char *name, const char *exec)
511 struct helper_data *data = transport->data;
512 struct strbuf cmdbuf = STRBUF_INIT;
513 struct child_process *helper;
514 int r, duped, ret = 0;
515 FILE *input;
517 helper = get_helper(transport);
520 * Yes, dup the pipe another time, as we need unbuffered version
521 * of input pipe as FILE*. fclose() closes the underlying fd and
522 * stream buffering only can be changed before first I/O operation
523 * on it.
525 duped = dup(helper->out);
526 if (duped < 0)
527 die_errno("Can't dup helper output fd");
528 input = xfdopen(duped, "r");
529 setvbuf(input, NULL, _IONBF, 0);
532 * Handle --upload-pack and friends. This is fire and forget...
533 * just warn if it fails.
535 if (strcmp(name, exec)) {
536 r = set_helper_option(transport, "servpath", exec);
537 if (r > 0)
538 warning("Setting remote service path not supported by protocol.");
539 else if (r < 0)
540 warning("Invalid remote service path.");
543 if (data->connect)
544 strbuf_addf(&cmdbuf, "connect %s\n", name);
545 else
546 goto exit;
548 sendline(data, &cmdbuf);
549 recvline_fh(input, &cmdbuf, name);
550 if (!strcmp(cmdbuf.buf, "")) {
551 data->no_disconnect_req = 1;
552 if (debug)
553 fprintf(stderr, "Debug: Smart transport connection "
554 "ready.\n");
555 ret = 1;
556 } else if (!strcmp(cmdbuf.buf, "fallback")) {
557 if (debug)
558 fprintf(stderr, "Debug: Falling back to dumb "
559 "transport.\n");
560 } else
561 die("Unknown response to connect: %s",
562 cmdbuf.buf);
564 exit:
565 fclose(input);
566 return ret;
569 static int process_connect(struct transport *transport,
570 int for_push)
572 struct helper_data *data = transport->data;
573 const char *name;
574 const char *exec;
576 name = for_push ? "git-receive-pack" : "git-upload-pack";
577 if (for_push)
578 exec = data->transport_options.receivepack;
579 else
580 exec = data->transport_options.uploadpack;
582 return process_connect_service(transport, name, exec);
585 static int connect_helper(struct transport *transport, const char *name,
586 const char *exec, int fd[2])
588 struct helper_data *data = transport->data;
590 /* Get_helper so connect is inited. */
591 get_helper(transport);
592 if (!data->connect)
593 die("Operation not supported by protocol.");
595 if (!process_connect_service(transport, name, exec))
596 die("Can't connect to subservice %s.", name);
598 fd[0] = data->helper->out;
599 fd[1] = data->helper->in;
600 return 0;
603 static int fetch(struct transport *transport,
604 int nr_heads, struct ref **to_fetch)
606 struct helper_data *data = transport->data;
607 int i, count;
609 if (process_connect(transport, 0)) {
610 do_take_over(transport);
611 return transport->fetch(transport, nr_heads, to_fetch);
614 count = 0;
615 for (i = 0; i < nr_heads; i++)
616 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
617 count++;
619 if (!count)
620 return 0;
622 if (data->fetch)
623 return fetch_with_fetch(transport, nr_heads, to_fetch);
625 if (data->import)
626 return fetch_with_import(transport, nr_heads, to_fetch);
628 return -1;
631 static int push_update_ref_status(struct strbuf *buf,
632 struct ref **ref,
633 struct ref *remote_refs)
635 char *refname, *msg;
636 int status;
638 if (!prefixcmp(buf->buf, "ok ")) {
639 status = REF_STATUS_OK;
640 refname = buf->buf + 3;
641 } else if (!prefixcmp(buf->buf, "error ")) {
642 status = REF_STATUS_REMOTE_REJECT;
643 refname = buf->buf + 6;
644 } else
645 die("expected ok/error, helper said '%s'", buf->buf);
647 msg = strchr(refname, ' ');
648 if (msg) {
649 struct strbuf msg_buf = STRBUF_INIT;
650 const char *end;
652 *msg++ = '\0';
653 if (!unquote_c_style(&msg_buf, msg, &end))
654 msg = strbuf_detach(&msg_buf, NULL);
655 else
656 msg = xstrdup(msg);
657 strbuf_release(&msg_buf);
659 if (!strcmp(msg, "no match")) {
660 status = REF_STATUS_NONE;
661 free(msg);
662 msg = NULL;
664 else if (!strcmp(msg, "up to date")) {
665 status = REF_STATUS_UPTODATE;
666 free(msg);
667 msg = NULL;
669 else if (!strcmp(msg, "non-fast forward")) {
670 status = REF_STATUS_REJECT_NONFASTFORWARD;
671 free(msg);
672 msg = NULL;
674 else if (!strcmp(msg, "already exists")) {
675 status = REF_STATUS_REJECT_ALREADY_EXISTS;
676 free(msg);
677 msg = NULL;
679 else if (!strcmp(msg, "fetch first")) {
680 status = REF_STATUS_REJECT_FETCH_FIRST;
681 free(msg);
682 msg = NULL;
684 else if (!strcmp(msg, "needs force")) {
685 status = REF_STATUS_REJECT_NEEDS_FORCE;
686 free(msg);
687 msg = NULL;
691 if (*ref)
692 *ref = find_ref_by_name(*ref, refname);
693 if (!*ref)
694 *ref = find_ref_by_name(remote_refs, refname);
695 if (!*ref) {
696 warning("helper reported unexpected status of %s", refname);
697 return 1;
700 if ((*ref)->status != REF_STATUS_NONE) {
702 * Earlier, the ref was marked not to be pushed, so ignore the ref
703 * status reported by the remote helper if the latter is 'no match'.
705 if (status == REF_STATUS_NONE)
706 return 1;
709 (*ref)->status = status;
710 (*ref)->remote_status = msg;
711 return !(status == REF_STATUS_OK);
714 static void push_update_refs_status(struct helper_data *data,
715 struct ref *remote_refs)
717 struct strbuf buf = STRBUF_INIT;
718 struct ref *ref = remote_refs;
719 for (;;) {
720 char *private;
722 recvline(data, &buf);
723 if (!buf.len)
724 break;
726 if (push_update_ref_status(&buf, &ref, remote_refs))
727 continue;
729 if (!data->refspecs || data->no_private_update)
730 continue;
732 /* propagate back the update to the remote namespace */
733 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
734 if (!private)
735 continue;
736 update_ref("update by helper", private, ref->new_sha1, NULL, 0, 0);
737 free(private);
739 strbuf_release(&buf);
742 static int push_refs_with_push(struct transport *transport,
743 struct ref *remote_refs, int flags)
745 int force_all = flags & TRANSPORT_PUSH_FORCE;
746 int mirror = flags & TRANSPORT_PUSH_MIRROR;
747 struct helper_data *data = transport->data;
748 struct strbuf buf = STRBUF_INIT;
749 struct ref *ref;
751 get_helper(transport);
752 if (!data->push)
753 return 1;
755 for (ref = remote_refs; ref; ref = ref->next) {
756 if (!ref->peer_ref && !mirror)
757 continue;
759 /* Check for statuses set by set_ref_status_for_push() */
760 switch (ref->status) {
761 case REF_STATUS_REJECT_NONFASTFORWARD:
762 case REF_STATUS_REJECT_ALREADY_EXISTS:
763 case REF_STATUS_UPTODATE:
764 continue;
765 default:
766 ; /* do nothing */
769 if (force_all)
770 ref->force = 1;
772 strbuf_addstr(&buf, "push ");
773 if (!ref->deletion) {
774 if (ref->force)
775 strbuf_addch(&buf, '+');
776 if (ref->peer_ref)
777 strbuf_addstr(&buf, ref->peer_ref->name);
778 else
779 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
781 strbuf_addch(&buf, ':');
782 strbuf_addstr(&buf, ref->name);
783 strbuf_addch(&buf, '\n');
785 if (buf.len == 0)
786 return 0;
788 standard_options(transport);
790 if (flags & TRANSPORT_PUSH_DRY_RUN) {
791 if (set_helper_option(transport, "dry-run", "true") != 0)
792 die("helper %s does not support dry-run", data->name);
795 strbuf_addch(&buf, '\n');
796 sendline(data, &buf);
797 strbuf_release(&buf);
799 push_update_refs_status(data, remote_refs);
800 return 0;
803 static int push_refs_with_export(struct transport *transport,
804 struct ref *remote_refs, int flags)
806 struct ref *ref;
807 struct child_process *helper, exporter;
808 struct helper_data *data = transport->data;
809 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
810 struct strbuf buf = STRBUF_INIT;
812 if (!data->refspecs)
813 die("remote-helper doesn't support push; refspec needed");
815 if (flags & TRANSPORT_PUSH_DRY_RUN) {
816 if (set_helper_option(transport, "dry-run", "true") != 0)
817 die("helper %s does not support dry-run", data->name);
820 helper = get_helper(transport);
822 write_constant(helper->in, "export\n");
824 strbuf_reset(&buf);
826 for (ref = remote_refs; ref; ref = ref->next) {
827 char *private;
828 unsigned char sha1[20];
830 if (ref->deletion)
831 die("remote-helpers do not support ref deletion");
833 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
834 if (private && !get_sha1(private, sha1)) {
835 strbuf_addf(&buf, "^%s", private);
836 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
837 hashcpy(ref->old_sha1, sha1);
839 free(private);
841 if (ref->deletion)
842 die("remote-helpers do not support ref deletion");
844 if (ref->peer_ref) {
845 if (strcmp(ref->peer_ref->name, ref->name))
846 die("remote-helpers do not support old:new syntax");
847 string_list_append(&revlist_args, ref->peer_ref->name);
851 if (get_exporter(transport, &exporter, &revlist_args))
852 die("Couldn't run fast-export");
854 if (finish_command(&exporter))
855 die("Error while running fast-export");
856 push_update_refs_status(data, remote_refs);
857 return 0;
860 static int push_refs(struct transport *transport,
861 struct ref *remote_refs, int flags)
863 struct helper_data *data = transport->data;
865 if (process_connect(transport, 1)) {
866 do_take_over(transport);
867 return transport->push_refs(transport, remote_refs, flags);
870 if (!remote_refs) {
871 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
872 "Perhaps you should specify a branch such as 'master'.\n");
873 return 0;
876 if (data->push)
877 return push_refs_with_push(transport, remote_refs, flags);
879 if (data->export)
880 return push_refs_with_export(transport, remote_refs, flags);
882 return -1;
886 static int has_attribute(const char *attrs, const char *attr) {
887 int len;
888 if (!attrs)
889 return 0;
891 len = strlen(attr);
892 for (;;) {
893 const char *space = strchrnul(attrs, ' ');
894 if (len == space - attrs && !strncmp(attrs, attr, len))
895 return 1;
896 if (!*space)
897 return 0;
898 attrs = space + 1;
902 static struct ref *get_refs_list(struct transport *transport, int for_push)
904 struct helper_data *data = transport->data;
905 struct child_process *helper;
906 struct ref *ret = NULL;
907 struct ref **tail = &ret;
908 struct ref *posn;
909 struct strbuf buf = STRBUF_INIT;
911 helper = get_helper(transport);
913 if (process_connect(transport, for_push)) {
914 do_take_over(transport);
915 return transport->get_refs_list(transport, for_push);
918 if (data->push && for_push)
919 write_str_in_full(helper->in, "list for-push\n");
920 else
921 write_str_in_full(helper->in, "list\n");
923 while (1) {
924 char *eov, *eon;
925 recvline(data, &buf);
927 if (!*buf.buf)
928 break;
930 eov = strchr(buf.buf, ' ');
931 if (!eov)
932 die("Malformed response in ref list: %s", buf.buf);
933 eon = strchr(eov + 1, ' ');
934 *eov = '\0';
935 if (eon)
936 *eon = '\0';
937 *tail = alloc_ref(eov + 1);
938 if (buf.buf[0] == '@')
939 (*tail)->symref = xstrdup(buf.buf + 1);
940 else if (buf.buf[0] != '?')
941 get_sha1_hex(buf.buf, (*tail)->old_sha1);
942 if (eon) {
943 if (has_attribute(eon + 1, "unchanged")) {
944 (*tail)->status |= REF_STATUS_UPTODATE;
945 read_ref((*tail)->name, (*tail)->old_sha1);
948 tail = &((*tail)->next);
950 if (debug)
951 fprintf(stderr, "Debug: Read ref listing.\n");
952 strbuf_release(&buf);
954 for (posn = ret; posn; posn = posn->next)
955 resolve_remote_symref(posn, ret);
957 return ret;
960 int transport_helper_init(struct transport *transport, const char *name)
962 struct helper_data *data = xcalloc(sizeof(*data), 1);
963 data->name = name;
965 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
966 debug = 1;
968 transport->data = data;
969 transport->set_option = set_helper_option;
970 transport->get_refs_list = get_refs_list;
971 transport->fetch = fetch;
972 transport->push_refs = push_refs;
973 transport->disconnect = release_helper;
974 transport->connect = connect_helper;
975 transport->smart_options = &(data->transport_options);
976 return 0;
980 * Linux pipes can buffer 65536 bytes at once (and most platforms can
981 * buffer less), so attempt reads and writes with up to that size.
983 #define BUFFERSIZE 65536
984 /* This should be enough to hold debugging message. */
985 #define PBUFFERSIZE 8192
987 /* Print bidirectional transfer loop debug message. */
988 __attribute__((format (printf, 1, 2)))
989 static void transfer_debug(const char *fmt, ...)
991 va_list args;
992 char msgbuf[PBUFFERSIZE];
993 static int debug_enabled = -1;
995 if (debug_enabled < 0)
996 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
997 if (!debug_enabled)
998 return;
1000 va_start(args, fmt);
1001 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1002 va_end(args);
1003 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1006 /* Stream state: More data may be coming in this direction. */
1007 #define SSTATE_TRANSFERING 0
1009 * Stream state: No more data coming in this direction, flushing rest of
1010 * data.
1012 #define SSTATE_FLUSHING 1
1013 /* Stream state: Transfer in this direction finished. */
1014 #define SSTATE_FINISHED 2
1016 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1017 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1018 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1020 /* Unidirectional transfer. */
1021 struct unidirectional_transfer {
1022 /* Source */
1023 int src;
1024 /* Destination */
1025 int dest;
1026 /* Is source socket? */
1027 int src_is_sock;
1028 /* Is destination socket? */
1029 int dest_is_sock;
1030 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1031 int state;
1032 /* Buffer. */
1033 char buf[BUFFERSIZE];
1034 /* Buffer used. */
1035 size_t bufuse;
1036 /* Name of source. */
1037 const char *src_name;
1038 /* Name of destination. */
1039 const char *dest_name;
1042 /* Closes the target (for writing) if transfer has finished. */
1043 static void udt_close_if_finished(struct unidirectional_transfer *t)
1045 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1046 t->state = SSTATE_FINISHED;
1047 if (t->dest_is_sock)
1048 shutdown(t->dest, SHUT_WR);
1049 else
1050 close(t->dest);
1051 transfer_debug("Closed %s.", t->dest_name);
1056 * Tries to read read data from source into buffer. If buffer is full,
1057 * no data is read. Returns 0 on success, -1 on error.
1059 static int udt_do_read(struct unidirectional_transfer *t)
1061 ssize_t bytes;
1063 if (t->bufuse == BUFFERSIZE)
1064 return 0; /* No space for more. */
1066 transfer_debug("%s is readable", t->src_name);
1067 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1068 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1069 errno != EINTR) {
1070 error("read(%s) failed: %s", t->src_name, strerror(errno));
1071 return -1;
1072 } else if (bytes == 0) {
1073 transfer_debug("%s EOF (with %i bytes in buffer)",
1074 t->src_name, (int)t->bufuse);
1075 t->state = SSTATE_FLUSHING;
1076 } else if (bytes > 0) {
1077 t->bufuse += bytes;
1078 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1079 (int)bytes, t->src_name, (int)t->bufuse);
1081 return 0;
1084 /* Tries to write data from buffer into destination. If buffer is empty,
1085 * no data is written. Returns 0 on success, -1 on error.
1087 static int udt_do_write(struct unidirectional_transfer *t)
1089 ssize_t bytes;
1091 if (t->bufuse == 0)
1092 return 0; /* Nothing to write. */
1094 transfer_debug("%s is writable", t->dest_name);
1095 bytes = write(t->dest, t->buf, t->bufuse);
1096 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1097 errno != EINTR) {
1098 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1099 return -1;
1100 } else if (bytes > 0) {
1101 t->bufuse -= bytes;
1102 if (t->bufuse)
1103 memmove(t->buf, t->buf + bytes, t->bufuse);
1104 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1105 (int)bytes, t->dest_name, (int)t->bufuse);
1107 return 0;
1111 /* State of bidirectional transfer loop. */
1112 struct bidirectional_transfer_state {
1113 /* Direction from program to git. */
1114 struct unidirectional_transfer ptg;
1115 /* Direction from git to program. */
1116 struct unidirectional_transfer gtp;
1119 static void *udt_copy_task_routine(void *udt)
1121 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1122 while (t->state != SSTATE_FINISHED) {
1123 if (STATE_NEEDS_READING(t->state))
1124 if (udt_do_read(t))
1125 return NULL;
1126 if (STATE_NEEDS_WRITING(t->state))
1127 if (udt_do_write(t))
1128 return NULL;
1129 if (STATE_NEEDS_CLOSING(t->state))
1130 udt_close_if_finished(t);
1132 return udt; /* Just some non-NULL value. */
1135 #ifndef NO_PTHREADS
1138 * Join thread, with appropriate errors on failure. Name is name for the
1139 * thread (for error messages). Returns 0 on success, 1 on failure.
1141 static int tloop_join(pthread_t thread, const char *name)
1143 int err;
1144 void *tret;
1145 err = pthread_join(thread, &tret);
1146 if (!tret) {
1147 error("%s thread failed", name);
1148 return 1;
1150 if (err) {
1151 error("%s thread failed to join: %s", name, strerror(err));
1152 return 1;
1154 return 0;
1158 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1159 * -1 on failure.
1161 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1163 pthread_t gtp_thread;
1164 pthread_t ptg_thread;
1165 int err;
1166 int ret = 0;
1167 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1168 &s->gtp);
1169 if (err)
1170 die("Can't start thread for copying data: %s", strerror(err));
1171 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1172 &s->ptg);
1173 if (err)
1174 die("Can't start thread for copying data: %s", strerror(err));
1176 ret |= tloop_join(gtp_thread, "Git to program copy");
1177 ret |= tloop_join(ptg_thread, "Program to git copy");
1178 return ret;
1180 #else
1182 /* Close the source and target (for writing) for transfer. */
1183 static void udt_kill_transfer(struct unidirectional_transfer *t)
1185 t->state = SSTATE_FINISHED;
1187 * Socket read end left open isn't a disaster if nobody
1188 * attempts to read from it (mingw compat headers do not
1189 * have SHUT_RD)...
1191 * We can't fully close the socket since otherwise gtp
1192 * task would first close the socket it sends data to
1193 * while closing the ptg file descriptors.
1195 if (!t->src_is_sock)
1196 close(t->src);
1197 if (t->dest_is_sock)
1198 shutdown(t->dest, SHUT_WR);
1199 else
1200 close(t->dest);
1204 * Join process, with appropriate errors on failure. Name is name for the
1205 * process (for error messages). Returns 0 on success, 1 on failure.
1207 static int tloop_join(pid_t pid, const char *name)
1209 int tret;
1210 if (waitpid(pid, &tret, 0) < 0) {
1211 error("%s process failed to wait: %s", name, strerror(errno));
1212 return 1;
1214 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1215 error("%s process failed", name);
1216 return 1;
1218 return 0;
1222 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1223 * -1 on failure.
1225 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1227 pid_t pid1, pid2;
1228 int ret = 0;
1230 /* Fork thread #1: git to program. */
1231 pid1 = fork();
1232 if (pid1 < 0)
1233 die_errno("Can't start thread for copying data");
1234 else if (pid1 == 0) {
1235 udt_kill_transfer(&s->ptg);
1236 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1239 /* Fork thread #2: program to git. */
1240 pid2 = fork();
1241 if (pid2 < 0)
1242 die_errno("Can't start thread for copying data");
1243 else if (pid2 == 0) {
1244 udt_kill_transfer(&s->gtp);
1245 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1249 * Close both streams in parent as to not interfere with
1250 * end of file detection and wait for both tasks to finish.
1252 udt_kill_transfer(&s->gtp);
1253 udt_kill_transfer(&s->ptg);
1254 ret |= tloop_join(pid1, "Git to program copy");
1255 ret |= tloop_join(pid2, "Program to git copy");
1256 return ret;
1258 #endif
1261 * Copies data from stdin to output and from input to stdout simultaneously.
1262 * Additionally filtering through given filter. If filter is NULL, uses
1263 * identity filter.
1265 int bidirectional_transfer_loop(int input, int output)
1267 struct bidirectional_transfer_state state;
1269 /* Fill the state fields. */
1270 state.ptg.src = input;
1271 state.ptg.dest = 1;
1272 state.ptg.src_is_sock = (input == output);
1273 state.ptg.dest_is_sock = 0;
1274 state.ptg.state = SSTATE_TRANSFERING;
1275 state.ptg.bufuse = 0;
1276 state.ptg.src_name = "remote input";
1277 state.ptg.dest_name = "stdout";
1279 state.gtp.src = 0;
1280 state.gtp.dest = output;
1281 state.gtp.src_is_sock = 0;
1282 state.gtp.dest_is_sock = (input == output);
1283 state.gtp.state = SSTATE_TRANSFERING;
1284 state.gtp.bufuse = 0;
1285 state.gtp.src_name = "stdin";
1286 state.gtp.dest_name = "remote output";
1288 return tloop_spawnwait_tasks(&state);