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