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