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
15static int debug;
16
17struct helper_data {
18 const char *name;
19 struct child_process *helper;
20 FILE *out;
21 unsigned fetch : 1,
22 import : 1,
23 bidi_import : 1,
24 export : 1,
25 option : 1,
26 push : 1,
27 connect : 1,
28 signed_tags : 1,
29 check_connectivity : 1,
30 no_disconnect_req : 1;
31 char *export_marks;
32 char *import_marks;
33 /* These go from remote name (as in "list") to private name */
34 struct refspec *refspecs;
35 int refspec_nr;
36 /* Transport options for fetch-pack/send-pack (should one of
37 * those be invoked).
38 */
39 struct git_transport_options transport_options;
40};
41
42static void sendline(struct helper_data *helper, struct strbuf *buffer)
43{
44 if (debug)
45 fprintf(stderr, "Debug: Remote helper: -> %s", buffer->buf);
46 if (write_in_full(helper->helper->in, buffer->buf, buffer->len)
47 != buffer->len)
48 die_errno("Full write to remote helper failed");
49}
50
51static int recvline_fh(FILE *helper, struct strbuf *buffer)
52{
53 strbuf_reset(buffer);
54 if (debug)
55 fprintf(stderr, "Debug: Remote helper: Waiting...\n");
56 if (strbuf_getline(buffer, helper, '\n') == EOF) {
57 if (debug)
58 fprintf(stderr, "Debug: Remote helper quit.\n");
59 exit(128);
60 }
61
62 if (debug)
63 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
64 return 0;
65}
66
67static int recvline(struct helper_data *helper, struct strbuf *buffer)
68{
69 return recvline_fh(helper->out, buffer);
70}
71
72static void xchgline(struct helper_data *helper, struct strbuf *buffer)
73{
74 sendline(helper, buffer);
75 recvline(helper, buffer);
76}
77
78static void write_constant(int fd, const char *str)
79{
80 if (debug)
81 fprintf(stderr, "Debug: Remote helper: -> %s", str);
82 if (write_in_full(fd, str, strlen(str)) != strlen(str))
83 die_errno("Full write to remote helper failed");
84}
85
86static const char *remove_ext_force(const char *url)
87{
88 if (url) {
89 const char *colon = strchr(url, ':');
90 if (colon && colon[1] == ':')
91 return colon + 2;
92 }
93 return url;
94}
95
96static void do_take_over(struct transport *transport)
97{
98 struct helper_data *data;
99 data = (struct helper_data *)transport->data;
100 transport_take_over(transport, data->helper);
101 fclose(data->out);
102 free(data);
103}
104
105static struct child_process *get_helper(struct transport *transport)
106{
107 struct helper_data *data = transport->data;
108 struct argv_array argv = ARGV_ARRAY_INIT;
109 struct strbuf buf = STRBUF_INIT;
110 struct child_process *helper;
111 const char **refspecs = NULL;
112 int refspec_nr = 0;
113 int refspec_alloc = 0;
114 int duped;
115 int code;
116 char git_dir_buf[sizeof(GIT_DIR_ENVIRONMENT) + PATH_MAX + 1];
117 const char *helper_env[] = {
118 git_dir_buf,
119 NULL
120 };
121
122
123 if (data->helper)
124 return data->helper;
125
126 helper = xcalloc(1, sizeof(*helper));
127 helper->in = -1;
128 helper->out = -1;
129 helper->err = 0;
130 argv_array_pushf(&argv, "git-remote-%s", data->name);
131 argv_array_push(&argv, transport->remote->name);
132 argv_array_push(&argv, remove_ext_force(transport->url));
133 helper->argv = argv_array_detach(&argv, NULL);
134 helper->git_cmd = 0;
135 helper->silent_exec_failure = 1;
136
137 snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
138 helper->env = helper_env;
139
140 code = start_command(helper);
141 if (code < 0 && errno == ENOENT)
142 die("Unable to find remote helper for '%s'", data->name);
143 else if (code != 0)
144 exit(code);
145
146 data->helper = helper;
147 data->no_disconnect_req = 0;
148
149 /*
150 * Open the output as FILE* so strbuf_getline() can be used.
151 * Do this with duped fd because fclose() will close the fd,
152 * and stuff like taking over will require the fd to remain.
153 */
154 duped = dup(helper->out);
155 if (duped < 0)
156 die_errno("Can't dup helper output fd");
157 data->out = xfdopen(duped, "r");
158
159 write_constant(helper->in, "capabilities\n");
160
161 while (1) {
162 const char *capname;
163 int mandatory = 0;
164 recvline(data, &buf);
165
166 if (!*buf.buf)
167 break;
168
169 if (*buf.buf == '*') {
170 capname = buf.buf + 1;
171 mandatory = 1;
172 } else
173 capname = buf.buf;
174
175 if (debug)
176 fprintf(stderr, "Debug: Got cap %s\n", capname);
177 if (!strcmp(capname, "fetch"))
178 data->fetch = 1;
179 else if (!strcmp(capname, "option"))
180 data->option = 1;
181 else if (!strcmp(capname, "push"))
182 data->push = 1;
183 else if (!strcmp(capname, "import"))
184 data->import = 1;
185 else if (!strcmp(capname, "bidi-import"))
186 data->bidi_import = 1;
187 else if (!strcmp(capname, "export"))
188 data->export = 1;
189 else if (!strcmp(capname, "check-connectivity"))
190 data->check_connectivity = 1;
191 else if (!data->refspecs && !prefixcmp(capname, "refspec ")) {
192 ALLOC_GROW(refspecs,
193 refspec_nr + 1,
194 refspec_alloc);
195 refspecs[refspec_nr++] = xstrdup(capname + strlen("refspec "));
196 } else if (!strcmp(capname, "connect")) {
197 data->connect = 1;
198 } else if (!strcmp(capname, "signed-tags")) {
199 data->signed_tags = 1;
200 } else if (!prefixcmp(capname, "export-marks ")) {
201 struct strbuf arg = STRBUF_INIT;
202 strbuf_addstr(&arg, "--export-marks=");
203 strbuf_addstr(&arg, capname + strlen("export-marks "));
204 data->export_marks = strbuf_detach(&arg, NULL);
205 } else if (!prefixcmp(capname, "import-marks")) {
206 struct strbuf arg = STRBUF_INIT;
207 strbuf_addstr(&arg, "--import-marks=");
208 strbuf_addstr(&arg, capname + strlen("import-marks "));
209 data->import_marks = strbuf_detach(&arg, NULL);
210 } else if (mandatory) {
211 die("Unknown mandatory capability %s. This remote "
212 "helper probably needs newer version of Git.",
213 capname);
214 }
215 }
216 if (refspecs) {
217 int i;
218 data->refspec_nr = refspec_nr;
219 data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
220 for (i = 0; i < refspec_nr; i++)
221 free((char *)refspecs[i]);
222 free(refspecs);
223 }
224 strbuf_release(&buf);
225 if (debug)
226 fprintf(stderr, "Debug: Capabilities complete.\n");
227 return data->helper;
228}
229
230static int disconnect_helper(struct transport *transport)
231{
232 struct helper_data *data = transport->data;
233 int res = 0;
234
235 if (data->helper) {
236 if (debug)
237 fprintf(stderr, "Debug: Disconnecting.\n");
238 if (!data->no_disconnect_req) {
239 /*
240 * Ignore write errors; there's nothing we can do,
241 * since we're about to close the pipe anyway. And the
242 * most likely error is EPIPE due to the helper dying
243 * to report an error itself.
244 */
245 sigchain_push(SIGPIPE, SIG_IGN);
246 xwrite(data->helper->in, "\n", 1);
247 sigchain_pop(SIGPIPE);
248 }
249 close(data->helper->in);
250 close(data->helper->out);
251 fclose(data->out);
252 res = finish_command(data->helper);
253 argv_array_free_detached(data->helper->argv);
254 free(data->helper);
255 data->helper = NULL;
256 }
257 return res;
258}
259
260static const char *unsupported_options[] = {
261 TRANS_OPT_UPLOADPACK,
262 TRANS_OPT_RECEIVEPACK,
263 TRANS_OPT_THIN,
264 TRANS_OPT_KEEP
265 };
266static const char *boolean_options[] = {
267 TRANS_OPT_THIN,
268 TRANS_OPT_KEEP,
269 TRANS_OPT_FOLLOWTAGS
270 };
271
272static int set_helper_option(struct transport *transport,
273 const char *name, const char *value)
274{
275 struct helper_data *data = transport->data;
276 struct strbuf buf = STRBUF_INIT;
277 int i, ret, is_bool = 0;
278
279 get_helper(transport);
280
281 if (!data->option)
282 return 1;
283
284 for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
285 if (!strcmp(name, unsupported_options[i]))
286 return 1;
287 }
288
289 for (i = 0; i < ARRAY_SIZE(boolean_options); i++) {
290 if (!strcmp(name, boolean_options[i])) {
291 is_bool = 1;
292 break;
293 }
294 }
295
296 strbuf_addf(&buf, "option %s ", name);
297 if (is_bool)
298 strbuf_addstr(&buf, value ? "true" : "false");
299 else
300 quote_c_style(value, &buf, NULL, 0);
301 strbuf_addch(&buf, '\n');
302
303 xchgline(data, &buf);
304
305 if (!strcmp(buf.buf, "ok"))
306 ret = 0;
307 else if (!prefixcmp(buf.buf, "error")) {
308 ret = -1;
309 } else if (!strcmp(buf.buf, "unsupported"))
310 ret = 1;
311 else {
312 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
313 ret = 1;
314 }
315 strbuf_release(&buf);
316 return ret;
317}
318
319static void standard_options(struct transport *t)
320{
321 char buf[16];
322 int n;
323 int v = t->verbose;
324
325 set_helper_option(t, "progress", t->progress ? "true" : "false");
326
327 n = snprintf(buf, sizeof(buf), "%d", v + 1);
328 if (n >= sizeof(buf))
329 die("impossibly large verbosity value");
330 set_helper_option(t, "verbosity", buf);
331}
332
333static int release_helper(struct transport *transport)
334{
335 int res = 0;
336 struct helper_data *data = transport->data;
337 free_refspec(data->refspec_nr, data->refspecs);
338 data->refspecs = NULL;
339 res = disconnect_helper(transport);
340 free(transport->data);
341 return res;
342}
343
344static int fetch_with_fetch(struct transport *transport,
345 int nr_heads, struct ref **to_fetch)
346{
347 struct helper_data *data = transport->data;
348 int i;
349 struct strbuf buf = STRBUF_INIT;
350
351 standard_options(transport);
352 if (data->check_connectivity &&
353 data->transport_options.check_self_contained_and_connected)
354 set_helper_option(transport, "check-connectivity", "true");
355
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;
360
361 strbuf_addf(&buf, "fetch %s %s\n",
362 sha1_to_hex(posn->old_sha1), posn->name);
363 }
364
365 strbuf_addch(&buf, '\n');
366 sendline(data, &buf);
367
368 while (1) {
369 recvline(data, &buf);
370
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);
377 }
378 else if (data->check_connectivity &&
379 data->transport_options.check_self_contained_and_connected &&
380 !strcmp(buf.buf, "connectivity-ok"))
381 data->transport_options.self_contained_and_connected = 1;
382 else if (!buf.len)
383 break;
384 else
385 warning("%s unexpectedly said: '%s'", data->name, buf.buf);
386 }
387 strbuf_release(&buf);
388 return 0;
389}
390
391static int get_importer(struct transport *transport, struct child_process *fastimport)
392{
393 struct child_process *helper = get_helper(transport);
394 struct helper_data *data = transport->data;
395 struct argv_array argv = ARGV_ARRAY_INIT;
396 int cat_blob_fd, code;
397 memset(fastimport, 0, sizeof(*fastimport));
398 fastimport->in = helper->out;
399 argv_array_push(&argv, "fast-import");
400 argv_array_push(&argv, debug ? "--stats" : "--quiet");
401
402 if (data->bidi_import) {
403 cat_blob_fd = xdup(helper->in);
404 argv_array_pushf(&argv, "--cat-blob-fd=%d", cat_blob_fd);
405 }
406 fastimport->argv = argv.argv;
407 fastimport->git_cmd = 1;
408
409 code = start_command(fastimport);
410 return code;
411}
412
413static int get_exporter(struct transport *transport,
414 struct child_process *fastexport,
415 struct string_list *revlist_args)
416{
417 struct helper_data *data = transport->data;
418 struct child_process *helper = get_helper(transport);
419 int argc = 0, i;
420 memset(fastexport, 0, sizeof(*fastexport));
421
422 /* we need to duplicate helper->in because we want to use it after
423 * fastexport is done with it. */
424 fastexport->out = dup(helper->in);
425 fastexport->argv = xcalloc(6 + revlist_args->nr, sizeof(*fastexport->argv));
426 fastexport->argv[argc++] = "fast-export";
427 fastexport->argv[argc++] = "--use-done-feature";
428 fastexport->argv[argc++] = data->signed_tags ?
429 "--signed-tags=verbatim" : "--signed-tags=warn-strip";
430 if (data->export_marks)
431 fastexport->argv[argc++] = data->export_marks;
432 if (data->import_marks)
433 fastexport->argv[argc++] = data->import_marks;
434
435 for (i = 0; i < revlist_args->nr; i++)
436 fastexport->argv[argc++] = revlist_args->items[i].string;
437
438 fastexport->git_cmd = 1;
439 return start_command(fastexport);
440}
441
442static int fetch_with_import(struct transport *transport,
443 int nr_heads, struct ref **to_fetch)
444{
445 struct child_process fastimport;
446 struct helper_data *data = transport->data;
447 int i;
448 struct ref *posn;
449 struct strbuf buf = STRBUF_INIT;
450
451 get_helper(transport);
452
453 if (get_importer(transport, &fastimport))
454 die("Couldn't run fast-import");
455
456 for (i = 0; i < nr_heads; i++) {
457 posn = to_fetch[i];
458 if (posn->status & REF_STATUS_UPTODATE)
459 continue;
460
461 strbuf_addf(&buf, "import %s\n", posn->name);
462 sendline(data, &buf);
463 strbuf_reset(&buf);
464 }
465
466 write_constant(data->helper->in, "\n");
467 /*
468 * remote-helpers that advertise the bidi-import capability are required to
469 * buffer the complete batch of import commands until this newline before
470 * sending data to fast-import.
471 * These helpers read back data from fast-import on their stdin, which could
472 * be mixed with import commands, otherwise.
473 */
474
475 if (finish_command(&fastimport))
476 die("Error while running fast-import");
477 argv_array_free_detached(fastimport.argv);
478
479 /*
480 * The fast-import stream of a remote helper that advertises
481 * the "refspec" capability writes to the refs named after the
482 * right hand side of the first refspec matching each ref we
483 * were fetching.
484 *
485 * (If no "refspec" capability was specified, for historical
486 * reasons we default to *:*.)
487 *
488 * Store the result in to_fetch[i].old_sha1. Callers such
489 * as "git fetch" can use the value to write feedback to the
490 * terminal, populate FETCH_HEAD, and determine what new value
491 * should be written to peer_ref if the update is a
492 * fast-forward or this is a forced update.
493 */
494 for (i = 0; i < nr_heads; i++) {
495 char *private;
496 posn = to_fetch[i];
497 if (posn->status & REF_STATUS_UPTODATE)
498 continue;
499 if (data->refspecs)
500 private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
501 else
502 private = xstrdup(posn->name);
503 if (private) {
504 read_ref(private, posn->old_sha1);
505 free(private);
506 }
507 }
508 strbuf_release(&buf);
509 return 0;
510}
511
512static int process_connect_service(struct transport *transport,
513 const char *name, const char *exec)
514{
515 struct helper_data *data = transport->data;
516 struct strbuf cmdbuf = STRBUF_INIT;
517 struct child_process *helper;
518 int r, duped, ret = 0;
519 FILE *input;
520
521 helper = get_helper(transport);
522
523 /*
524 * Yes, dup the pipe another time, as we need unbuffered version
525 * of input pipe as FILE*. fclose() closes the underlying fd and
526 * stream buffering only can be changed before first I/O operation
527 * on it.
528 */
529 duped = dup(helper->out);
530 if (duped < 0)
531 die_errno("Can't dup helper output fd");
532 input = xfdopen(duped, "r");
533 setvbuf(input, NULL, _IONBF, 0);
534
535 /*
536 * Handle --upload-pack and friends. This is fire and forget...
537 * just warn if it fails.
538 */
539 if (strcmp(name, exec)) {
540 r = set_helper_option(transport, "servpath", exec);
541 if (r > 0)
542 warning("Setting remote service path not supported by protocol.");
543 else if (r < 0)
544 warning("Invalid remote service path.");
545 }
546
547 if (data->connect)
548 strbuf_addf(&cmdbuf, "connect %s\n", name);
549 else
550 goto exit;
551
552 sendline(data, &cmdbuf);
553 recvline_fh(input, &cmdbuf);
554 if (!strcmp(cmdbuf.buf, "")) {
555 data->no_disconnect_req = 1;
556 if (debug)
557 fprintf(stderr, "Debug: Smart transport connection "
558 "ready.\n");
559 ret = 1;
560 } else if (!strcmp(cmdbuf.buf, "fallback")) {
561 if (debug)
562 fprintf(stderr, "Debug: Falling back to dumb "
563 "transport.\n");
564 } else
565 die("Unknown response to connect: %s",
566 cmdbuf.buf);
567
568exit:
569 fclose(input);
570 return ret;
571}
572
573static int process_connect(struct transport *transport,
574 int for_push)
575{
576 struct helper_data *data = transport->data;
577 const char *name;
578 const char *exec;
579
580 name = for_push ? "git-receive-pack" : "git-upload-pack";
581 if (for_push)
582 exec = data->transport_options.receivepack;
583 else
584 exec = data->transport_options.uploadpack;
585
586 return process_connect_service(transport, name, exec);
587}
588
589static int connect_helper(struct transport *transport, const char *name,
590 const char *exec, int fd[2])
591{
592 struct helper_data *data = transport->data;
593
594 /* Get_helper so connect is inited. */
595 get_helper(transport);
596 if (!data->connect)
597 die("Operation not supported by protocol.");
598
599 if (!process_connect_service(transport, name, exec))
600 die("Can't connect to subservice %s.", name);
601
602 fd[0] = data->helper->out;
603 fd[1] = data->helper->in;
604 return 0;
605}
606
607static int fetch(struct transport *transport,
608 int nr_heads, struct ref **to_fetch)
609{
610 struct helper_data *data = transport->data;
611 int i, count;
612
613 if (process_connect(transport, 0)) {
614 do_take_over(transport);
615 return transport->fetch(transport, nr_heads, to_fetch);
616 }
617
618 count = 0;
619 for (i = 0; i < nr_heads; i++)
620 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
621 count++;
622
623 if (!count)
624 return 0;
625
626 if (data->fetch)
627 return fetch_with_fetch(transport, nr_heads, to_fetch);
628
629 if (data->import)
630 return fetch_with_import(transport, nr_heads, to_fetch);
631
632 return -1;
633}
634
635static void push_update_ref_status(struct strbuf *buf,
636 struct ref **ref,
637 struct ref *remote_refs)
638{
639 char *refname, *msg;
640 int status;
641
642 if (!prefixcmp(buf->buf, "ok ")) {
643 status = REF_STATUS_OK;
644 refname = buf->buf + 3;
645 } else if (!prefixcmp(buf->buf, "error ")) {
646 status = REF_STATUS_REMOTE_REJECT;
647 refname = buf->buf + 6;
648 } else
649 die("expected ok/error, helper said '%s'", buf->buf);
650
651 msg = strchr(refname, ' ');
652 if (msg) {
653 struct strbuf msg_buf = STRBUF_INIT;
654 const char *end;
655
656 *msg++ = '\0';
657 if (!unquote_c_style(&msg_buf, msg, &end))
658 msg = strbuf_detach(&msg_buf, NULL);
659 else
660 msg = xstrdup(msg);
661 strbuf_release(&msg_buf);
662
663 if (!strcmp(msg, "no match")) {
664 status = REF_STATUS_NONE;
665 free(msg);
666 msg = NULL;
667 }
668 else if (!strcmp(msg, "up to date")) {
669 status = REF_STATUS_UPTODATE;
670 free(msg);
671 msg = NULL;
672 }
673 else if (!strcmp(msg, "non-fast forward")) {
674 status = REF_STATUS_REJECT_NONFASTFORWARD;
675 free(msg);
676 msg = NULL;
677 }
678 else if (!strcmp(msg, "already exists")) {
679 status = REF_STATUS_REJECT_ALREADY_EXISTS;
680 free(msg);
681 msg = NULL;
682 }
683 else if (!strcmp(msg, "fetch first")) {
684 status = REF_STATUS_REJECT_FETCH_FIRST;
685 free(msg);
686 msg = NULL;
687 }
688 else if (!strcmp(msg, "needs force")) {
689 status = REF_STATUS_REJECT_NEEDS_FORCE;
690 free(msg);
691 msg = NULL;
692 }
693 }
694
695 if (*ref)
696 *ref = find_ref_by_name(*ref, refname);
697 if (!*ref)
698 *ref = find_ref_by_name(remote_refs, refname);
699 if (!*ref) {
700 warning("helper reported unexpected status of %s", refname);
701 return;
702 }
703
704 if ((*ref)->status != REF_STATUS_NONE) {
705 /*
706 * Earlier, the ref was marked not to be pushed, so ignore the ref
707 * status reported by the remote helper if the latter is 'no match'.
708 */
709 if (status == REF_STATUS_NONE)
710 return;
711 }
712
713 (*ref)->status = status;
714 (*ref)->remote_status = msg;
715}
716
717static void push_update_refs_status(struct helper_data *data,
718 struct ref *remote_refs)
719{
720 struct strbuf buf = STRBUF_INIT;
721 struct ref *ref = remote_refs;
722 for (;;) {
723 recvline(data, &buf);
724 if (!buf.len)
725 break;
726
727 push_update_ref_status(&buf, &ref, remote_refs);
728 }
729 strbuf_release(&buf);
730}
731
732static int push_refs_with_push(struct transport *transport,
733 struct ref *remote_refs, int flags)
734{
735 int force_all = flags & TRANSPORT_PUSH_FORCE;
736 int mirror = flags & TRANSPORT_PUSH_MIRROR;
737 struct helper_data *data = transport->data;
738 struct strbuf buf = STRBUF_INIT;
739 struct ref *ref;
740
741 get_helper(transport);
742 if (!data->push)
743 return 1;
744
745 for (ref = remote_refs; ref; ref = ref->next) {
746 if (!ref->peer_ref && !mirror)
747 continue;
748
749 /* Check for statuses set by set_ref_status_for_push() */
750 switch (ref->status) {
751 case REF_STATUS_REJECT_NONFASTFORWARD:
752 case REF_STATUS_REJECT_ALREADY_EXISTS:
753 case REF_STATUS_UPTODATE:
754 continue;
755 default:
756 ; /* do nothing */
757 }
758
759 if (force_all)
760 ref->force = 1;
761
762 strbuf_addstr(&buf, "push ");
763 if (!ref->deletion) {
764 if (ref->force)
765 strbuf_addch(&buf, '+');
766 if (ref->peer_ref)
767 strbuf_addstr(&buf, ref->peer_ref->name);
768 else
769 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
770 }
771 strbuf_addch(&buf, ':');
772 strbuf_addstr(&buf, ref->name);
773 strbuf_addch(&buf, '\n');
774 }
775 if (buf.len == 0)
776 return 0;
777
778 standard_options(transport);
779
780 if (flags & TRANSPORT_PUSH_DRY_RUN) {
781 if (set_helper_option(transport, "dry-run", "true") != 0)
782 die("helper %s does not support dry-run", data->name);
783 }
784
785 strbuf_addch(&buf, '\n');
786 sendline(data, &buf);
787 strbuf_release(&buf);
788
789 push_update_refs_status(data, remote_refs);
790 return 0;
791}
792
793static int push_refs_with_export(struct transport *transport,
794 struct ref *remote_refs, int flags)
795{
796 struct ref *ref;
797 struct child_process *helper, exporter;
798 struct helper_data *data = transport->data;
799 struct string_list revlist_args = STRING_LIST_INIT_NODUP;
800 struct strbuf buf = STRBUF_INIT;
801
802 helper = get_helper(transport);
803
804 write_constant(helper->in, "export\n");
805
806 strbuf_reset(&buf);
807
808 for (ref = remote_refs; ref; ref = ref->next) {
809 char *private;
810 unsigned char sha1[20];
811
812 if (!data->refspecs)
813 continue;
814 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
815 if (private && !get_sha1(private, sha1)) {
816 strbuf_addf(&buf, "^%s", private);
817 string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
818 hashcpy(ref->old_sha1, sha1);
819 }
820 free(private);
821
822 if (ref->deletion) {
823 die("remote-helpers do not support ref deletion");
824 }
825
826 if (ref->peer_ref)
827 string_list_append(&revlist_args, ref->peer_ref->name);
828
829 }
830
831 if (get_exporter(transport, &exporter, &revlist_args))
832 die("Couldn't run fast-export");
833
834 if (finish_command(&exporter))
835 die("Error while running fast-export");
836 push_update_refs_status(data, remote_refs);
837 return 0;
838}
839
840static int push_refs(struct transport *transport,
841 struct ref *remote_refs, int flags)
842{
843 struct helper_data *data = transport->data;
844
845 if (process_connect(transport, 1)) {
846 do_take_over(transport);
847 return transport->push_refs(transport, remote_refs, flags);
848 }
849
850 if (!remote_refs) {
851 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
852 "Perhaps you should specify a branch such as 'master'.\n");
853 return 0;
854 }
855
856 if (data->push)
857 return push_refs_with_push(transport, remote_refs, flags);
858
859 if (data->export)
860 return push_refs_with_export(transport, remote_refs, flags);
861
862 return -1;
863}
864
865
866static int has_attribute(const char *attrs, const char *attr) {
867 int len;
868 if (!attrs)
869 return 0;
870
871 len = strlen(attr);
872 for (;;) {
873 const char *space = strchrnul(attrs, ' ');
874 if (len == space - attrs && !strncmp(attrs, attr, len))
875 return 1;
876 if (!*space)
877 return 0;
878 attrs = space + 1;
879 }
880}
881
882static struct ref *get_refs_list(struct transport *transport, int for_push)
883{
884 struct helper_data *data = transport->data;
885 struct child_process *helper;
886 struct ref *ret = NULL;
887 struct ref **tail = &ret;
888 struct ref *posn;
889 struct strbuf buf = STRBUF_INIT;
890
891 helper = get_helper(transport);
892
893 if (process_connect(transport, for_push)) {
894 do_take_over(transport);
895 return transport->get_refs_list(transport, for_push);
896 }
897
898 if (data->push && for_push)
899 write_str_in_full(helper->in, "list for-push\n");
900 else
901 write_str_in_full(helper->in, "list\n");
902
903 while (1) {
904 char *eov, *eon;
905 recvline(data, &buf);
906
907 if (!*buf.buf)
908 break;
909
910 eov = strchr(buf.buf, ' ');
911 if (!eov)
912 die("Malformed response in ref list: %s", buf.buf);
913 eon = strchr(eov + 1, ' ');
914 *eov = '\0';
915 if (eon)
916 *eon = '\0';
917 *tail = alloc_ref(eov + 1);
918 if (buf.buf[0] == '@')
919 (*tail)->symref = xstrdup(buf.buf + 1);
920 else if (buf.buf[0] != '?')
921 get_sha1_hex(buf.buf, (*tail)->old_sha1);
922 if (eon) {
923 if (has_attribute(eon + 1, "unchanged")) {
924 (*tail)->status |= REF_STATUS_UPTODATE;
925 read_ref((*tail)->name, (*tail)->old_sha1);
926 }
927 }
928 tail = &((*tail)->next);
929 }
930 if (debug)
931 fprintf(stderr, "Debug: Read ref listing.\n");
932 strbuf_release(&buf);
933
934 for (posn = ret; posn; posn = posn->next)
935 resolve_remote_symref(posn, ret);
936
937 return ret;
938}
939
940int transport_helper_init(struct transport *transport, const char *name)
941{
942 struct helper_data *data = xcalloc(sizeof(*data), 1);
943 data->name = name;
944
945 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
946 debug = 1;
947
948 transport->data = data;
949 transport->set_option = set_helper_option;
950 transport->get_refs_list = get_refs_list;
951 transport->fetch = fetch;
952 transport->push_refs = push_refs;
953 transport->disconnect = release_helper;
954 transport->connect = connect_helper;
955 transport->smart_options = &(data->transport_options);
956 return 0;
957}
958
959/*
960 * Linux pipes can buffer 65536 bytes at once (and most platforms can
961 * buffer less), so attempt reads and writes with up to that size.
962 */
963#define BUFFERSIZE 65536
964/* This should be enough to hold debugging message. */
965#define PBUFFERSIZE 8192
966
967/* Print bidirectional transfer loop debug message. */
968static void transfer_debug(const char *fmt, ...)
969{
970 va_list args;
971 char msgbuf[PBUFFERSIZE];
972 static int debug_enabled = -1;
973
974 if (debug_enabled < 0)
975 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
976 if (!debug_enabled)
977 return;
978
979 va_start(args, fmt);
980 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
981 va_end(args);
982 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
983}
984
985/* Stream state: More data may be coming in this direction. */
986#define SSTATE_TRANSFERING 0
987/*
988 * Stream state: No more data coming in this direction, flushing rest of
989 * data.
990 */
991#define SSTATE_FLUSHING 1
992/* Stream state: Transfer in this direction finished. */
993#define SSTATE_FINISHED 2
994
995#define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
996#define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
997#define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
998
999/* Unidirectional transfer. */
1000struct unidirectional_transfer {
1001 /* Source */
1002 int src;
1003 /* Destination */
1004 int dest;
1005 /* Is source socket? */
1006 int src_is_sock;
1007 /* Is destination socket? */
1008 int dest_is_sock;
1009 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1010 int state;
1011 /* Buffer. */
1012 char buf[BUFFERSIZE];
1013 /* Buffer used. */
1014 size_t bufuse;
1015 /* Name of source. */
1016 const char *src_name;
1017 /* Name of destination. */
1018 const char *dest_name;
1019};
1020
1021/* Closes the target (for writing) if transfer has finished. */
1022static void udt_close_if_finished(struct unidirectional_transfer *t)
1023{
1024 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1025 t->state = SSTATE_FINISHED;
1026 if (t->dest_is_sock)
1027 shutdown(t->dest, SHUT_WR);
1028 else
1029 close(t->dest);
1030 transfer_debug("Closed %s.", t->dest_name);
1031 }
1032}
1033
1034/*
1035 * Tries to read read data from source into buffer. If buffer is full,
1036 * no data is read. Returns 0 on success, -1 on error.
1037 */
1038static int udt_do_read(struct unidirectional_transfer *t)
1039{
1040 ssize_t bytes;
1041
1042 if (t->bufuse == BUFFERSIZE)
1043 return 0; /* No space for more. */
1044
1045 transfer_debug("%s is readable", t->src_name);
1046 bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1047 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1048 errno != EINTR) {
1049 error("read(%s) failed: %s", t->src_name, strerror(errno));
1050 return -1;
1051 } else if (bytes == 0) {
1052 transfer_debug("%s EOF (with %i bytes in buffer)",
1053 t->src_name, t->bufuse);
1054 t->state = SSTATE_FLUSHING;
1055 } else if (bytes > 0) {
1056 t->bufuse += bytes;
1057 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1058 (int)bytes, t->src_name, (int)t->bufuse);
1059 }
1060 return 0;
1061}
1062
1063/* Tries to write data from buffer into destination. If buffer is empty,
1064 * no data is written. Returns 0 on success, -1 on error.
1065 */
1066static int udt_do_write(struct unidirectional_transfer *t)
1067{
1068 ssize_t bytes;
1069
1070 if (t->bufuse == 0)
1071 return 0; /* Nothing to write. */
1072
1073 transfer_debug("%s is writable", t->dest_name);
1074 bytes = write(t->dest, t->buf, t->bufuse);
1075 if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1076 errno != EINTR) {
1077 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1078 return -1;
1079 } else if (bytes > 0) {
1080 t->bufuse -= bytes;
1081 if (t->bufuse)
1082 memmove(t->buf, t->buf + bytes, t->bufuse);
1083 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1084 (int)bytes, t->dest_name, (int)t->bufuse);
1085 }
1086 return 0;
1087}
1088
1089
1090/* State of bidirectional transfer loop. */
1091struct bidirectional_transfer_state {
1092 /* Direction from program to git. */
1093 struct unidirectional_transfer ptg;
1094 /* Direction from git to program. */
1095 struct unidirectional_transfer gtp;
1096};
1097
1098static void *udt_copy_task_routine(void *udt)
1099{
1100 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1101 while (t->state != SSTATE_FINISHED) {
1102 if (STATE_NEEDS_READING(t->state))
1103 if (udt_do_read(t))
1104 return NULL;
1105 if (STATE_NEEDS_WRITING(t->state))
1106 if (udt_do_write(t))
1107 return NULL;
1108 if (STATE_NEEDS_CLOSING(t->state))
1109 udt_close_if_finished(t);
1110 }
1111 return udt; /* Just some non-NULL value. */
1112}
1113
1114#ifndef NO_PTHREADS
1115
1116/*
1117 * Join thread, with apporiate errors on failure. Name is name for the
1118 * thread (for error messages). Returns 0 on success, 1 on failure.
1119 */
1120static int tloop_join(pthread_t thread, const char *name)
1121{
1122 int err;
1123 void *tret;
1124 err = pthread_join(thread, &tret);
1125 if (!tret) {
1126 error("%s thread failed", name);
1127 return 1;
1128 }
1129 if (err) {
1130 error("%s thread failed to join: %s", name, strerror(err));
1131 return 1;
1132 }
1133 return 0;
1134}
1135
1136/*
1137 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1138 * -1 on failure.
1139 */
1140static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1141{
1142 pthread_t gtp_thread;
1143 pthread_t ptg_thread;
1144 int err;
1145 int ret = 0;
1146 err = pthread_create(>p_thread, NULL, udt_copy_task_routine,
1147 &s->gtp);
1148 if (err)
1149 die("Can't start thread for copying data: %s", strerror(err));
1150 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1151 &s->ptg);
1152 if (err)
1153 die("Can't start thread for copying data: %s", strerror(err));
1154
1155 ret |= tloop_join(gtp_thread, "Git to program copy");
1156 ret |= tloop_join(ptg_thread, "Program to git copy");
1157 return ret;
1158}
1159#else
1160
1161/* Close the source and target (for writing) for transfer. */
1162static void udt_kill_transfer(struct unidirectional_transfer *t)
1163{
1164 t->state = SSTATE_FINISHED;
1165 /*
1166 * Socket read end left open isn't a disaster if nobody
1167 * attempts to read from it (mingw compat headers do not
1168 * have SHUT_RD)...
1169 *
1170 * We can't fully close the socket since otherwise gtp
1171 * task would first close the socket it sends data to
1172 * while closing the ptg file descriptors.
1173 */
1174 if (!t->src_is_sock)
1175 close(t->src);
1176 if (t->dest_is_sock)
1177 shutdown(t->dest, SHUT_WR);
1178 else
1179 close(t->dest);
1180}
1181
1182/*
1183 * Join process, with apporiate errors on failure. Name is name for the
1184 * process (for error messages). Returns 0 on success, 1 on failure.
1185 */
1186static int tloop_join(pid_t pid, const char *name)
1187{
1188 int tret;
1189 if (waitpid(pid, &tret, 0) < 0) {
1190 error("%s process failed to wait: %s", name, strerror(errno));
1191 return 1;
1192 }
1193 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1194 error("%s process failed", name);
1195 return 1;
1196 }
1197 return 0;
1198}
1199
1200/*
1201 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1202 * -1 on failure.
1203 */
1204static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1205{
1206 pid_t pid1, pid2;
1207 int ret = 0;
1208
1209 /* Fork thread #1: git to program. */
1210 pid1 = fork();
1211 if (pid1 < 0)
1212 die_errno("Can't start thread for copying data");
1213 else if (pid1 == 0) {
1214 udt_kill_transfer(&s->ptg);
1215 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1216 }
1217
1218 /* Fork thread #2: program to git. */
1219 pid2 = fork();
1220 if (pid2 < 0)
1221 die_errno("Can't start thread for copying data");
1222 else if (pid2 == 0) {
1223 udt_kill_transfer(&s->gtp);
1224 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1225 }
1226
1227 /*
1228 * Close both streams in parent as to not interfere with
1229 * end of file detection and wait for both tasks to finish.
1230 */
1231 udt_kill_transfer(&s->gtp);
1232 udt_kill_transfer(&s->ptg);
1233 ret |= tloop_join(pid1, "Git to program copy");
1234 ret |= tloop_join(pid2, "Program to git copy");
1235 return ret;
1236}
1237#endif
1238
1239/*
1240 * Copies data from stdin to output and from input to stdout simultaneously.
1241 * Additionally filtering through given filter. If filter is NULL, uses
1242 * identity filter.
1243 */
1244int bidirectional_transfer_loop(int input, int output)
1245{
1246 struct bidirectional_transfer_state state;
1247
1248 /* Fill the state fields. */
1249 state.ptg.src = input;
1250 state.ptg.dest = 1;
1251 state.ptg.src_is_sock = (input == output);
1252 state.ptg.dest_is_sock = 0;
1253 state.ptg.state = SSTATE_TRANSFERING;
1254 state.ptg.bufuse = 0;
1255 state.ptg.src_name = "remote input";
1256 state.ptg.dest_name = "stdout";
1257
1258 state.gtp.src = 0;
1259 state.gtp.dest = output;
1260 state.gtp.src_is_sock = 0;
1261 state.gtp.dest_is_sock = (input == output);
1262 state.gtp.state = SSTATE_TRANSFERING;
1263 state.gtp.bufuse = 0;
1264 state.gtp.src_name = "stdin";
1265 state.gtp.dest_name = "remote output";
1266
1267 return tloop_spawnwait_tasks(&state);
1268}