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