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