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