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 strvec_push(&fastexport->args, "fast-export");
491 strvec_push(&fastexport->args, "--use-done-feature");
492 strvec_push(&fastexport->args, data->signed_tags ?
493 "--signed-tags=verbatim" : "--signed-tags=warn-strip");
494 if (data->export_marks)
495 strvec_pushf(&fastexport->args, "--export-marks=%s.tmp", data->export_marks);
496 if (data->import_marks)
497 strvec_pushf(&fastexport->args, "--import-marks=%s", data->import_marks);
498
499 for (size_t i = 0; i < revlist_args->nr; i++)
500 strvec_push(&fastexport->args, revlist_args->items[i].string);
501
502 fastexport->git_cmd = 1;
503 return start_command(fastexport);
504 }
505
506 static int fetch_with_import(struct transport *transport,
507 int nr_heads, struct ref **to_fetch)
508 {
509 struct child_process fastimport;
510 struct helper_data *data = transport->data;
511 int i;
512 struct ref *posn;
513 struct strbuf buf = STRBUF_INIT;
514
515 get_helper(transport);
516
517 if (get_importer(transport, &fastimport))
518 die(_("couldn't run fast-import"));
519
520 for (i = 0; i < nr_heads; i++) {
521 posn = to_fetch[i];
522 if (posn->status & REF_STATUS_UPTODATE)
523 continue;
524
525 strbuf_addf(&buf, "import %s\n",
526 posn->symref ? posn->symref : posn->name);
527 sendline(data, &buf);
528 strbuf_reset(&buf);
529 }
530
531 write_constant(data->helper->in, "\n");
532 /*
533 * remote-helpers that advertise the bidi-import capability are required to
534 * buffer the complete batch of import commands until this newline before
535 * sending data to fast-import.
536 * These helpers read back data from fast-import on their stdin, which could
537 * be mixed with import commands, otherwise.
538 */
539
540 if (finish_command(&fastimport))
541 die(_("error while running fast-import"));
542
543 /*
544 * The fast-import stream of a remote helper that advertises
545 * the "refspec" capability writes to the refs named after the
546 * right hand side of the first refspec matching each ref we
547 * were fetching.
548 *
549 * (If no "refspec" capability was specified, for historical
550 * reasons we default to the equivalent of *:*.)
551 *
552 * Store the result in to_fetch[i].old_sha1. Callers such
553 * as "git fetch" can use the value to write feedback to the
554 * terminal, populate FETCH_HEAD, and determine what new value
555 * should be written to peer_ref if the update is a
556 * fast-forward or this is a forced update.
557 */
558 for (i = 0; i < nr_heads; i++) {
559 char *private, *name;
560 posn = to_fetch[i];
561 if (posn->status & REF_STATUS_UPTODATE)
562 continue;
563 name = posn->symref ? posn->symref : posn->name;
564 if (data->rs.nr)
565 private = apply_refspecs(&data->rs, name);
566 else
567 private = xstrdup(name);
568 if (private) {
569 if (refs_read_ref(get_main_ref_store(the_repository), private, &posn->old_oid) < 0)
570 die(_("could not read ref %s"), private);
571 free(private);
572 }
573 }
574 strbuf_release(&buf);
575 return 0;
576 }
577
578 static int run_connect(struct transport *transport, struct strbuf *cmdbuf)
579 {
580 struct helper_data *data = transport->data;
581 int ret = 0;
582 int duped;
583 FILE *input;
584 struct child_process *helper;
585
586 helper = get_helper(transport);
587
588 /*
589 * Yes, dup the pipe another time, as we need unbuffered version
590 * of input pipe as FILE*. fclose() closes the underlying fd and
591 * stream buffering only can be changed before first I/O operation
592 * on it.
593 */
594 duped = dup(helper->out);
595 if (duped < 0)
596 die_errno(_("can't dup helper output fd"));
597 input = xfdopen(duped, "r");
598 setvbuf(input, NULL, _IONBF, 0);
599
600 sendline(data, cmdbuf);
601 if (recvline_fh(input, cmdbuf))
602 exit(128);
603
604 if (!strcmp(cmdbuf->buf, "")) {
605 data->no_disconnect_req = 1;
606 if (debug)
607 fprintf(stderr, "Debug: Smart transport connection "
608 "ready.\n");
609 ret = 1;
610 } else if (!strcmp(cmdbuf->buf, "fallback")) {
611 if (debug)
612 fprintf(stderr, "Debug: Falling back to dumb "
613 "transport.\n");
614 } else {
615 die(_("unknown response to connect: %s"),
616 cmdbuf->buf);
617 }
618
619 fclose(input);
620 return ret;
621 }
622
623 static const char *connect_service_cmd(enum git_connect_service service)
624 {
625 switch (service) {
626 case GIT_CONNECT_UPLOAD_PACK:
627 return "git-upload-pack";
628 case GIT_CONNECT_RECEIVE_PACK:
629 return "git-receive-pack";
630 case GIT_CONNECT_UPLOAD_ARCHIVE:
631 return "git-upload-archive";
632 }
633 BUG("unknown git_connect_service: %d", service);
634 }
635
636 static int process_connect_service(struct transport *transport,
637 enum git_connect_service service,
638 const char *exec)
639 {
640 struct helper_data *data = transport->data;
641 struct strbuf cmdbuf = STRBUF_INIT;
642 int ret = 0;
643
644 /*
645 * Handle --upload-pack and friends. This is fire and forget...
646 * just warn if it fails.
647 */
648 if (strcmp(connect_service_cmd(service), exec)) {
649 int r = set_helper_option(transport, "servpath", exec);
650 if (r > 0)
651 warning(_("setting remote service path not supported by protocol"));
652 else if (r < 0)
653 warning(_("invalid remote service path"));
654 }
655
656 if (data->connect) {
657 strbuf_addf(&cmdbuf, "connect %s\n",
658 connect_service_cmd(service));
659 ret = run_connect(transport, &cmdbuf);
660 } else if (data->stateless_connect &&
661 (get_protocol_version_config() == protocol_v2) &&
662 (service == GIT_CONNECT_UPLOAD_PACK ||
663 service == GIT_CONNECT_UPLOAD_ARCHIVE)) {
664 strbuf_addf(&cmdbuf, "stateless-connect %s\n",
665 connect_service_cmd(service));
666 ret = run_connect(transport, &cmdbuf);
667 if (ret)
668 transport->stateless_rpc = 1;
669 }
670
671 strbuf_release(&cmdbuf);
672 return ret;
673 }
674
675 static int process_connect(struct transport *transport,
676 int for_push)
677 {
678 struct helper_data *data = transport->data;
679 enum git_connect_service service;
680 const char *exec;
681 int ret;
682
683 service = for_push ? GIT_CONNECT_RECEIVE_PACK : GIT_CONNECT_UPLOAD_PACK;
684 if (for_push)
685 exec = data->transport_options.receivepack;
686 else
687 exec = data->transport_options.uploadpack;
688
689 ret = process_connect_service(transport, service, exec);
690 if (ret)
691 do_take_over(transport);
692 return ret;
693 }
694
695 static int connect_helper(struct transport *transport, enum git_connect_service service,
696 const char *exec, int fd[2])
697 {
698 struct helper_data *data = transport->data;
699
700 /* Get_helper so connect is inited. */
701 get_helper(transport);
702
703 if (!process_connect_service(transport, service, exec))
704 die(_("can't connect to subservice %s"),
705 connect_service_cmd(service));
706
707 fd[0] = data->helper->out;
708 fd[1] = data->helper->in;
709
710 do_take_over(transport);
711 return 0;
712 }
713
714 static struct ref *get_refs_list_using_list(struct transport *transport,
715 int for_push);
716
717 static int fetch_refs(struct transport *transport,
718 int nr_heads, struct ref **to_fetch)
719 {
720 struct helper_data *data = transport->data;
721 int i, count;
722
723 get_helper(transport);
724
725 if (process_connect(transport, 0))
726 return transport->vtable->fetch_refs(transport, nr_heads, to_fetch);
727
728 /*
729 * If we reach here, then the server, the client, and/or the transport
730 * helper does not support protocol v2. --negotiate-only requires
731 * protocol v2.
732 */
733 if (data->transport_options.acked_commits) {
734 warning(_("--negotiate-only requires protocol v2"));
735 return -1;
736 }
737
738 if (!data->get_refs_list_called) {
739 /*
740 * We do not care about the list of refs returned, but only
741 * that the "list" command was sent.
742 */
743 struct ref *dummy = get_refs_list_using_list(transport, 0);
744 free_refs(dummy);
745 }
746
747 count = 0;
748 for (i = 0; i < nr_heads; i++)
749 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
750 count++;
751
752 if (!count)
753 return 0;
754
755 if (data->check_connectivity &&
756 data->transport_options.check_self_contained_and_connected)
757 set_helper_option(transport, "check-connectivity", "true");
758
759 if (transport->cloning)
760 set_helper_option(transport, "cloning", "true");
761
762 if (data->transport_options.update_shallow)
763 set_helper_option(transport, "update-shallow", "true");
764
765 if (data->transport_options.refetch)
766 set_helper_option(transport, "refetch", "true");
767
768 if (data->transport_options.filter_options.choice) {
769 const char *spec = expand_list_objects_filter_spec(
770 &data->transport_options.filter_options);
771 set_helper_option(transport, "filter", spec);
772 }
773
774 if (data->transport_options.negotiation_restrict_tips)
775 warning(_("ignoring %s because the protocol does not support it."),
776 "--negotiation-restrict");
777
778 if (data->fetch)
779 return fetch_with_fetch(transport, nr_heads, to_fetch);
780
781 if (data->import)
782 return fetch_with_import(transport, nr_heads, to_fetch);
783
784 return -1;
785 }
786
787 static int fetch_object_info_helper(struct transport *transport)
788 {
789 get_helper(transport);
790 if (process_connect(transport, 0))
791 return transport->vtable->fetch_object_info(transport);
792
793 die(_("object-info requires protocol v2"));
794 }
795
796 struct push_update_ref_state {
797 struct ref *hint;
798 struct ref_push_report *report;
799 int new_report;
800 };
801
802 static int push_update_ref_status(struct strbuf *buf,
803 struct push_update_ref_state *state,
804 struct ref *remote_refs)
805 {
806 char *refname, *msg;
807 int status, forced = 0;
808
809 if (starts_with(buf->buf, "option ")) {
810 struct object_id old_oid, new_oid;
811 char *key;
812 const char *val;
813 char *p;
814
815 if (!state->hint || !(state->report || state->new_report))
816 die(_("'option' without a matching 'ok/error' directive"));
817 if (state->new_report) {
818 if (!state->hint->report) {
819 CALLOC_ARRAY(state->hint->report, 1);
820 state->report = state->hint->report;
821 } else {
822 state->report = state->hint->report;
823 while (state->report->next)
824 state->report = state->report->next;
825 CALLOC_ARRAY(state->report->next, 1);
826 state->report = state->report->next;
827 }
828 state->new_report = 0;
829 }
830 key = buf->buf + 7;
831 p = strchr(key, ' ');
832 if (p)
833 *p++ = '\0';
834 val = p;
835 if (!strcmp(key, "refname"))
836 state->report->ref_name = xstrdup_or_null(val);
837 else if (!strcmp(key, "old-oid") && val &&
838 !parse_oid_hex(val, &old_oid, &val))
839 state->report->old_oid = oiddup(&old_oid);
840 else if (!strcmp(key, "new-oid") && val &&
841 !parse_oid_hex(val, &new_oid, &val))
842 state->report->new_oid = oiddup(&new_oid);
843 else if (!strcmp(key, "forced-update"))
844 state->report->forced_update = 1;
845 /* Not update remote namespace again. */
846 return 1;
847 }
848
849 state->report = NULL;
850 state->new_report = 0;
851
852 if (starts_with(buf->buf, "ok ")) {
853 status = REF_STATUS_OK;
854 refname = buf->buf + 3;
855 } else if (starts_with(buf->buf, "error ")) {
856 status = REF_STATUS_REMOTE_REJECT;
857 refname = buf->buf + 6;
858 } else
859 die(_("expected ok/error, helper said '%s'"), buf->buf);
860
861 msg = strchr(refname, ' ');
862 if (msg) {
863 struct strbuf msg_buf = STRBUF_INIT;
864 const char *end;
865
866 *msg++ = '\0';
867 if (!unquote_c_style(&msg_buf, msg, &end))
868 msg = strbuf_detach(&msg_buf, NULL);
869 else
870 msg = xstrdup(msg);
871 strbuf_release(&msg_buf);
872
873 if (!strcmp(msg, "no match")) {
874 status = REF_STATUS_NONE;
875 FREE_AND_NULL(msg);
876 }
877 else if (!strcmp(msg, "up to date")) {
878 status = REF_STATUS_UPTODATE;
879 FREE_AND_NULL(msg);
880 }
881 else if (!strcmp(msg, "non-fast forward")) {
882 status = REF_STATUS_REJECT_NONFASTFORWARD;
883 FREE_AND_NULL(msg);
884 }
885 else if (!strcmp(msg, "already exists")) {
886 status = REF_STATUS_REJECT_ALREADY_EXISTS;
887 FREE_AND_NULL(msg);
888 }
889 else if (!strcmp(msg, "fetch first")) {
890 status = REF_STATUS_REJECT_FETCH_FIRST;
891 FREE_AND_NULL(msg);
892 }
893 else if (!strcmp(msg, "needs force")) {
894 status = REF_STATUS_REJECT_NEEDS_FORCE;
895 FREE_AND_NULL(msg);
896 }
897 else if (!strcmp(msg, "stale info")) {
898 status = REF_STATUS_REJECT_STALE;
899 FREE_AND_NULL(msg);
900 }
901 else if (!strcmp(msg, "remote ref updated since checkout")) {
902 status = REF_STATUS_REJECT_REMOTE_UPDATED;
903 FREE_AND_NULL(msg);
904 }
905 else if (!strcmp(msg, "forced update")) {
906 forced = 1;
907 FREE_AND_NULL(msg);
908 }
909 else if (!strcmp(msg, "expecting report")) {
910 status = REF_STATUS_EXPECTING_REPORT;
911 FREE_AND_NULL(msg);
912 }
913 }
914
915 if (state->hint)
916 state->hint = find_ref_by_name(state->hint, refname);
917 if (!state->hint)
918 state->hint = find_ref_by_name(remote_refs, refname);
919 if (!state->hint) {
920 warning(_("helper reported unexpected status of %s"), refname);
921 return 1;
922 }
923
924 if (state->hint->status != REF_STATUS_NONE) {
925 /*
926 * Earlier, the ref was marked not to be pushed, so ignore the ref
927 * status reported by the remote helper if the latter is 'no match'.
928 */
929 if (status == REF_STATUS_NONE)
930 return 1;
931 }
932
933 if (status == REF_STATUS_OK)
934 state->new_report = 1;
935 state->hint->status = status;
936 state->hint->forced_update |= forced;
937 state->hint->remote_status = msg;
938 return !(status == REF_STATUS_OK);
939 }
940
941 static int push_update_refs_status(struct helper_data *data,
942 struct ref *remote_refs,
943 int flags)
944 {
945 struct ref *ref;
946 struct ref_push_report *report;
947 struct strbuf buf = STRBUF_INIT;
948 struct push_update_ref_state state = { remote_refs, NULL, 0 };
949
950 for (;;) {
951 if (recvline(data, &buf)) {
952 strbuf_release(&buf);
953 return 1;
954 }
955 if (!buf.len)
956 break;
957 push_update_ref_status(&buf, &state, remote_refs);
958 }
959 strbuf_release(&buf);
960
961 if (flags & TRANSPORT_PUSH_DRY_RUN || !data->rs.nr || data->no_private_update)
962 return 0;
963
964 /* propagate back the update to the remote namespace */
965 for (ref = remote_refs; ref; ref = ref->next) {
966 char *private;
967
968 if (ref->status != REF_STATUS_OK)
969 continue;
970
971 if (!ref->report) {
972 private = apply_refspecs(&data->rs, ref->name);
973 if (!private)
974 continue;
975 refs_update_ref(get_main_ref_store(the_repository),
976 "update by helper", private,
977 &(ref->new_oid),
978 NULL, 0, 0);
979 free(private);
980 } else {
981 for (report = ref->report; report; report = report->next) {
982 private = apply_refspecs(&data->rs,
983 report->ref_name
984 ? report->ref_name
985 : ref->name);
986 if (!private)
987 continue;
988 refs_update_ref(get_main_ref_store(the_repository),
989 "update by helper", private,
990 report->new_oid
991 ? report->new_oid
992 : &(ref->new_oid),
993 NULL, 0, 0);
994 free(private);
995 }
996 }
997 }
998 return 0;
999 }
1000
1001 static void set_common_push_options(struct transport *transport,
1002 const char *name, int flags)
1003 {
1004 if (flags & TRANSPORT_PUSH_DRY_RUN) {
1005 if (set_helper_option(transport, "dry-run", "true") != 0)
1006 die(_("helper %s does not support dry-run"), name);
1007 } else if (flags & TRANSPORT_PUSH_CERT_ALWAYS) {
1008 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "true") != 0)
1009 die(_("helper %s does not support --signed"), name);
1010 } else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED) {
1011 if (set_helper_option(transport, TRANS_OPT_PUSH_CERT, "if-asked") != 0)
1012 die(_("helper %s does not support --signed=if-asked"), name);
1013 }
1014
1015 if (flags & TRANSPORT_PUSH_ATOMIC)
1016 if (set_helper_option(transport, TRANS_OPT_ATOMIC, "true") != 0)
1017 die(_("helper %s does not support --atomic"), name);
1018
1019 if (flags & TRANSPORT_PUSH_FORCE_IF_INCLUDES)
1020 if (set_helper_option(transport, TRANS_OPT_FORCE_IF_INCLUDES, "true") != 0)
1021 die(_("helper %s does not support --%s"),
1022 name, TRANS_OPT_FORCE_IF_INCLUDES);
1023
1024 if (flags & TRANSPORT_PUSH_OPTIONS) {
1025 struct string_list_item *item;
1026 for_each_string_list_item(item, transport->push_options)
1027 if (set_helper_option(transport, "push-option", item->string) != 0)
1028 die(_("helper %s does not support 'push-option'"), name);
1029 }
1030 }
1031
1032 static int push_refs_with_push(struct transport *transport,
1033 struct ref *remote_refs, int flags)
1034 {
1035 int force_all = flags & TRANSPORT_PUSH_FORCE;
1036 int mirror = flags & TRANSPORT_PUSH_MIRROR;
1037 int atomic = flags & TRANSPORT_PUSH_ATOMIC;
1038 struct helper_data *data = transport->data;
1039 struct strbuf buf = STRBUF_INIT;
1040 struct ref *ref;
1041 struct string_list cas_options = STRING_LIST_INIT_DUP;
1042 struct string_list_item *cas_option;
1043
1044 get_helper(transport);
1045 if (!data->push)
1046 return 1;
1047
1048 for (ref = remote_refs; ref; ref = ref->next) {
1049 if (!ref->peer_ref && !mirror)
1050 continue;
1051
1052 /* Check for statuses set by set_ref_status_for_push() */
1053 switch (ref->status) {
1054 case REF_STATUS_REJECT_NONFASTFORWARD:
1055 case REF_STATUS_REJECT_STALE:
1056 case REF_STATUS_REJECT_ALREADY_EXISTS:
1057 case REF_STATUS_REJECT_REMOTE_UPDATED:
1058 if (atomic) {
1059 reject_atomic_push(remote_refs, mirror);
1060 string_list_clear(&cas_options, 0);
1061 strbuf_release(&buf);
1062 return 0;
1063 } else
1064 continue;
1065 case REF_STATUS_UPTODATE:
1066 continue;
1067 default:
1068 ; /* do nothing */
1069 }
1070
1071 if (force_all)
1072 ref->force = 1;
1073
1074 strbuf_addstr(&buf, "push ");
1075 if (!ref->deletion) {
1076 if (ref->force)
1077 strbuf_addch(&buf, '+');
1078 if (ref->peer_ref)
1079 strbuf_addstr(&buf, ref->peer_ref->name);
1080 else
1081 strbuf_add_oid_hex(&buf, &ref->new_oid);
1082 }
1083 strbuf_addch(&buf, ':');
1084 strbuf_addstr(&buf, ref->name);
1085 strbuf_addch(&buf, '\n');
1086
1087 /*
1088 * The "--force-with-lease" options without explicit
1089 * values to expect have already been expanded into
1090 * the ref->old_oid_expect[] field; we can ignore
1091 * transport->smart_options->cas altogether and instead
1092 * can enumerate them from the refs.
1093 */
1094 if (ref->expect_old_sha1) {
1095 struct strbuf cas = STRBUF_INIT;
1096 strbuf_addf(&cas, "%s:%s",
1097 ref->name, oid_to_hex(&ref->old_oid_expect));
1098 string_list_append_nodup(&cas_options,
1099 strbuf_detach(&cas, NULL));
1100 }
1101 }
1102 if (buf.len == 0) {
1103 string_list_clear(&cas_options, 0);
1104 return 0;
1105 }
1106
1107 for_each_string_list_item(cas_option, &cas_options)
1108 set_helper_option(transport, "cas", cas_option->string);
1109 set_common_push_options(transport, data->name, flags);
1110
1111 strbuf_addch(&buf, '\n');
1112 sendline(data, &buf);
1113 strbuf_release(&buf);
1114 string_list_clear(&cas_options, 0);
1115
1116 return push_update_refs_status(data, remote_refs, flags);
1117 }
1118
1119 static int push_refs_with_export(struct transport *transport,
1120 struct ref *remote_refs, int flags)
1121 {
1122 struct ref *ref;
1123 struct child_process *helper, exporter;
1124 struct helper_data *data = transport->data;
1125 struct string_list revlist_args = STRING_LIST_INIT_DUP;
1126 struct strbuf buf = STRBUF_INIT;
1127
1128 if (!data->rs.nr)
1129 die(_("remote-helper doesn't support push; refspec needed"));
1130
1131 set_common_push_options(transport, data->name, flags);
1132 if (flags & TRANSPORT_PUSH_FORCE) {
1133 if (set_helper_option(transport, "force", "true") != 0)
1134 warning(_("helper %s does not support '--force'"), data->name);
1135 }
1136
1137 helper = get_helper(transport);
1138
1139 write_constant(helper->in, "export\n");
1140
1141 for (ref = remote_refs; ref; ref = ref->next) {
1142 char *private;
1143 struct object_id oid;
1144
1145 private = apply_refspecs(&data->rs, ref->name);
1146 if (private && !repo_get_oid(the_repository, private, &oid)) {
1147 strbuf_addf(&buf, "^%s", private);
1148 string_list_append_nodup(&revlist_args,
1149 strbuf_detach(&buf, NULL));
1150 oidcpy(&ref->old_oid, &oid);
1151 }
1152 free(private);
1153
1154 if (ref->peer_ref) {
1155 if (strcmp(ref->name, ref->peer_ref->name)) {
1156 if (!ref->deletion) {
1157 const char *name;
1158 int flag;
1159
1160 /* Follow symbolic refs (mainly for HEAD). */
1161 name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1162 ref->peer_ref->name,
1163 RESOLVE_REF_READING,
1164 &oid,
1165 &flag);
1166 if (!name || !(flag & REF_ISSYMREF))
1167 name = ref->peer_ref->name;
1168
1169 strbuf_addf(&buf, "%s:%s", name, ref->name);
1170 } else
1171 strbuf_addf(&buf, ":%s", ref->name);
1172
1173 string_list_append(&revlist_args, "--refspec");
1174 string_list_append(&revlist_args, buf.buf);
1175 strbuf_release(&buf);
1176 }
1177 if (!ref->deletion)
1178 string_list_append(&revlist_args, ref->peer_ref->name);
1179 }
1180 }
1181
1182 if (get_exporter(transport, &exporter, &revlist_args))
1183 die(_("couldn't run fast-export"));
1184
1185 string_list_clear(&revlist_args, 1);
1186
1187 if (finish_command(&exporter))
1188 die(_("error while running fast-export"));
1189 if (push_update_refs_status(data, remote_refs, flags))
1190 return 1;
1191
1192 if (data->export_marks) {
1193 strbuf_addf(&buf, "%s.tmp", data->export_marks);
1194 rename(buf.buf, data->export_marks);
1195 strbuf_release(&buf);
1196 }
1197
1198 return 0;
1199 }
1200
1201 static int push_refs(struct transport *transport,
1202 struct ref *remote_refs, int flags)
1203 {
1204 struct helper_data *data = transport->data;
1205
1206 if (process_connect(transport, 1))
1207 return transport->vtable->push_refs(transport, remote_refs, flags);
1208
1209 if (!remote_refs) {
1210 fprintf(stderr,
1211 _("No refs in common and none specified; doing nothing.\n"
1212 "Perhaps you should specify a branch.\n"));
1213 return 0;
1214 }
1215
1216 if (data->push)
1217 return push_refs_with_push(transport, remote_refs, flags);
1218
1219 if (data->export)
1220 return push_refs_with_export(transport, remote_refs, flags);
1221
1222 return -1;
1223 }
1224
1225
1226 static int has_attribute(const char *attrs, const char *attr)
1227 {
1228 int len;
1229 if (!attrs)
1230 return 0;
1231
1232 len = strlen(attr);
1233 for (;;) {
1234 const char *space = strchrnul(attrs, ' ');
1235 if (len == space - attrs && !strncmp(attrs, attr, len))
1236 return 1;
1237 if (!*space)
1238 return 0;
1239 attrs = space + 1;
1240 }
1241 }
1242
1243 static struct ref *get_refs_list(struct transport *transport, int for_push,
1244 struct transport_ls_refs_options *transport_options)
1245 {
1246 get_helper(transport);
1247
1248 if (process_connect(transport, for_push))
1249 return transport->vtable->get_refs_list(transport, for_push,
1250 transport_options);
1251
1252 return get_refs_list_using_list(transport, for_push);
1253 }
1254
1255 static struct ref *get_refs_list_using_list(struct transport *transport,
1256 int for_push)
1257 {
1258 struct helper_data *data = transport->data;
1259 struct child_process *helper;
1260 struct ref *ret = NULL;
1261 struct ref **tail = &ret;
1262 struct ref *posn;
1263 struct strbuf buf = STRBUF_INIT;
1264
1265 data->get_refs_list_called = 1;
1266 helper = get_helper(transport);
1267
1268 if (data->object_format)
1269 set_helper_option(transport, "object-format", "true");
1270
1271 if (data->push && for_push)
1272 write_constant(helper->in, "list for-push\n");
1273 else
1274 write_constant(helper->in, "list\n");
1275
1276 while (1) {
1277 char *eov, *eon;
1278 if (recvline(data, &buf))
1279 exit(128);
1280
1281 if (!*buf.buf)
1282 break;
1283 else if (buf.buf[0] == ':') {
1284 const char *value;
1285 if (skip_prefix(buf.buf, ":object-format ", &value)) {
1286 int algo = hash_algo_by_name(value);
1287 if (algo == GIT_HASH_UNKNOWN)
1288 die(_("unsupported object format '%s'"),
1289 value);
1290 transport->hash_algo = &hash_algos[algo];
1291 }
1292 continue;
1293 }
1294
1295 eov = strchr(buf.buf, ' ');
1296 if (!eov)
1297 die(_("malformed response in ref list: %s"), buf.buf);
1298 eon = strchr(eov + 1, ' ');
1299 *eov = '\0';
1300 if (eon)
1301 *eon = '\0';
1302 *tail = alloc_ref(eov + 1);
1303 if (buf.buf[0] == '@')
1304 (*tail)->symref = xstrdup(buf.buf + 1);
1305 else if (buf.buf[0] != '?')
1306 get_oid_hex_algop(buf.buf, &(*tail)->old_oid, transport->hash_algo);
1307 if (eon) {
1308 if (has_attribute(eon + 1, "unchanged")) {
1309 (*tail)->status |= REF_STATUS_UPTODATE;
1310 if (refs_read_ref(get_main_ref_store(the_repository), (*tail)->name, &(*tail)->old_oid) < 0)
1311 die(_("could not read ref %s"),
1312 (*tail)->name);
1313 }
1314 }
1315 tail = &((*tail)->next);
1316 }
1317 if (debug)
1318 fprintf(stderr, "Debug: Read ref listing.\n");
1319 strbuf_release(&buf);
1320
1321 for (posn = ret; posn; posn = posn->next)
1322 resolve_remote_symref(posn, ret);
1323
1324 return ret;
1325 }
1326
1327 static int get_bundle_uri(struct transport *transport)
1328 {
1329 get_helper(transport);
1330
1331 if (process_connect(transport, 0))
1332 return transport->vtable->get_bundle_uri(transport);
1333
1334 return -1;
1335 }
1336
1337 static struct transport_vtable vtable = {
1338 .set_option = set_helper_option,
1339 .get_refs_list = get_refs_list,
1340 .get_bundle_uri = get_bundle_uri,
1341 .fetch_refs = fetch_refs,
1342 .fetch_object_info = fetch_object_info_helper,
1343 .push_refs = push_refs,
1344 .connect = connect_helper,
1345 .disconnect = release_helper
1346 };
1347
1348 int transport_helper_init(struct transport *transport, const char *name)
1349 {
1350 struct helper_data *data = xcalloc(1, sizeof(*data));
1351 data->name = xstrdup(name);
1352
1353 transport_check_allowed(name);
1354
1355 if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
1356 debug = 1;
1357
1358 list_objects_filter_init(&data->transport_options.filter_options);
1359
1360 transport->data = data;
1361 transport->vtable = &vtable;
1362 transport->smart_options = &(data->transport_options);
1363 return 0;
1364 }
1365
1366 /*
1367 * Linux pipes can buffer 65536 bytes at once (and most platforms can
1368 * buffer less), so attempt reads and writes with up to that size.
1369 */
1370 #define BUFFERSIZE 65536
1371 /* This should be enough to hold debugging message. */
1372 #define PBUFFERSIZE 8192
1373
1374 static int transfer_debug_enabled = -1;
1375
1376 /* Print bidirectional transfer loop debug message. */
1377 __attribute__((format (printf, 1, 2)))
1378 static void transfer_debug(const char *fmt, ...)
1379 {
1380 va_list args;
1381 char msgbuf[PBUFFERSIZE];
1382
1383 if (transfer_debug_enabled < 0)
1384 BUG("somebody forgot to check GIT_TRANSLOOP_DEBUG!");
1385 if (!transfer_debug_enabled)
1386 return;
1387
1388 va_start(args, fmt);
1389 vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
1390 va_end(args);
1391 fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
1392 }
1393
1394 /* Stream state: More data may be coming in this direction. */
1395 #define SSTATE_TRANSFERRING 0
1396 /*
1397 * Stream state: No more data coming in this direction, flushing rest of
1398 * data.
1399 */
1400 #define SSTATE_FLUSHING 1
1401 /* Stream state: Transfer in this direction finished. */
1402 #define SSTATE_FINISHED 2
1403
1404 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERRING)
1405 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
1406 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
1407
1408 /* Unidirectional transfer. */
1409 struct unidirectional_transfer {
1410 /* Source */
1411 int src;
1412 /* Destination */
1413 int dest;
1414 /* Is source socket? */
1415 int src_is_sock;
1416 /* Is destination socket? */
1417 int dest_is_sock;
1418 /* Transfer state (TRANSFERRING/FLUSHING/FINISHED) */
1419 int state;
1420 /* Buffer. */
1421 char buf[BUFFERSIZE];
1422 /* Buffer used. */
1423 size_t bufuse;
1424 /* Name of source. */
1425 const char *src_name;
1426 /* Name of destination. */
1427 const char *dest_name;
1428 };
1429
1430 /* Closes the target (for writing) if transfer has finished. */
1431 static void udt_close_if_finished(struct unidirectional_transfer *t)
1432 {
1433 if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
1434 t->state = SSTATE_FINISHED;
1435 if (t->dest_is_sock)
1436 shutdown(t->dest, SHUT_WR);
1437 else
1438 close(t->dest);
1439 transfer_debug("Closed %s.", t->dest_name);
1440 }
1441 }
1442
1443 /*
1444 * Tries to read data from source into buffer. If buffer is full,
1445 * no data is read. Returns 0 on success, -1 on error.
1446 */
1447 static int udt_do_read(struct unidirectional_transfer *t)
1448 {
1449 ssize_t bytes;
1450
1451 if (t->bufuse == BUFFERSIZE)
1452 return 0; /* No space for more. */
1453
1454 transfer_debug("%s is readable", t->src_name);
1455 bytes = xread(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
1456 if (bytes < 0) {
1457 error_errno(_("read(%s) failed"), t->src_name);
1458 return -1;
1459 } else if (bytes == 0) {
1460 transfer_debug("%s EOF (with %i bytes in buffer)",
1461 t->src_name, (int)t->bufuse);
1462 t->state = SSTATE_FLUSHING;
1463 } else {
1464 t->bufuse += bytes;
1465 transfer_debug("Read %i bytes from %s (buffer now at %i)",
1466 (int)bytes, t->src_name, (int)t->bufuse);
1467 }
1468 return 0;
1469 }
1470
1471 /* Tries to write data from buffer into destination. If buffer is empty,
1472 * no data is written. Returns 0 on success, -1 on error.
1473 */
1474 static int udt_do_write(struct unidirectional_transfer *t)
1475 {
1476 ssize_t bytes;
1477
1478 if (t->bufuse == 0)
1479 return 0; /* Nothing to write. */
1480
1481 transfer_debug("%s is writable", t->dest_name);
1482 bytes = xwrite(t->dest, t->buf, t->bufuse);
1483 if (bytes < 0) {
1484 error_errno(_("write(%s) failed"), t->dest_name);
1485 return -1;
1486 } else if (bytes > 0) {
1487 t->bufuse -= bytes;
1488 if (t->bufuse)
1489 memmove(t->buf, t->buf + bytes, t->bufuse);
1490 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1491 (int)bytes, t->dest_name, (int)t->bufuse);
1492 }
1493 return 0;
1494 }
1495
1496
1497 /* State of bidirectional transfer loop. */
1498 struct bidirectional_transfer_state {
1499 /* Direction from program to git. */
1500 struct unidirectional_transfer ptg;
1501 /* Direction from git to program. */
1502 struct unidirectional_transfer gtp;
1503 };
1504
1505 static void *udt_copy_task_routine(void *udt)
1506 {
1507 struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1508 while (t->state != SSTATE_FINISHED) {
1509 if (STATE_NEEDS_READING(t->state))
1510 if (udt_do_read(t))
1511 return NULL;
1512 if (STATE_NEEDS_WRITING(t->state))
1513 if (udt_do_write(t))
1514 return NULL;
1515 if (STATE_NEEDS_CLOSING(t->state))
1516 udt_close_if_finished(t);
1517 }
1518 return udt; /* Just some non-NULL value. */
1519 }
1520
1521 #ifndef NO_PTHREADS
1522
1523 /*
1524 * Join thread, with appropriate errors on failure. Name is name for the
1525 * thread (for error messages). Returns 0 on success, 1 on failure.
1526 */
1527 static int tloop_join(pthread_t thread, const char *name)
1528 {
1529 int err;
1530 void *tret;
1531 err = pthread_join(thread, &tret);
1532 if (!tret) {
1533 error(_("%s thread failed"), name);
1534 return 1;
1535 }
1536 if (err) {
1537 error(_("%s thread failed to join: %s"), name, strerror(err));
1538 return 1;
1539 }
1540 return 0;
1541 }
1542
1543 /*
1544 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1545 * -1 on failure.
1546 */
1547 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1548 {
1549 pthread_t gtp_thread;
1550 pthread_t ptg_thread;
1551 int err;
1552 int ret = 0;
1553 err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1554 &s->gtp);
1555 if (err)
1556 die(_("can't start thread for copying data: %s"), strerror(err));
1557 err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1558 &s->ptg);
1559 if (err)
1560 die(_("can't start thread for copying data: %s"), strerror(err));
1561
1562 ret |= tloop_join(gtp_thread, "Git to program copy");
1563 ret |= tloop_join(ptg_thread, "Program to git copy");
1564 return ret;
1565 }
1566 #else
1567
1568 /* Close the source and target (for writing) for transfer. */
1569 static void udt_kill_transfer(struct unidirectional_transfer *t)
1570 {
1571 t->state = SSTATE_FINISHED;
1572 /*
1573 * Socket read end left open isn't a disaster if nobody
1574 * attempts to read from it (mingw compat headers do not
1575 * have SHUT_RD)...
1576 *
1577 * We can't fully close the socket since otherwise gtp
1578 * task would first close the socket it sends data to
1579 * while closing the ptg file descriptors.
1580 */
1581 if (!t->src_is_sock)
1582 close(t->src);
1583 if (t->dest_is_sock)
1584 shutdown(t->dest, SHUT_WR);
1585 else
1586 close(t->dest);
1587 }
1588
1589 /*
1590 * Join process, with appropriate errors on failure. Name is name for the
1591 * process (for error messages). Returns 0 on success, 1 on failure.
1592 */
1593 static int tloop_join(pid_t pid, const char *name)
1594 {
1595 int tret;
1596 if (waitpid(pid, &tret, 0) < 0) {
1597 error_errno(_("%s process failed to wait"), name);
1598 return 1;
1599 }
1600 if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1601 error(_("%s process failed"), name);
1602 return 1;
1603 }
1604 return 0;
1605 }
1606
1607 /*
1608 * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1609 * -1 on failure.
1610 */
1611 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1612 {
1613 pid_t pid1, pid2;
1614 int ret = 0;
1615
1616 /* Fork thread #1: git to program. */
1617 pid1 = fork();
1618 if (pid1 < 0)
1619 die_errno(_("can't start thread for copying data"));
1620 else if (pid1 == 0) {
1621 udt_kill_transfer(&s->ptg);
1622 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1623 }
1624
1625 /* Fork thread #2: program to git. */
1626 pid2 = fork();
1627 if (pid2 < 0)
1628 die_errno(_("can't start thread for copying data"));
1629 else if (pid2 == 0) {
1630 udt_kill_transfer(&s->gtp);
1631 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1632 }
1633
1634 /*
1635 * Close both streams in parent as to not interfere with
1636 * end of file detection and wait for both tasks to finish.
1637 */
1638 udt_kill_transfer(&s->gtp);
1639 udt_kill_transfer(&s->ptg);
1640 ret |= tloop_join(pid1, "Git to program copy");
1641 ret |= tloop_join(pid2, "Program to git copy");
1642 return ret;
1643 }
1644 #endif
1645
1646 /*
1647 * Copies data from stdin to output and from input to stdout simultaneously.
1648 * Additionally filtering through given filter. If filter is NULL, uses
1649 * identity filter.
1650 */
1651 int bidirectional_transfer_loop(int input, int output)
1652 {
1653 struct bidirectional_transfer_state state;
1654
1655 if (transfer_debug_enabled < 0)
1656 transfer_debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
1657
1658 /* Fill the state fields. */
1659 state.ptg.src = input;
1660 state.ptg.dest = 1;
1661 state.ptg.src_is_sock = (input == output);
1662 state.ptg.dest_is_sock = 0;
1663 state.ptg.state = SSTATE_TRANSFERRING;
1664 state.ptg.bufuse = 0;
1665 state.ptg.src_name = "remote input";
1666 state.ptg.dest_name = "stdout";
1667
1668 state.gtp.src = 0;
1669 state.gtp.dest = output;
1670 state.gtp.src_is_sock = 0;
1671 state.gtp.dest_is_sock = (input == output);
1672 state.gtp.state = SSTATE_TRANSFERRING;
1673 state.gtp.bufuse = 0;
1674 state.gtp.src_name = "stdin";
1675 state.gtp.dest_name = "remote output";
1676
1677 return tloop_spawnwait_tasks(&state);
1678 }
1679
1680 void reject_atomic_push(struct ref *remote_refs, int mirror_mode)
1681 {
1682 struct ref *ref;
1683
1684 /* Mark other refs as failed */
1685 for (ref = remote_refs; ref; ref = ref->next) {
1686 if (!ref->peer_ref && !mirror_mode)
1687 continue;
1688
1689 switch (ref->status) {
1690 case REF_STATUS_NONE:
1691 case REF_STATUS_OK:
1692 case REF_STATUS_EXPECTING_REPORT:
1693 ref->status = REF_STATUS_ATOMIC_PUSH_FAILED;
1694 continue;
1695 default:
1696 break; /* do nothing */
1697 }
1698 }
1699 return;
1700 }