t5332-multi-pack-reuse.sh: demonstrate duplicate packing failure
[git/gitster.git] / builtin / receive-pack.c
blob536d22761d6d9e5a2a6645ab7a68e29f07b9bfa3
1 #define USE_THE_REPOSITORY_VARIABLE
2 #include "builtin.h"
3 #include "abspath.h"
5 #include "config.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hex.h"
9 #include "lockfile.h"
10 #include "pack.h"
11 #include "refs.h"
12 #include "pkt-line.h"
13 #include "sideband.h"
14 #include "run-command.h"
15 #include "hook.h"
16 #include "exec-cmd.h"
17 #include "commit.h"
18 #include "object.h"
19 #include "remote.h"
20 #include "connect.h"
21 #include "string-list.h"
22 #include "oid-array.h"
23 #include "connected.h"
24 #include "strvec.h"
25 #include "version.h"
26 #include "gpg-interface.h"
27 #include "sigchain.h"
28 #include "fsck.h"
29 #include "tmp-objdir.h"
30 #include "oidset.h"
31 #include "packfile.h"
32 #include "object-name.h"
33 #include "object-store-ll.h"
34 #include "path.h"
35 #include "protocol.h"
36 #include "commit-reach.h"
37 #include "server-info.h"
38 #include "trace.h"
39 #include "trace2.h"
40 #include "worktree.h"
41 #include "shallow.h"
42 #include "parse-options.h"
44 static const char * const receive_pack_usage[] = {
45 N_("git receive-pack <git-dir>"),
46 NULL
49 enum deny_action {
50 DENY_UNCONFIGURED,
51 DENY_IGNORE,
52 DENY_WARN,
53 DENY_REFUSE,
54 DENY_UPDATE_INSTEAD
57 static int deny_deletes;
58 static int deny_non_fast_forwards;
59 static enum deny_action deny_current_branch = DENY_UNCONFIGURED;
60 static enum deny_action deny_delete_current = DENY_UNCONFIGURED;
61 static int receive_fsck_objects = -1;
62 static int transfer_fsck_objects = -1;
63 static struct strbuf fsck_msg_types = STRBUF_INIT;
64 static int receive_unpack_limit = -1;
65 static int transfer_unpack_limit = -1;
66 static int advertise_atomic_push = 1;
67 static int advertise_push_options;
68 static int advertise_sid;
69 static int unpack_limit = 100;
70 static off_t max_input_size;
71 static int report_status;
72 static int report_status_v2;
73 static int use_sideband;
74 static int use_atomic;
75 static int use_push_options;
76 static int quiet;
77 static int prefer_ofs_delta = 1;
78 static int auto_update_server_info;
79 static int auto_gc = 1;
80 static int reject_thin;
81 static int stateless_rpc;
82 static const char *service_dir;
83 static const char *head_name;
84 static void *head_name_to_free;
85 static int sent_capabilities;
86 static int shallow_update;
87 static const char *alt_shallow_file;
88 static struct strbuf push_cert = STRBUF_INIT;
89 static struct object_id push_cert_oid;
90 static struct signature_check sigcheck;
91 static const char *push_cert_nonce;
92 static char *cert_nonce_seed;
93 static struct strvec hidden_refs = STRVEC_INIT;
95 static const char *NONCE_UNSOLICITED = "UNSOLICITED";
96 static const char *NONCE_BAD = "BAD";
97 static const char *NONCE_MISSING = "MISSING";
98 static const char *NONCE_OK = "OK";
99 static const char *NONCE_SLOP = "SLOP";
100 static const char *nonce_status;
101 static long nonce_stamp_slop;
102 static timestamp_t nonce_stamp_slop_limit;
103 static struct ref_transaction *transaction;
105 static enum {
106 KEEPALIVE_NEVER = 0,
107 KEEPALIVE_AFTER_NUL,
108 KEEPALIVE_ALWAYS
109 } use_keepalive;
110 static int keepalive_in_sec = 5;
112 static struct tmp_objdir *tmp_objdir;
114 static struct proc_receive_ref {
115 unsigned int want_add:1,
116 want_delete:1,
117 want_modify:1,
118 negative_ref:1;
119 char *ref_prefix;
120 struct proc_receive_ref *next;
121 } *proc_receive_ref;
123 static void proc_receive_ref_append(const char *prefix);
125 static enum deny_action parse_deny_action(const char *var, const char *value)
127 if (value) {
128 if (!strcasecmp(value, "ignore"))
129 return DENY_IGNORE;
130 if (!strcasecmp(value, "warn"))
131 return DENY_WARN;
132 if (!strcasecmp(value, "refuse"))
133 return DENY_REFUSE;
134 if (!strcasecmp(value, "updateinstead"))
135 return DENY_UPDATE_INSTEAD;
137 if (git_config_bool(var, value))
138 return DENY_REFUSE;
139 return DENY_IGNORE;
142 static int receive_pack_config(const char *var, const char *value,
143 const struct config_context *ctx, void *cb)
145 const char *msg_id;
146 int status = parse_hide_refs_config(var, value, "receive", &hidden_refs);
148 if (status)
149 return status;
151 if (strcmp(var, "receive.denydeletes") == 0) {
152 deny_deletes = git_config_bool(var, value);
153 return 0;
156 if (strcmp(var, "receive.denynonfastforwards") == 0) {
157 deny_non_fast_forwards = git_config_bool(var, value);
158 return 0;
161 if (strcmp(var, "receive.unpacklimit") == 0) {
162 receive_unpack_limit = git_config_int(var, value, ctx->kvi);
163 return 0;
166 if (strcmp(var, "transfer.unpacklimit") == 0) {
167 transfer_unpack_limit = git_config_int(var, value, ctx->kvi);
168 return 0;
171 if (strcmp(var, "receive.fsck.skiplist") == 0) {
172 char *path;
174 if (git_config_pathname(&path, var, value))
175 return 1;
176 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
177 fsck_msg_types.len ? ',' : '=', path);
178 free(path);
179 return 0;
182 if (skip_prefix(var, "receive.fsck.", &msg_id)) {
183 if (!value)
184 return config_error_nonbool(var);
185 if (is_valid_msg_type(msg_id, value))
186 strbuf_addf(&fsck_msg_types, "%c%s=%s",
187 fsck_msg_types.len ? ',' : '=', msg_id, value);
188 else
189 warning("skipping unknown msg id '%s'", msg_id);
190 return 0;
193 if (strcmp(var, "receive.fsckobjects") == 0) {
194 receive_fsck_objects = git_config_bool(var, value);
195 return 0;
198 if (strcmp(var, "transfer.fsckobjects") == 0) {
199 transfer_fsck_objects = git_config_bool(var, value);
200 return 0;
203 if (!strcmp(var, "receive.denycurrentbranch")) {
204 deny_current_branch = parse_deny_action(var, value);
205 return 0;
208 if (strcmp(var, "receive.denydeletecurrent") == 0) {
209 deny_delete_current = parse_deny_action(var, value);
210 return 0;
213 if (strcmp(var, "repack.usedeltabaseoffset") == 0) {
214 prefer_ofs_delta = git_config_bool(var, value);
215 return 0;
218 if (strcmp(var, "receive.updateserverinfo") == 0) {
219 auto_update_server_info = git_config_bool(var, value);
220 return 0;
223 if (strcmp(var, "receive.autogc") == 0) {
224 auto_gc = git_config_bool(var, value);
225 return 0;
228 if (strcmp(var, "receive.shallowupdate") == 0) {
229 shallow_update = git_config_bool(var, value);
230 return 0;
233 if (strcmp(var, "receive.certnonceseed") == 0)
234 return git_config_string(&cert_nonce_seed, var, value);
236 if (strcmp(var, "receive.certnonceslop") == 0) {
237 nonce_stamp_slop_limit = git_config_ulong(var, value, ctx->kvi);
238 return 0;
241 if (strcmp(var, "receive.advertiseatomic") == 0) {
242 advertise_atomic_push = git_config_bool(var, value);
243 return 0;
246 if (strcmp(var, "receive.advertisepushoptions") == 0) {
247 advertise_push_options = git_config_bool(var, value);
248 return 0;
251 if (strcmp(var, "receive.keepalive") == 0) {
252 keepalive_in_sec = git_config_int(var, value, ctx->kvi);
253 return 0;
256 if (strcmp(var, "receive.maxinputsize") == 0) {
257 max_input_size = git_config_int64(var, value, ctx->kvi);
258 return 0;
261 if (strcmp(var, "receive.procreceiverefs") == 0) {
262 if (!value)
263 return config_error_nonbool(var);
264 proc_receive_ref_append(value);
265 return 0;
268 if (strcmp(var, "transfer.advertisesid") == 0) {
269 advertise_sid = git_config_bool(var, value);
270 return 0;
273 return git_default_config(var, value, ctx, cb);
276 static void show_ref(const char *path, const struct object_id *oid)
278 if (sent_capabilities) {
279 packet_write_fmt(1, "%s %s\n", oid_to_hex(oid), path);
280 } else {
281 struct strbuf cap = STRBUF_INIT;
283 strbuf_addstr(&cap,
284 "report-status report-status-v2 delete-refs side-band-64k quiet");
285 if (advertise_atomic_push)
286 strbuf_addstr(&cap, " atomic");
287 if (prefer_ofs_delta)
288 strbuf_addstr(&cap, " ofs-delta");
289 if (push_cert_nonce)
290 strbuf_addf(&cap, " push-cert=%s", push_cert_nonce);
291 if (advertise_push_options)
292 strbuf_addstr(&cap, " push-options");
293 if (advertise_sid)
294 strbuf_addf(&cap, " session-id=%s", trace2_session_id());
295 strbuf_addf(&cap, " object-format=%s", the_hash_algo->name);
296 strbuf_addf(&cap, " agent=%s", git_user_agent_sanitized());
297 packet_write_fmt(1, "%s %s%c%s\n",
298 oid_to_hex(oid), path, 0, cap.buf);
299 strbuf_release(&cap);
300 sent_capabilities = 1;
304 static int show_ref_cb(const char *path_full, const char *referent UNUSED, const struct object_id *oid,
305 int flag UNUSED, void *data)
307 struct oidset *seen = data;
308 const char *path = strip_namespace(path_full);
310 if (ref_is_hidden(path, path_full, &hidden_refs))
311 return 0;
314 * Advertise refs outside our current namespace as ".have"
315 * refs, so that the client can use them to minimize data
316 * transfer but will otherwise ignore them.
318 if (!path) {
319 if (oidset_insert(seen, oid))
320 return 0;
321 path = ".have";
322 } else {
323 oidset_insert(seen, oid);
325 show_ref(path, oid);
326 return 0;
329 static void show_one_alternate_ref(const struct object_id *oid,
330 void *data)
332 struct oidset *seen = data;
334 if (oidset_insert(seen, oid))
335 return;
337 show_ref(".have", oid);
340 static void write_head_info(void)
342 static struct oidset seen = OIDSET_INIT;
343 struct strvec excludes_vector = STRVEC_INIT;
344 const char **exclude_patterns;
347 * We need access to the reference names both with and without their
348 * namespace and thus cannot use `refs_for_each_namespaced_ref()`. We
349 * thus have to adapt exclude patterns to carry the namespace prefix
350 * ourselves.
352 exclude_patterns = get_namespaced_exclude_patterns(
353 hidden_refs_to_excludes(&hidden_refs),
354 get_git_namespace(), &excludes_vector);
356 refs_for_each_fullref_in(get_main_ref_store(the_repository), "",
357 exclude_patterns, show_ref_cb, &seen);
358 for_each_alternate_ref(show_one_alternate_ref, &seen);
360 oidset_clear(&seen);
361 strvec_clear(&excludes_vector);
363 if (!sent_capabilities)
364 show_ref("capabilities^{}", null_oid());
366 advertise_shallow_grafts(1);
368 /* EOF */
369 packet_flush(1);
372 #define RUN_PROC_RECEIVE_SCHEDULED 1
373 #define RUN_PROC_RECEIVE_RETURNED 2
374 struct command {
375 struct command *next;
376 const char *error_string;
377 struct ref_push_report *report;
378 unsigned int skip_update:1,
379 did_not_exist:1,
380 run_proc_receive:2;
381 int index;
382 struct object_id old_oid;
383 struct object_id new_oid;
384 char ref_name[FLEX_ARRAY]; /* more */
387 static void proc_receive_ref_append(const char *prefix)
389 struct proc_receive_ref *ref_pattern;
390 char *p;
391 int len;
393 CALLOC_ARRAY(ref_pattern, 1);
394 p = strchr(prefix, ':');
395 if (p) {
396 while (prefix < p) {
397 if (*prefix == 'a')
398 ref_pattern->want_add = 1;
399 else if (*prefix == 'd')
400 ref_pattern->want_delete = 1;
401 else if (*prefix == 'm')
402 ref_pattern->want_modify = 1;
403 else if (*prefix == '!')
404 ref_pattern->negative_ref = 1;
405 prefix++;
407 prefix++;
408 } else {
409 ref_pattern->want_add = 1;
410 ref_pattern->want_delete = 1;
411 ref_pattern->want_modify = 1;
413 len = strlen(prefix);
414 while (len && prefix[len - 1] == '/')
415 len--;
416 ref_pattern->ref_prefix = xmemdupz(prefix, len);
417 if (!proc_receive_ref) {
418 proc_receive_ref = ref_pattern;
419 } else {
420 struct proc_receive_ref *end;
422 end = proc_receive_ref;
423 while (end->next)
424 end = end->next;
425 end->next = ref_pattern;
429 static int proc_receive_ref_matches(struct command *cmd)
431 struct proc_receive_ref *p;
433 if (!proc_receive_ref)
434 return 0;
436 for (p = proc_receive_ref; p; p = p->next) {
437 const char *match = p->ref_prefix;
438 const char *remains;
440 if (!p->want_add && is_null_oid(&cmd->old_oid))
441 continue;
442 else if (!p->want_delete && is_null_oid(&cmd->new_oid))
443 continue;
444 else if (!p->want_modify &&
445 !is_null_oid(&cmd->old_oid) &&
446 !is_null_oid(&cmd->new_oid))
447 continue;
449 if (skip_prefix(cmd->ref_name, match, &remains) &&
450 (!*remains || *remains == '/')) {
451 if (!p->negative_ref)
452 return 1;
453 } else if (p->negative_ref) {
454 return 1;
457 return 0;
460 static void report_message(const char *prefix, const char *err, va_list params)
462 int sz;
463 char msg[4096];
465 sz = xsnprintf(msg, sizeof(msg), "%s", prefix);
466 sz += vsnprintf(msg + sz, sizeof(msg) - sz, err, params);
467 if (sz > (sizeof(msg) - 1))
468 sz = sizeof(msg) - 1;
469 msg[sz++] = '\n';
471 if (use_sideband)
472 send_sideband(1, 2, msg, sz, use_sideband);
473 else
474 xwrite(2, msg, sz);
477 __attribute__((format (printf, 1, 2)))
478 static void rp_warning(const char *err, ...)
480 va_list params;
481 va_start(params, err);
482 report_message("warning: ", err, params);
483 va_end(params);
486 __attribute__((format (printf, 1, 2)))
487 static void rp_error(const char *err, ...)
489 va_list params;
490 va_start(params, err);
491 report_message("error: ", err, params);
492 va_end(params);
495 static int copy_to_sideband(int in, int out UNUSED, void *arg UNUSED)
497 char data[128];
498 int keepalive_active = 0;
500 if (keepalive_in_sec <= 0)
501 use_keepalive = KEEPALIVE_NEVER;
502 if (use_keepalive == KEEPALIVE_ALWAYS)
503 keepalive_active = 1;
505 while (1) {
506 ssize_t sz;
508 if (keepalive_active) {
509 struct pollfd pfd;
510 int ret;
512 pfd.fd = in;
513 pfd.events = POLLIN;
514 ret = poll(&pfd, 1, 1000 * keepalive_in_sec);
516 if (ret < 0) {
517 if (errno == EINTR)
518 continue;
519 else
520 break;
521 } else if (ret == 0) {
522 /* no data; send a keepalive packet */
523 static const char buf[] = "0005\1";
524 write_or_die(1, buf, sizeof(buf) - 1);
525 continue;
526 } /* else there is actual data to read */
529 sz = xread(in, data, sizeof(data));
530 if (sz <= 0)
531 break;
533 if (use_keepalive == KEEPALIVE_AFTER_NUL && !keepalive_active) {
534 const char *p = memchr(data, '\0', sz);
535 if (p) {
537 * The NUL tells us to start sending keepalives. Make
538 * sure we send any other data we read along
539 * with it.
541 keepalive_active = 1;
542 send_sideband(1, 2, data, p - data, use_sideband);
543 send_sideband(1, 2, p + 1, sz - (p - data + 1), use_sideband);
544 continue;
549 * Either we're not looking for a NUL signal, or we didn't see
550 * it yet; just pass along the data.
552 send_sideband(1, 2, data, sz, use_sideband);
554 close(in);
555 return 0;
558 static void hmac_hash(unsigned char *out,
559 const char *key_in, size_t key_len,
560 const char *text, size_t text_len)
562 unsigned char key[GIT_MAX_BLKSZ];
563 unsigned char k_ipad[GIT_MAX_BLKSZ];
564 unsigned char k_opad[GIT_MAX_BLKSZ];
565 int i;
566 git_hash_ctx ctx;
568 /* RFC 2104 2. (1) */
569 memset(key, '\0', GIT_MAX_BLKSZ);
570 if (the_hash_algo->blksz < key_len) {
571 the_hash_algo->init_fn(&ctx);
572 the_hash_algo->update_fn(&ctx, key_in, key_len);
573 the_hash_algo->final_fn(key, &ctx);
574 } else {
575 memcpy(key, key_in, key_len);
578 /* RFC 2104 2. (2) & (5) */
579 for (i = 0; i < sizeof(key); i++) {
580 k_ipad[i] = key[i] ^ 0x36;
581 k_opad[i] = key[i] ^ 0x5c;
584 /* RFC 2104 2. (3) & (4) */
585 the_hash_algo->init_fn(&ctx);
586 the_hash_algo->update_fn(&ctx, k_ipad, sizeof(k_ipad));
587 the_hash_algo->update_fn(&ctx, text, text_len);
588 the_hash_algo->final_fn(out, &ctx);
590 /* RFC 2104 2. (6) & (7) */
591 the_hash_algo->init_fn(&ctx);
592 the_hash_algo->update_fn(&ctx, k_opad, sizeof(k_opad));
593 the_hash_algo->update_fn(&ctx, out, the_hash_algo->rawsz);
594 the_hash_algo->final_fn(out, &ctx);
597 static char *prepare_push_cert_nonce(const char *path, timestamp_t stamp)
599 struct strbuf buf = STRBUF_INIT;
600 unsigned char hash[GIT_MAX_RAWSZ];
602 strbuf_addf(&buf, "%s:%"PRItime, path, stamp);
603 hmac_hash(hash, buf.buf, buf.len, cert_nonce_seed, strlen(cert_nonce_seed));
604 strbuf_release(&buf);
606 /* RFC 2104 5. HMAC-SHA1 or HMAC-SHA256 */
607 strbuf_addf(&buf, "%"PRItime"-%.*s", stamp, (int)the_hash_algo->hexsz, hash_to_hex(hash));
608 return strbuf_detach(&buf, NULL);
612 * Return zero if a and b are equal up to n bytes and nonzero if they are not.
613 * This operation is guaranteed to run in constant time to avoid leaking data.
615 static int constant_memequal(const char *a, const char *b, size_t n)
617 int res = 0;
618 size_t i;
620 for (i = 0; i < n; i++)
621 res |= a[i] ^ b[i];
622 return res;
625 static const char *check_nonce(const char *buf)
627 size_t noncelen;
628 const char *found = find_commit_header(buf, "nonce", &noncelen);
629 char *nonce = found ? xmemdupz(found, noncelen) : NULL;
630 timestamp_t stamp, ostamp;
631 char *bohmac, *expect = NULL;
632 const char *retval = NONCE_BAD;
634 if (!nonce) {
635 retval = NONCE_MISSING;
636 goto leave;
637 } else if (!push_cert_nonce) {
638 retval = NONCE_UNSOLICITED;
639 goto leave;
640 } else if (!strcmp(push_cert_nonce, nonce)) {
641 retval = NONCE_OK;
642 goto leave;
645 if (!stateless_rpc) {
646 /* returned nonce MUST match what we gave out earlier */
647 retval = NONCE_BAD;
648 goto leave;
652 * In stateless mode, we may be receiving a nonce issued by
653 * another instance of the server that serving the same
654 * repository, and the timestamps may not match, but the
655 * nonce-seed and dir should match, so we can recompute and
656 * report the time slop.
658 * In addition, when a nonce issued by another instance has
659 * timestamp within receive.certnonceslop seconds, we pretend
660 * as if we issued that nonce when reporting to the hook.
663 /* nonce is concat(<seconds-since-epoch>, "-", <hmac>) */
664 if (*nonce <= '0' || '9' < *nonce) {
665 retval = NONCE_BAD;
666 goto leave;
668 stamp = parse_timestamp(nonce, &bohmac, 10);
669 if (bohmac == nonce || bohmac[0] != '-') {
670 retval = NONCE_BAD;
671 goto leave;
674 expect = prepare_push_cert_nonce(service_dir, stamp);
675 if (noncelen != strlen(expect)) {
676 /* This is not even the right size. */
677 retval = NONCE_BAD;
678 goto leave;
680 if (constant_memequal(expect, nonce, noncelen)) {
681 /* Not what we would have signed earlier */
682 retval = NONCE_BAD;
683 goto leave;
687 * By how many seconds is this nonce stale? Negative value
688 * would mean it was issued by another server with its clock
689 * skewed in the future.
691 ostamp = parse_timestamp(push_cert_nonce, NULL, 10);
692 nonce_stamp_slop = (long)ostamp - (long)stamp;
694 if (nonce_stamp_slop_limit &&
695 labs(nonce_stamp_slop) <= nonce_stamp_slop_limit) {
697 * Pretend as if the received nonce (which passes the
698 * HMAC check, so it is not a forged by third-party)
699 * is what we issued.
701 free((void *)push_cert_nonce);
702 push_cert_nonce = xstrdup(nonce);
703 retval = NONCE_OK;
704 } else {
705 retval = NONCE_SLOP;
708 leave:
709 free(nonce);
710 free(expect);
711 return retval;
715 * Return 1 if there is no push_cert or if the push options in push_cert are
716 * the same as those in the argument; 0 otherwise.
718 static int check_cert_push_options(const struct string_list *push_options)
720 const char *buf = push_cert.buf;
722 const char *option;
723 size_t optionlen;
724 int options_seen = 0;
726 int retval = 1;
728 if (!*buf)
729 return 1;
731 while ((option = find_commit_header(buf, "push-option", &optionlen))) {
732 buf = option + optionlen + 1;
733 options_seen++;
734 if (options_seen > push_options->nr
735 || xstrncmpz(push_options->items[options_seen - 1].string,
736 option, optionlen))
737 return 0;
740 if (options_seen != push_options->nr)
741 retval = 0;
743 return retval;
746 static void prepare_push_cert_sha1(struct child_process *proc)
748 static int already_done;
750 if (!push_cert.len)
751 return;
753 if (!already_done) {
754 int bogs /* beginning_of_gpg_sig */;
756 already_done = 1;
757 if (write_object_file(push_cert.buf, push_cert.len, OBJ_BLOB,
758 &push_cert_oid))
759 oidclr(&push_cert_oid, the_repository->hash_algo);
761 memset(&sigcheck, '\0', sizeof(sigcheck));
763 bogs = parse_signed_buffer(push_cert.buf, push_cert.len);
764 sigcheck.payload = xmemdupz(push_cert.buf, bogs);
765 sigcheck.payload_len = bogs;
766 check_signature(&sigcheck, push_cert.buf + bogs,
767 push_cert.len - bogs);
769 nonce_status = check_nonce(sigcheck.payload);
771 if (!is_null_oid(&push_cert_oid)) {
772 strvec_pushf(&proc->env, "GIT_PUSH_CERT=%s",
773 oid_to_hex(&push_cert_oid));
774 strvec_pushf(&proc->env, "GIT_PUSH_CERT_SIGNER=%s",
775 sigcheck.signer ? sigcheck.signer : "");
776 strvec_pushf(&proc->env, "GIT_PUSH_CERT_KEY=%s",
777 sigcheck.key ? sigcheck.key : "");
778 strvec_pushf(&proc->env, "GIT_PUSH_CERT_STATUS=%c",
779 sigcheck.result);
780 if (push_cert_nonce) {
781 strvec_pushf(&proc->env,
782 "GIT_PUSH_CERT_NONCE=%s",
783 push_cert_nonce);
784 strvec_pushf(&proc->env,
785 "GIT_PUSH_CERT_NONCE_STATUS=%s",
786 nonce_status);
787 if (nonce_status == NONCE_SLOP)
788 strvec_pushf(&proc->env,
789 "GIT_PUSH_CERT_NONCE_SLOP=%ld",
790 nonce_stamp_slop);
795 struct receive_hook_feed_state {
796 struct command *cmd;
797 struct ref_push_report *report;
798 int skip_broken;
799 struct strbuf buf;
800 const struct string_list *push_options;
803 typedef int (*feed_fn)(void *, const char **, size_t *);
804 static int run_and_feed_hook(const char *hook_name, feed_fn feed,
805 struct receive_hook_feed_state *feed_state)
807 struct child_process proc = CHILD_PROCESS_INIT;
808 struct async muxer;
809 int code;
810 const char *hook_path = find_hook(the_repository, hook_name);
812 if (!hook_path)
813 return 0;
815 strvec_push(&proc.args, hook_path);
816 proc.in = -1;
817 proc.stdout_to_stderr = 1;
818 proc.trace2_hook_name = hook_name;
820 if (feed_state->push_options) {
821 size_t i;
822 for (i = 0; i < feed_state->push_options->nr; i++)
823 strvec_pushf(&proc.env,
824 "GIT_PUSH_OPTION_%"PRIuMAX"=%s",
825 (uintmax_t)i,
826 feed_state->push_options->items[i].string);
827 strvec_pushf(&proc.env, "GIT_PUSH_OPTION_COUNT=%"PRIuMAX"",
828 (uintmax_t)feed_state->push_options->nr);
829 } else
830 strvec_pushf(&proc.env, "GIT_PUSH_OPTION_COUNT");
832 if (tmp_objdir)
833 strvec_pushv(&proc.env, tmp_objdir_env(tmp_objdir));
835 if (use_sideband) {
836 memset(&muxer, 0, sizeof(muxer));
837 muxer.proc = copy_to_sideband;
838 muxer.in = -1;
839 code = start_async(&muxer);
840 if (code)
841 return code;
842 proc.err = muxer.in;
845 prepare_push_cert_sha1(&proc);
847 code = start_command(&proc);
848 if (code) {
849 if (use_sideband)
850 finish_async(&muxer);
851 return code;
854 sigchain_push(SIGPIPE, SIG_IGN);
856 while (1) {
857 const char *buf;
858 size_t n;
859 if (feed(feed_state, &buf, &n))
860 break;
861 if (write_in_full(proc.in, buf, n) < 0)
862 break;
864 close(proc.in);
865 if (use_sideband)
866 finish_async(&muxer);
868 sigchain_pop(SIGPIPE);
870 return finish_command(&proc);
873 static int feed_receive_hook(void *state_, const char **bufp, size_t *sizep)
875 struct receive_hook_feed_state *state = state_;
876 struct command *cmd = state->cmd;
878 while (cmd &&
879 state->skip_broken && (cmd->error_string || cmd->did_not_exist))
880 cmd = cmd->next;
881 if (!cmd)
882 return -1; /* EOF */
883 if (!bufp)
884 return 0; /* OK, can feed something. */
885 strbuf_reset(&state->buf);
886 if (!state->report)
887 state->report = cmd->report;
888 if (state->report) {
889 struct object_id *old_oid;
890 struct object_id *new_oid;
891 const char *ref_name;
893 old_oid = state->report->old_oid ? state->report->old_oid : &cmd->old_oid;
894 new_oid = state->report->new_oid ? state->report->new_oid : &cmd->new_oid;
895 ref_name = state->report->ref_name ? state->report->ref_name : cmd->ref_name;
896 strbuf_addf(&state->buf, "%s %s %s\n",
897 oid_to_hex(old_oid), oid_to_hex(new_oid),
898 ref_name);
899 state->report = state->report->next;
900 if (!state->report)
901 state->cmd = cmd->next;
902 } else {
903 strbuf_addf(&state->buf, "%s %s %s\n",
904 oid_to_hex(&cmd->old_oid), oid_to_hex(&cmd->new_oid),
905 cmd->ref_name);
906 state->cmd = cmd->next;
908 if (bufp) {
909 *bufp = state->buf.buf;
910 *sizep = state->buf.len;
912 return 0;
915 static int run_receive_hook(struct command *commands,
916 const char *hook_name,
917 int skip_broken,
918 const struct string_list *push_options)
920 struct receive_hook_feed_state state;
921 int status;
923 strbuf_init(&state.buf, 0);
924 state.cmd = commands;
925 state.skip_broken = skip_broken;
926 state.report = NULL;
927 if (feed_receive_hook(&state, NULL, NULL))
928 return 0;
929 state.cmd = commands;
930 state.push_options = push_options;
931 status = run_and_feed_hook(hook_name, feed_receive_hook, &state);
932 strbuf_release(&state.buf);
933 return status;
936 static int run_update_hook(struct command *cmd)
938 struct child_process proc = CHILD_PROCESS_INIT;
939 int code;
940 const char *hook_path = find_hook(the_repository, "update");
942 if (!hook_path)
943 return 0;
945 strvec_push(&proc.args, hook_path);
946 strvec_push(&proc.args, cmd->ref_name);
947 strvec_push(&proc.args, oid_to_hex(&cmd->old_oid));
948 strvec_push(&proc.args, oid_to_hex(&cmd->new_oid));
950 proc.no_stdin = 1;
951 proc.stdout_to_stderr = 1;
952 proc.err = use_sideband ? -1 : 0;
953 proc.trace2_hook_name = "update";
955 code = start_command(&proc);
956 if (code)
957 return code;
958 if (use_sideband)
959 copy_to_sideband(proc.err, -1, NULL);
960 return finish_command(&proc);
963 static struct command *find_command_by_refname(struct command *list,
964 const char *refname)
966 for (; list; list = list->next)
967 if (!strcmp(list->ref_name, refname))
968 return list;
969 return NULL;
972 static int read_proc_receive_report(struct packet_reader *reader,
973 struct command *commands,
974 struct strbuf *errmsg)
976 struct command *cmd;
977 struct command *hint = NULL;
978 struct ref_push_report *report = NULL;
979 int new_report = 0;
980 int code = 0;
981 int once = 0;
982 int response = 0;
984 for (;;) {
985 struct object_id old_oid, new_oid;
986 const char *head;
987 const char *refname;
988 char *p;
989 enum packet_read_status status;
991 status = packet_reader_read(reader);
992 if (status != PACKET_READ_NORMAL) {
993 /* Check whether proc-receive exited abnormally */
994 if (status == PACKET_READ_EOF && !response) {
995 strbuf_addstr(errmsg, "proc-receive exited abnormally");
996 return -1;
998 break;
1000 response++;
1002 head = reader->line;
1003 p = strchr(head, ' ');
1004 if (!p) {
1005 strbuf_addf(errmsg, "proc-receive reported incomplete status line: '%s'\n", head);
1006 code = -1;
1007 continue;
1009 *p++ = '\0';
1010 if (!strcmp(head, "option")) {
1011 const char *key, *val;
1013 if (!hint || !(report || new_report)) {
1014 if (!once++)
1015 strbuf_addstr(errmsg, "proc-receive reported 'option' without a matching 'ok/ng' directive\n");
1016 code = -1;
1017 continue;
1019 if (new_report) {
1020 if (!hint->report) {
1021 CALLOC_ARRAY(hint->report, 1);
1022 report = hint->report;
1023 } else {
1024 report = hint->report;
1025 while (report->next)
1026 report = report->next;
1027 report->next = xcalloc(1, sizeof(struct ref_push_report));
1028 report = report->next;
1030 new_report = 0;
1032 key = p;
1033 p = strchr(key, ' ');
1034 if (p)
1035 *p++ = '\0';
1036 val = p;
1037 if (!strcmp(key, "refname"))
1038 report->ref_name = xstrdup_or_null(val);
1039 else if (!strcmp(key, "old-oid") && val &&
1040 !parse_oid_hex(val, &old_oid, &val))
1041 report->old_oid = oiddup(&old_oid);
1042 else if (!strcmp(key, "new-oid") && val &&
1043 !parse_oid_hex(val, &new_oid, &val))
1044 report->new_oid = oiddup(&new_oid);
1045 else if (!strcmp(key, "forced-update"))
1046 report->forced_update = 1;
1047 else if (!strcmp(key, "fall-through"))
1048 /* Fall through, let 'receive-pack' to execute it. */
1049 hint->run_proc_receive = 0;
1050 continue;
1053 report = NULL;
1054 new_report = 0;
1055 refname = p;
1056 p = strchr(refname, ' ');
1057 if (p)
1058 *p++ = '\0';
1059 if (strcmp(head, "ok") && strcmp(head, "ng")) {
1060 strbuf_addf(errmsg, "proc-receive reported bad status '%s' on ref '%s'\n",
1061 head, refname);
1062 code = -1;
1063 continue;
1066 /* first try searching at our hint, falling back to all refs */
1067 if (hint)
1068 hint = find_command_by_refname(hint, refname);
1069 if (!hint)
1070 hint = find_command_by_refname(commands, refname);
1071 if (!hint) {
1072 strbuf_addf(errmsg, "proc-receive reported status on unknown ref: %s\n",
1073 refname);
1074 code = -1;
1075 continue;
1077 if (!hint->run_proc_receive) {
1078 strbuf_addf(errmsg, "proc-receive reported status on unexpected ref: %s\n",
1079 refname);
1080 code = -1;
1081 continue;
1083 hint->run_proc_receive |= RUN_PROC_RECEIVE_RETURNED;
1084 if (!strcmp(head, "ng")) {
1085 if (p)
1086 hint->error_string = xstrdup(p);
1087 else
1088 hint->error_string = "failed";
1089 code = -1;
1090 continue;
1092 new_report = 1;
1095 for (cmd = commands; cmd; cmd = cmd->next)
1096 if (cmd->run_proc_receive && !cmd->error_string &&
1097 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED)) {
1098 cmd->error_string = "proc-receive failed to report status";
1099 code = -1;
1101 return code;
1104 static int run_proc_receive_hook(struct command *commands,
1105 const struct string_list *push_options)
1107 struct child_process proc = CHILD_PROCESS_INIT;
1108 struct async muxer;
1109 struct command *cmd;
1110 struct packet_reader reader;
1111 struct strbuf cap = STRBUF_INIT;
1112 struct strbuf errmsg = STRBUF_INIT;
1113 int hook_use_push_options = 0;
1114 int version = 0;
1115 int code;
1116 const char *hook_path = find_hook(the_repository, "proc-receive");
1118 if (!hook_path) {
1119 rp_error("cannot find hook 'proc-receive'");
1120 return -1;
1123 strvec_push(&proc.args, hook_path);
1124 proc.in = -1;
1125 proc.out = -1;
1126 proc.trace2_hook_name = "proc-receive";
1128 if (use_sideband) {
1129 memset(&muxer, 0, sizeof(muxer));
1130 muxer.proc = copy_to_sideband;
1131 muxer.in = -1;
1132 code = start_async(&muxer);
1133 if (code)
1134 return code;
1135 proc.err = muxer.in;
1136 } else {
1137 proc.err = 0;
1140 code = start_command(&proc);
1141 if (code) {
1142 if (use_sideband)
1143 finish_async(&muxer);
1144 return code;
1147 sigchain_push(SIGPIPE, SIG_IGN);
1149 /* Version negotiaton */
1150 packet_reader_init(&reader, proc.out, NULL, 0,
1151 PACKET_READ_CHOMP_NEWLINE |
1152 PACKET_READ_GENTLE_ON_EOF);
1153 if (use_atomic)
1154 strbuf_addstr(&cap, " atomic");
1155 if (use_push_options)
1156 strbuf_addstr(&cap, " push-options");
1157 if (cap.len) {
1158 code = packet_write_fmt_gently(proc.in, "version=1%c%s\n", '\0', cap.buf + 1);
1159 strbuf_release(&cap);
1160 } else {
1161 code = packet_write_fmt_gently(proc.in, "version=1\n");
1163 if (!code)
1164 code = packet_flush_gently(proc.in);
1166 if (!code)
1167 for (;;) {
1168 int linelen;
1169 enum packet_read_status status;
1171 status = packet_reader_read(&reader);
1172 if (status != PACKET_READ_NORMAL) {
1173 /* Check whether proc-receive exited abnormally */
1174 if (status == PACKET_READ_EOF)
1175 code = -1;
1176 break;
1179 if (reader.pktlen > 8 && starts_with(reader.line, "version=")) {
1180 version = atoi(reader.line + 8);
1181 linelen = strlen(reader.line);
1182 if (linelen < reader.pktlen) {
1183 const char *feature_list = reader.line + linelen + 1;
1184 if (parse_feature_request(feature_list, "push-options"))
1185 hook_use_push_options = 1;
1190 if (code) {
1191 strbuf_addstr(&errmsg, "fail to negotiate version with proc-receive hook");
1192 goto cleanup;
1195 switch (version) {
1196 case 0:
1197 /* fallthrough */
1198 case 1:
1199 break;
1200 default:
1201 strbuf_addf(&errmsg, "proc-receive version '%d' is not supported",
1202 version);
1203 code = -1;
1204 goto cleanup;
1207 /* Send commands */
1208 for (cmd = commands; cmd; cmd = cmd->next) {
1209 if (!cmd->run_proc_receive || cmd->skip_update || cmd->error_string)
1210 continue;
1211 code = packet_write_fmt_gently(proc.in, "%s %s %s",
1212 oid_to_hex(&cmd->old_oid),
1213 oid_to_hex(&cmd->new_oid),
1214 cmd->ref_name);
1215 if (code)
1216 break;
1218 if (!code)
1219 code = packet_flush_gently(proc.in);
1220 if (code) {
1221 strbuf_addstr(&errmsg, "fail to write commands to proc-receive hook");
1222 goto cleanup;
1225 /* Send push options */
1226 if (hook_use_push_options) {
1227 struct string_list_item *item;
1229 for_each_string_list_item(item, push_options) {
1230 code = packet_write_fmt_gently(proc.in, "%s", item->string);
1231 if (code)
1232 break;
1234 if (!code)
1235 code = packet_flush_gently(proc.in);
1236 if (code) {
1237 strbuf_addstr(&errmsg,
1238 "fail to write push-options to proc-receive hook");
1239 goto cleanup;
1243 /* Read result from proc-receive */
1244 code = read_proc_receive_report(&reader, commands, &errmsg);
1246 cleanup:
1247 close(proc.in);
1248 close(proc.out);
1249 if (use_sideband)
1250 finish_async(&muxer);
1251 if (finish_command(&proc))
1252 code = -1;
1253 if (errmsg.len >0) {
1254 char *p = errmsg.buf;
1256 p += errmsg.len - 1;
1257 if (*p == '\n')
1258 *p = '\0';
1259 rp_error("%s", errmsg.buf);
1260 strbuf_release(&errmsg);
1262 sigchain_pop(SIGPIPE);
1264 return code;
1267 static const char *refuse_unconfigured_deny_msg =
1268 N_("By default, updating the current branch in a non-bare repository\n"
1269 "is denied, because it will make the index and work tree inconsistent\n"
1270 "with what you pushed, and will require 'git reset --hard' to match\n"
1271 "the work tree to HEAD.\n"
1272 "\n"
1273 "You can set the 'receive.denyCurrentBranch' configuration variable\n"
1274 "to 'ignore' or 'warn' in the remote repository to allow pushing into\n"
1275 "its current branch; however, this is not recommended unless you\n"
1276 "arranged to update its work tree to match what you pushed in some\n"
1277 "other way.\n"
1278 "\n"
1279 "To squelch this message and still keep the default behaviour, set\n"
1280 "'receive.denyCurrentBranch' configuration variable to 'refuse'.");
1282 static void refuse_unconfigured_deny(void)
1284 rp_error("%s", _(refuse_unconfigured_deny_msg));
1287 static const char *refuse_unconfigured_deny_delete_current_msg =
1288 N_("By default, deleting the current branch is denied, because the next\n"
1289 "'git clone' won't result in any file checked out, causing confusion.\n"
1290 "\n"
1291 "You can set 'receive.denyDeleteCurrent' configuration variable to\n"
1292 "'warn' or 'ignore' in the remote repository to allow deleting the\n"
1293 "current branch, with or without a warning message.\n"
1294 "\n"
1295 "To squelch this message, you can set it to 'refuse'.");
1297 static void refuse_unconfigured_deny_delete_current(void)
1299 rp_error("%s", _(refuse_unconfigured_deny_delete_current_msg));
1302 static const struct object_id *command_singleton_iterator(void *cb_data);
1303 static int update_shallow_ref(struct command *cmd, struct shallow_info *si)
1305 struct shallow_lock shallow_lock = SHALLOW_LOCK_INIT;
1306 struct oid_array extra = OID_ARRAY_INIT;
1307 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1308 uint32_t mask = 1 << (cmd->index % 32);
1309 int i;
1311 trace_printf_key(&trace_shallow,
1312 "shallow: update_shallow_ref %s\n", cmd->ref_name);
1313 for (i = 0; i < si->shallow->nr; i++)
1314 if (si->used_shallow[i] &&
1315 (si->used_shallow[i][cmd->index / 32] & mask) &&
1316 !delayed_reachability_test(si, i))
1317 oid_array_append(&extra, &si->shallow->oid[i]);
1319 opt.env = tmp_objdir_env(tmp_objdir);
1320 setup_alternate_shallow(&shallow_lock, &opt.shallow_file, &extra);
1321 if (check_connected(command_singleton_iterator, cmd, &opt)) {
1322 rollback_shallow_file(the_repository, &shallow_lock);
1323 oid_array_clear(&extra);
1324 return -1;
1327 commit_shallow_file(the_repository, &shallow_lock);
1330 * Make sure setup_alternate_shallow() for the next ref does
1331 * not lose these new roots..
1333 for (i = 0; i < extra.nr; i++)
1334 register_shallow(the_repository, &extra.oid[i]);
1336 si->shallow_ref[cmd->index] = 0;
1337 oid_array_clear(&extra);
1338 return 0;
1342 * NEEDSWORK: we should consolidate various implementations of "are we
1343 * on an unborn branch?" test into one, and make the unified one more
1344 * robust. !get_sha1() based check used here and elsewhere would not
1345 * allow us to tell an unborn branch from corrupt ref, for example.
1346 * For the purpose of fixing "deploy-to-update does not work when
1347 * pushing into an empty repository" issue, this should suffice for
1348 * now.
1350 static int head_has_history(void)
1352 struct object_id oid;
1354 return !repo_get_oid(the_repository, "HEAD", &oid);
1357 static const char *push_to_deploy(unsigned char *sha1,
1358 struct strvec *env,
1359 const char *work_tree)
1361 struct child_process child = CHILD_PROCESS_INIT;
1363 strvec_pushl(&child.args, "update-index", "-q", "--ignore-submodules",
1364 "--refresh", NULL);
1365 strvec_pushv(&child.env, env->v);
1366 child.dir = work_tree;
1367 child.no_stdin = 1;
1368 child.stdout_to_stderr = 1;
1369 child.git_cmd = 1;
1370 if (run_command(&child))
1371 return "Up-to-date check failed";
1373 /* run_command() does not clean up completely; reinitialize */
1374 child_process_init(&child);
1375 strvec_pushl(&child.args, "diff-files", "--quiet",
1376 "--ignore-submodules", "--", NULL);
1377 strvec_pushv(&child.env, env->v);
1378 child.dir = work_tree;
1379 child.no_stdin = 1;
1380 child.stdout_to_stderr = 1;
1381 child.git_cmd = 1;
1382 if (run_command(&child))
1383 return "Working directory has unstaged changes";
1385 child_process_init(&child);
1386 strvec_pushl(&child.args, "diff-index", "--quiet", "--cached",
1387 "--ignore-submodules",
1388 /* diff-index with either HEAD or an empty tree */
1389 head_has_history() ? "HEAD" : empty_tree_oid_hex(the_repository->hash_algo),
1390 "--", NULL);
1391 strvec_pushv(&child.env, env->v);
1392 child.no_stdin = 1;
1393 child.no_stdout = 1;
1394 child.stdout_to_stderr = 0;
1395 child.git_cmd = 1;
1396 if (run_command(&child))
1397 return "Working directory has staged changes";
1399 child_process_init(&child);
1400 strvec_pushl(&child.args, "read-tree", "-u", "-m", hash_to_hex(sha1),
1401 NULL);
1402 strvec_pushv(&child.env, env->v);
1403 child.dir = work_tree;
1404 child.no_stdin = 1;
1405 child.no_stdout = 1;
1406 child.stdout_to_stderr = 0;
1407 child.git_cmd = 1;
1408 if (run_command(&child))
1409 return "Could not update working tree to new HEAD";
1411 return NULL;
1414 static const char *push_to_checkout_hook = "push-to-checkout";
1416 static const char *push_to_checkout(unsigned char *hash,
1417 int *invoked_hook,
1418 struct strvec *env,
1419 const char *work_tree)
1421 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1422 opt.invoked_hook = invoked_hook;
1424 strvec_pushf(env, "GIT_WORK_TREE=%s", absolute_path(work_tree));
1425 strvec_pushv(&opt.env, env->v);
1426 strvec_push(&opt.args, hash_to_hex(hash));
1427 if (run_hooks_opt(the_repository, push_to_checkout_hook, &opt))
1428 return "push-to-checkout hook declined";
1429 else
1430 return NULL;
1433 static const char *update_worktree(unsigned char *sha1, const struct worktree *worktree)
1435 const char *retval, *git_dir;
1436 struct strvec env = STRVEC_INIT;
1437 int invoked_hook;
1439 if (!worktree || !worktree->path)
1440 BUG("worktree->path must be non-NULL");
1442 if (worktree->is_bare)
1443 return "denyCurrentBranch = updateInstead needs a worktree";
1444 git_dir = get_worktree_git_dir(worktree);
1446 strvec_pushf(&env, "GIT_DIR=%s", absolute_path(git_dir));
1448 retval = push_to_checkout(sha1, &invoked_hook, &env, worktree->path);
1449 if (!invoked_hook)
1450 retval = push_to_deploy(sha1, &env, worktree->path);
1452 strvec_clear(&env);
1453 return retval;
1456 static const char *update(struct command *cmd, struct shallow_info *si)
1458 const char *name = cmd->ref_name;
1459 struct strbuf namespaced_name_buf = STRBUF_INIT;
1460 static char *namespaced_name;
1461 const char *ret;
1462 struct object_id *old_oid = &cmd->old_oid;
1463 struct object_id *new_oid = &cmd->new_oid;
1464 int do_update_worktree = 0;
1465 struct worktree **worktrees = get_worktrees();
1466 const struct worktree *worktree =
1467 find_shared_symref(worktrees, "HEAD", name);
1469 /* only refs/... are allowed */
1470 if (!starts_with(name, "refs/") ||
1471 check_refname_format(name + 5, is_null_oid(new_oid) ?
1472 REFNAME_ALLOW_ONELEVEL : 0)) {
1473 rp_error("refusing to update funny ref '%s' remotely", name);
1474 ret = "funny refname";
1475 goto out;
1478 strbuf_addf(&namespaced_name_buf, "%s%s", get_git_namespace(), name);
1479 free(namespaced_name);
1480 namespaced_name = strbuf_detach(&namespaced_name_buf, NULL);
1482 if (worktree && !worktree->is_bare) {
1483 switch (deny_current_branch) {
1484 case DENY_IGNORE:
1485 break;
1486 case DENY_WARN:
1487 rp_warning("updating the current branch");
1488 break;
1489 case DENY_REFUSE:
1490 case DENY_UNCONFIGURED:
1491 rp_error("refusing to update checked out branch: %s", name);
1492 if (deny_current_branch == DENY_UNCONFIGURED)
1493 refuse_unconfigured_deny();
1494 ret = "branch is currently checked out";
1495 goto out;
1496 case DENY_UPDATE_INSTEAD:
1497 /* pass -- let other checks intervene first */
1498 do_update_worktree = 1;
1499 break;
1503 if (!is_null_oid(new_oid) && !repo_has_object_file(the_repository, new_oid)) {
1504 error("unpack should have generated %s, "
1505 "but I can't find it!", oid_to_hex(new_oid));
1506 ret = "bad pack";
1507 goto out;
1510 if (!is_null_oid(old_oid) && is_null_oid(new_oid)) {
1511 if (deny_deletes && starts_with(name, "refs/heads/")) {
1512 rp_error("denying ref deletion for %s", name);
1513 ret = "deletion prohibited";
1514 goto out;
1517 if (worktree || (head_name && !strcmp(namespaced_name, head_name))) {
1518 switch (deny_delete_current) {
1519 case DENY_IGNORE:
1520 break;
1521 case DENY_WARN:
1522 rp_warning("deleting the current branch");
1523 break;
1524 case DENY_REFUSE:
1525 case DENY_UNCONFIGURED:
1526 case DENY_UPDATE_INSTEAD:
1527 if (deny_delete_current == DENY_UNCONFIGURED)
1528 refuse_unconfigured_deny_delete_current();
1529 rp_error("refusing to delete the current branch: %s", name);
1530 ret = "deletion of the current branch prohibited";
1531 goto out;
1532 default:
1533 ret = "Invalid denyDeleteCurrent setting";
1534 goto out;
1539 if (deny_non_fast_forwards && !is_null_oid(new_oid) &&
1540 !is_null_oid(old_oid) &&
1541 starts_with(name, "refs/heads/")) {
1542 struct object *old_object, *new_object;
1543 struct commit *old_commit, *new_commit;
1544 int ret2;
1546 old_object = parse_object(the_repository, old_oid);
1547 new_object = parse_object(the_repository, new_oid);
1549 if (!old_object || !new_object ||
1550 old_object->type != OBJ_COMMIT ||
1551 new_object->type != OBJ_COMMIT) {
1552 error("bad sha1 objects for %s", name);
1553 ret = "bad ref";
1554 goto out;
1556 old_commit = (struct commit *)old_object;
1557 new_commit = (struct commit *)new_object;
1558 ret2 = repo_in_merge_bases(the_repository, old_commit, new_commit);
1559 if (ret2 < 0)
1560 exit(128);
1561 if (!ret2) {
1562 rp_error("denying non-fast-forward %s"
1563 " (you should pull first)", name);
1564 ret = "non-fast-forward";
1565 goto out;
1568 if (run_update_hook(cmd)) {
1569 rp_error("hook declined to update %s", name);
1570 ret = "hook declined";
1571 goto out;
1574 if (do_update_worktree) {
1575 ret = update_worktree(new_oid->hash, worktree);
1576 if (ret)
1577 goto out;
1580 if (is_null_oid(new_oid)) {
1581 struct strbuf err = STRBUF_INIT;
1582 if (!parse_object(the_repository, old_oid)) {
1583 old_oid = NULL;
1584 if (refs_ref_exists(get_main_ref_store(the_repository), name)) {
1585 rp_warning("allowing deletion of corrupt ref");
1586 } else {
1587 rp_warning("deleting a non-existent ref");
1588 cmd->did_not_exist = 1;
1591 if (ref_transaction_delete(transaction,
1592 namespaced_name,
1593 old_oid,
1594 NULL, 0,
1595 "push", &err)) {
1596 rp_error("%s", err.buf);
1597 ret = "failed to delete";
1598 } else {
1599 ret = NULL; /* good */
1601 strbuf_release(&err);
1603 else {
1604 struct strbuf err = STRBUF_INIT;
1605 if (shallow_update && si->shallow_ref[cmd->index] &&
1606 update_shallow_ref(cmd, si)) {
1607 ret = "shallow error";
1608 goto out;
1611 if (ref_transaction_update(transaction,
1612 namespaced_name,
1613 new_oid, old_oid,
1614 NULL, NULL,
1615 0, "push",
1616 &err)) {
1617 rp_error("%s", err.buf);
1618 ret = "failed to update ref";
1619 } else {
1620 ret = NULL; /* good */
1622 strbuf_release(&err);
1625 out:
1626 free_worktrees(worktrees);
1627 return ret;
1630 static void run_update_post_hook(struct command *commands)
1632 struct command *cmd;
1633 struct child_process proc = CHILD_PROCESS_INIT;
1634 const char *hook;
1636 hook = find_hook(the_repository, "post-update");
1637 if (!hook)
1638 return;
1640 for (cmd = commands; cmd; cmd = cmd->next) {
1641 if (cmd->error_string || cmd->did_not_exist)
1642 continue;
1643 if (!proc.args.nr)
1644 strvec_push(&proc.args, hook);
1645 strvec_push(&proc.args, cmd->ref_name);
1647 if (!proc.args.nr)
1648 return;
1650 proc.no_stdin = 1;
1651 proc.stdout_to_stderr = 1;
1652 proc.err = use_sideband ? -1 : 0;
1653 proc.trace2_hook_name = "post-update";
1655 if (!start_command(&proc)) {
1656 if (use_sideband)
1657 copy_to_sideband(proc.err, -1, NULL);
1658 finish_command(&proc);
1662 static void check_aliased_update_internal(struct command *cmd,
1663 struct string_list *list,
1664 const char *dst_name, int flag)
1666 struct string_list_item *item;
1667 struct command *dst_cmd;
1669 if (!(flag & REF_ISSYMREF))
1670 return;
1672 if (!dst_name) {
1673 rp_error("refusing update to broken symref '%s'", cmd->ref_name);
1674 cmd->skip_update = 1;
1675 cmd->error_string = "broken symref";
1676 return;
1678 dst_name = strip_namespace(dst_name);
1680 if (!(item = string_list_lookup(list, dst_name)))
1681 return;
1683 cmd->skip_update = 1;
1685 dst_cmd = (struct command *) item->util;
1687 if (oideq(&cmd->old_oid, &dst_cmd->old_oid) &&
1688 oideq(&cmd->new_oid, &dst_cmd->new_oid))
1689 return;
1691 dst_cmd->skip_update = 1;
1693 rp_error("refusing inconsistent update between symref '%s' (%s..%s) and"
1694 " its target '%s' (%s..%s)",
1695 cmd->ref_name,
1696 repo_find_unique_abbrev(the_repository, &cmd->old_oid, DEFAULT_ABBREV),
1697 repo_find_unique_abbrev(the_repository, &cmd->new_oid, DEFAULT_ABBREV),
1698 dst_cmd->ref_name,
1699 repo_find_unique_abbrev(the_repository, &dst_cmd->old_oid, DEFAULT_ABBREV),
1700 repo_find_unique_abbrev(the_repository, &dst_cmd->new_oid, DEFAULT_ABBREV));
1702 cmd->error_string = dst_cmd->error_string =
1703 "inconsistent aliased update";
1706 static void check_aliased_update(struct command *cmd, struct string_list *list)
1708 struct strbuf buf = STRBUF_INIT;
1709 const char *dst_name;
1710 int flag;
1712 strbuf_addf(&buf, "%s%s", get_git_namespace(), cmd->ref_name);
1713 dst_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1714 buf.buf, 0, NULL, &flag);
1715 check_aliased_update_internal(cmd, list, dst_name, flag);
1716 strbuf_release(&buf);
1719 static void check_aliased_updates(struct command *commands)
1721 struct command *cmd;
1722 struct string_list ref_list = STRING_LIST_INIT_NODUP;
1724 for (cmd = commands; cmd; cmd = cmd->next) {
1725 struct string_list_item *item =
1726 string_list_append(&ref_list, cmd->ref_name);
1727 item->util = (void *)cmd;
1729 string_list_sort(&ref_list);
1731 for (cmd = commands; cmd; cmd = cmd->next) {
1732 if (!cmd->error_string)
1733 check_aliased_update(cmd, &ref_list);
1736 string_list_clear(&ref_list, 0);
1739 static const struct object_id *command_singleton_iterator(void *cb_data)
1741 struct command **cmd_list = cb_data;
1742 struct command *cmd = *cmd_list;
1744 if (!cmd || is_null_oid(&cmd->new_oid))
1745 return NULL;
1746 *cmd_list = NULL; /* this returns only one */
1747 return &cmd->new_oid;
1750 static void set_connectivity_errors(struct command *commands,
1751 struct shallow_info *si)
1753 struct command *cmd;
1755 for (cmd = commands; cmd; cmd = cmd->next) {
1756 struct command *singleton = cmd;
1757 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1759 if (shallow_update && si->shallow_ref[cmd->index])
1760 /* to be checked in update_shallow_ref() */
1761 continue;
1763 opt.env = tmp_objdir_env(tmp_objdir);
1764 if (!check_connected(command_singleton_iterator, &singleton,
1765 &opt))
1766 continue;
1768 cmd->error_string = "missing necessary objects";
1772 struct iterate_data {
1773 struct command *cmds;
1774 struct shallow_info *si;
1777 static const struct object_id *iterate_receive_command_list(void *cb_data)
1779 struct iterate_data *data = cb_data;
1780 struct command **cmd_list = &data->cmds;
1781 struct command *cmd = *cmd_list;
1783 for (; cmd; cmd = cmd->next) {
1784 if (shallow_update && data->si->shallow_ref[cmd->index])
1785 /* to be checked in update_shallow_ref() */
1786 continue;
1787 if (!is_null_oid(&cmd->new_oid) && !cmd->skip_update) {
1788 *cmd_list = cmd->next;
1789 return &cmd->new_oid;
1792 return NULL;
1795 static void reject_updates_to_hidden(struct command *commands)
1797 struct strbuf refname_full = STRBUF_INIT;
1798 size_t prefix_len;
1799 struct command *cmd;
1801 strbuf_addstr(&refname_full, get_git_namespace());
1802 prefix_len = refname_full.len;
1804 for (cmd = commands; cmd; cmd = cmd->next) {
1805 if (cmd->error_string)
1806 continue;
1808 strbuf_setlen(&refname_full, prefix_len);
1809 strbuf_addstr(&refname_full, cmd->ref_name);
1811 if (!ref_is_hidden(cmd->ref_name, refname_full.buf, &hidden_refs))
1812 continue;
1813 if (is_null_oid(&cmd->new_oid))
1814 cmd->error_string = "deny deleting a hidden ref";
1815 else
1816 cmd->error_string = "deny updating a hidden ref";
1819 strbuf_release(&refname_full);
1822 static int should_process_cmd(struct command *cmd)
1824 return !cmd->error_string && !cmd->skip_update;
1827 static void BUG_if_skipped_connectivity_check(struct command *commands,
1828 struct shallow_info *si)
1830 struct command *cmd;
1832 for (cmd = commands; cmd; cmd = cmd->next) {
1833 if (should_process_cmd(cmd) && si->shallow_ref[cmd->index])
1834 bug("connectivity check has not been run on ref %s",
1835 cmd->ref_name);
1837 BUG_if_bug("connectivity check skipped???");
1840 static void execute_commands_non_atomic(struct command *commands,
1841 struct shallow_info *si)
1843 struct command *cmd;
1844 struct strbuf err = STRBUF_INIT;
1846 for (cmd = commands; cmd; cmd = cmd->next) {
1847 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1848 continue;
1850 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1851 &err);
1852 if (!transaction) {
1853 rp_error("%s", err.buf);
1854 strbuf_reset(&err);
1855 cmd->error_string = "transaction failed to start";
1856 continue;
1859 cmd->error_string = update(cmd, si);
1861 if (!cmd->error_string
1862 && ref_transaction_commit(transaction, &err)) {
1863 rp_error("%s", err.buf);
1864 strbuf_reset(&err);
1865 cmd->error_string = "failed to update ref";
1867 ref_transaction_free(transaction);
1869 strbuf_release(&err);
1872 static void execute_commands_atomic(struct command *commands,
1873 struct shallow_info *si)
1875 struct command *cmd;
1876 struct strbuf err = STRBUF_INIT;
1877 const char *reported_error = "atomic push failure";
1879 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1880 &err);
1881 if (!transaction) {
1882 rp_error("%s", err.buf);
1883 strbuf_reset(&err);
1884 reported_error = "transaction failed to start";
1885 goto failure;
1888 for (cmd = commands; cmd; cmd = cmd->next) {
1889 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1890 continue;
1892 cmd->error_string = update(cmd, si);
1894 if (cmd->error_string)
1895 goto failure;
1898 if (ref_transaction_commit(transaction, &err)) {
1899 rp_error("%s", err.buf);
1900 reported_error = "atomic transaction failed";
1901 goto failure;
1903 goto cleanup;
1905 failure:
1906 for (cmd = commands; cmd; cmd = cmd->next)
1907 if (!cmd->error_string)
1908 cmd->error_string = reported_error;
1910 cleanup:
1911 ref_transaction_free(transaction);
1912 strbuf_release(&err);
1915 static void execute_commands(struct command *commands,
1916 const char *unpacker_error,
1917 struct shallow_info *si,
1918 const struct string_list *push_options)
1920 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1921 struct command *cmd;
1922 struct iterate_data data;
1923 struct async muxer;
1924 int err_fd = 0;
1925 int run_proc_receive = 0;
1927 if (unpacker_error) {
1928 for (cmd = commands; cmd; cmd = cmd->next)
1929 cmd->error_string = "unpacker error";
1930 return;
1933 if (use_sideband) {
1934 memset(&muxer, 0, sizeof(muxer));
1935 muxer.proc = copy_to_sideband;
1936 muxer.in = -1;
1937 if (!start_async(&muxer))
1938 err_fd = muxer.in;
1939 /* ...else, continue without relaying sideband */
1942 data.cmds = commands;
1943 data.si = si;
1944 opt.err_fd = err_fd;
1945 opt.progress = err_fd && !quiet;
1946 opt.env = tmp_objdir_env(tmp_objdir);
1947 opt.exclude_hidden_refs_section = "receive";
1949 if (check_connected(iterate_receive_command_list, &data, &opt))
1950 set_connectivity_errors(commands, si);
1952 if (use_sideband)
1953 finish_async(&muxer);
1955 reject_updates_to_hidden(commands);
1958 * Try to find commands that have special prefix in their reference names,
1959 * and mark them to run an external "proc-receive" hook later.
1961 if (proc_receive_ref) {
1962 for (cmd = commands; cmd; cmd = cmd->next) {
1963 if (!should_process_cmd(cmd))
1964 continue;
1966 if (proc_receive_ref_matches(cmd)) {
1967 cmd->run_proc_receive = RUN_PROC_RECEIVE_SCHEDULED;
1968 run_proc_receive = 1;
1973 if (run_receive_hook(commands, "pre-receive", 0, push_options)) {
1974 for (cmd = commands; cmd; cmd = cmd->next) {
1975 if (!cmd->error_string)
1976 cmd->error_string = "pre-receive hook declined";
1978 return;
1982 * If there is no command ready to run, should return directly to destroy
1983 * temporary data in the quarantine area.
1985 for (cmd = commands; cmd && cmd->error_string; cmd = cmd->next)
1986 ; /* nothing */
1987 if (!cmd)
1988 return;
1991 * Now we'll start writing out refs, which means the objects need
1992 * to be in their final positions so that other processes can see them.
1994 if (tmp_objdir_migrate(tmp_objdir) < 0) {
1995 for (cmd = commands; cmd; cmd = cmd->next) {
1996 if (!cmd->error_string)
1997 cmd->error_string = "unable to migrate objects to permanent storage";
1999 return;
2001 tmp_objdir = NULL;
2003 check_aliased_updates(commands);
2005 free(head_name_to_free);
2006 head_name = head_name_to_free = refs_resolve_refdup(get_main_ref_store(the_repository),
2007 "HEAD", 0, NULL,
2008 NULL);
2010 if (run_proc_receive &&
2011 run_proc_receive_hook(commands, push_options))
2012 for (cmd = commands; cmd; cmd = cmd->next)
2013 if (!cmd->error_string &&
2014 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED) &&
2015 (cmd->run_proc_receive || use_atomic))
2016 cmd->error_string = "fail to run proc-receive hook";
2018 if (use_atomic)
2019 execute_commands_atomic(commands, si);
2020 else
2021 execute_commands_non_atomic(commands, si);
2023 if (shallow_update)
2024 BUG_if_skipped_connectivity_check(commands, si);
2027 static struct command **queue_command(struct command **tail,
2028 const char *line,
2029 int linelen)
2031 struct object_id old_oid, new_oid;
2032 struct command *cmd;
2033 const char *refname;
2034 int reflen;
2035 const char *p;
2037 if (parse_oid_hex(line, &old_oid, &p) ||
2038 *p++ != ' ' ||
2039 parse_oid_hex(p, &new_oid, &p) ||
2040 *p++ != ' ')
2041 die("protocol error: expected old/new/ref, got '%s'", line);
2043 refname = p;
2044 reflen = linelen - (p - line);
2045 FLEX_ALLOC_MEM(cmd, ref_name, refname, reflen);
2046 oidcpy(&cmd->old_oid, &old_oid);
2047 oidcpy(&cmd->new_oid, &new_oid);
2048 *tail = cmd;
2049 return &cmd->next;
2052 static void free_commands(struct command *commands)
2054 while (commands) {
2055 struct command *next = commands->next;
2057 free(commands);
2058 commands = next;
2062 static void queue_commands_from_cert(struct command **tail,
2063 struct strbuf *push_cert)
2065 const char *boc, *eoc;
2067 if (*tail)
2068 die("protocol error: got both push certificate and unsigned commands");
2070 boc = strstr(push_cert->buf, "\n\n");
2071 if (!boc)
2072 die("malformed push certificate %.*s", 100, push_cert->buf);
2073 else
2074 boc += 2;
2075 eoc = push_cert->buf + parse_signed_buffer(push_cert->buf, push_cert->len);
2077 while (boc < eoc) {
2078 const char *eol = memchr(boc, '\n', eoc - boc);
2079 tail = queue_command(tail, boc, eol ? eol - boc : eoc - boc);
2080 boc = eol ? eol + 1 : eoc;
2084 static struct command *read_head_info(struct packet_reader *reader,
2085 struct oid_array *shallow)
2087 struct command *commands = NULL;
2088 struct command **p = &commands;
2089 for (;;) {
2090 int linelen;
2092 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2093 break;
2095 if (reader->pktlen > 8 && starts_with(reader->line, "shallow ")) {
2096 struct object_id oid;
2097 if (get_oid_hex(reader->line + 8, &oid))
2098 die("protocol error: expected shallow sha, got '%s'",
2099 reader->line + 8);
2100 oid_array_append(shallow, &oid);
2101 continue;
2104 linelen = strlen(reader->line);
2105 if (linelen < reader->pktlen) {
2106 const char *feature_list = reader->line + linelen + 1;
2107 const char *hash = NULL;
2108 const char *client_sid;
2109 size_t len = 0;
2110 if (parse_feature_request(feature_list, "report-status"))
2111 report_status = 1;
2112 if (parse_feature_request(feature_list, "report-status-v2"))
2113 report_status_v2 = 1;
2114 if (parse_feature_request(feature_list, "side-band-64k"))
2115 use_sideband = LARGE_PACKET_MAX;
2116 if (parse_feature_request(feature_list, "quiet"))
2117 quiet = 1;
2118 if (advertise_atomic_push
2119 && parse_feature_request(feature_list, "atomic"))
2120 use_atomic = 1;
2121 if (advertise_push_options
2122 && parse_feature_request(feature_list, "push-options"))
2123 use_push_options = 1;
2124 hash = parse_feature_value(feature_list, "object-format", &len, NULL);
2125 if (!hash) {
2126 hash = hash_algos[GIT_HASH_SHA1].name;
2127 len = strlen(hash);
2129 if (xstrncmpz(the_hash_algo->name, hash, len))
2130 die("error: unsupported object format '%s'", hash);
2131 client_sid = parse_feature_value(feature_list, "session-id", &len, NULL);
2132 if (client_sid) {
2133 char *sid = xstrndup(client_sid, len);
2134 trace2_data_string("transfer", NULL, "client-sid", client_sid);
2135 free(sid);
2139 if (!strcmp(reader->line, "push-cert")) {
2140 int true_flush = 0;
2141 int saved_options = reader->options;
2142 reader->options &= ~PACKET_READ_CHOMP_NEWLINE;
2144 for (;;) {
2145 packet_reader_read(reader);
2146 if (reader->status == PACKET_READ_FLUSH) {
2147 true_flush = 1;
2148 break;
2150 if (reader->status != PACKET_READ_NORMAL) {
2151 die("protocol error: got an unexpected packet");
2153 if (!strcmp(reader->line, "push-cert-end\n"))
2154 break; /* end of cert */
2155 strbuf_addstr(&push_cert, reader->line);
2157 reader->options = saved_options;
2159 if (true_flush)
2160 break;
2161 continue;
2164 p = queue_command(p, reader->line, linelen);
2167 if (push_cert.len)
2168 queue_commands_from_cert(p, &push_cert);
2170 return commands;
2173 static void read_push_options(struct packet_reader *reader,
2174 struct string_list *options)
2176 while (1) {
2177 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2178 break;
2180 string_list_append(options, reader->line);
2184 static const char *parse_pack_header(struct pack_header *hdr)
2186 switch (read_pack_header(0, hdr)) {
2187 case PH_ERROR_EOF:
2188 return "eof before pack header was fully read";
2190 case PH_ERROR_PACK_SIGNATURE:
2191 return "protocol error (pack signature mismatch detected)";
2193 case PH_ERROR_PROTOCOL:
2194 return "protocol error (pack version unsupported)";
2196 default:
2197 return "unknown error in parse_pack_header";
2199 case 0:
2200 return NULL;
2204 static struct tempfile *pack_lockfile;
2206 static void push_header_arg(struct strvec *args, struct pack_header *hdr)
2208 strvec_pushf(args, "--pack_header=%"PRIu32",%"PRIu32,
2209 ntohl(hdr->hdr_version), ntohl(hdr->hdr_entries));
2212 static const char *unpack(int err_fd, struct shallow_info *si)
2214 struct pack_header hdr;
2215 const char *hdr_err;
2216 int status;
2217 struct child_process child = CHILD_PROCESS_INIT;
2218 int fsck_objects = (receive_fsck_objects >= 0
2219 ? receive_fsck_objects
2220 : transfer_fsck_objects >= 0
2221 ? transfer_fsck_objects
2222 : 0);
2224 hdr_err = parse_pack_header(&hdr);
2225 if (hdr_err) {
2226 if (err_fd > 0)
2227 close(err_fd);
2228 return hdr_err;
2231 if (si->nr_ours || si->nr_theirs) {
2232 alt_shallow_file = setup_temporary_shallow(si->shallow);
2233 strvec_push(&child.args, "--shallow-file");
2234 strvec_push(&child.args, alt_shallow_file);
2237 tmp_objdir = tmp_objdir_create("incoming");
2238 if (!tmp_objdir) {
2239 if (err_fd > 0)
2240 close(err_fd);
2241 return "unable to create temporary object directory";
2243 strvec_pushv(&child.env, tmp_objdir_env(tmp_objdir));
2246 * Normally we just pass the tmp_objdir environment to the child
2247 * processes that do the heavy lifting, but we may need to see these
2248 * objects ourselves to set up shallow information.
2250 tmp_objdir_add_as_alternate(tmp_objdir);
2252 if (ntohl(hdr.hdr_entries) < unpack_limit) {
2253 strvec_push(&child.args, "unpack-objects");
2254 push_header_arg(&child.args, &hdr);
2255 if (quiet)
2256 strvec_push(&child.args, "-q");
2257 if (fsck_objects)
2258 strvec_pushf(&child.args, "--strict%s",
2259 fsck_msg_types.buf);
2260 if (max_input_size)
2261 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2262 (uintmax_t)max_input_size);
2263 child.no_stdout = 1;
2264 child.err = err_fd;
2265 child.git_cmd = 1;
2266 status = run_command(&child);
2267 if (status)
2268 return "unpack-objects abnormal exit";
2269 } else {
2270 char hostname[HOST_NAME_MAX + 1];
2271 char *lockfile;
2273 strvec_pushl(&child.args, "index-pack", "--stdin", NULL);
2274 push_header_arg(&child.args, &hdr);
2276 if (xgethostname(hostname, sizeof(hostname)))
2277 xsnprintf(hostname, sizeof(hostname), "localhost");
2278 strvec_pushf(&child.args,
2279 "--keep=receive-pack %"PRIuMAX" on %s",
2280 (uintmax_t)getpid(),
2281 hostname);
2283 if (!quiet && err_fd)
2284 strvec_push(&child.args, "--show-resolving-progress");
2285 if (use_sideband)
2286 strvec_push(&child.args, "--report-end-of-input");
2287 if (fsck_objects)
2288 strvec_pushf(&child.args, "--strict%s",
2289 fsck_msg_types.buf);
2290 if (!reject_thin)
2291 strvec_push(&child.args, "--fix-thin");
2292 if (max_input_size)
2293 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2294 (uintmax_t)max_input_size);
2295 child.out = -1;
2296 child.err = err_fd;
2297 child.git_cmd = 1;
2298 status = start_command(&child);
2299 if (status)
2300 return "index-pack fork failed";
2302 lockfile = index_pack_lockfile(child.out, NULL);
2303 if (lockfile) {
2304 pack_lockfile = register_tempfile(lockfile);
2305 free(lockfile);
2307 close(child.out);
2309 status = finish_command(&child);
2310 if (status)
2311 return "index-pack abnormal exit";
2312 reprepare_packed_git(the_repository);
2314 return NULL;
2317 static const char *unpack_with_sideband(struct shallow_info *si)
2319 struct async muxer;
2320 const char *ret;
2322 if (!use_sideband)
2323 return unpack(0, si);
2325 use_keepalive = KEEPALIVE_AFTER_NUL;
2326 memset(&muxer, 0, sizeof(muxer));
2327 muxer.proc = copy_to_sideband;
2328 muxer.in = -1;
2329 if (start_async(&muxer))
2330 return NULL;
2332 ret = unpack(muxer.in, si);
2334 finish_async(&muxer);
2335 return ret;
2338 static void prepare_shallow_update(struct shallow_info *si)
2340 int i, j, k, bitmap_size = DIV_ROUND_UP(si->ref->nr, 32);
2342 ALLOC_ARRAY(si->used_shallow, si->shallow->nr);
2343 assign_shallow_commits_to_refs(si, si->used_shallow, NULL);
2345 CALLOC_ARRAY(si->need_reachability_test, si->shallow->nr);
2346 CALLOC_ARRAY(si->reachable, si->shallow->nr);
2347 CALLOC_ARRAY(si->shallow_ref, si->ref->nr);
2349 for (i = 0; i < si->nr_ours; i++)
2350 si->need_reachability_test[si->ours[i]] = 1;
2352 for (i = 0; i < si->shallow->nr; i++) {
2353 if (!si->used_shallow[i])
2354 continue;
2355 for (j = 0; j < bitmap_size; j++) {
2356 if (!si->used_shallow[i][j])
2357 continue;
2358 si->need_reachability_test[i]++;
2359 for (k = 0; k < 32; k++)
2360 if (si->used_shallow[i][j] & (1U << k))
2361 si->shallow_ref[j * 32 + k]++;
2365 * true for those associated with some refs and belong
2366 * in "ours" list aka "step 7 not done yet"
2368 si->need_reachability_test[i] =
2369 si->need_reachability_test[i] > 1;
2373 * keep hooks happy by forcing a temporary shallow file via
2374 * env variable because we can't add --shallow-file to every
2375 * command. check_connected() will be done with
2376 * true .git/shallow though.
2378 setenv(GIT_SHALLOW_FILE_ENVIRONMENT, alt_shallow_file, 1);
2381 static void update_shallow_info(struct command *commands,
2382 struct shallow_info *si,
2383 struct oid_array *ref)
2385 struct command *cmd;
2386 int *ref_status;
2387 remove_nonexistent_theirs_shallow(si);
2388 if (!si->nr_ours && !si->nr_theirs) {
2389 shallow_update = 0;
2390 return;
2393 for (cmd = commands; cmd; cmd = cmd->next) {
2394 if (is_null_oid(&cmd->new_oid))
2395 continue;
2396 oid_array_append(ref, &cmd->new_oid);
2397 cmd->index = ref->nr - 1;
2399 si->ref = ref;
2401 if (shallow_update) {
2402 prepare_shallow_update(si);
2403 return;
2406 ALLOC_ARRAY(ref_status, ref->nr);
2407 assign_shallow_commits_to_refs(si, NULL, ref_status);
2408 for (cmd = commands; cmd; cmd = cmd->next) {
2409 if (is_null_oid(&cmd->new_oid))
2410 continue;
2411 if (ref_status[cmd->index]) {
2412 cmd->error_string = "shallow update not allowed";
2413 cmd->skip_update = 1;
2416 free(ref_status);
2419 static void report(struct command *commands, const char *unpack_status)
2421 struct command *cmd;
2422 struct strbuf buf = STRBUF_INIT;
2424 packet_buf_write(&buf, "unpack %s\n",
2425 unpack_status ? unpack_status : "ok");
2426 for (cmd = commands; cmd; cmd = cmd->next) {
2427 if (!cmd->error_string)
2428 packet_buf_write(&buf, "ok %s\n",
2429 cmd->ref_name);
2430 else
2431 packet_buf_write(&buf, "ng %s %s\n",
2432 cmd->ref_name, cmd->error_string);
2434 packet_buf_flush(&buf);
2436 if (use_sideband)
2437 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2438 else
2439 write_or_die(1, buf.buf, buf.len);
2440 strbuf_release(&buf);
2443 static void report_v2(struct command *commands, const char *unpack_status)
2445 struct command *cmd;
2446 struct strbuf buf = STRBUF_INIT;
2447 struct ref_push_report *report;
2449 packet_buf_write(&buf, "unpack %s\n",
2450 unpack_status ? unpack_status : "ok");
2451 for (cmd = commands; cmd; cmd = cmd->next) {
2452 int count = 0;
2454 if (cmd->error_string) {
2455 packet_buf_write(&buf, "ng %s %s\n",
2456 cmd->ref_name,
2457 cmd->error_string);
2458 continue;
2460 packet_buf_write(&buf, "ok %s\n",
2461 cmd->ref_name);
2462 for (report = cmd->report; report; report = report->next) {
2463 if (count++ > 0)
2464 packet_buf_write(&buf, "ok %s\n",
2465 cmd->ref_name);
2466 if (report->ref_name)
2467 packet_buf_write(&buf, "option refname %s\n",
2468 report->ref_name);
2469 if (report->old_oid)
2470 packet_buf_write(&buf, "option old-oid %s\n",
2471 oid_to_hex(report->old_oid));
2472 if (report->new_oid)
2473 packet_buf_write(&buf, "option new-oid %s\n",
2474 oid_to_hex(report->new_oid));
2475 if (report->forced_update)
2476 packet_buf_write(&buf, "option forced-update\n");
2479 packet_buf_flush(&buf);
2481 if (use_sideband)
2482 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2483 else
2484 write_or_die(1, buf.buf, buf.len);
2485 strbuf_release(&buf);
2488 static int delete_only(struct command *commands)
2490 struct command *cmd;
2491 for (cmd = commands; cmd; cmd = cmd->next) {
2492 if (!is_null_oid(&cmd->new_oid))
2493 return 0;
2495 return 1;
2498 int cmd_receive_pack(int argc,
2499 const char **argv,
2500 const char *prefix,
2501 struct repository *repo UNUSED)
2503 int advertise_refs = 0;
2504 struct command *commands;
2505 struct oid_array shallow = OID_ARRAY_INIT;
2506 struct oid_array ref = OID_ARRAY_INIT;
2507 struct shallow_info si;
2508 struct packet_reader reader;
2510 struct option options[] = {
2511 OPT__QUIET(&quiet, N_("quiet")),
2512 OPT_HIDDEN_BOOL(0, "stateless-rpc", &stateless_rpc, NULL),
2513 OPT_HIDDEN_BOOL(0, "http-backend-info-refs", &advertise_refs, NULL),
2514 OPT_ALIAS(0, "advertise-refs", "http-backend-info-refs"),
2515 OPT_HIDDEN_BOOL(0, "reject-thin-pack-for-testing", &reject_thin, NULL),
2516 OPT_END()
2519 packet_trace_identity("receive-pack");
2521 argc = parse_options(argc, argv, prefix, options, receive_pack_usage, 0);
2523 if (argc > 1)
2524 usage_msg_opt(_("too many arguments"), receive_pack_usage, options);
2525 if (argc == 0)
2526 usage_msg_opt(_("you must specify a directory"), receive_pack_usage, options);
2528 service_dir = argv[0];
2530 setup_path();
2532 if (!enter_repo(service_dir, 0))
2533 die("'%s' does not appear to be a git repository", service_dir);
2535 git_config(receive_pack_config, NULL);
2536 if (cert_nonce_seed)
2537 push_cert_nonce = prepare_push_cert_nonce(service_dir, time(NULL));
2539 if (0 <= receive_unpack_limit)
2540 unpack_limit = receive_unpack_limit;
2541 else if (0 <= transfer_unpack_limit)
2542 unpack_limit = transfer_unpack_limit;
2544 switch (determine_protocol_version_server()) {
2545 case protocol_v2:
2547 * push support for protocol v2 has not been implemented yet,
2548 * so ignore the request to use v2 and fallback to using v0.
2550 break;
2551 case protocol_v1:
2553 * v1 is just the original protocol with a version string,
2554 * so just fall through after writing the version string.
2556 if (advertise_refs || !stateless_rpc)
2557 packet_write_fmt(1, "version 1\n");
2559 /* fallthrough */
2560 case protocol_v0:
2561 break;
2562 case protocol_unknown_version:
2563 BUG("unknown protocol version");
2566 if (advertise_refs || !stateless_rpc) {
2567 write_head_info();
2569 if (advertise_refs)
2570 return 0;
2572 packet_reader_init(&reader, 0, NULL, 0,
2573 PACKET_READ_CHOMP_NEWLINE |
2574 PACKET_READ_DIE_ON_ERR_PACKET);
2576 if ((commands = read_head_info(&reader, &shallow))) {
2577 const char *unpack_status = NULL;
2578 struct string_list push_options = STRING_LIST_INIT_DUP;
2580 if (use_push_options)
2581 read_push_options(&reader, &push_options);
2582 if (!check_cert_push_options(&push_options)) {
2583 struct command *cmd;
2584 for (cmd = commands; cmd; cmd = cmd->next)
2585 cmd->error_string = "inconsistent push options";
2588 prepare_shallow_info(&si, &shallow);
2589 if (!si.nr_ours && !si.nr_theirs)
2590 shallow_update = 0;
2591 if (!delete_only(commands)) {
2592 unpack_status = unpack_with_sideband(&si);
2593 update_shallow_info(commands, &si, &ref);
2595 use_keepalive = KEEPALIVE_ALWAYS;
2596 execute_commands(commands, unpack_status, &si,
2597 &push_options);
2598 delete_tempfile(&pack_lockfile);
2599 sigchain_push(SIGPIPE, SIG_IGN);
2600 if (report_status_v2)
2601 report_v2(commands, unpack_status);
2602 else if (report_status)
2603 report(commands, unpack_status);
2604 sigchain_pop(SIGPIPE);
2605 run_receive_hook(commands, "post-receive", 1,
2606 &push_options);
2607 run_update_post_hook(commands);
2608 free_commands(commands);
2609 string_list_clear(&push_options, 0);
2610 if (auto_gc) {
2611 struct child_process proc = CHILD_PROCESS_INIT;
2613 if (prepare_auto_maintenance(1, &proc)) {
2614 proc.no_stdin = 1;
2615 proc.stdout_to_stderr = 1;
2616 proc.err = use_sideband ? -1 : 0;
2618 if (!start_command(&proc)) {
2619 if (use_sideband)
2620 copy_to_sideband(proc.err, -1, NULL);
2621 finish_command(&proc);
2625 if (auto_update_server_info)
2626 update_server_info(0);
2627 clear_shallow_info(&si);
2629 if (use_sideband)
2630 packet_flush(1);
2631 oid_array_clear(&shallow);
2632 oid_array_clear(&ref);
2633 strvec_clear(&hidden_refs);
2634 free((void *)push_cert_nonce);
2635 return 0;