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