gitk: Use an external icon file on Windows
[git/mingw/4msysgit.git] / transport-helper.c
blobe6e1f749ba7c99af3c2a17a6dae712fa5cb65028
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"
15 static int debug;
16 /* TODO: put somewhere sensible, e.g. git_transport_options? */
17 static int auto_gc = 1;
19 struct helper_data {
20 const char *name;
21 struct child_process *helper;
22 FILE *out;
23 unsigned fetch : 1,
24 import : 1,
25 bidi_import : 1,
26 export : 1,
27 option : 1,
28 push : 1,
29 connect : 1,
30 signed_tags : 1,
31 no_disconnect_req : 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)
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);
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 (mandatory) {
210 die("Unknown mandatory capability %s. This remote "
211 "helper probably needs newer version of Git.",
212 capname);
215 if (refspecs) {
216 int i;
217 data->refspec_nr = refspec_nr;
218 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
219 for (i = 0; i < refspec_nr; i++)
220 free((char *)refspecs[i]);
221 free(refspecs);
223 strbuf_release(&buf);
224 if (debug)
225 fprintf(stderr, "Debug: Capabilities complete.\n");
226 return data->helper;
229 static int disconnect_helper(struct transport *transport)
231 struct helper_data *data = transport->data;
232 int res = 0;
234 if (data->helper) {
235 if (debug)
236 fprintf(stderr, "Debug: Disconnecting.\n");
237 if (!data->no_disconnect_req) {
239 * Ignore write errors; there's nothing we can do,
240 * since we're about to close the pipe anyway. And the
241 * most likely error is EPIPE due to the helper dying
242 * to report an error itself.
244 sigchain_push(SIGPIPE, SIG_IGN);
245 xwrite(data->helper->in, "\n", 1);
246 sigchain_pop(SIGPIPE);
248 close(data->helper->in);
249 close(data->helper->out);
250 fclose(data->out);
251 res = finish_command(data->helper);
252 argv_array_free_detached(data->helper->argv);
253 free(data->helper);
254 data->helper = NULL;
256 return res;
259 static const char *unsupported_options[] = {
260 TRANS_OPT_UPLOADPACK,
261 TRANS_OPT_RECEIVEPACK,
262 TRANS_OPT_THIN,
263 TRANS_OPT_KEEP
265 static const char *boolean_options[] = {
266 TRANS_OPT_THIN,
267 TRANS_OPT_KEEP,
268 TRANS_OPT_FOLLOWTAGS
271 static int set_helper_option(struct transport *transport,
272 const char *name, const char *value)
274 struct helper_data *data = transport->data;
275 struct strbuf buf = STRBUF_INIT;
276 int i, ret, is_bool = 0;
278 get_helper(transport);
280 if (!data->option)
281 return 1;
283 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
284 if (!strcmp(name, unsupported_options[i]))
285 return 1;
288 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
289 if (!strcmp(name, boolean_options[i])) {
290 is_bool = 1;
291 break;
295 strbuf_addf(&buf, "option %s ", name);
296 if (is_bool)
297 strbuf_addstr(&buf, value ? "true" : "false");
298 else
299 quote_c_style(value, &buf, NULL, 0);
300 strbuf_addch(&buf, '\n');
302 xchgline(data, &buf);
304 if (!strcmp(buf.buf, "ok"))
305 ret = 0;
306 else if (!prefixcmp(buf.buf, "error")) {
307 ret = -1;
308 } else if (!strcmp(buf.buf, "unsupported"))
309 ret = 1;
310 else {
311 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
312 ret = 1;
314 strbuf_release(&buf);
315 return ret;
318 static void standard_options(struct transport *t)
320 char buf[16];
321 int n;
322 int v = t->verbose;
324 set_helper_option(t, "progress", t->progress ? "true" : "false");
326 n = snprintf(buf, sizeof(buf), "%d", v + 1);
327 if (n >= sizeof(buf))
328 die("impossibly large verbosity value");
329 set_helper_option(t, "verbosity", buf);
332 static int release_helper(struct transport *transport)
334 int res = 0;
335 struct helper_data *data = transport->data;
336 free_refspec(data->refspec_nr, data->refspecs);
337 data->refspecs = NULL;
338 res = disconnect_helper(transport);
339 free(transport->data);
340 return res;
343 static int fetch_with_fetch(struct transport *transport,
344 int nr_heads, struct ref **to_fetch)
346 struct helper_data *data = transport->data;
347 int i;
348 struct strbuf buf = STRBUF_INIT;
350 standard_options(transport);
352 for (i = 0; i < nr_heads; i++) {
353 const struct ref *posn = to_fetch[i];
354 if (posn->status & REF_STATUS_UPTODATE)
355 continue;
357 strbuf_addf(&buf, "fetch %s %s\n",
358 sha1_to_hex(posn->old_sha1), posn->name);
361 strbuf_addch(&buf, '\n');
362 sendline(data, &buf);
364 while (1) {
365 recvline(data, &buf);
367 if (!prefixcmp(buf.buf, "lock ")) {
368 const char *name = buf.buf + 5;
369 if (transport->pack_lockfile)
370 warning("%s also locked %s", data->name, name);
371 else
372 transport->pack_lockfile = xstrdup(name);
374 else if (!buf.len)
375 break;
376 else
377 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
379 strbuf_release(&buf);
380 return 0;
383 static int get_importer(struct transport *transport, struct child_process *fastimport)
385 struct child_process *helper = get_helper(transport);
386 struct helper_data *data = transport->data;
387 struct argv_array argv = ARGV_ARRAY_INIT;
388 int cat_blob_fd, code;
389 memset(fastimport, 0, sizeof(*fastimport));
390 fastimport->in = helper->out;
391 argv_array_push(&argv, "fast-import");
392 argv_array_push(&argv, debug ? "--stats" : "--quiet");
394 if (data->bidi_import) {
395 cat_blob_fd = xdup(helper->in);
396 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
398 fastimport->argv = argv.argv;
399 fastimport->git_cmd = 1;
401 code = start_command(fastimport);
402 return code;
405 static int get_exporter(struct transport *transport,
406 struct child_process *fastexport,
407 struct string_list *revlist_args)
409 struct helper_data *data = transport->data;
410 struct child_process *helper = get_helper(transport);
411 int argc = 0, i;
412 memset(fastexport, 0, sizeof(*fastexport));
414 /* we need to duplicate helper->in because we want to use it after
415 * fastexport is done with it. */
416 fastexport->out = dup(helper->in);
417 fastexport->argv = xcalloc(7 + revlist_args->nr, sizeof(*fastexport->argv));
418 fastexport->argv[argc++] = "fast-export";
419 fastexport->argv[argc++] = "--use-done-feature";
420 fastexport->argv[argc++] = data->signed_tags ?
421 "--signed-tags=verbatim" : "--signed-tags=warn-strip";
422 if (data->export_marks)
423 fastexport->argv[argc++] = data->export_marks;
424 if (data->import_marks)
425 fastexport->argv[argc++] = data->import_marks;
427 for (i = 0; i < revlist_args->nr; i++)
428 fastexport->argv[argc++] = revlist_args->items[i].string;
430 fastexport->argv[argc++] = "--";
432 fastexport->git_cmd = 1;
433 return start_command(fastexport);
436 static void check_helper_status(struct helper_data *data)
438 int pid, status;
440 pid = waitpid(data->helper->pid, &status, WNOHANG);
441 if (pid < 0)
442 die("Could not retrieve status of remote helper '%s'",
443 data->name);
444 if (pid > 0 && WIFEXITED(status))
445 die("Remote helper '%s' died with %d",
446 data->name, WEXITSTATUS(status));
449 static int fetch_with_import(struct transport *transport,
450 int nr_heads, struct ref **to_fetch)
452 struct child_process fastimport;
453 struct helper_data *data = transport->data;
454 int i;
455 struct ref *posn;
456 struct strbuf buf = STRBUF_INIT;
458 get_helper(transport);
460 if (get_importer(transport, &fastimport))
461 die("Couldn't run fast-import");
463 for (i = 0; i < nr_heads; i++) {
464 posn = to_fetch[i];
465 if (posn->status & REF_STATUS_UPTODATE)
466 continue;
468 strbuf_addf(&buf, "import %s\n", posn->name);
469 sendline(data, &buf);
470 strbuf_reset(&buf);
473 write_constant(data->helper->in, "\n");
475 * remote-helpers that advertise the bidi-import capability are required to
476 * buffer the complete batch of import commands until this newline before
477 * sending data to fast-import.
478 * These helpers read back data from fast-import on their stdin, which could
479 * be mixed with import commands, otherwise.
482 if (finish_command(&fastimport))
483 die("Error while running fast-import");
484 argv_array_free_detached(fastimport.argv);
485 check_helper_status(data);
488 * The fast-import stream of a remote helper that advertises
489 * the "refspec" capability writes to the refs named after the
490 * right hand side of the first refspec matching each ref we
491 * were fetching.
493 * (If no "refspec" capability was specified, for historical
494 * reasons we default to *:*.)
496 * Store the result in to_fetch[i].old_sha1. Callers such
497 * as "git fetch" can use the value to write feedback to the
498 * terminal, populate FETCH_HEAD, and determine what new value
499 * should be written to peer_ref if the update is a
500 * fast-forward or this is a forced update.
502 for (i = 0; i < nr_heads; i++) {
503 char *private;
504 posn = to_fetch[i];
505 if (posn->status & REF_STATUS_UPTODATE)
506 continue;
507 if (data->refspecs)
508 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
509 else
510 private = xstrdup(posn->name);
511 if (private) {
512 read_ref(private, posn->old_sha1);
513 free(private);
516 strbuf_release(&buf);
517 if (auto_gc) {
518 const char *argv_gc_auto[] = {
519 "gc", "--auto", "--quiet", NULL,
521 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
523 return 0;
526 static int process_connect_service(struct transport *transport,
527 const char *name, const char *exec)
529 struct helper_data *data = transport->data;
530 struct strbuf cmdbuf = STRBUF_INIT;
531 struct child_process *helper;
532 int r, duped, ret = 0;
533 FILE *input;
535 helper = get_helper(transport);
538 * Yes, dup the pipe another time, as we need unbuffered version
539 * of input pipe as FILE*. fclose() closes the underlying fd and
540 * stream buffering only can be changed before first I/O operation
541 * on it.
543 duped = dup(helper->out);
544 if (duped < 0)
545 die_errno("Can't dup helper output fd");
546 input = xfdopen(duped, "r");
547 setvbuf(input, NULL, _IONBF, 0);
550 * Handle --upload-pack and friends. This is fire and forget...
551 * just warn if it fails.
553 if (strcmp(name, exec)) {
554 r = set_helper_option(transport, "servpath", exec);
555 if (r > 0)
556 warning("Setting remote service path not supported by protocol.");
557 else if (r < 0)
558 warning("Invalid remote service path.");
561 if (data->connect)
562 strbuf_addf(&cmdbuf, "connect %s\n", name);
563 else
564 goto exit;
566 sendline(data, &cmdbuf);
567 recvline_fh(input, &cmdbuf);
568 if (!strcmp(cmdbuf.buf, "")) {
569 data->no_disconnect_req = 1;
570 if (debug)
571 fprintf(stderr, "Debug: Smart transport connection "
572 "ready.\n");
573 ret = 1;
574 } else if (!strcmp(cmdbuf.buf, "fallback")) {
575 if (debug)
576 fprintf(stderr, "Debug: Falling back to dumb "
577 "transport.\n");
578 } else
579 die("Unknown response to connect: %s",
580 cmdbuf.buf);
582 exit:
583 fclose(input);
584 return ret;
587 static int process_connect(struct transport *transport,
588 int for_push)
590 struct helper_data *data = transport->data;
591 const char *name;
592 const char *exec;
594 name = for_push ? "git-receive-pack" : "git-upload-pack";
595 if (for_push)
596 exec = data->transport_options.receivepack;
597 else
598 exec = data->transport_options.uploadpack;
600 return process_connect_service(transport, name, exec);
603 static int connect_helper(struct transport *transport, const char *name,
604 const char *exec, int fd[2])
606 struct helper_data *data = transport->data;
608 /* Get_helper so connect is inited. */
609 get_helper(transport);
610 if (!data->connect)
611 die("Operation not supported by protocol.");
613 if (!process_connect_service(transport, name, exec))
614 die("Can't connect to subservice %s.", name);
616 fd[0] = data->helper->out;
617 fd[1] = data->helper->in;
618 return 0;
621 static int fetch(struct transport *transport,
622 int nr_heads, struct ref **to_fetch)
624 struct helper_data *data = transport->data;
625 int i, count;
627 if (process_connect(transport, 0)) {
628 do_take_over(transport);
629 return transport->fetch(transport, nr_heads, to_fetch);
632 count = 0;
633 for (i = 0; i < nr_heads; i++)
634 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
635 count++;
637 if (!count)
638 return 0;
640 if (data->fetch)
641 return fetch_with_fetch(transport, nr_heads, to_fetch);
643 if (data->import)
644 return fetch_with_import(transport, nr_heads, to_fetch);
646 return -1;
649 static void push_update_ref_status(struct strbuf *buf,
650 struct ref **ref,
651 struct ref *remote_refs)
653 char *refname, *msg;
654 int status;
656 if (!prefixcmp(buf->buf, "ok ")) {
657 status = REF_STATUS_OK;
658 refname = buf->buf + 3;
659 } else if (!prefixcmp(buf->buf, "error ")) {
660 status = REF_STATUS_REMOTE_REJECT;
661 refname = buf->buf + 6;
662 } else
663 die("expected ok/error, helper said '%s'", buf->buf);
665 msg = strchr(refname, ' ');
666 if (msg) {
667 struct strbuf msg_buf = STRBUF_INIT;
668 const char *end;
670 *msg++ = '\0';
671 if (!unquote_c_style(&msg_buf, msg, &end))
672 msg = strbuf_detach(&msg_buf, NULL);
673 else
674 msg = xstrdup(msg);
675 strbuf_release(&msg_buf);
677 if (!strcmp(msg, "no match")) {
678 status = REF_STATUS_NONE;
679 free(msg);
680 msg = NULL;
682 else if (!strcmp(msg, "up to date")) {
683 status = REF_STATUS_UPTODATE;
684 free(msg);
685 msg = NULL;
687 else if (!strcmp(msg, "non-fast forward")) {
688 status = REF_STATUS_REJECT_NONFASTFORWARD;
689 free(msg);
690 msg = NULL;
692 else if (!strcmp(msg, "already exists")) {
693 status = REF_STATUS_REJECT_ALREADY_EXISTS;
694 free(msg);
695 msg = NULL;
697 else if (!strcmp(msg, "fetch first")) {
698 status = REF_STATUS_REJECT_FETCH_FIRST;
699 free(msg);
700 msg = NULL;
702 else if (!strcmp(msg, "needs force")) {
703 status = REF_STATUS_REJECT_NEEDS_FORCE;
704 free(msg);
705 msg = NULL;
709 if (*ref)
710 *ref = find_ref_by_name(*ref, refname);
711 if (!*ref)
712 *ref = find_ref_by_name(remote_refs, refname);
713 if (!*ref) {
714 warning("helper reported unexpected status of %s", refname);
715 return;
718 if ((*ref)->status != REF_STATUS_NONE) {
720 * Earlier, the ref was marked not to be pushed, so ignore the ref
721 * status reported by the remote helper if the latter is 'no match'.
723 if (status == REF_STATUS_NONE)
724 return;
727 (*ref)->status = status;
728 (*ref)->remote_status = msg;
731 static void push_update_refs_status(struct helper_data *data,
732 struct ref *remote_refs)
734 struct strbuf buf = STRBUF_INIT;
735 struct ref *ref = remote_refs;
736 for (;;) {
737 recvline(data, &buf);
738 if (!buf.len)
739 break;
741 push_update_ref_status(&buf, &ref, remote_refs);
743 strbuf_release(&buf);
746 static int push_refs_with_push(struct transport *transport,
747 struct ref *remote_refs, int flags)
749 int force_all = flags & TRANSPORT_PUSH_FORCE;
750 int mirror = flags & TRANSPORT_PUSH_MIRROR;
751 struct helper_data *data = transport->data;
752 struct strbuf buf = STRBUF_INIT;
753 struct ref *ref;
755 get_helper(transport);
756 if (!data->push)
757 return 1;
759 for (ref = remote_refs; ref; ref = ref->next) {
760 if (!ref->peer_ref && !mirror)
761 continue;
763 /* Check for statuses set by set_ref_status_for_push() */
764 switch (ref->status) {
765 case REF_STATUS_REJECT_NONFASTFORWARD:
766 case REF_STATUS_REJECT_ALREADY_EXISTS:
767 case REF_STATUS_UPTODATE:
768 continue;
769 default:
770 ; /* do nothing */
773 if (force_all)
774 ref->force = 1;
776 strbuf_addstr(&buf, "push ");
777 if (!ref->deletion) {
778 if (ref->force)
779 strbuf_addch(&buf, '+');
780 if (ref->peer_ref)
781 strbuf_addstr(&buf, ref->peer_ref->name);
782 else
783 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
785 strbuf_addch(&buf, ':');
786 strbuf_addstr(&buf, ref->name);
787 strbuf_addch(&buf, '\n');
789 if (buf.len == 0)
790 return 0;
792 standard_options(transport);
794 if (flags & TRANSPORT_PUSH_DRY_RUN) {
795 if (set_helper_option(transport, "dry-run", "true") != 0)
796 die("helper %s does not support dry-run", data->name);
799 strbuf_addch(&buf, '\n');
800 sendline(data, &buf);
801 strbuf_release(&buf);
803 push_update_refs_status(data, remote_refs);
804 return 0;
807 static int push_refs_with_export(struct transport *transport,
808 struct ref *remote_refs, int flags)
810 struct ref *ref;
811 struct child_process *helper, exporter;
812 struct helper_data *data = transport->data;
813 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
814 struct strbuf buf = STRBUF_INIT;
816 helper = get_helper(transport);
818 write_constant(helper->in, "export\n");
820 strbuf_reset(&buf);
822 for (ref = remote_refs; ref; ref = ref->next) {
823 char *private;
824 unsigned char sha1[20];
826 if (!data->refspecs)
827 continue;
828 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
829 if (private && !get_sha1(private, sha1)) {
830 strbuf_addf(&buf, "^%s", private);
831 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
832 hashcpy(ref->old_sha1, sha1);
834 free(private);
836 if (ref->deletion) {
837 die("remote-helpers do not support ref deletion");
840 if (ref->peer_ref)
841 string_list_append(&revlist_args, ref->peer_ref->name);
845 if (get_exporter(transport, &exporter, &revlist_args))
846 die("Couldn't run fast-export");
848 if (finish_command(&exporter))
849 die("Error while running fast-export");
850 check_helper_status(data);
851 push_update_refs_status(data, remote_refs);
852 return 0;
855 static int push_refs(struct transport *transport,
856 struct ref *remote_refs, int flags)
858 struct helper_data *data = transport->data;
860 if (process_connect(transport, 1)) {
861 do_take_over(transport);
862 return transport->push_refs(transport, remote_refs, flags);
865 if (!remote_refs) {
866 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
867 "Perhaps you should specify a branch such as 'master'.\n");
868 return 0;
871 if (data->push)
872 return push_refs_with_push(transport, remote_refs, flags);
874 if (data->export)
875 return push_refs_with_export(transport, remote_refs, flags);
877 return -1;
881 static int has_attribute(const char *attrs, const char *attr) {
882 int len;
883 if (!attrs)
884 return 0;
886 len = strlen(attr);
887 for (;;) {
888 const char *space = strchrnul(attrs, ' ');
889 if (len == space - attrs && !strncmp(attrs, attr, len))
890 return 1;
891 if (!*space)
892 return 0;
893 attrs = space + 1;
897 static struct ref *get_refs_list(struct transport *transport, int for_push)
899 struct helper_data *data = transport->data;
900 struct child_process *helper;
901 struct ref *ret = NULL;
902 struct ref **tail = &ret;
903 struct ref *posn;
904 struct strbuf buf = STRBUF_INIT;
906 helper = get_helper(transport);
908 if (process_connect(transport, for_push)) {
909 do_take_over(transport);
910 return transport->get_refs_list(transport, for_push);
913 if (data->push && for_push)
914 write_str_in_full(helper->in, "list for-push\n");
915 else
916 write_str_in_full(helper->in, "list\n");
918 while (1) {
919 char *eov, *eon;
920 recvline(data, &buf);
922 if (!*buf.buf)
923 break;
925 eov = strchr(buf.buf, ' ');
926 if (!eov)
927 die("Malformed response in ref list: %s", buf.buf);
928 eon = strchr(eov + 1, ' ');
929 *eov = '\0';
930 if (eon)
931 *eon = '\0';
932 *tail = alloc_ref(eov + 1);
933 if (buf.buf[0] == '@')
934 (*tail)->symref = xstrdup(buf.buf + 1);
935 else if (buf.buf[0] != '?')
936 get_sha1_hex(buf.buf, (*tail)->old_sha1);
937 if (eon) {
938 if (has_attribute(eon + 1, "unchanged")) {
939 (*tail)->status |= REF_STATUS_UPTODATE;
940 read_ref((*tail)->name, (*tail)->old_sha1);
943 tail = &((*tail)->next);
945 if (debug)
946 fprintf(stderr, "Debug: Read ref listing.\n");
947 strbuf_release(&buf);
949 for (posn = ret; posn; posn = posn->next)
950 resolve_remote_symref(posn, ret);
952 return ret;
955 int transport_helper_init(struct transport *transport, const char *name)
957 struct helper_data *data = xcalloc(sizeof(*data), 1);
958 data->name = name;
960 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
961 debug = 1;
963 transport->data = data;
964 transport->set_option = set_helper_option;
965 transport->get_refs_list = get_refs_list;
966 transport->fetch = fetch;
967 transport->push_refs = push_refs;
968 transport->disconnect = release_helper;
969 transport->connect = connect_helper;
970 transport->smart_options = &(data->transport_options);
971 return 0;
975 * Linux pipes can buffer 65536 bytes at once (and most platforms can
976 * buffer less), so attempt reads and writes with up to that size.
978 #define BUFFERSIZE 65536
979 /* This should be enough to hold debugging message. */
980 #define PBUFFERSIZE 8192
982 /* Print bidirectional transfer loop debug message. */
983 static void transfer_debug(const char *fmt, ...)
985 va_list args;
986 char msgbuf[PBUFFERSIZE];
987 static int debug_enabled = -1;
989 if (debug_enabled < 0)
990 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
991 if (!debug_enabled)
992 return;
994 va_start(args, fmt);
995 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
996 va_end(args);
997 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1000 /* Stream state: More data may be coming in this direction. */
1001 #define SSTATE_TRANSFERING 0
1003 * Stream state: No more data coming in this direction, flushing rest of
1004 * data.
1006 #define SSTATE_FLUSHING 1
1007 /* Stream state: Transfer in this direction finished. */
1008 #define SSTATE_FINISHED 2
1010 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
1011 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1012 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1014 /* Unidirectional transfer. */
1015 struct unidirectional_transfer {
1016 /* Source */
1017 int src;
1018 /* Destination */
1019 int dest;
1020 /* Is source socket? */
1021 int src_is_sock;
1022 /* Is destination socket? */
1023 int dest_is_sock;
1024 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1025 int state;
1026 /* Buffer. */
1027 char buf[BUFFERSIZE];
1028 /* Buffer used. */
1029 size_t bufuse;
1030 /* Name of source. */
1031 const char *src_name;
1032 /* Name of destination. */
1033 const char *dest_name;
1036 /* Closes the target (for writing) if transfer has finished. */
1037 static void udt_close_if_finished(struct unidirectional_transfer *t)
1039 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1040 t->state = SSTATE_FINISHED;
1041 if (t->dest_is_sock)
1042 shutdown(t->dest, SHUT_WR);
1043 else
1044 close(t->dest);
1045 transfer_debug("Closed %s.", t->dest_name);
1050 * Tries to read read data from source into buffer. If buffer is full,
1051 * no data is read. Returns 0 on success, -1 on error.
1053 static int udt_do_read(struct unidirectional_transfer *t)
1055 ssize_t bytes;
1057 if (t->bufuse == BUFFERSIZE)
1058 return 0; /* No space for more. */
1060 transfer_debug("%s is readable", t->src_name);
1061 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1062 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1063 errno != EINTR) {
1064 error("read(%s) failed: %s", t->src_name, strerror(errno));
1065 return -1;
1066 } else if (bytes == 0) {
1067 transfer_debug("%s EOF (with %i bytes in buffer)",
1068 t->src_name, t->bufuse);
1069 t->state = SSTATE_FLUSHING;
1070 } else if (bytes > 0) {
1071 t->bufuse += bytes;
1072 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1073 (int)bytes, t->src_name, (int)t->bufuse);
1075 return 0;
1078 /* Tries to write data from buffer into destination. If buffer is empty,
1079 * no data is written. Returns 0 on success, -1 on error.
1081 static int udt_do_write(struct unidirectional_transfer *t)
1083 ssize_t bytes;
1085 if (t->bufuse == 0)
1086 return 0; /* Nothing to write. */
1088 transfer_debug("%s is writable", t->dest_name);
1089 bytes = write(t->dest, t->buf, t->bufuse);
1090 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1091 errno != EINTR) {
1092 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1093 return -1;
1094 } else if (bytes > 0) {
1095 t->bufuse -= bytes;
1096 if (t->bufuse)
1097 memmove(t->buf, t->buf + bytes, t->bufuse);
1098 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1099 (int)bytes, t->dest_name, (int)t->bufuse);
1101 return 0;
1105 /* State of bidirectional transfer loop. */
1106 struct bidirectional_transfer_state {
1107 /* Direction from program to git. */
1108 struct unidirectional_transfer ptg;
1109 /* Direction from git to program. */
1110 struct unidirectional_transfer gtp;
1113 static void *udt_copy_task_routine(void *udt)
1115 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1116 while (t->state != SSTATE_FINISHED) {
1117 if (STATE_NEEDS_READING(t->state))
1118 if (udt_do_read(t))
1119 return NULL;
1120 if (STATE_NEEDS_WRITING(t->state))
1121 if (udt_do_write(t))
1122 return NULL;
1123 if (STATE_NEEDS_CLOSING(t->state))
1124 udt_close_if_finished(t);
1126 return udt; /* Just some non-NULL value. */
1129 #ifndef NO_PTHREADS
1132 * Join thread, with apporiate errors on failure. Name is name for the
1133 * thread (for error messages). Returns 0 on success, 1 on failure.
1135 static int tloop_join(pthread_t thread, const char *name)
1137 int err;
1138 void *tret;
1139 err = pthread_join(thread, &tret);
1140 if (!tret) {
1141 error("%s thread failed", name);
1142 return 1;
1144 if (err) {
1145 error("%s thread failed to join: %s", name, strerror(err));
1146 return 1;
1148 return 0;
1152 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1153 * -1 on failure.
1155 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1157 pthread_t gtp_thread;
1158 pthread_t ptg_thread;
1159 int err;
1160 int ret = 0;
1161 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1162 &s->gtp);
1163 if (err)
1164 die("Can't start thread for copying data: %s", strerror(err));
1165 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1166 &s->ptg);
1167 if (err)
1168 die("Can't start thread for copying data: %s", strerror(err));
1170 ret |= tloop_join(gtp_thread, "Git to program copy");
1171 ret |= tloop_join(ptg_thread, "Program to git copy");
1172 return ret;
1174 #else
1176 /* Close the source and target (for writing) for transfer. */
1177 static void udt_kill_transfer(struct unidirectional_transfer *t)
1179 t->state = SSTATE_FINISHED;
1181 * Socket read end left open isn't a disaster if nobody
1182 * attempts to read from it (mingw compat headers do not
1183 * have SHUT_RD)...
1185 * We can't fully close the socket since otherwise gtp
1186 * task would first close the socket it sends data to
1187 * while closing the ptg file descriptors.
1189 if (!t->src_is_sock)
1190 close(t->src);
1191 if (t->dest_is_sock)
1192 shutdown(t->dest, SHUT_WR);
1193 else
1194 close(t->dest);
1198 * Join process, with apporiate errors on failure. Name is name for the
1199 * process (for error messages). Returns 0 on success, 1 on failure.
1201 static int tloop_join(pid_t pid, const char *name)
1203 int tret;
1204 if (waitpid(pid, &tret, 0) < 0) {
1205 error("%s process failed to wait: %s", name, strerror(errno));
1206 return 1;
1208 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1209 error("%s process failed", name);
1210 return 1;
1212 return 0;
1216 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1217 * -1 on failure.
1219 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1221 pid_t pid1, pid2;
1222 int ret = 0;
1224 /* Fork thread #1: git to program. */
1225 pid1 = fork();
1226 if (pid1 < 0)
1227 die_errno("Can't start thread for copying data");
1228 else if (pid1 == 0) {
1229 udt_kill_transfer(&s->ptg);
1230 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1233 /* Fork thread #2: program to git. */
1234 pid2 = fork();
1235 if (pid2 < 0)
1236 die_errno("Can't start thread for copying data");
1237 else if (pid2 == 0) {
1238 udt_kill_transfer(&s->gtp);
1239 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1243 * Close both streams in parent as to not interfere with
1244 * end of file detection and wait for both tasks to finish.
1246 udt_kill_transfer(&s->gtp);
1247 udt_kill_transfer(&s->ptg);
1248 ret |= tloop_join(pid1, "Git to program copy");
1249 ret |= tloop_join(pid2, "Program to git copy");
1250 return ret;
1252 #endif
1255 * Copies data from stdin to output and from input to stdout simultaneously.
1256 * Additionally filtering through given filter. If filter is NULL, uses
1257 * identity filter.
1259 int bidirectional_transfer_loop(int input, int output)
1261 struct bidirectional_transfer_state state;
1263 /* Fill the state fields. */
1264 state.ptg.src = input;
1265 state.ptg.dest = 1;
1266 state.ptg.src_is_sock = (input == output);
1267 state.ptg.dest_is_sock = 0;
1268 state.ptg.state = SSTATE_TRANSFERING;
1269 state.ptg.bufuse = 0;
1270 state.ptg.src_name = "remote input";
1271 state.ptg.dest_name = "stdout";
1273 state.gtp.src = 0;
1274 state.gtp.dest = output;
1275 state.gtp.src_is_sock = 0;
1276 state.gtp.dest_is_sock = (input == output);
1277 state.gtp.state = SSTATE_TRANSFERING;
1278 state.gtp.bufuse = 0;
1279 state.gtp.src_name = "stdin";
1280 state.gtp.dest_name = "remote output";
1282 return tloop_spawnwait_tasks(&state);