Code

transport-helper: use the new done feature where possible
[git.git] / transport-helper.c
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"
13 static int debug;
15 struct 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 };
35 static 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 }
44 static 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         }
55         if (debug)
56                 fprintf(stderr, "Debug: Remote helper: <- %s\n", buffer->buf);
57         return 0;
58 }
60 static int recvline(struct helper_data *helper, struct strbuf *buffer)
61 {
62         return recvline_fh(helper->out, buffer);
63 }
65 static void xchgline(struct helper_data *helper, struct strbuf *buffer)
66 {
67         sendline(helper, buffer);
68         recvline(helper, buffer);
69 }
71 static 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 }
79 static 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 }
89 static 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 }
98 static 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         };
115         if (data->helper)
116                 return data->helper;
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;
130         snprintf(git_dir_buf, sizeof(git_dir_buf), "%s=%s", GIT_DIR_ENVIRONMENT, get_git_dir());
131         helper->env = helper_env;
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);
139         data->helper = helper;
140         data->no_disconnect_req = 0;
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");
152         write_constant(helper->in, "capabilities\n");
154         while (1) {
155                 const char *capname;
156                 int mandatory = 0;
157                 recvline(data, &buf);
159                 if (!*buf.buf)
160                         break;
162                 if (*buf.buf == '*') {
163                         capname = buf.buf + 1;
164                         mandatory = 1;
165                 } else
166                         capname = buf.buf;
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;
208 static int disconnect_helper(struct transport *transport)
210         struct helper_data *data = transport->data;
211         struct strbuf buf = STRBUF_INIT;
212         int res = 0;
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;
233 static const char *unsupported_options[] = {
234         TRANS_OPT_UPLOADPACK,
235         TRANS_OPT_RECEIVEPACK,
236         TRANS_OPT_THIN,
237         TRANS_OPT_KEEP
238         };
239 static const char *boolean_options[] = {
240         TRANS_OPT_THIN,
241         TRANS_OPT_KEEP,
242         TRANS_OPT_FOLLOWTAGS
243         };
245 static int set_helper_option(struct transport *transport,
246                           const char *name, const char *value)
248         struct helper_data *data = transport->data;
249         struct strbuf buf = STRBUF_INIT;
250         int i, ret, is_bool = 0;
252         get_helper(transport);
254         if (!data->option)
255                 return 1;
257         for (i = 0; i < ARRAY_SIZE(unsupported_options); i++) {
258                 if (!strcmp(name, unsupported_options[i]))
259                         return 1;
260         }
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         }
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');
276         xchgline(data, &buf);
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;
292 static void standard_options(struct transport *t)
294         char buf[16];
295         int n;
296         int v = t->verbose;
298         set_helper_option(t, "progress", t->progress ? "true" : "false");
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);
306 static int release_helper(struct transport *transport)
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;
317 static int fetch_with_fetch(struct transport *transport,
318                             int nr_heads, struct ref **to_fetch)
320         struct helper_data *data = transport->data;
321         int i;
322         struct strbuf buf = STRBUF_INIT;
324         standard_options(transport);
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;
331                 strbuf_addf(&buf, "fetch %s %s\n",
332                             sha1_to_hex(posn->old_sha1), posn->name);
333         }
335         strbuf_addch(&buf, '\n');
336         sendline(data, &buf);
338         while (1) {
339                 recvline(data, &buf);
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;
357 static int get_importer(struct transport *transport, struct child_process *fastimport)
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";
366         fastimport->git_cmd = 1;
367         return start_command(fastimport);
370 static 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)
376         struct child_process *helper = get_helper(transport);
377         int argc = 0, i;
378         memset(fastexport, 0, sizeof(*fastexport));
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(5 + revlist_args->nr, sizeof(*fastexport->argv));
384         fastexport->argv[argc++] = "fast-export";
385         fastexport->argv[argc++] = "--use-done-feature";
386         if (export_marks)
387                 fastexport->argv[argc++] = export_marks;
388         if (import_marks)
389                 fastexport->argv[argc++] = import_marks;
391         for (i = 0; i < revlist_args->nr; i++)
392                 fastexport->argv[argc++] = revlist_args->items[i].string;
394         fastexport->git_cmd = 1;
395         return start_command(fastexport);
398 static int fetch_with_import(struct transport *transport,
399                              int nr_heads, struct ref **to_fetch)
401         struct child_process fastimport;
402         struct helper_data *data = transport->data;
403         int i;
404         struct ref *posn;
405         struct strbuf buf = STRBUF_INIT;
407         get_helper(transport);
409         if (get_importer(transport, &fastimport))
410                 die("Couldn't run fast-import");
412         for (i = 0; i < nr_heads; i++) {
413                 posn = to_fetch[i];
414                 if (posn->status & REF_STATUS_UPTODATE)
415                         continue;
417                 strbuf_addf(&buf, "import %s\n", posn->name);
418                 sendline(data, &buf);
419                 strbuf_reset(&buf);
420         }
421         if (finish_command(&fastimport))
422                 die("Error while running fast-import");
423         free(fastimport.argv);
424         fastimport.argv = NULL;
426         for (i = 0; i < nr_heads; i++) {
427                 char *private;
428                 posn = to_fetch[i];
429                 if (posn->status & REF_STATUS_UPTODATE)
430                         continue;
431                 if (data->refspecs)
432                         private = apply_refspecs(data->refspecs, data->refspec_nr, posn->name);
433                 else
434                         private = strdup(posn->name);
435                 read_ref(private, posn->old_sha1);
436                 free(private);
437         }
438         strbuf_release(&buf);
439         return 0;
442 static int process_connect_service(struct transport *transport,
443                                    const char *name, const char *exec)
445         struct helper_data *data = transport->data;
446         struct strbuf cmdbuf = STRBUF_INIT;
447         struct child_process *helper;
448         int r, duped, ret = 0;
449         FILE *input;
451         helper = get_helper(transport);
453         /*
454          * Yes, dup the pipe another time, as we need unbuffered version
455          * of input pipe as FILE*. fclose() closes the underlying fd and
456          * stream buffering only can be changed before first I/O operation
457          * on it.
458          */
459         duped = dup(helper->out);
460         if (duped < 0)
461                 die_errno("Can't dup helper output fd");
462         input = xfdopen(duped, "r");
463         setvbuf(input, NULL, _IONBF, 0);
465         /*
466          * Handle --upload-pack and friends. This is fire and forget...
467          * just warn if it fails.
468          */
469         if (strcmp(name, exec)) {
470                 r = set_helper_option(transport, "servpath", exec);
471                 if (r > 0)
472                         warning("Setting remote service path not supported by protocol.");
473                 else if (r < 0)
474                         warning("Invalid remote service path.");
475         }
477         if (data->connect)
478                 strbuf_addf(&cmdbuf, "connect %s\n", name);
479         else
480                 goto exit;
482         sendline(data, &cmdbuf);
483         recvline_fh(input, &cmdbuf);
484         if (!strcmp(cmdbuf.buf, "")) {
485                 data->no_disconnect_req = 1;
486                 if (debug)
487                         fprintf(stderr, "Debug: Smart transport connection "
488                                 "ready.\n");
489                 ret = 1;
490         } else if (!strcmp(cmdbuf.buf, "fallback")) {
491                 if (debug)
492                         fprintf(stderr, "Debug: Falling back to dumb "
493                                 "transport.\n");
494         } else
495                 die("Unknown response to connect: %s",
496                         cmdbuf.buf);
498 exit:
499         fclose(input);
500         return ret;
503 static int process_connect(struct transport *transport,
504                                      int for_push)
506         struct helper_data *data = transport->data;
507         const char *name;
508         const char *exec;
510         name = for_push ? "git-receive-pack" : "git-upload-pack";
511         if (for_push)
512                 exec = data->transport_options.receivepack;
513         else
514                 exec = data->transport_options.uploadpack;
516         return process_connect_service(transport, name, exec);
519 static int connect_helper(struct transport *transport, const char *name,
520                    const char *exec, int fd[2])
522         struct helper_data *data = transport->data;
524         /* Get_helper so connect is inited. */
525         get_helper(transport);
526         if (!data->connect)
527                 die("Operation not supported by protocol.");
529         if (!process_connect_service(transport, name, exec))
530                 die("Can't connect to subservice %s.", name);
532         fd[0] = data->helper->out;
533         fd[1] = data->helper->in;
534         return 0;
537 static int fetch(struct transport *transport,
538                  int nr_heads, struct ref **to_fetch)
540         struct helper_data *data = transport->data;
541         int i, count;
543         if (process_connect(transport, 0)) {
544                 do_take_over(transport);
545                 return transport->fetch(transport, nr_heads, to_fetch);
546         }
548         count = 0;
549         for (i = 0; i < nr_heads; i++)
550                 if (!(to_fetch[i]->status & REF_STATUS_UPTODATE))
551                         count++;
553         if (!count)
554                 return 0;
556         if (data->fetch)
557                 return fetch_with_fetch(transport, nr_heads, to_fetch);
559         if (data->import)
560                 return fetch_with_import(transport, nr_heads, to_fetch);
562         return -1;
565 static void push_update_ref_status(struct strbuf *buf,
566                                    struct ref **ref,
567                                    struct ref *remote_refs)
569         char *refname, *msg;
570         int status;
572         if (!prefixcmp(buf->buf, "ok ")) {
573                 status = REF_STATUS_OK;
574                 refname = buf->buf + 3;
575         } else if (!prefixcmp(buf->buf, "error ")) {
576                 status = REF_STATUS_REMOTE_REJECT;
577                 refname = buf->buf + 6;
578         } else
579                 die("expected ok/error, helper said '%s'\n", buf->buf);
581         msg = strchr(refname, ' ');
582         if (msg) {
583                 struct strbuf msg_buf = STRBUF_INIT;
584                 const char *end;
586                 *msg++ = '\0';
587                 if (!unquote_c_style(&msg_buf, msg, &end))
588                         msg = strbuf_detach(&msg_buf, NULL);
589                 else
590                         msg = xstrdup(msg);
591                 strbuf_release(&msg_buf);
593                 if (!strcmp(msg, "no match")) {
594                         status = REF_STATUS_NONE;
595                         free(msg);
596                         msg = NULL;
597                 }
598                 else if (!strcmp(msg, "up to date")) {
599                         status = REF_STATUS_UPTODATE;
600                         free(msg);
601                         msg = NULL;
602                 }
603                 else if (!strcmp(msg, "non-fast forward")) {
604                         status = REF_STATUS_REJECT_NONFASTFORWARD;
605                         free(msg);
606                         msg = NULL;
607                 }
608         }
610         if (*ref)
611                 *ref = find_ref_by_name(*ref, refname);
612         if (!*ref)
613                 *ref = find_ref_by_name(remote_refs, refname);
614         if (!*ref) {
615                 warning("helper reported unexpected status of %s", refname);
616                 return;
617         }
619         if ((*ref)->status != REF_STATUS_NONE) {
620                 /*
621                  * Earlier, the ref was marked not to be pushed, so ignore the ref
622                  * status reported by the remote helper if the latter is 'no match'.
623                  */
624                 if (status == REF_STATUS_NONE)
625                         return;
626         }
628         (*ref)->status = status;
629         (*ref)->remote_status = msg;
632 static void push_update_refs_status(struct helper_data *data,
633                                     struct ref *remote_refs)
635         struct strbuf buf = STRBUF_INIT;
636         struct ref *ref = remote_refs;
637         for (;;) {
638                 recvline(data, &buf);
639                 if (!buf.len)
640                         break;
642                 push_update_ref_status(&buf, &ref, remote_refs);
643         }
644         strbuf_release(&buf);
647 static int push_refs_with_push(struct transport *transport,
648                 struct ref *remote_refs, int flags)
650         int force_all = flags & TRANSPORT_PUSH_FORCE;
651         int mirror = flags & TRANSPORT_PUSH_MIRROR;
652         struct helper_data *data = transport->data;
653         struct strbuf buf = STRBUF_INIT;
654         struct ref *ref;
656         get_helper(transport);
657         if (!data->push)
658                 return 1;
660         for (ref = remote_refs; ref; ref = ref->next) {
661                 if (!ref->peer_ref && !mirror)
662                         continue;
664                 /* Check for statuses set by set_ref_status_for_push() */
665                 switch (ref->status) {
666                 case REF_STATUS_REJECT_NONFASTFORWARD:
667                 case REF_STATUS_UPTODATE:
668                         continue;
669                 default:
670                         ; /* do nothing */
671                 }
673                 if (force_all)
674                         ref->force = 1;
676                 strbuf_addstr(&buf, "push ");
677                 if (!ref->deletion) {
678                         if (ref->force)
679                                 strbuf_addch(&buf, '+');
680                         if (ref->peer_ref)
681                                 strbuf_addstr(&buf, ref->peer_ref->name);
682                         else
683                                 strbuf_addstr(&buf, sha1_to_hex(ref->new_sha1));
684                 }
685                 strbuf_addch(&buf, ':');
686                 strbuf_addstr(&buf, ref->name);
687                 strbuf_addch(&buf, '\n');
688         }
689         if (buf.len == 0)
690                 return 0;
692         standard_options(transport);
694         if (flags & TRANSPORT_PUSH_DRY_RUN) {
695                 if (set_helper_option(transport, "dry-run", "true") != 0)
696                         die("helper %s does not support dry-run", data->name);
697         }
699         strbuf_addch(&buf, '\n');
700         sendline(data, &buf);
701         strbuf_release(&buf);
703         push_update_refs_status(data, remote_refs);
704         return 0;
707 static int push_refs_with_export(struct transport *transport,
708                 struct ref *remote_refs, int flags)
710         struct ref *ref;
711         struct child_process *helper, exporter;
712         struct helper_data *data = transport->data;
713         char *export_marks = NULL, *import_marks = NULL;
714         struct string_list revlist_args = STRING_LIST_INIT_NODUP;
715         struct strbuf buf = STRBUF_INIT;
717         helper = get_helper(transport);
719         write_constant(helper->in, "export\n");
721         recvline(data, &buf);
722         if (debug)
723                 fprintf(stderr, "Debug: Got export_marks '%s'\n", buf.buf);
724         if (buf.len) {
725                 struct strbuf arg = STRBUF_INIT;
726                 strbuf_addstr(&arg, "--export-marks=");
727                 strbuf_addbuf(&arg, &buf);
728                 export_marks = strbuf_detach(&arg, NULL);
729         }
731         recvline(data, &buf);
732         if (debug)
733                 fprintf(stderr, "Debug: Got import_marks '%s'\n", buf.buf);
734         if (buf.len) {
735                 struct strbuf arg = STRBUF_INIT;
736                 strbuf_addstr(&arg, "--import-marks=");
737                 strbuf_addbuf(&arg, &buf);
738                 import_marks = strbuf_detach(&arg, NULL);
739         }
741         strbuf_reset(&buf);
743         for (ref = remote_refs; ref; ref = ref->next) {
744                 char *private;
745                 unsigned char sha1[20];
747                 if (!data->refspecs)
748                         continue;
749                 private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
750                 if (private && !get_sha1(private, sha1)) {
751                         strbuf_addf(&buf, "^%s", private);
752                         string_list_append(&revlist_args, strbuf_detach(&buf, NULL));
753                 }
754                 free(private);
756                 if (ref->peer_ref)
757                         string_list_append(&revlist_args, ref->peer_ref->name);
759         }
761         if (get_exporter(transport, &exporter,
762                          export_marks, import_marks, &revlist_args))
763                 die("Couldn't run fast-export");
765         if (finish_command(&exporter))
766                 die("Error while running fast-export");
767         return 0;
770 static int push_refs(struct transport *transport,
771                 struct ref *remote_refs, int flags)
773         struct helper_data *data = transport->data;
775         if (process_connect(transport, 1)) {
776                 do_take_over(transport);
777                 return transport->push_refs(transport, remote_refs, flags);
778         }
780         if (!remote_refs) {
781                 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
782                         "Perhaps you should specify a branch such as 'master'.\n");
783                 return 0;
784         }
786         if (data->push)
787                 return push_refs_with_push(transport, remote_refs, flags);
789         if (data->export)
790                 return push_refs_with_export(transport, remote_refs, flags);
792         return -1;
796 static int has_attribute(const char *attrs, const char *attr) {
797         int len;
798         if (!attrs)
799                 return 0;
801         len = strlen(attr);
802         for (;;) {
803                 const char *space = strchrnul(attrs, ' ');
804                 if (len == space - attrs && !strncmp(attrs, attr, len))
805                         return 1;
806                 if (!*space)
807                         return 0;
808                 attrs = space + 1;
809         }
812 static struct ref *get_refs_list(struct transport *transport, int for_push)
814         struct helper_data *data = transport->data;
815         struct child_process *helper;
816         struct ref *ret = NULL;
817         struct ref **tail = &ret;
818         struct ref *posn;
819         struct strbuf buf = STRBUF_INIT;
821         helper = get_helper(transport);
823         if (process_connect(transport, for_push)) {
824                 do_take_over(transport);
825                 return transport->get_refs_list(transport, for_push);
826         }
828         if (data->push && for_push)
829                 write_str_in_full(helper->in, "list for-push\n");
830         else
831                 write_str_in_full(helper->in, "list\n");
833         while (1) {
834                 char *eov, *eon;
835                 recvline(data, &buf);
837                 if (!*buf.buf)
838                         break;
840                 eov = strchr(buf.buf, ' ');
841                 if (!eov)
842                         die("Malformed response in ref list: %s", buf.buf);
843                 eon = strchr(eov + 1, ' ');
844                 *eov = '\0';
845                 if (eon)
846                         *eon = '\0';
847                 *tail = alloc_ref(eov + 1);
848                 if (buf.buf[0] == '@')
849                         (*tail)->symref = xstrdup(buf.buf + 1);
850                 else if (buf.buf[0] != '?')
851                         get_sha1_hex(buf.buf, (*tail)->old_sha1);
852                 if (eon) {
853                         if (has_attribute(eon + 1, "unchanged")) {
854                                 (*tail)->status |= REF_STATUS_UPTODATE;
855                                 read_ref((*tail)->name, (*tail)->old_sha1);
856                         }
857                 }
858                 tail = &((*tail)->next);
859         }
860         if (debug)
861                 fprintf(stderr, "Debug: Read ref listing.\n");
862         strbuf_release(&buf);
864         for (posn = ret; posn; posn = posn->next)
865                 resolve_remote_symref(posn, ret);
867         return ret;
870 int transport_helper_init(struct transport *transport, const char *name)
872         struct helper_data *data = xcalloc(sizeof(*data), 1);
873         data->name = name;
875         if (getenv("GIT_TRANSPORT_HELPER_DEBUG"))
876                 debug = 1;
878         transport->data = data;
879         transport->set_option = set_helper_option;
880         transport->get_refs_list = get_refs_list;
881         transport->fetch = fetch;
882         transport->push_refs = push_refs;
883         transport->disconnect = release_helper;
884         transport->connect = connect_helper;
885         transport->smart_options = &(data->transport_options);
886         return 0;
889 /*
890  * Linux pipes can buffer 65536 bytes at once (and most platforms can
891  * buffer less), so attempt reads and writes with up to that size.
892  */
893 #define BUFFERSIZE 65536
894 /* This should be enough to hold debugging message. */
895 #define PBUFFERSIZE 8192
897 /* Print bidirectional transfer loop debug message. */
898 static void transfer_debug(const char *fmt, ...)
900         va_list args;
901         char msgbuf[PBUFFERSIZE];
902         static int debug_enabled = -1;
904         if (debug_enabled < 0)
905                 debug_enabled = getenv("GIT_TRANSLOOP_DEBUG") ? 1 : 0;
906         if (!debug_enabled)
907                 return;
909         va_start(args, fmt);
910         vsnprintf(msgbuf, PBUFFERSIZE, fmt, args);
911         va_end(args);
912         fprintf(stderr, "Transfer loop debugging: %s\n", msgbuf);
915 /* Stream state: More data may be coming in this direction. */
916 #define SSTATE_TRANSFERING 0
917 /*
918  * Stream state: No more data coming in this direction, flushing rest of
919  * data.
920  */
921 #define SSTATE_FLUSHING 1
922 /* Stream state: Transfer in this direction finished. */
923 #define SSTATE_FINISHED 2
925 #define STATE_NEEDS_READING(state) ((state) <= SSTATE_TRANSFERING)
926 #define STATE_NEEDS_WRITING(state) ((state) <= SSTATE_FLUSHING)
927 #define STATE_NEEDS_CLOSING(state) ((state) == SSTATE_FLUSHING)
929 /* Unidirectional transfer. */
930 struct unidirectional_transfer {
931         /* Source */
932         int src;
933         /* Destination */
934         int dest;
935         /* Is source socket? */
936         int src_is_sock;
937         /* Is destination socket? */
938         int dest_is_sock;
939         /* Transfer state (TRANSFERING/FLUSHING/FINISHED) */
940         int state;
941         /* Buffer. */
942         char buf[BUFFERSIZE];
943         /* Buffer used. */
944         size_t bufuse;
945         /* Name of source. */
946         const char *src_name;
947         /* Name of destination. */
948         const char *dest_name;
949 };
951 /* Closes the target (for writing) if transfer has finished. */
952 static void udt_close_if_finished(struct unidirectional_transfer *t)
954         if (STATE_NEEDS_CLOSING(t->state) && !t->bufuse) {
955                 t->state = SSTATE_FINISHED;
956                 if (t->dest_is_sock)
957                         shutdown(t->dest, SHUT_WR);
958                 else
959                         close(t->dest);
960                 transfer_debug("Closed %s.", t->dest_name);
961         }
964 /*
965  * Tries to read read data from source into buffer. If buffer is full,
966  * no data is read. Returns 0 on success, -1 on error.
967  */
968 static int udt_do_read(struct unidirectional_transfer *t)
970         ssize_t bytes;
972         if (t->bufuse == BUFFERSIZE)
973                 return 0;       /* No space for more. */
975         transfer_debug("%s is readable", t->src_name);
976         bytes = read(t->src, t->buf + t->bufuse, BUFFERSIZE - t->bufuse);
977         if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
978                 errno != EINTR) {
979                 error("read(%s) failed: %s", t->src_name, strerror(errno));
980                 return -1;
981         } else if (bytes == 0) {
982                 transfer_debug("%s EOF (with %i bytes in buffer)",
983                         t->src_name, t->bufuse);
984                 t->state = SSTATE_FLUSHING;
985         } else if (bytes > 0) {
986                 t->bufuse += bytes;
987                 transfer_debug("Read %i bytes from %s (buffer now at %i)",
988                         (int)bytes, t->src_name, (int)t->bufuse);
989         }
990         return 0;
993 /* Tries to write data from buffer into destination. If buffer is empty,
994  * no data is written. Returns 0 on success, -1 on error.
995  */
996 static int udt_do_write(struct unidirectional_transfer *t)
998         ssize_t bytes;
1000         if (t->bufuse == 0)
1001                 return 0;       /* Nothing to write. */
1003         transfer_debug("%s is writable", t->dest_name);
1004         bytes = write(t->dest, t->buf, t->bufuse);
1005         if (bytes < 0 && errno != EWOULDBLOCK && errno != EAGAIN &&
1006                 errno != EINTR) {
1007                 error("write(%s) failed: %s", t->dest_name, strerror(errno));
1008                 return -1;
1009         } else if (bytes > 0) {
1010                 t->bufuse -= bytes;
1011                 if (t->bufuse)
1012                         memmove(t->buf, t->buf + bytes, t->bufuse);
1013                 transfer_debug("Wrote %i bytes to %s (buffer now at %i)",
1014                         (int)bytes, t->dest_name, (int)t->bufuse);
1015         }
1016         return 0;
1020 /* State of bidirectional transfer loop. */
1021 struct bidirectional_transfer_state {
1022         /* Direction from program to git. */
1023         struct unidirectional_transfer ptg;
1024         /* Direction from git to program. */
1025         struct unidirectional_transfer gtp;
1026 };
1028 static void *udt_copy_task_routine(void *udt)
1030         struct unidirectional_transfer *t = (struct unidirectional_transfer *)udt;
1031         while (t->state != SSTATE_FINISHED) {
1032                 if (STATE_NEEDS_READING(t->state))
1033                         if (udt_do_read(t))
1034                                 return NULL;
1035                 if (STATE_NEEDS_WRITING(t->state))
1036                         if (udt_do_write(t))
1037                                 return NULL;
1038                 if (STATE_NEEDS_CLOSING(t->state))
1039                         udt_close_if_finished(t);
1040         }
1041         return udt;     /* Just some non-NULL value. */
1044 #ifndef NO_PTHREADS
1046 /*
1047  * Join thread, with apporiate errors on failure. Name is name for the
1048  * thread (for error messages). Returns 0 on success, 1 on failure.
1049  */
1050 static int tloop_join(pthread_t thread, const char *name)
1052         int err;
1053         void *tret;
1054         err = pthread_join(thread, &tret);
1055         if (!tret) {
1056                 error("%s thread failed", name);
1057                 return 1;
1058         }
1059         if (err) {
1060                 error("%s thread failed to join: %s", name, strerror(err));
1061                 return 1;
1062         }
1063         return 0;
1066 /*
1067  * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1068  * -1 on failure.
1069  */
1070 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1072         pthread_t gtp_thread;
1073         pthread_t ptg_thread;
1074         int err;
1075         int ret = 0;
1076         err = pthread_create(&gtp_thread, NULL, udt_copy_task_routine,
1077                 &s->gtp);
1078         if (err)
1079                 die("Can't start thread for copying data: %s", strerror(err));
1080         err = pthread_create(&ptg_thread, NULL, udt_copy_task_routine,
1081                 &s->ptg);
1082         if (err)
1083                 die("Can't start thread for copying data: %s", strerror(err));
1085         ret |= tloop_join(gtp_thread, "Git to program copy");
1086         ret |= tloop_join(ptg_thread, "Program to git copy");
1087         return ret;
1089 #else
1091 /* Close the source and target (for writing) for transfer. */
1092 static void udt_kill_transfer(struct unidirectional_transfer *t)
1094         t->state = SSTATE_FINISHED;
1095         /*
1096          * Socket read end left open isn't a disaster if nobody
1097          * attempts to read from it (mingw compat headers do not
1098          * have SHUT_RD)...
1099          *
1100          * We can't fully close the socket since otherwise gtp
1101          * task would first close the socket it sends data to
1102          * while closing the ptg file descriptors.
1103          */
1104         if (!t->src_is_sock)
1105                 close(t->src);
1106         if (t->dest_is_sock)
1107                 shutdown(t->dest, SHUT_WR);
1108         else
1109                 close(t->dest);
1112 /*
1113  * Join process, with apporiate errors on failure. Name is name for the
1114  * process (for error messages). Returns 0 on success, 1 on failure.
1115  */
1116 static int tloop_join(pid_t pid, const char *name)
1118         int tret;
1119         if (waitpid(pid, &tret, 0) < 0) {
1120                 error("%s process failed to wait: %s", name, strerror(errno));
1121                 return 1;
1122         }
1123         if (!WIFEXITED(tret) || WEXITSTATUS(tret)) {
1124                 error("%s process failed", name);
1125                 return 1;
1126         }
1127         return 0;
1130 /*
1131  * Spawn the transfer tasks and then wait for them. Returns 0 on success,
1132  * -1 on failure.
1133  */
1134 static int tloop_spawnwait_tasks(struct bidirectional_transfer_state *s)
1136         pid_t pid1, pid2;
1137         int ret = 0;
1139         /* Fork thread #1: git to program. */
1140         pid1 = fork();
1141         if (pid1 < 0)
1142                 die_errno("Can't start thread for copying data");
1143         else if (pid1 == 0) {
1144                 udt_kill_transfer(&s->ptg);
1145                 exit(udt_copy_task_routine(&s->gtp) ? 0 : 1);
1146         }
1148         /* Fork thread #2: program to git. */
1149         pid2 = fork();
1150         if (pid2 < 0)
1151                 die_errno("Can't start thread for copying data");
1152         else if (pid2 == 0) {
1153                 udt_kill_transfer(&s->gtp);
1154                 exit(udt_copy_task_routine(&s->ptg) ? 0 : 1);
1155         }
1157         /*
1158          * Close both streams in parent as to not interfere with
1159          * end of file detection and wait for both tasks to finish.
1160          */
1161         udt_kill_transfer(&s->gtp);
1162         udt_kill_transfer(&s->ptg);
1163         ret |= tloop_join(pid1, "Git to program copy");
1164         ret |= tloop_join(pid2, "Program to git copy");
1165         return ret;
1167 #endif
1169 /*
1170  * Copies data from stdin to output and from input to stdout simultaneously.
1171  * Additionally filtering through given filter. If filter is NULL, uses
1172  * identity filter.
1173  */
1174 int bidirectional_transfer_loop(int input, int output)
1176         struct bidirectional_transfer_state state;
1178         /* Fill the state fields. */
1179         state.ptg.src = input;
1180         state.ptg.dest = 1;
1181         state.ptg.src_is_sock = (input == output);
1182         state.ptg.dest_is_sock = 0;
1183         state.ptg.state = SSTATE_TRANSFERING;
1184         state.ptg.bufuse = 0;
1185         state.ptg.src_name = "remote input";
1186         state.ptg.dest_name = "stdout";
1188         state.gtp.src = 0;
1189         state.gtp.dest = output;
1190         state.gtp.src_is_sock = 0;
1191         state.gtp.dest_is_sock = (input == output);
1192         state.gtp.state = SSTATE_TRANSFERING;
1193         state.gtp.bufuse = 0;
1194         state.gtp.src_name = "stdin";
1195         state.gtp.dest_name = "remote output";
1197         return tloop_spawnwait_tasks(&state);