push --force-with-lease: implement logic to populate old_sha1_expect[]
[git] / transport.c
1 #include "cache.h"
2 #include "transport.h"
3 #include "run-command.h"
4 #include "pkt-line.h"
5 #include "fetch-pack.h"
6 #include "remote.h"
7 #include "connect.h"
8 #include "send-pack.h"
9 #include "walker.h"
10 #include "bundle.h"
11 #include "dir.h"
12 #include "refs.h"
13 #include "branch.h"
14 #include "url.h"
15 #include "submodule.h"
16 #include "string-list.h"
17
18 /* rsync support */
19
20 /*
21  * We copy packed-refs and refs/ into a temporary file, then read the
22  * loose refs recursively (sorting whenever possible), and then inserting
23  * those packed refs that are not yet in the list (not validating, but
24  * assuming that the file is sorted).
25  *
26  * Appears refactoring this from refs.c is too cumbersome.
27  */
28
29 static int str_cmp(const void *a, const void *b)
30 {
31         const char *s1 = a;
32         const char *s2 = b;
33
34         return strcmp(s1, s2);
35 }
36
37 /* path->buf + name_offset is expected to point to "refs/" */
38
39 static int read_loose_refs(struct strbuf *path, int name_offset,
40                 struct ref **tail)
41 {
42         DIR *dir = opendir(path->buf);
43         struct dirent *de;
44         struct {
45                 char **entries;
46                 int nr, alloc;
47         } list;
48         int i, pathlen;
49
50         if (!dir)
51                 return -1;
52
53         memset (&list, 0, sizeof(list));
54
55         while ((de = readdir(dir))) {
56                 if (is_dot_or_dotdot(de->d_name))
57                         continue;
58                 ALLOC_GROW(list.entries, list.nr + 1, list.alloc);
59                 list.entries[list.nr++] = xstrdup(de->d_name);
60         }
61         closedir(dir);
62
63         /* sort the list */
64
65         qsort(list.entries, list.nr, sizeof(char *), str_cmp);
66
67         pathlen = path->len;
68         strbuf_addch(path, '/');
69
70         for (i = 0; i < list.nr; i++, strbuf_setlen(path, pathlen + 1)) {
71                 strbuf_addstr(path, list.entries[i]);
72                 if (read_loose_refs(path, name_offset, tail)) {
73                         int fd = open(path->buf, O_RDONLY);
74                         char buffer[40];
75                         struct ref *next;
76
77                         if (fd < 0)
78                                 continue;
79                         next = alloc_ref(path->buf + name_offset);
80                         if (read_in_full(fd, buffer, 40) != 40 ||
81                                         get_sha1_hex(buffer, next->old_sha1)) {
82                                 close(fd);
83                                 free(next);
84                                 continue;
85                         }
86                         close(fd);
87                         (*tail)->next = next;
88                         *tail = next;
89                 }
90         }
91         strbuf_setlen(path, pathlen);
92
93         for (i = 0; i < list.nr; i++)
94                 free(list.entries[i]);
95         free(list.entries);
96
97         return 0;
98 }
99
100 /* insert the packed refs for which no loose refs were found */
101
102 static void insert_packed_refs(const char *packed_refs, struct ref **list)
103 {
104         FILE *f = fopen(packed_refs, "r");
105         static char buffer[PATH_MAX];
106
107         if (!f)
108                 return;
109
110         for (;;) {
111                 int cmp = 0; /* assigned before used */
112                 int len;
113
114                 if (!fgets(buffer, sizeof(buffer), f)) {
115                         fclose(f);
116                         return;
117                 }
118
119                 if (hexval(buffer[0]) > 0xf)
120                         continue;
121                 len = strlen(buffer);
122                 if (len && buffer[len - 1] == '\n')
123                         buffer[--len] = '\0';
124                 if (len < 41)
125                         continue;
126                 while ((*list)->next &&
127                                 (cmp = strcmp(buffer + 41,
128                                       (*list)->next->name)) > 0)
129                         list = &(*list)->next;
130                 if (!(*list)->next || cmp < 0) {
131                         struct ref *next = alloc_ref(buffer + 41);
132                         buffer[40] = '\0';
133                         if (get_sha1_hex(buffer, next->old_sha1)) {
134                                 warning ("invalid SHA-1: %s", buffer);
135                                 free(next);
136                                 continue;
137                         }
138                         next->next = (*list)->next;
139                         (*list)->next = next;
140                         list = &(*list)->next;
141                 }
142         }
143 }
144
145 static void set_upstreams(struct transport *transport, struct ref *refs,
146         int pretend)
147 {
148         struct ref *ref;
149         for (ref = refs; ref; ref = ref->next) {
150                 const char *localname;
151                 const char *tmp;
152                 const char *remotename;
153                 unsigned char sha[20];
154                 int flag = 0;
155                 /*
156                  * Check suitability for tracking. Must be successful /
157                  * already up-to-date ref create/modify (not delete).
158                  */
159                 if (ref->status != REF_STATUS_OK &&
160                         ref->status != REF_STATUS_UPTODATE)
161                         continue;
162                 if (!ref->peer_ref)
163                         continue;
164                 if (is_null_sha1(ref->new_sha1))
165                         continue;
166
167                 /* Follow symbolic refs (mainly for HEAD). */
168                 localname = ref->peer_ref->name;
169                 remotename = ref->name;
170                 tmp = resolve_ref_unsafe(localname, sha, 1, &flag);
171                 if (tmp && flag & REF_ISSYMREF &&
172                         !prefixcmp(tmp, "refs/heads/"))
173                         localname = tmp;
174
175                 /* Both source and destination must be local branches. */
176                 if (!localname || prefixcmp(localname, "refs/heads/"))
177                         continue;
178                 if (!remotename || prefixcmp(remotename, "refs/heads/"))
179                         continue;
180
181                 if (!pretend)
182                         install_branch_config(BRANCH_CONFIG_VERBOSE,
183                                 localname + 11, transport->remote->name,
184                                 remotename);
185                 else
186                         printf("Would set upstream of '%s' to '%s' of '%s'\n",
187                                 localname + 11, remotename + 11,
188                                 transport->remote->name);
189         }
190 }
191
192 static const char *rsync_url(const char *url)
193 {
194         return prefixcmp(url, "rsync://") ? skip_prefix(url, "rsync:") : url;
195 }
196
197 static struct ref *get_refs_via_rsync(struct transport *transport, int for_push)
198 {
199         struct strbuf buf = STRBUF_INIT, temp_dir = STRBUF_INIT;
200         struct ref dummy = {NULL}, *tail = &dummy;
201         struct child_process rsync;
202         const char *args[5];
203         int temp_dir_len;
204
205         if (for_push)
206                 return NULL;
207
208         /* copy the refs to the temporary directory */
209
210         strbuf_addstr(&temp_dir, git_path("rsync-refs-XXXXXX"));
211         if (!mkdtemp(temp_dir.buf))
212                 die_errno ("Could not make temporary directory");
213         temp_dir_len = temp_dir.len;
214
215         strbuf_addstr(&buf, rsync_url(transport->url));
216         strbuf_addstr(&buf, "/refs");
217
218         memset(&rsync, 0, sizeof(rsync));
219         rsync.argv = args;
220         rsync.stdout_to_stderr = 1;
221         args[0] = "rsync";
222         args[1] = (transport->verbose > 1) ? "-rv" : "-r";
223         args[2] = buf.buf;
224         args[3] = temp_dir.buf;
225         args[4] = NULL;
226
227         if (run_command(&rsync))
228                 die ("Could not run rsync to get refs");
229
230         strbuf_reset(&buf);
231         strbuf_addstr(&buf, rsync_url(transport->url));
232         strbuf_addstr(&buf, "/packed-refs");
233
234         args[2] = buf.buf;
235
236         if (run_command(&rsync))
237                 die ("Could not run rsync to get refs");
238
239         /* read the copied refs */
240
241         strbuf_addstr(&temp_dir, "/refs");
242         read_loose_refs(&temp_dir, temp_dir_len + 1, &tail);
243         strbuf_setlen(&temp_dir, temp_dir_len);
244
245         tail = &dummy;
246         strbuf_addstr(&temp_dir, "/packed-refs");
247         insert_packed_refs(temp_dir.buf, &tail);
248         strbuf_setlen(&temp_dir, temp_dir_len);
249
250         if (remove_dir_recursively(&temp_dir, 0))
251                 warning ("Error removing temporary directory %s.",
252                                 temp_dir.buf);
253
254         strbuf_release(&buf);
255         strbuf_release(&temp_dir);
256
257         return dummy.next;
258 }
259
260 static int fetch_objs_via_rsync(struct transport *transport,
261                                 int nr_objs, struct ref **to_fetch)
262 {
263         struct strbuf buf = STRBUF_INIT;
264         struct child_process rsync;
265         const char *args[8];
266         int result;
267
268         strbuf_addstr(&buf, rsync_url(transport->url));
269         strbuf_addstr(&buf, "/objects/");
270
271         memset(&rsync, 0, sizeof(rsync));
272         rsync.argv = args;
273         rsync.stdout_to_stderr = 1;
274         args[0] = "rsync";
275         args[1] = (transport->verbose > 1) ? "-rv" : "-r";
276         args[2] = "--ignore-existing";
277         args[3] = "--exclude";
278         args[4] = "info";
279         args[5] = buf.buf;
280         args[6] = get_object_directory();
281         args[7] = NULL;
282
283         /* NEEDSWORK: handle one level of alternates */
284         result = run_command(&rsync);
285
286         strbuf_release(&buf);
287
288         return result;
289 }
290
291 static int write_one_ref(const char *name, const unsigned char *sha1,
292                 int flags, void *data)
293 {
294         struct strbuf *buf = data;
295         int len = buf->len;
296         FILE *f;
297
298         /* when called via for_each_ref(), flags is non-zero */
299         if (flags && prefixcmp(name, "refs/heads/") &&
300                         prefixcmp(name, "refs/tags/"))
301                 return 0;
302
303         strbuf_addstr(buf, name);
304         if (safe_create_leading_directories(buf->buf) ||
305                         !(f = fopen(buf->buf, "w")) ||
306                         fprintf(f, "%s\n", sha1_to_hex(sha1)) < 0 ||
307                         fclose(f))
308                 return error("problems writing temporary file %s", buf->buf);
309         strbuf_setlen(buf, len);
310         return 0;
311 }
312
313 static int write_refs_to_temp_dir(struct strbuf *temp_dir,
314                 int refspec_nr, const char **refspec)
315 {
316         int i;
317
318         for (i = 0; i < refspec_nr; i++) {
319                 unsigned char sha1[20];
320                 char *ref;
321
322                 if (dwim_ref(refspec[i], strlen(refspec[i]), sha1, &ref) != 1)
323                         return error("Could not get ref %s", refspec[i]);
324
325                 if (write_one_ref(ref, sha1, 0, temp_dir)) {
326                         free(ref);
327                         return -1;
328                 }
329                 free(ref);
330         }
331         return 0;
332 }
333
334 static int rsync_transport_push(struct transport *transport,
335                 int refspec_nr, const char **refspec, int flags)
336 {
337         struct strbuf buf = STRBUF_INIT, temp_dir = STRBUF_INIT;
338         int result = 0, i;
339         struct child_process rsync;
340         const char *args[10];
341
342         if (flags & TRANSPORT_PUSH_MIRROR)
343                 return error("rsync transport does not support mirror mode");
344
345         /* first push the objects */
346
347         strbuf_addstr(&buf, rsync_url(transport->url));
348         strbuf_addch(&buf, '/');
349
350         memset(&rsync, 0, sizeof(rsync));
351         rsync.argv = args;
352         rsync.stdout_to_stderr = 1;
353         i = 0;
354         args[i++] = "rsync";
355         args[i++] = "-a";
356         if (flags & TRANSPORT_PUSH_DRY_RUN)
357                 args[i++] = "--dry-run";
358         if (transport->verbose > 1)
359                 args[i++] = "-v";
360         args[i++] = "--ignore-existing";
361         args[i++] = "--exclude";
362         args[i++] = "info";
363         args[i++] = get_object_directory();
364         args[i++] = buf.buf;
365         args[i++] = NULL;
366
367         if (run_command(&rsync))
368                 return error("Could not push objects to %s",
369                                 rsync_url(transport->url));
370
371         /* copy the refs to the temporary directory; they could be packed. */
372
373         strbuf_addstr(&temp_dir, git_path("rsync-refs-XXXXXX"));
374         if (!mkdtemp(temp_dir.buf))
375                 die_errno ("Could not make temporary directory");
376         strbuf_addch(&temp_dir, '/');
377
378         if (flags & TRANSPORT_PUSH_ALL) {
379                 if (for_each_ref(write_one_ref, &temp_dir))
380                         return -1;
381         } else if (write_refs_to_temp_dir(&temp_dir, refspec_nr, refspec))
382                 return -1;
383
384         i = 2;
385         if (flags & TRANSPORT_PUSH_DRY_RUN)
386                 args[i++] = "--dry-run";
387         if (!(flags & TRANSPORT_PUSH_FORCE))
388                 args[i++] = "--ignore-existing";
389         args[i++] = temp_dir.buf;
390         args[i++] = rsync_url(transport->url);
391         args[i++] = NULL;
392         if (run_command(&rsync))
393                 result = error("Could not push to %s",
394                                 rsync_url(transport->url));
395
396         if (remove_dir_recursively(&temp_dir, 0))
397                 warning ("Could not remove temporary directory %s.",
398                                 temp_dir.buf);
399
400         strbuf_release(&buf);
401         strbuf_release(&temp_dir);
402
403         return result;
404 }
405
406 struct bundle_transport_data {
407         int fd;
408         struct bundle_header header;
409 };
410
411 static struct ref *get_refs_from_bundle(struct transport *transport, int for_push)
412 {
413         struct bundle_transport_data *data = transport->data;
414         struct ref *result = NULL;
415         int i;
416
417         if (for_push)
418                 return NULL;
419
420         if (data->fd > 0)
421                 close(data->fd);
422         data->fd = read_bundle_header(transport->url, &data->header);
423         if (data->fd < 0)
424                 die ("Could not read bundle '%s'.", transport->url);
425         for (i = 0; i < data->header.references.nr; i++) {
426                 struct ref_list_entry *e = data->header.references.list + i;
427                 struct ref *ref = alloc_ref(e->name);
428                 hashcpy(ref->old_sha1, e->sha1);
429                 ref->next = result;
430                 result = ref;
431         }
432         return result;
433 }
434
435 static int fetch_refs_from_bundle(struct transport *transport,
436                                int nr_heads, struct ref **to_fetch)
437 {
438         struct bundle_transport_data *data = transport->data;
439         return unbundle(&data->header, data->fd,
440                         transport->progress ? BUNDLE_VERBOSE : 0);
441 }
442
443 static int close_bundle(struct transport *transport)
444 {
445         struct bundle_transport_data *data = transport->data;
446         if (data->fd > 0)
447                 close(data->fd);
448         free(data);
449         return 0;
450 }
451
452 struct git_transport_data {
453         struct git_transport_options options;
454         struct child_process *conn;
455         int fd[2];
456         unsigned got_remote_heads : 1;
457         struct extra_have_objects extra_have;
458 };
459
460 static int set_git_option(struct git_transport_options *opts,
461                           const char *name, const char *value)
462 {
463         if (!strcmp(name, TRANS_OPT_UPLOADPACK)) {
464                 opts->uploadpack = value;
465                 return 0;
466         } else if (!strcmp(name, TRANS_OPT_RECEIVEPACK)) {
467                 opts->receivepack = value;
468                 return 0;
469         } else if (!strcmp(name, TRANS_OPT_THIN)) {
470                 opts->thin = !!value;
471                 return 0;
472         } else if (!strcmp(name, TRANS_OPT_FOLLOWTAGS)) {
473                 opts->followtags = !!value;
474                 return 0;
475         } else if (!strcmp(name, TRANS_OPT_KEEP)) {
476                 opts->keep = !!value;
477                 return 0;
478         } else if (!strcmp(name, TRANS_OPT_DEPTH)) {
479                 if (!value)
480                         opts->depth = 0;
481                 else {
482                         char *end;
483                         opts->depth = strtol(value, &end, 0);
484                         if (*end)
485                                 die("transport: invalid depth option '%s'", value);
486                 }
487                 return 0;
488         }
489         return 1;
490 }
491
492 static int connect_setup(struct transport *transport, int for_push, int verbose)
493 {
494         struct git_transport_data *data = transport->data;
495
496         if (data->conn)
497                 return 0;
498
499         data->conn = git_connect(data->fd, transport->url,
500                                  for_push ? data->options.receivepack :
501                                  data->options.uploadpack,
502                                  verbose ? CONNECT_VERBOSE : 0);
503
504         return 0;
505 }
506
507 static struct ref *get_refs_via_connect(struct transport *transport, int for_push)
508 {
509         struct git_transport_data *data = transport->data;
510         struct ref *refs;
511
512         connect_setup(transport, for_push, 0);
513         get_remote_heads(data->fd[0], NULL, 0, &refs,
514                          for_push ? REF_NORMAL : 0, &data->extra_have);
515         data->got_remote_heads = 1;
516
517         return refs;
518 }
519
520 static int fetch_refs_via_pack(struct transport *transport,
521                                int nr_heads, struct ref **to_fetch)
522 {
523         struct git_transport_data *data = transport->data;
524         const struct ref *refs;
525         char *dest = xstrdup(transport->url);
526         struct fetch_pack_args args;
527         struct ref *refs_tmp = NULL;
528
529         memset(&args, 0, sizeof(args));
530         args.uploadpack = data->options.uploadpack;
531         args.keep_pack = data->options.keep;
532         args.lock_pack = 1;
533         args.use_thin_pack = data->options.thin;
534         args.include_tag = data->options.followtags;
535         args.verbose = (transport->verbose > 1);
536         args.quiet = (transport->verbose < 0);
537         args.no_progress = !transport->progress;
538         args.depth = data->options.depth;
539         args.check_self_contained_and_connected =
540                 data->options.check_self_contained_and_connected;
541
542         if (!data->got_remote_heads) {
543                 connect_setup(transport, 0, 0);
544                 get_remote_heads(data->fd[0], NULL, 0, &refs_tmp, 0, NULL);
545                 data->got_remote_heads = 1;
546         }
547
548         refs = fetch_pack(&args, data->fd, data->conn,
549                           refs_tmp ? refs_tmp : transport->remote_refs,
550                           dest, to_fetch, nr_heads,
551                           &transport->pack_lockfile);
552         close(data->fd[0]);
553         close(data->fd[1]);
554         if (finish_connect(data->conn))
555                 refs = NULL;
556         data->conn = NULL;
557         data->got_remote_heads = 0;
558         data->options.self_contained_and_connected =
559                 args.self_contained_and_connected;
560
561         free_refs(refs_tmp);
562
563         free(dest);
564         return (refs ? 0 : -1);
565 }
566
567 static int push_had_errors(struct ref *ref)
568 {
569         for (; ref; ref = ref->next) {
570                 switch (ref->status) {
571                 case REF_STATUS_NONE:
572                 case REF_STATUS_UPTODATE:
573                 case REF_STATUS_OK:
574                         break;
575                 default:
576                         return 1;
577                 }
578         }
579         return 0;
580 }
581
582 int transport_refs_pushed(struct ref *ref)
583 {
584         for (; ref; ref = ref->next) {
585                 switch(ref->status) {
586                 case REF_STATUS_NONE:
587                 case REF_STATUS_UPTODATE:
588                         break;
589                 default:
590                         return 1;
591                 }
592         }
593         return 0;
594 }
595
596 void transport_update_tracking_ref(struct remote *remote, struct ref *ref, int verbose)
597 {
598         struct refspec rs;
599
600         if (ref->status != REF_STATUS_OK && ref->status != REF_STATUS_UPTODATE)
601                 return;
602
603         rs.src = ref->name;
604         rs.dst = NULL;
605
606         if (!remote_find_tracking(remote, &rs)) {
607                 if (verbose)
608                         fprintf(stderr, "updating local tracking ref '%s'\n", rs.dst);
609                 if (ref->deletion) {
610                         delete_ref(rs.dst, NULL, 0);
611                 } else
612                         update_ref("update by push", rs.dst,
613                                         ref->new_sha1, NULL, 0, 0);
614                 free(rs.dst);
615         }
616 }
617
618 static void print_ref_status(char flag, const char *summary, struct ref *to, struct ref *from, const char *msg, int porcelain)
619 {
620         if (porcelain) {
621                 if (from)
622                         fprintf(stdout, "%c\t%s:%s\t", flag, from->name, to->name);
623                 else
624                         fprintf(stdout, "%c\t:%s\t", flag, to->name);
625                 if (msg)
626                         fprintf(stdout, "%s (%s)\n", summary, msg);
627                 else
628                         fprintf(stdout, "%s\n", summary);
629         } else {
630                 fprintf(stderr, " %c %-*s ", flag, TRANSPORT_SUMMARY_WIDTH, summary);
631                 if (from)
632                         fprintf(stderr, "%s -> %s", prettify_refname(from->name), prettify_refname(to->name));
633                 else
634                         fputs(prettify_refname(to->name), stderr);
635                 if (msg) {
636                         fputs(" (", stderr);
637                         fputs(msg, stderr);
638                         fputc(')', stderr);
639                 }
640                 fputc('\n', stderr);
641         }
642 }
643
644 static const char *status_abbrev(unsigned char sha1[20])
645 {
646         return find_unique_abbrev(sha1, DEFAULT_ABBREV);
647 }
648
649 static void print_ok_ref_status(struct ref *ref, int porcelain)
650 {
651         if (ref->deletion)
652                 print_ref_status('-', "[deleted]", ref, NULL, NULL, porcelain);
653         else if (is_null_sha1(ref->old_sha1))
654                 print_ref_status('*',
655                         (!prefixcmp(ref->name, "refs/tags/") ? "[new tag]" :
656                         "[new branch]"),
657                         ref, ref->peer_ref, NULL, porcelain);
658         else {
659                 char quickref[84];
660                 char type;
661                 const char *msg;
662
663                 strcpy(quickref, status_abbrev(ref->old_sha1));
664                 if (ref->forced_update) {
665                         strcat(quickref, "...");
666                         type = '+';
667                         msg = "forced update";
668                 } else {
669                         strcat(quickref, "..");
670                         type = ' ';
671                         msg = NULL;
672                 }
673                 strcat(quickref, status_abbrev(ref->new_sha1));
674
675                 print_ref_status(type, quickref, ref, ref->peer_ref, msg, porcelain);
676         }
677 }
678
679 static int print_one_push_status(struct ref *ref, const char *dest, int count, int porcelain)
680 {
681         if (!count)
682                 fprintf(porcelain ? stdout : stderr, "To %s\n", dest);
683
684         switch(ref->status) {
685         case REF_STATUS_NONE:
686                 print_ref_status('X', "[no match]", ref, NULL, NULL, porcelain);
687                 break;
688         case REF_STATUS_REJECT_NODELETE:
689                 print_ref_status('!', "[rejected]", ref, NULL,
690                                                  "remote does not support deleting refs", porcelain);
691                 break;
692         case REF_STATUS_UPTODATE:
693                 print_ref_status('=', "[up to date]", ref,
694                                                  ref->peer_ref, NULL, porcelain);
695                 break;
696         case REF_STATUS_REJECT_NONFASTFORWARD:
697                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
698                                                  "non-fast-forward", porcelain);
699                 break;
700         case REF_STATUS_REJECT_ALREADY_EXISTS:
701                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
702                                                  "already exists", porcelain);
703                 break;
704         case REF_STATUS_REJECT_FETCH_FIRST:
705                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
706                                                  "fetch first", porcelain);
707                 break;
708         case REF_STATUS_REJECT_NEEDS_FORCE:
709                 print_ref_status('!', "[rejected]", ref, ref->peer_ref,
710                                                  "needs force", porcelain);
711                 break;
712         case REF_STATUS_REMOTE_REJECT:
713                 print_ref_status('!', "[remote rejected]", ref,
714                                                  ref->deletion ? NULL : ref->peer_ref,
715                                                  ref->remote_status, porcelain);
716                 break;
717         case REF_STATUS_EXPECTING_REPORT:
718                 print_ref_status('!', "[remote failure]", ref,
719                                                  ref->deletion ? NULL : ref->peer_ref,
720                                                  "remote failed to report status", porcelain);
721                 break;
722         case REF_STATUS_OK:
723                 print_ok_ref_status(ref, porcelain);
724                 break;
725         }
726
727         return 1;
728 }
729
730 void transport_print_push_status(const char *dest, struct ref *refs,
731                                   int verbose, int porcelain, unsigned int *reject_reasons)
732 {
733         struct ref *ref;
734         int n = 0;
735         unsigned char head_sha1[20];
736         char *head;
737
738         head = resolve_refdup("HEAD", head_sha1, 1, NULL);
739
740         if (verbose) {
741                 for (ref = refs; ref; ref = ref->next)
742                         if (ref->status == REF_STATUS_UPTODATE)
743                                 n += print_one_push_status(ref, dest, n, porcelain);
744         }
745
746         for (ref = refs; ref; ref = ref->next)
747                 if (ref->status == REF_STATUS_OK)
748                         n += print_one_push_status(ref, dest, n, porcelain);
749
750         *reject_reasons = 0;
751         for (ref = refs; ref; ref = ref->next) {
752                 if (ref->status != REF_STATUS_NONE &&
753                     ref->status != REF_STATUS_UPTODATE &&
754                     ref->status != REF_STATUS_OK)
755                         n += print_one_push_status(ref, dest, n, porcelain);
756                 if (ref->status == REF_STATUS_REJECT_NONFASTFORWARD) {
757                         if (head != NULL && !strcmp(head, ref->name))
758                                 *reject_reasons |= REJECT_NON_FF_HEAD;
759                         else
760                                 *reject_reasons |= REJECT_NON_FF_OTHER;
761                 } else if (ref->status == REF_STATUS_REJECT_ALREADY_EXISTS) {
762                         *reject_reasons |= REJECT_ALREADY_EXISTS;
763                 } else if (ref->status == REF_STATUS_REJECT_FETCH_FIRST) {
764                         *reject_reasons |= REJECT_FETCH_FIRST;
765                 } else if (ref->status == REF_STATUS_REJECT_NEEDS_FORCE) {
766                         *reject_reasons |= REJECT_NEEDS_FORCE;
767                 }
768         }
769 }
770
771 void transport_verify_remote_names(int nr_heads, const char **heads)
772 {
773         int i;
774
775         for (i = 0; i < nr_heads; i++) {
776                 const char *local = heads[i];
777                 const char *remote = strrchr(heads[i], ':');
778
779                 if (*local == '+')
780                         local++;
781
782                 /* A matching refspec is okay.  */
783                 if (remote == local && remote[1] == '\0')
784                         continue;
785
786                 remote = remote ? (remote + 1) : local;
787                 if (check_refname_format(remote,
788                                 REFNAME_ALLOW_ONELEVEL|REFNAME_REFSPEC_PATTERN))
789                         die("remote part of refspec is not a valid name in %s",
790                                 heads[i]);
791         }
792 }
793
794 static int git_transport_push(struct transport *transport, struct ref *remote_refs, int flags)
795 {
796         struct git_transport_data *data = transport->data;
797         struct send_pack_args args;
798         int ret;
799
800         if (!data->got_remote_heads) {
801                 struct ref *tmp_refs;
802                 connect_setup(transport, 1, 0);
803
804                 get_remote_heads(data->fd[0], NULL, 0, &tmp_refs, REF_NORMAL, NULL);
805                 data->got_remote_heads = 1;
806         }
807
808         memset(&args, 0, sizeof(args));
809         args.send_mirror = !!(flags & TRANSPORT_PUSH_MIRROR);
810         args.force_update = !!(flags & TRANSPORT_PUSH_FORCE);
811         args.use_thin_pack = data->options.thin;
812         args.verbose = (transport->verbose > 0);
813         args.quiet = (transport->verbose < 0);
814         args.progress = transport->progress;
815         args.dry_run = !!(flags & TRANSPORT_PUSH_DRY_RUN);
816         args.porcelain = !!(flags & TRANSPORT_PUSH_PORCELAIN);
817
818         ret = send_pack(&args, data->fd, data->conn, remote_refs,
819                         &data->extra_have);
820
821         close(data->fd[1]);
822         close(data->fd[0]);
823         ret |= finish_connect(data->conn);
824         data->conn = NULL;
825         data->got_remote_heads = 0;
826
827         return ret;
828 }
829
830 static int connect_git(struct transport *transport, const char *name,
831                        const char *executable, int fd[2])
832 {
833         struct git_transport_data *data = transport->data;
834         data->conn = git_connect(data->fd, transport->url,
835                                  executable, 0);
836         fd[0] = data->fd[0];
837         fd[1] = data->fd[1];
838         return 0;
839 }
840
841 static int disconnect_git(struct transport *transport)
842 {
843         struct git_transport_data *data = transport->data;
844         if (data->conn) {
845                 if (data->got_remote_heads)
846                         packet_flush(data->fd[1]);
847                 close(data->fd[0]);
848                 close(data->fd[1]);
849                 finish_connect(data->conn);
850         }
851
852         free(data);
853         return 0;
854 }
855
856 void transport_take_over(struct transport *transport,
857                          struct child_process *child)
858 {
859         struct git_transport_data *data;
860
861         if (!transport->smart_options)
862                 die("Bug detected: Taking over transport requires non-NULL "
863                     "smart_options field.");
864
865         data = xcalloc(1, sizeof(*data));
866         data->options = *transport->smart_options;
867         data->conn = child;
868         data->fd[0] = data->conn->out;
869         data->fd[1] = data->conn->in;
870         data->got_remote_heads = 0;
871         transport->data = data;
872
873         transport->set_option = NULL;
874         transport->get_refs_list = get_refs_via_connect;
875         transport->fetch = fetch_refs_via_pack;
876         transport->push = NULL;
877         transport->push_refs = git_transport_push;
878         transport->disconnect = disconnect_git;
879         transport->smart_options = &(data->options);
880 }
881
882 static int is_local(const char *url)
883 {
884         const char *colon = strchr(url, ':');
885         const char *slash = strchr(url, '/');
886         return !colon || (slash && slash < colon) ||
887                 has_dos_drive_prefix(url);
888 }
889
890 static int is_file(const char *url)
891 {
892         struct stat buf;
893         if (stat(url, &buf))
894                 return 0;
895         return S_ISREG(buf.st_mode);
896 }
897
898 static int external_specification_len(const char *url)
899 {
900         return strchr(url, ':') - url;
901 }
902
903 struct transport *transport_get(struct remote *remote, const char *url)
904 {
905         const char *helper;
906         struct transport *ret = xcalloc(1, sizeof(*ret));
907
908         ret->progress = isatty(2);
909
910         if (!remote)
911                 die("No remote provided to transport_get()");
912
913         ret->got_remote_refs = 0;
914         ret->remote = remote;
915         helper = remote->foreign_vcs;
916
917         if (!url && remote->url)
918                 url = remote->url[0];
919         ret->url = url;
920
921         /* maybe it is a foreign URL? */
922         if (url) {
923                 const char *p = url;
924
925                 while (is_urlschemechar(p == url, *p))
926                         p++;
927                 if (!prefixcmp(p, "::"))
928                         helper = xstrndup(url, p - url);
929         }
930
931         if (helper) {
932                 transport_helper_init(ret, helper);
933         } else if (!prefixcmp(url, "rsync:")) {
934                 ret->get_refs_list = get_refs_via_rsync;
935                 ret->fetch = fetch_objs_via_rsync;
936                 ret->push = rsync_transport_push;
937                 ret->smart_options = NULL;
938         } else if (is_local(url) && is_file(url) && is_bundle(url, 1)) {
939                 struct bundle_transport_data *data = xcalloc(1, sizeof(*data));
940                 ret->data = data;
941                 ret->get_refs_list = get_refs_from_bundle;
942                 ret->fetch = fetch_refs_from_bundle;
943                 ret->disconnect = close_bundle;
944                 ret->smart_options = NULL;
945         } else if (!is_url(url)
946                 || !prefixcmp(url, "file://")
947                 || !prefixcmp(url, "git://")
948                 || !prefixcmp(url, "ssh://")
949                 || !prefixcmp(url, "git+ssh://")
950                 || !prefixcmp(url, "ssh+git://")) {
951                 /* These are builtin smart transports. */
952                 struct git_transport_data *data = xcalloc(1, sizeof(*data));
953                 ret->data = data;
954                 ret->set_option = NULL;
955                 ret->get_refs_list = get_refs_via_connect;
956                 ret->fetch = fetch_refs_via_pack;
957                 ret->push_refs = git_transport_push;
958                 ret->connect = connect_git;
959                 ret->disconnect = disconnect_git;
960                 ret->smart_options = &(data->options);
961
962                 data->conn = NULL;
963                 data->got_remote_heads = 0;
964         } else {
965                 /* Unknown protocol in URL. Pass to external handler. */
966                 int len = external_specification_len(url);
967                 char *handler = xmalloc(len + 1);
968                 handler[len] = 0;
969                 strncpy(handler, url, len);
970                 transport_helper_init(ret, handler);
971         }
972
973         if (ret->smart_options) {
974                 ret->smart_options->thin = 1;
975                 ret->smart_options->uploadpack = "git-upload-pack";
976                 if (remote->uploadpack)
977                         ret->smart_options->uploadpack = remote->uploadpack;
978                 ret->smart_options->receivepack = "git-receive-pack";
979                 if (remote->receivepack)
980                         ret->smart_options->receivepack = remote->receivepack;
981         }
982
983         return ret;
984 }
985
986 int transport_set_option(struct transport *transport,
987                          const char *name, const char *value)
988 {
989         int git_reports = 1, protocol_reports = 1;
990
991         if (transport->smart_options)
992                 git_reports = set_git_option(transport->smart_options,
993                                              name, value);
994
995         if (transport->set_option)
996                 protocol_reports = transport->set_option(transport, name,
997                                                         value);
998
999         /* If either report is 0, report 0 (success). */
1000         if (!git_reports || !protocol_reports)
1001                 return 0;
1002         /* If either reports -1 (invalid value), report -1. */
1003         if ((git_reports == -1) || (protocol_reports == -1))
1004                 return -1;
1005         /* Otherwise if both report unknown, report unknown. */
1006         return 1;
1007 }
1008
1009 void transport_set_verbosity(struct transport *transport, int verbosity,
1010         int force_progress)
1011 {
1012         if (verbosity >= 1)
1013                 transport->verbose = verbosity <= 3 ? verbosity : 3;
1014         if (verbosity < 0)
1015                 transport->verbose = -1;
1016
1017         /**
1018          * Rules used to determine whether to report progress (processing aborts
1019          * when a rule is satisfied):
1020          *
1021          *   . Report progress, if force_progress is 1 (ie. --progress).
1022          *   . Don't report progress, if force_progress is 0 (ie. --no-progress).
1023          *   . Don't report progress, if verbosity < 0 (ie. -q/--quiet ).
1024          *   . Report progress if isatty(2) is 1.
1025          **/
1026         if (force_progress >= 0)
1027                 transport->progress = !!force_progress;
1028         else
1029                 transport->progress = verbosity >= 0 && isatty(2);
1030 }
1031
1032 static void die_with_unpushed_submodules(struct string_list *needs_pushing)
1033 {
1034         int i;
1035
1036         fprintf(stderr, "The following submodule paths contain changes that can\n"
1037                         "not be found on any remote:\n");
1038         for (i = 0; i < needs_pushing->nr; i++)
1039                 printf("  %s\n", needs_pushing->items[i].string);
1040         fprintf(stderr, "\nPlease try\n\n"
1041                         "       git push --recurse-submodules=on-demand\n\n"
1042                         "or cd to the path and use\n\n"
1043                         "       git push\n\n"
1044                         "to push them to a remote.\n\n");
1045
1046         string_list_clear(needs_pushing, 0);
1047
1048         die("Aborting.");
1049 }
1050
1051 static int run_pre_push_hook(struct transport *transport,
1052                              struct ref *remote_refs)
1053 {
1054         int ret = 0, x;
1055         struct ref *r;
1056         struct child_process proc;
1057         struct strbuf buf;
1058         const char *argv[4];
1059
1060         if (!(argv[0] = find_hook("pre-push")))
1061                 return 0;
1062
1063         argv[1] = transport->remote->name;
1064         argv[2] = transport->url;
1065         argv[3] = NULL;
1066
1067         memset(&proc, 0, sizeof(proc));
1068         proc.argv = argv;
1069         proc.in = -1;
1070
1071         if (start_command(&proc)) {
1072                 finish_command(&proc);
1073                 return -1;
1074         }
1075
1076         strbuf_init(&buf, 256);
1077
1078         for (r = remote_refs; r; r = r->next) {
1079                 if (!r->peer_ref) continue;
1080                 if (r->status == REF_STATUS_REJECT_NONFASTFORWARD) continue;
1081                 if (r->status == REF_STATUS_UPTODATE) continue;
1082
1083                 strbuf_reset(&buf);
1084                 strbuf_addf( &buf, "%s %s %s %s\n",
1085                          r->peer_ref->name, sha1_to_hex(r->new_sha1),
1086                          r->name, sha1_to_hex(r->old_sha1));
1087
1088                 if (write_in_full(proc.in, buf.buf, buf.len) != buf.len) {
1089                         ret = -1;
1090                         break;
1091                 }
1092         }
1093
1094         strbuf_release(&buf);
1095
1096         x = close(proc.in);
1097         if (!ret)
1098                 ret = x;
1099
1100         x = finish_command(&proc);
1101         if (!ret)
1102                 ret = x;
1103
1104         return ret;
1105 }
1106
1107 int transport_push(struct transport *transport,
1108                    int refspec_nr, const char **refspec, int flags,
1109                    unsigned int *reject_reasons)
1110 {
1111         *reject_reasons = 0;
1112         transport_verify_remote_names(refspec_nr, refspec);
1113
1114         if (transport->push) {
1115                 /* Maybe FIXME. But no important transport uses this case. */
1116                 if (flags & TRANSPORT_PUSH_SET_UPSTREAM)
1117                         die("This transport does not support using --set-upstream");
1118
1119                 return transport->push(transport, refspec_nr, refspec, flags);
1120         } else if (transport->push_refs) {
1121                 struct ref *remote_refs =
1122                         transport->get_refs_list(transport, 1);
1123                 struct ref *local_refs = get_local_heads();
1124                 int match_flags = MATCH_REFS_NONE;
1125                 int verbose = (transport->verbose > 0);
1126                 int quiet = (transport->verbose < 0);
1127                 int porcelain = flags & TRANSPORT_PUSH_PORCELAIN;
1128                 int pretend = flags & TRANSPORT_PUSH_DRY_RUN;
1129                 int push_ret, ret, err;
1130
1131                 if (flags & TRANSPORT_PUSH_ALL)
1132                         match_flags |= MATCH_REFS_ALL;
1133                 if (flags & TRANSPORT_PUSH_MIRROR)
1134                         match_flags |= MATCH_REFS_MIRROR;
1135                 if (flags & TRANSPORT_PUSH_PRUNE)
1136                         match_flags |= MATCH_REFS_PRUNE;
1137                 if (flags & TRANSPORT_PUSH_FOLLOW_TAGS)
1138                         match_flags |= MATCH_REFS_FOLLOW_TAGS;
1139
1140                 if (match_push_refs(local_refs, &remote_refs,
1141                                     refspec_nr, refspec, match_flags)) {
1142                         return -1;
1143                 }
1144
1145                 if (transport->smart_options &&
1146                     transport->smart_options->cas &&
1147                     !is_empty_cas(transport->smart_options->cas))
1148                         apply_push_cas(transport->smart_options->cas,
1149                                        transport->remote, remote_refs);
1150
1151                 set_ref_status_for_push(remote_refs,
1152                         flags & TRANSPORT_PUSH_MIRROR,
1153                         flags & TRANSPORT_PUSH_FORCE);
1154
1155                 if (!(flags & TRANSPORT_PUSH_NO_HOOK))
1156                         if (run_pre_push_hook(transport, remote_refs))
1157                                 return -1;
1158
1159                 if ((flags & TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND) && !is_bare_repository()) {
1160                         struct ref *ref = remote_refs;
1161                         for (; ref; ref = ref->next)
1162                                 if (!is_null_sha1(ref->new_sha1) &&
1163                                     !push_unpushed_submodules(ref->new_sha1,
1164                                             transport->remote->name))
1165                                     die ("Failed to push all needed submodules!");
1166                 }
1167
1168                 if ((flags & (TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND |
1169                               TRANSPORT_RECURSE_SUBMODULES_CHECK)) && !is_bare_repository()) {
1170                         struct ref *ref = remote_refs;
1171                         struct string_list needs_pushing;
1172
1173                         memset(&needs_pushing, 0, sizeof(struct string_list));
1174                         needs_pushing.strdup_strings = 1;
1175                         for (; ref; ref = ref->next)
1176                                 if (!is_null_sha1(ref->new_sha1) &&
1177                                     find_unpushed_submodules(ref->new_sha1,
1178                                             transport->remote->name, &needs_pushing))
1179                                         die_with_unpushed_submodules(&needs_pushing);
1180                 }
1181
1182                 push_ret = transport->push_refs(transport, remote_refs, flags);
1183                 err = push_had_errors(remote_refs);
1184                 ret = push_ret | err;
1185
1186                 if (!quiet || err)
1187                         transport_print_push_status(transport->url, remote_refs,
1188                                         verbose | porcelain, porcelain,
1189                                         reject_reasons);
1190
1191                 if (flags & TRANSPORT_PUSH_SET_UPSTREAM)
1192                         set_upstreams(transport, remote_refs, pretend);
1193
1194                 if (!(flags & TRANSPORT_PUSH_DRY_RUN)) {
1195                         struct ref *ref;
1196                         for (ref = remote_refs; ref; ref = ref->next)
1197                                 transport_update_tracking_ref(transport->remote, ref, verbose);
1198                 }
1199
1200                 if (porcelain && !push_ret)
1201                         puts("Done");
1202                 else if (!quiet && !ret && !transport_refs_pushed(remote_refs))
1203                         fprintf(stderr, "Everything up-to-date\n");
1204
1205                 return ret;
1206         }
1207         return 1;
1208 }
1209
1210 const struct ref *transport_get_remote_refs(struct transport *transport)
1211 {
1212         if (!transport->got_remote_refs) {
1213                 transport->remote_refs = transport->get_refs_list(transport, 0);
1214                 transport->got_remote_refs = 1;
1215         }
1216
1217         return transport->remote_refs;
1218 }
1219
1220 int transport_fetch_refs(struct transport *transport, struct ref *refs)
1221 {
1222         int rc;
1223         int nr_heads = 0, nr_alloc = 0, nr_refs = 0;
1224         struct ref **heads = NULL;
1225         struct ref *rm;
1226
1227         for (rm = refs; rm; rm = rm->next) {
1228                 nr_refs++;
1229                 if (rm->peer_ref &&
1230                     !is_null_sha1(rm->old_sha1) &&
1231                     !hashcmp(rm->peer_ref->old_sha1, rm->old_sha1))
1232                         continue;
1233                 ALLOC_GROW(heads, nr_heads + 1, nr_alloc);
1234                 heads[nr_heads++] = rm;
1235         }
1236
1237         if (!nr_heads) {
1238                 /*
1239                  * When deepening of a shallow repository is requested,
1240                  * then local and remote refs are likely to still be equal.
1241                  * Just feed them all to the fetch method in that case.
1242                  * This condition shouldn't be met in a non-deepening fetch
1243                  * (see builtin/fetch.c:quickfetch()).
1244                  */
1245                 heads = xmalloc(nr_refs * sizeof(*heads));
1246                 for (rm = refs; rm; rm = rm->next)
1247                         heads[nr_heads++] = rm;
1248         }
1249
1250         rc = transport->fetch(transport, nr_heads, heads);
1251
1252         free(heads);
1253         return rc;
1254 }
1255
1256 void transport_unlock_pack(struct transport *transport)
1257 {
1258         if (transport->pack_lockfile) {
1259                 unlink_or_warn(transport->pack_lockfile);
1260                 free(transport->pack_lockfile);
1261                 transport->pack_lockfile = NULL;
1262         }
1263 }
1264
1265 int transport_connect(struct transport *transport, const char *name,
1266                       const char *exec, int fd[2])
1267 {
1268         if (transport->connect)
1269                 return transport->connect(transport, name, exec, fd);
1270         else
1271                 die("Operation not supported by protocol");
1272 }
1273
1274 int transport_disconnect(struct transport *transport)
1275 {
1276         int ret = 0;
1277         if (transport->disconnect)
1278                 ret = transport->disconnect(transport);
1279         free(transport);
1280         return ret;
1281 }
1282
1283 /*
1284  * Strip username (and password) from a URL and return
1285  * it in a newly allocated string.
1286  */
1287 char *transport_anonymize_url(const char *url)
1288 {
1289         char *anon_url, *scheme_prefix, *anon_part;
1290         size_t anon_len, prefix_len = 0;
1291
1292         anon_part = strchr(url, '@');
1293         if (is_local(url) || !anon_part)
1294                 goto literal_copy;
1295
1296         anon_len = strlen(++anon_part);
1297         scheme_prefix = strstr(url, "://");
1298         if (!scheme_prefix) {
1299                 if (!strchr(anon_part, ':'))
1300                         /* cannot be "me@there:/path/name" */
1301                         goto literal_copy;
1302         } else {
1303                 const char *cp;
1304                 /* make sure scheme is reasonable */
1305                 for (cp = url; cp < scheme_prefix; cp++) {
1306                         switch (*cp) {
1307                                 /* RFC 1738 2.1 */
1308                         case '+': case '.': case '-':
1309                                 break; /* ok */
1310                         default:
1311                                 if (isalnum(*cp))
1312                                         break;
1313                                 /* it isn't */
1314                                 goto literal_copy;
1315                         }
1316                 }
1317                 /* @ past the first slash does not count */
1318                 cp = strchr(scheme_prefix + 3, '/');
1319                 if (cp && cp < anon_part)
1320                         goto literal_copy;
1321                 prefix_len = scheme_prefix - url + 3;
1322         }
1323         anon_url = xcalloc(1, 1 + prefix_len + anon_len);
1324         memcpy(anon_url, url, prefix_len);
1325         memcpy(anon_url + prefix_len, anon_part, anon_len);
1326         return anon_url;
1327 literal_copy:
1328         return xstrdup(url);
1329 }
1330
1331 struct alternate_refs_data {
1332         alternate_ref_fn *fn;
1333         void *data;
1334 };
1335
1336 static int refs_from_alternate_cb(struct alternate_object_database *e,
1337                                   void *data)
1338 {
1339         char *other;
1340         size_t len;
1341         struct remote *remote;
1342         struct transport *transport;
1343         const struct ref *extra;
1344         struct alternate_refs_data *cb = data;
1345
1346         e->name[-1] = '\0';
1347         other = xstrdup(real_path(e->base));
1348         e->name[-1] = '/';
1349         len = strlen(other);
1350
1351         while (other[len-1] == '/')
1352                 other[--len] = '\0';
1353         if (len < 8 || memcmp(other + len - 8, "/objects", 8))
1354                 return 0;
1355         /* Is this a git repository with refs? */
1356         memcpy(other + len - 8, "/refs", 6);
1357         if (!is_directory(other))
1358                 return 0;
1359         other[len - 8] = '\0';
1360         remote = remote_get(other);
1361         transport = transport_get(remote, other);
1362         for (extra = transport_get_remote_refs(transport);
1363              extra;
1364              extra = extra->next)
1365                 cb->fn(extra, cb->data);
1366         transport_disconnect(transport);
1367         free(other);
1368         return 0;
1369 }
1370
1371 void for_each_alternate_ref(alternate_ref_fn fn, void *data)
1372 {
1373         struct alternate_refs_data cb;
1374         cb.fn = fn;
1375         cb.data = data;
1376         foreach_alt_odb(refs_from_alternate_cb, &cb);
1377 }