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