New capability "report-status-v2" for git-push
[git] / send-pack.c
1 #include "builtin.h"
2 #include "config.h"
3 #include "commit.h"
4 #include "refs.h"
5 #include "object-store.h"
6 #include "pkt-line.h"
7 #include "sideband.h"
8 #include "run-command.h"
9 #include "remote.h"
10 #include "connect.h"
11 #include "send-pack.h"
12 #include "quote.h"
13 #include "transport.h"
14 #include "version.h"
15 #include "oid-array.h"
16 #include "gpg-interface.h"
17 #include "cache.h"
18
19 int option_parse_push_signed(const struct option *opt,
20                              const char *arg, int unset)
21 {
22         if (unset) {
23                 *(int *)(opt->value) = SEND_PACK_PUSH_CERT_NEVER;
24                 return 0;
25         }
26         switch (git_parse_maybe_bool(arg)) {
27         case 1:
28                 *(int *)(opt->value) = SEND_PACK_PUSH_CERT_ALWAYS;
29                 return 0;
30         case 0:
31                 *(int *)(opt->value) = SEND_PACK_PUSH_CERT_NEVER;
32                 return 0;
33         }
34         if (!strcasecmp("if-asked", arg)) {
35                 *(int *)(opt->value) = SEND_PACK_PUSH_CERT_IF_ASKED;
36                 return 0;
37         }
38         die("bad %s argument: %s", opt->long_name, arg);
39 }
40
41 static void feed_object(const struct object_id *oid, FILE *fh, int negative)
42 {
43         if (negative &&
44             !has_object_file_with_flags(oid,
45                                         OBJECT_INFO_SKIP_FETCH_OBJECT |
46                                         OBJECT_INFO_QUICK))
47                 return;
48
49         if (negative)
50                 putc('^', fh);
51         fputs(oid_to_hex(oid), fh);
52         putc('\n', fh);
53 }
54
55 /*
56  * Make a pack stream and spit it out into file descriptor fd
57  */
58 static int pack_objects(int fd, struct ref *refs, struct oid_array *extra, struct send_pack_args *args)
59 {
60         /*
61          * The child becomes pack-objects --revs; we feed
62          * the revision parameters to it via its stdin and
63          * let its stdout go back to the other end.
64          */
65         struct child_process po = CHILD_PROCESS_INIT;
66         FILE *po_in;
67         int i;
68         int rc;
69
70         argv_array_push(&po.args, "pack-objects");
71         argv_array_push(&po.args, "--all-progress-implied");
72         argv_array_push(&po.args, "--revs");
73         argv_array_push(&po.args, "--stdout");
74         if (args->use_thin_pack)
75                 argv_array_push(&po.args, "--thin");
76         if (args->use_ofs_delta)
77                 argv_array_push(&po.args, "--delta-base-offset");
78         if (args->quiet || !args->progress)
79                 argv_array_push(&po.args, "-q");
80         if (args->progress)
81                 argv_array_push(&po.args, "--progress");
82         if (is_repository_shallow(the_repository))
83                 argv_array_push(&po.args, "--shallow");
84         po.in = -1;
85         po.out = args->stateless_rpc ? -1 : fd;
86         po.git_cmd = 1;
87         if (start_command(&po))
88                 die_errno("git pack-objects failed");
89
90         /*
91          * We feed the pack-objects we just spawned with revision
92          * parameters by writing to the pipe.
93          */
94         po_in = xfdopen(po.in, "w");
95         for (i = 0; i < extra->nr; i++)
96                 feed_object(&extra->oid[i], po_in, 1);
97
98         while (refs) {
99                 if (!is_null_oid(&refs->old_oid))
100                         feed_object(&refs->old_oid, po_in, 1);
101                 if (!is_null_oid(&refs->new_oid))
102                         feed_object(&refs->new_oid, po_in, 0);
103                 refs = refs->next;
104         }
105
106         fflush(po_in);
107         if (ferror(po_in))
108                 die_errno("error writing to pack-objects");
109         fclose(po_in);
110
111         if (args->stateless_rpc) {
112                 char *buf = xmalloc(LARGE_PACKET_MAX);
113                 while (1) {
114                         ssize_t n = xread(po.out, buf, LARGE_PACKET_MAX);
115                         if (n <= 0)
116                                 break;
117                         send_sideband(fd, -1, buf, n, LARGE_PACKET_MAX);
118                 }
119                 free(buf);
120                 close(po.out);
121                 po.out = -1;
122         }
123
124         rc = finish_command(&po);
125         if (rc) {
126                 /*
127                  * For a normal non-zero exit, we assume pack-objects wrote
128                  * something useful to stderr. For death by signal, though,
129                  * we should mention it to the user. The exception is SIGPIPE
130                  * (141), because that's a normal occurrence if the remote end
131                  * hangs up (and we'll report that by trying to read the unpack
132                  * status).
133                  */
134                 if (rc > 128 && rc != 141)
135                         error("pack-objects died of signal %d", rc - 128);
136                 return -1;
137         }
138         return 0;
139 }
140
141 static int receive_unpack_status(struct packet_reader *reader)
142 {
143         if (packet_reader_read(reader) != PACKET_READ_NORMAL)
144                 return error(_("unexpected flush packet while reading remote unpack status"));
145         if (!skip_prefix(reader->line, "unpack ", &reader->line))
146                 return error(_("unable to parse remote unpack status: %s"), reader->line);
147         if (strcmp(reader->line, "ok"))
148                 return error(_("remote unpack failed: %s"), reader->line);
149         return 0;
150 }
151
152 static int receive_status(struct packet_reader *reader, struct ref *refs)
153 {
154         struct ref *hint;
155         int ret;
156         struct ref_push_report *report = NULL;
157         int new_report = 0;
158         int once = 0;
159
160         hint = NULL;
161         ret = receive_unpack_status(reader);
162         while (1) {
163                 struct object_id old_oid, new_oid;
164                 const char *head;
165                 const char *refname;
166                 char *p;
167                 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
168                         break;
169                 head = reader->line;
170                 p = strchr(head, ' ');
171                 if (!p) {
172                         error("invalid status line from remote: %s", reader->line);
173                         ret = -1;
174                         break;
175                 }
176                 *p++ = '\0';
177
178                 if (!strcmp(head, "option")) {
179                         const char *key, *val;
180
181                         if (!hint || !(report || new_report)) {
182                                 if (!once++)
183                                         error("'option' without a matching 'ok/ng' directive");
184                                 ret = -1;
185                                 continue;
186                         }
187                         if (new_report) {
188                                 if (!hint->report) {
189                                         hint->report = xcalloc(1, sizeof(struct ref_push_report));
190                                         report = hint->report;
191                                 } else {
192                                         report = hint->report;
193                                         while (report->next)
194                                                 report = report->next;
195                                         report->next = xcalloc(1, sizeof(struct ref_push_report));
196                                         report = report->next;
197                                 }
198                                 new_report = 0;
199                         }
200                         key = p;
201                         p = strchr(key, ' ');
202                         if (p)
203                                 *p++ = '\0';
204                         val = p;
205                         if (!strcmp(key, "refname"))
206                                 report->ref_name = xstrdup_or_null(val);
207                         else if (!strcmp(key, "old-oid") && val &&
208                                  !parse_oid_hex(val, &old_oid, &val))
209                                 report->old_oid = oiddup(&old_oid);
210                         else if (!strcmp(key, "new-oid") && val &&
211                                  !parse_oid_hex(val, &new_oid, &val))
212                                 report->new_oid = oiddup(&new_oid);
213                         else if (!strcmp(key, "forced-update"))
214                                 report->forced_update = 1;
215                         continue;
216                 }
217
218                 report = NULL;
219                 new_report = 0;
220                 if (strcmp(head, "ok") && strcmp(head, "ng")) {
221                         error("invalid ref status from remote: %s", head);
222                         ret = -1;
223                         break;
224                 }
225                 refname = p;
226                 p = strchr(refname, ' ');
227                 if (p)
228                         *p++ = '\0';
229                 /* first try searching at our hint, falling back to all refs */
230                 if (hint)
231                         hint = find_ref_by_name(hint, refname);
232                 if (!hint)
233                         hint = find_ref_by_name(refs, refname);
234                 if (!hint) {
235                         warning("remote reported status on unknown ref: %s",
236                                 refname);
237                         continue;
238                 }
239                 if (hint->status != REF_STATUS_EXPECTING_REPORT &&
240                     hint->status != REF_STATUS_OK &&
241                     hint->status != REF_STATUS_REMOTE_REJECT) {
242                         warning("remote reported status on unexpected ref: %s",
243                                 refname);
244                         continue;
245                 }
246                 if (!strcmp(head, "ng")) {
247                         hint->status = REF_STATUS_REMOTE_REJECT;
248                         if (p)
249                                 hint->remote_status = xstrdup(p);
250                         else
251                                 hint->remote_status = "failed";
252                 } else {
253                         hint->status = REF_STATUS_OK;
254                         hint->remote_status = xstrdup_or_null(p);
255                         new_report = 1;
256                 }
257         }
258         return ret;
259 }
260
261 static int sideband_demux(int in, int out, void *data)
262 {
263         int *fd = data, ret;
264         if (async_with_fork())
265                 close(fd[1]);
266         ret = recv_sideband("send-pack", fd[0], out);
267         close(out);
268         return ret;
269 }
270
271 static int advertise_shallow_grafts_cb(const struct commit_graft *graft, void *cb)
272 {
273         struct strbuf *sb = cb;
274         if (graft->nr_parent == -1)
275                 packet_buf_write(sb, "shallow %s\n", oid_to_hex(&graft->oid));
276         return 0;
277 }
278
279 static void advertise_shallow_grafts_buf(struct strbuf *sb)
280 {
281         if (!is_repository_shallow(the_repository))
282                 return;
283         for_each_commit_graft(advertise_shallow_grafts_cb, sb);
284 }
285
286 #define CHECK_REF_NO_PUSH -1
287 #define CHECK_REF_STATUS_REJECTED -2
288 #define CHECK_REF_UPTODATE -3
289 static int check_to_send_update(const struct ref *ref, const struct send_pack_args *args)
290 {
291         if (!ref->peer_ref && !args->send_mirror)
292                 return CHECK_REF_NO_PUSH;
293
294         /* Check for statuses set by set_ref_status_for_push() */
295         switch (ref->status) {
296         case REF_STATUS_REJECT_NONFASTFORWARD:
297         case REF_STATUS_REJECT_ALREADY_EXISTS:
298         case REF_STATUS_REJECT_FETCH_FIRST:
299         case REF_STATUS_REJECT_NEEDS_FORCE:
300         case REF_STATUS_REJECT_STALE:
301         case REF_STATUS_REJECT_NODELETE:
302                 return CHECK_REF_STATUS_REJECTED;
303         case REF_STATUS_UPTODATE:
304                 return CHECK_REF_UPTODATE;
305         default:
306                 return 0;
307         }
308 }
309
310 /*
311  * the beginning of the next line, or the end of buffer.
312  *
313  * NEEDSWORK: perhaps move this to git-compat-util.h or somewhere and
314  * convert many similar uses found by "git grep -A4 memchr".
315  */
316 static const char *next_line(const char *line, size_t len)
317 {
318         const char *nl = memchr(line, '\n', len);
319         if (!nl)
320                 return line + len; /* incomplete line */
321         return nl + 1;
322 }
323
324 static int generate_push_cert(struct strbuf *req_buf,
325                               const struct ref *remote_refs,
326                               struct send_pack_args *args,
327                               const char *cap_string,
328                               const char *push_cert_nonce)
329 {
330         const struct ref *ref;
331         struct string_list_item *item;
332         char *signing_key = xstrdup(get_signing_key());
333         const char *cp, *np;
334         struct strbuf cert = STRBUF_INIT;
335         int update_seen = 0;
336
337         strbuf_addstr(&cert, "certificate version 0.1\n");
338         strbuf_addf(&cert, "pusher %s ", signing_key);
339         datestamp(&cert);
340         strbuf_addch(&cert, '\n');
341         if (args->url && *args->url) {
342                 char *anon_url = transport_anonymize_url(args->url);
343                 strbuf_addf(&cert, "pushee %s\n", anon_url);
344                 free(anon_url);
345         }
346         if (push_cert_nonce[0])
347                 strbuf_addf(&cert, "nonce %s\n", push_cert_nonce);
348         if (args->push_options)
349                 for_each_string_list_item(item, args->push_options)
350                         strbuf_addf(&cert, "push-option %s\n", item->string);
351         strbuf_addstr(&cert, "\n");
352
353         for (ref = remote_refs; ref; ref = ref->next) {
354                 if (check_to_send_update(ref, args) < 0)
355                         continue;
356                 update_seen = 1;
357                 strbuf_addf(&cert, "%s %s %s\n",
358                             oid_to_hex(&ref->old_oid),
359                             oid_to_hex(&ref->new_oid),
360                             ref->name);
361         }
362         if (!update_seen)
363                 goto free_return;
364
365         if (sign_buffer(&cert, &cert, signing_key))
366                 die(_("failed to sign the push certificate"));
367
368         packet_buf_write(req_buf, "push-cert%c%s", 0, cap_string);
369         for (cp = cert.buf; cp < cert.buf + cert.len; cp = np) {
370                 np = next_line(cp, cert.buf + cert.len - cp);
371                 packet_buf_write(req_buf,
372                                  "%.*s", (int)(np - cp), cp);
373         }
374         packet_buf_write(req_buf, "push-cert-end\n");
375
376 free_return:
377         free(signing_key);
378         strbuf_release(&cert);
379         return update_seen;
380 }
381
382 #define NONCE_LEN_LIMIT 256
383
384 static void reject_invalid_nonce(const char *nonce, int len)
385 {
386         int i = 0;
387
388         if (NONCE_LEN_LIMIT <= len)
389                 die("the receiving end asked to sign an invalid nonce <%.*s>",
390                     len, nonce);
391
392         for (i = 0; i < len; i++) {
393                 int ch = nonce[i] & 0xFF;
394                 if (isalnum(ch) ||
395                     ch == '-' || ch == '.' ||
396                     ch == '/' || ch == '+' ||
397                     ch == '=' || ch == '_')
398                         continue;
399                 die("the receiving end asked to sign an invalid nonce <%.*s>",
400                     len, nonce);
401         }
402 }
403
404 int send_pack(struct send_pack_args *args,
405               int fd[], struct child_process *conn,
406               struct ref *remote_refs,
407               struct oid_array *extra_have)
408 {
409         int in = fd[0];
410         int out = fd[1];
411         struct strbuf req_buf = STRBUF_INIT;
412         struct strbuf cap_buf = STRBUF_INIT;
413         struct ref *ref;
414         int need_pack_data = 0;
415         int allow_deleting_refs = 0;
416         int status_report = 0;
417         int use_sideband = 0;
418         int quiet_supported = 0;
419         int agent_supported = 0;
420         int use_atomic = 0;
421         int atomic_supported = 0;
422         int use_push_options = 0;
423         int push_options_supported = 0;
424         unsigned cmds_sent = 0;
425         int ret;
426         struct async demux;
427         const char *push_cert_nonce = NULL;
428         struct packet_reader reader;
429
430         /* Does the other end support the reporting? */
431         if (server_supports("report-status-v2"))
432                 status_report = 2;
433         else if (server_supports("report-status"))
434                 status_report = 1;
435         if (server_supports("delete-refs"))
436                 allow_deleting_refs = 1;
437         if (server_supports("ofs-delta"))
438                 args->use_ofs_delta = 1;
439         if (server_supports("side-band-64k"))
440                 use_sideband = 1;
441         if (server_supports("quiet"))
442                 quiet_supported = 1;
443         if (server_supports("agent"))
444                 agent_supported = 1;
445         if (server_supports("no-thin"))
446                 args->use_thin_pack = 0;
447         if (server_supports("atomic"))
448                 atomic_supported = 1;
449         if (server_supports("push-options"))
450                 push_options_supported = 1;
451
452         if (args->push_cert != SEND_PACK_PUSH_CERT_NEVER) {
453                 int len;
454                 push_cert_nonce = server_feature_value("push-cert", &len);
455                 if (push_cert_nonce) {
456                         reject_invalid_nonce(push_cert_nonce, len);
457                         push_cert_nonce = xmemdupz(push_cert_nonce, len);
458                 } else if (args->push_cert == SEND_PACK_PUSH_CERT_ALWAYS) {
459                         die(_("the receiving end does not support --signed push"));
460                 } else if (args->push_cert == SEND_PACK_PUSH_CERT_IF_ASKED) {
461                         warning(_("not sending a push certificate since the"
462                                   " receiving end does not support --signed"
463                                   " push"));
464                 }
465         }
466
467         if (!remote_refs) {
468                 fprintf(stderr, "No refs in common and none specified; doing nothing.\n"
469                         "Perhaps you should specify a branch such as 'master'.\n");
470                 return 0;
471         }
472         if (args->atomic && !atomic_supported)
473                 die(_("the receiving end does not support --atomic push"));
474
475         use_atomic = atomic_supported && args->atomic;
476
477         if (args->push_options && !push_options_supported)
478                 die(_("the receiving end does not support push options"));
479
480         use_push_options = push_options_supported && args->push_options;
481
482         if (status_report == 1)
483                 strbuf_addstr(&cap_buf, " report-status");
484         else if (status_report == 2)
485                 strbuf_addstr(&cap_buf, " report-status-v2");
486         if (use_sideband)
487                 strbuf_addstr(&cap_buf, " side-band-64k");
488         if (quiet_supported && (args->quiet || !args->progress))
489                 strbuf_addstr(&cap_buf, " quiet");
490         if (use_atomic)
491                 strbuf_addstr(&cap_buf, " atomic");
492         if (use_push_options)
493                 strbuf_addstr(&cap_buf, " push-options");
494         if (agent_supported)
495                 strbuf_addf(&cap_buf, " agent=%s", git_user_agent_sanitized());
496
497         /*
498          * NEEDSWORK: why does delete-refs have to be so specific to
499          * send-pack machinery that set_ref_status_for_push() cannot
500          * set this bit for us???
501          */
502         for (ref = remote_refs; ref; ref = ref->next)
503                 if (ref->deletion && !allow_deleting_refs)
504                         ref->status = REF_STATUS_REJECT_NODELETE;
505
506         if (!args->dry_run)
507                 advertise_shallow_grafts_buf(&req_buf);
508
509         if (!args->dry_run && push_cert_nonce)
510                 cmds_sent = generate_push_cert(&req_buf, remote_refs, args,
511                                                cap_buf.buf, push_cert_nonce);
512
513         /*
514          * Clear the status for each ref and see if we need to send
515          * the pack data.
516          */
517         for (ref = remote_refs; ref; ref = ref->next) {
518                 switch (check_to_send_update(ref, args)) {
519                 case 0: /* no error */
520                         break;
521                 case CHECK_REF_STATUS_REJECTED:
522                         /*
523                          * When we know the server would reject a ref update if
524                          * we were to send it and we're trying to send the refs
525                          * atomically, abort the whole operation.
526                          */
527                         if (use_atomic) {
528                                 strbuf_release(&req_buf);
529                                 strbuf_release(&cap_buf);
530                                 reject_atomic_push(remote_refs, args->send_mirror);
531                                 error("atomic push failed for ref %s. status: %d\n",
532                                       ref->name, ref->status);
533                                 return args->porcelain ? 0 : -1;
534                         }
535                         /* else fallthrough */
536                 default:
537                         continue;
538                 }
539                 if (!ref->deletion)
540                         need_pack_data = 1;
541
542                 if (args->dry_run || !status_report)
543                         ref->status = REF_STATUS_OK;
544                 else
545                         ref->status = REF_STATUS_EXPECTING_REPORT;
546         }
547
548         /*
549          * Finally, tell the other end!
550          */
551         for (ref = remote_refs; ref; ref = ref->next) {
552                 char *old_hex, *new_hex;
553
554                 if (args->dry_run || push_cert_nonce)
555                         continue;
556
557                 if (check_to_send_update(ref, args) < 0)
558                         continue;
559
560                 old_hex = oid_to_hex(&ref->old_oid);
561                 new_hex = oid_to_hex(&ref->new_oid);
562                 if (!cmds_sent) {
563                         packet_buf_write(&req_buf,
564                                          "%s %s %s%c%s",
565                                          old_hex, new_hex, ref->name, 0,
566                                          cap_buf.buf);
567                         cmds_sent = 1;
568                 } else {
569                         packet_buf_write(&req_buf, "%s %s %s",
570                                          old_hex, new_hex, ref->name);
571                 }
572         }
573
574         if (use_push_options) {
575                 struct string_list_item *item;
576
577                 packet_buf_flush(&req_buf);
578                 for_each_string_list_item(item, args->push_options)
579                         packet_buf_write(&req_buf, "%s", item->string);
580         }
581
582         if (args->stateless_rpc) {
583                 if (!args->dry_run && (cmds_sent || is_repository_shallow(the_repository))) {
584                         packet_buf_flush(&req_buf);
585                         send_sideband(out, -1, req_buf.buf, req_buf.len, LARGE_PACKET_MAX);
586                 }
587         } else {
588                 write_or_die(out, req_buf.buf, req_buf.len);
589                 packet_flush(out);
590         }
591         strbuf_release(&req_buf);
592         strbuf_release(&cap_buf);
593
594         if (use_sideband && cmds_sent) {
595                 memset(&demux, 0, sizeof(demux));
596                 demux.proc = sideband_demux;
597                 demux.data = fd;
598                 demux.out = -1;
599                 demux.isolate_sigpipe = 1;
600                 if (start_async(&demux))
601                         die("send-pack: unable to fork off sideband demultiplexer");
602                 in = demux.out;
603         }
604
605         packet_reader_init(&reader, in, NULL, 0,
606                            PACKET_READ_CHOMP_NEWLINE |
607                            PACKET_READ_DIE_ON_ERR_PACKET);
608
609         if (need_pack_data && cmds_sent) {
610                 if (pack_objects(out, remote_refs, extra_have, args) < 0) {
611                         if (args->stateless_rpc)
612                                 close(out);
613                         if (git_connection_is_socket(conn))
614                                 shutdown(fd[0], SHUT_WR);
615
616                         /*
617                          * Do not even bother with the return value; we know we
618                          * are failing, and just want the error() side effects,
619                          * as well as marking refs with their remote status (if
620                          * we get one).
621                          */
622                         if (status_report)
623                                 receive_status(&reader, remote_refs);
624
625                         if (use_sideband) {
626                                 close(demux.out);
627                                 finish_async(&demux);
628                         }
629                         fd[1] = -1;
630                         return -1;
631                 }
632                 if (!args->stateless_rpc)
633                         /* Closed by pack_objects() via start_command() */
634                         fd[1] = -1;
635         }
636         if (args->stateless_rpc && cmds_sent)
637                 packet_flush(out);
638
639         if (status_report && cmds_sent)
640                 ret = receive_status(&reader, remote_refs);
641         else
642                 ret = 0;
643         if (args->stateless_rpc)
644                 packet_flush(out);
645
646         if (use_sideband && cmds_sent) {
647                 close(demux.out);
648                 if (finish_async(&demux)) {
649                         error("error in sideband demultiplexer");
650                         ret = -1;
651                 }
652         }
653
654         if (ret < 0)
655                 return ret;
656
657         if (args->porcelain)
658                 return 0;
659
660         for (ref = remote_refs; ref; ref = ref->next) {
661                 switch (ref->status) {
662                 case REF_STATUS_NONE:
663                 case REF_STATUS_UPTODATE:
664                 case REF_STATUS_OK:
665                         break;
666                 default:
667                         return -1;
668                 }
669         }
670         return 0;
671 }