Start the 2.48 cycle
[git/gitster.git] / builtin / receive-pack.c
blobab5b20e39c5038cdf6e6f05f4d66278a9c1ac156
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 char *error_string_owned;
378 struct ref_push_report *report;
379 unsigned int skip_update:1,
380 did_not_exist:1,
381 run_proc_receive:2;
382 int index;
383 struct object_id old_oid;
384 struct object_id new_oid;
385 char ref_name[FLEX_ARRAY]; /* more */
388 static void proc_receive_ref_append(const char *prefix)
390 struct proc_receive_ref *ref_pattern;
391 char *p;
392 int len;
394 CALLOC_ARRAY(ref_pattern, 1);
395 p = strchr(prefix, ':');
396 if (p) {
397 while (prefix < p) {
398 if (*prefix == 'a')
399 ref_pattern->want_add = 1;
400 else if (*prefix == 'd')
401 ref_pattern->want_delete = 1;
402 else if (*prefix == 'm')
403 ref_pattern->want_modify = 1;
404 else if (*prefix == '!')
405 ref_pattern->negative_ref = 1;
406 prefix++;
408 prefix++;
409 } else {
410 ref_pattern->want_add = 1;
411 ref_pattern->want_delete = 1;
412 ref_pattern->want_modify = 1;
414 len = strlen(prefix);
415 while (len && prefix[len - 1] == '/')
416 len--;
417 ref_pattern->ref_prefix = xmemdupz(prefix, len);
418 if (!proc_receive_ref) {
419 proc_receive_ref = ref_pattern;
420 } else {
421 struct proc_receive_ref *end;
423 end = proc_receive_ref;
424 while (end->next)
425 end = end->next;
426 end->next = ref_pattern;
430 static int proc_receive_ref_matches(struct command *cmd)
432 struct proc_receive_ref *p;
434 if (!proc_receive_ref)
435 return 0;
437 for (p = proc_receive_ref; p; p = p->next) {
438 const char *match = p->ref_prefix;
439 const char *remains;
441 if (!p->want_add && is_null_oid(&cmd->old_oid))
442 continue;
443 else if (!p->want_delete && is_null_oid(&cmd->new_oid))
444 continue;
445 else if (!p->want_modify &&
446 !is_null_oid(&cmd->old_oid) &&
447 !is_null_oid(&cmd->new_oid))
448 continue;
450 if (skip_prefix(cmd->ref_name, match, &remains) &&
451 (!*remains || *remains == '/')) {
452 if (!p->negative_ref)
453 return 1;
454 } else if (p->negative_ref) {
455 return 1;
458 return 0;
461 static void report_message(const char *prefix, const char *err, va_list params)
463 int sz;
464 char msg[4096];
466 sz = xsnprintf(msg, sizeof(msg), "%s", prefix);
467 sz += vsnprintf(msg + sz, sizeof(msg) - sz, err, params);
468 if (sz > (sizeof(msg) - 1))
469 sz = sizeof(msg) - 1;
470 msg[sz++] = '\n';
472 if (use_sideband)
473 send_sideband(1, 2, msg, sz, use_sideband);
474 else
475 xwrite(2, msg, sz);
478 __attribute__((format (printf, 1, 2)))
479 static void rp_warning(const char *err, ...)
481 va_list params;
482 va_start(params, err);
483 report_message("warning: ", err, params);
484 va_end(params);
487 __attribute__((format (printf, 1, 2)))
488 static void rp_error(const char *err, ...)
490 va_list params;
491 va_start(params, err);
492 report_message("error: ", err, params);
493 va_end(params);
496 static int copy_to_sideband(int in, int out UNUSED, void *arg UNUSED)
498 char data[128];
499 int keepalive_active = 0;
501 if (keepalive_in_sec <= 0)
502 use_keepalive = KEEPALIVE_NEVER;
503 if (use_keepalive == KEEPALIVE_ALWAYS)
504 keepalive_active = 1;
506 while (1) {
507 ssize_t sz;
509 if (keepalive_active) {
510 struct pollfd pfd;
511 int ret;
513 pfd.fd = in;
514 pfd.events = POLLIN;
515 ret = poll(&pfd, 1, 1000 * keepalive_in_sec);
517 if (ret < 0) {
518 if (errno == EINTR)
519 continue;
520 else
521 break;
522 } else if (ret == 0) {
523 /* no data; send a keepalive packet */
524 static const char buf[] = "0005\1";
525 write_or_die(1, buf, sizeof(buf) - 1);
526 continue;
527 } /* else there is actual data to read */
530 sz = xread(in, data, sizeof(data));
531 if (sz <= 0)
532 break;
534 if (use_keepalive == KEEPALIVE_AFTER_NUL && !keepalive_active) {
535 const char *p = memchr(data, '\0', sz);
536 if (p) {
538 * The NUL tells us to start sending keepalives. Make
539 * sure we send any other data we read along
540 * with it.
542 keepalive_active = 1;
543 send_sideband(1, 2, data, p - data, use_sideband);
544 send_sideband(1, 2, p + 1, sz - (p - data + 1), use_sideband);
545 continue;
550 * Either we're not looking for a NUL signal, or we didn't see
551 * it yet; just pass along the data.
553 send_sideband(1, 2, data, sz, use_sideband);
555 close(in);
556 return 0;
559 static void hmac_hash(unsigned char *out,
560 const char *key_in, size_t key_len,
561 const char *text, size_t text_len)
563 unsigned char key[GIT_MAX_BLKSZ];
564 unsigned char k_ipad[GIT_MAX_BLKSZ];
565 unsigned char k_opad[GIT_MAX_BLKSZ];
566 int i;
567 git_hash_ctx ctx;
569 /* RFC 2104 2. (1) */
570 memset(key, '\0', GIT_MAX_BLKSZ);
571 if (the_hash_algo->blksz < key_len) {
572 the_hash_algo->init_fn(&ctx);
573 the_hash_algo->update_fn(&ctx, key_in, key_len);
574 the_hash_algo->final_fn(key, &ctx);
575 } else {
576 memcpy(key, key_in, key_len);
579 /* RFC 2104 2. (2) & (5) */
580 for (i = 0; i < sizeof(key); i++) {
581 k_ipad[i] = key[i] ^ 0x36;
582 k_opad[i] = key[i] ^ 0x5c;
585 /* RFC 2104 2. (3) & (4) */
586 the_hash_algo->init_fn(&ctx);
587 the_hash_algo->update_fn(&ctx, k_ipad, sizeof(k_ipad));
588 the_hash_algo->update_fn(&ctx, text, text_len);
589 the_hash_algo->final_fn(out, &ctx);
591 /* RFC 2104 2. (6) & (7) */
592 the_hash_algo->init_fn(&ctx);
593 the_hash_algo->update_fn(&ctx, k_opad, sizeof(k_opad));
594 the_hash_algo->update_fn(&ctx, out, the_hash_algo->rawsz);
595 the_hash_algo->final_fn(out, &ctx);
598 static char *prepare_push_cert_nonce(const char *path, timestamp_t stamp)
600 struct strbuf buf = STRBUF_INIT;
601 unsigned char hash[GIT_MAX_RAWSZ];
603 strbuf_addf(&buf, "%s:%"PRItime, path, stamp);
604 hmac_hash(hash, buf.buf, buf.len, cert_nonce_seed, strlen(cert_nonce_seed));
605 strbuf_release(&buf);
607 /* RFC 2104 5. HMAC-SHA1 or HMAC-SHA256 */
608 strbuf_addf(&buf, "%"PRItime"-%.*s", stamp, (int)the_hash_algo->hexsz, hash_to_hex(hash));
609 return strbuf_detach(&buf, NULL);
613 * Return zero if a and b are equal up to n bytes and nonzero if they are not.
614 * This operation is guaranteed to run in constant time to avoid leaking data.
616 static int constant_memequal(const char *a, const char *b, size_t n)
618 int res = 0;
619 size_t i;
621 for (i = 0; i < n; i++)
622 res |= a[i] ^ b[i];
623 return res;
626 static const char *check_nonce(const char *buf)
628 size_t noncelen;
629 const char *found = find_commit_header(buf, "nonce", &noncelen);
630 char *nonce = found ? xmemdupz(found, noncelen) : NULL;
631 timestamp_t stamp, ostamp;
632 char *bohmac, *expect = NULL;
633 const char *retval = NONCE_BAD;
635 if (!nonce) {
636 retval = NONCE_MISSING;
637 goto leave;
638 } else if (!push_cert_nonce) {
639 retval = NONCE_UNSOLICITED;
640 goto leave;
641 } else if (!strcmp(push_cert_nonce, nonce)) {
642 retval = NONCE_OK;
643 goto leave;
646 if (!stateless_rpc) {
647 /* returned nonce MUST match what we gave out earlier */
648 retval = NONCE_BAD;
649 goto leave;
653 * In stateless mode, we may be receiving a nonce issued by
654 * another instance of the server that serving the same
655 * repository, and the timestamps may not match, but the
656 * nonce-seed and dir should match, so we can recompute and
657 * report the time slop.
659 * In addition, when a nonce issued by another instance has
660 * timestamp within receive.certnonceslop seconds, we pretend
661 * as if we issued that nonce when reporting to the hook.
664 /* nonce is concat(<seconds-since-epoch>, "-", <hmac>) */
665 if (*nonce <= '0' || '9' < *nonce) {
666 retval = NONCE_BAD;
667 goto leave;
669 stamp = parse_timestamp(nonce, &bohmac, 10);
670 if (bohmac == nonce || bohmac[0] != '-') {
671 retval = NONCE_BAD;
672 goto leave;
675 expect = prepare_push_cert_nonce(service_dir, stamp);
676 if (noncelen != strlen(expect)) {
677 /* This is not even the right size. */
678 retval = NONCE_BAD;
679 goto leave;
681 if (constant_memequal(expect, nonce, noncelen)) {
682 /* Not what we would have signed earlier */
683 retval = NONCE_BAD;
684 goto leave;
688 * By how many seconds is this nonce stale? Negative value
689 * would mean it was issued by another server with its clock
690 * skewed in the future.
692 ostamp = parse_timestamp(push_cert_nonce, NULL, 10);
693 nonce_stamp_slop = (long)ostamp - (long)stamp;
695 if (nonce_stamp_slop_limit &&
696 labs(nonce_stamp_slop) <= nonce_stamp_slop_limit) {
698 * Pretend as if the received nonce (which passes the
699 * HMAC check, so it is not a forged by third-party)
700 * is what we issued.
702 free((void *)push_cert_nonce);
703 push_cert_nonce = xstrdup(nonce);
704 retval = NONCE_OK;
705 } else {
706 retval = NONCE_SLOP;
709 leave:
710 free(nonce);
711 free(expect);
712 return retval;
716 * Return 1 if there is no push_cert or if the push options in push_cert are
717 * the same as those in the argument; 0 otherwise.
719 static int check_cert_push_options(const struct string_list *push_options)
721 const char *buf = push_cert.buf;
723 const char *option;
724 size_t optionlen;
725 int options_seen = 0;
727 int retval = 1;
729 if (!*buf)
730 return 1;
732 while ((option = find_commit_header(buf, "push-option", &optionlen))) {
733 buf = option + optionlen + 1;
734 options_seen++;
735 if (options_seen > push_options->nr
736 || xstrncmpz(push_options->items[options_seen - 1].string,
737 option, optionlen))
738 return 0;
741 if (options_seen != push_options->nr)
742 retval = 0;
744 return retval;
747 static void prepare_push_cert_sha1(struct child_process *proc)
749 static int already_done;
751 if (!push_cert.len)
752 return;
754 if (!already_done) {
755 int bogs /* beginning_of_gpg_sig */;
757 already_done = 1;
758 if (write_object_file(push_cert.buf, push_cert.len, OBJ_BLOB,
759 &push_cert_oid))
760 oidclr(&push_cert_oid, the_repository->hash_algo);
762 memset(&sigcheck, '\0', sizeof(sigcheck));
764 bogs = parse_signed_buffer(push_cert.buf, push_cert.len);
765 sigcheck.payload = xmemdupz(push_cert.buf, bogs);
766 sigcheck.payload_len = bogs;
767 check_signature(&sigcheck, push_cert.buf + bogs,
768 push_cert.len - bogs);
770 nonce_status = check_nonce(sigcheck.payload);
772 if (!is_null_oid(&push_cert_oid)) {
773 strvec_pushf(&proc->env, "GIT_PUSH_CERT=%s",
774 oid_to_hex(&push_cert_oid));
775 strvec_pushf(&proc->env, "GIT_PUSH_CERT_SIGNER=%s",
776 sigcheck.signer ? sigcheck.signer : "");
777 strvec_pushf(&proc->env, "GIT_PUSH_CERT_KEY=%s",
778 sigcheck.key ? sigcheck.key : "");
779 strvec_pushf(&proc->env, "GIT_PUSH_CERT_STATUS=%c",
780 sigcheck.result);
781 if (push_cert_nonce) {
782 strvec_pushf(&proc->env,
783 "GIT_PUSH_CERT_NONCE=%s",
784 push_cert_nonce);
785 strvec_pushf(&proc->env,
786 "GIT_PUSH_CERT_NONCE_STATUS=%s",
787 nonce_status);
788 if (nonce_status == NONCE_SLOP)
789 strvec_pushf(&proc->env,
790 "GIT_PUSH_CERT_NONCE_SLOP=%ld",
791 nonce_stamp_slop);
796 struct receive_hook_feed_state {
797 struct command *cmd;
798 struct ref_push_report *report;
799 int skip_broken;
800 struct strbuf buf;
801 const struct string_list *push_options;
804 typedef int (*feed_fn)(void *, const char **, size_t *);
805 static int run_and_feed_hook(const char *hook_name, feed_fn feed,
806 struct receive_hook_feed_state *feed_state)
808 struct child_process proc = CHILD_PROCESS_INIT;
809 struct async muxer;
810 int code;
811 const char *hook_path = find_hook(the_repository, hook_name);
813 if (!hook_path)
814 return 0;
816 strvec_push(&proc.args, hook_path);
817 proc.in = -1;
818 proc.stdout_to_stderr = 1;
819 proc.trace2_hook_name = hook_name;
821 if (feed_state->push_options) {
822 size_t i;
823 for (i = 0; i < feed_state->push_options->nr; i++)
824 strvec_pushf(&proc.env,
825 "GIT_PUSH_OPTION_%"PRIuMAX"=%s",
826 (uintmax_t)i,
827 feed_state->push_options->items[i].string);
828 strvec_pushf(&proc.env, "GIT_PUSH_OPTION_COUNT=%"PRIuMAX"",
829 (uintmax_t)feed_state->push_options->nr);
830 } else
831 strvec_pushf(&proc.env, "GIT_PUSH_OPTION_COUNT");
833 if (tmp_objdir)
834 strvec_pushv(&proc.env, tmp_objdir_env(tmp_objdir));
836 if (use_sideband) {
837 memset(&muxer, 0, sizeof(muxer));
838 muxer.proc = copy_to_sideband;
839 muxer.in = -1;
840 code = start_async(&muxer);
841 if (code)
842 return code;
843 proc.err = muxer.in;
846 prepare_push_cert_sha1(&proc);
848 code = start_command(&proc);
849 if (code) {
850 if (use_sideband)
851 finish_async(&muxer);
852 return code;
855 sigchain_push(SIGPIPE, SIG_IGN);
857 while (1) {
858 const char *buf;
859 size_t n;
860 if (feed(feed_state, &buf, &n))
861 break;
862 if (write_in_full(proc.in, buf, n) < 0)
863 break;
865 close(proc.in);
866 if (use_sideband)
867 finish_async(&muxer);
869 sigchain_pop(SIGPIPE);
871 return finish_command(&proc);
874 static int feed_receive_hook(void *state_, const char **bufp, size_t *sizep)
876 struct receive_hook_feed_state *state = state_;
877 struct command *cmd = state->cmd;
879 while (cmd &&
880 state->skip_broken && (cmd->error_string || cmd->did_not_exist))
881 cmd = cmd->next;
882 if (!cmd)
883 return -1; /* EOF */
884 if (!bufp)
885 return 0; /* OK, can feed something. */
886 strbuf_reset(&state->buf);
887 if (!state->report)
888 state->report = cmd->report;
889 if (state->report) {
890 struct object_id *old_oid;
891 struct object_id *new_oid;
892 const char *ref_name;
894 old_oid = state->report->old_oid ? state->report->old_oid : &cmd->old_oid;
895 new_oid = state->report->new_oid ? state->report->new_oid : &cmd->new_oid;
896 ref_name = state->report->ref_name ? state->report->ref_name : cmd->ref_name;
897 strbuf_addf(&state->buf, "%s %s %s\n",
898 oid_to_hex(old_oid), oid_to_hex(new_oid),
899 ref_name);
900 state->report = state->report->next;
901 if (!state->report)
902 state->cmd = cmd->next;
903 } else {
904 strbuf_addf(&state->buf, "%s %s %s\n",
905 oid_to_hex(&cmd->old_oid), oid_to_hex(&cmd->new_oid),
906 cmd->ref_name);
907 state->cmd = cmd->next;
909 if (bufp) {
910 *bufp = state->buf.buf;
911 *sizep = state->buf.len;
913 return 0;
916 static int run_receive_hook(struct command *commands,
917 const char *hook_name,
918 int skip_broken,
919 const struct string_list *push_options)
921 struct receive_hook_feed_state state;
922 int status;
924 strbuf_init(&state.buf, 0);
925 state.cmd = commands;
926 state.skip_broken = skip_broken;
927 state.report = NULL;
928 if (feed_receive_hook(&state, NULL, NULL))
929 return 0;
930 state.cmd = commands;
931 state.push_options = push_options;
932 status = run_and_feed_hook(hook_name, feed_receive_hook, &state);
933 strbuf_release(&state.buf);
934 return status;
937 static int run_update_hook(struct command *cmd)
939 struct child_process proc = CHILD_PROCESS_INIT;
940 int code;
941 const char *hook_path = find_hook(the_repository, "update");
943 if (!hook_path)
944 return 0;
946 strvec_push(&proc.args, hook_path);
947 strvec_push(&proc.args, cmd->ref_name);
948 strvec_push(&proc.args, oid_to_hex(&cmd->old_oid));
949 strvec_push(&proc.args, oid_to_hex(&cmd->new_oid));
951 proc.no_stdin = 1;
952 proc.stdout_to_stderr = 1;
953 proc.err = use_sideband ? -1 : 0;
954 proc.trace2_hook_name = "update";
956 code = start_command(&proc);
957 if (code)
958 return code;
959 if (use_sideband)
960 copy_to_sideband(proc.err, -1, NULL);
961 return finish_command(&proc);
964 static struct command *find_command_by_refname(struct command *list,
965 const char *refname)
967 for (; list; list = list->next)
968 if (!strcmp(list->ref_name, refname))
969 return list;
970 return NULL;
973 static int read_proc_receive_report(struct packet_reader *reader,
974 struct command *commands,
975 struct strbuf *errmsg)
977 struct command *cmd;
978 struct command *hint = NULL;
979 struct ref_push_report *report = NULL;
980 int new_report = 0;
981 int code = 0;
982 int once = 0;
983 int response = 0;
985 for (;;) {
986 struct object_id old_oid, new_oid;
987 const char *head;
988 const char *refname;
989 char *p;
990 enum packet_read_status status;
992 status = packet_reader_read(reader);
993 if (status != PACKET_READ_NORMAL) {
994 /* Check whether proc-receive exited abnormally */
995 if (status == PACKET_READ_EOF && !response) {
996 strbuf_addstr(errmsg, "proc-receive exited abnormally");
997 return -1;
999 break;
1001 response++;
1003 head = reader->line;
1004 p = strchr(head, ' ');
1005 if (!p) {
1006 strbuf_addf(errmsg, "proc-receive reported incomplete status line: '%s'\n", head);
1007 code = -1;
1008 continue;
1010 *p++ = '\0';
1011 if (!strcmp(head, "option")) {
1012 const char *key, *val;
1014 if (!hint || !(report || new_report)) {
1015 if (!once++)
1016 strbuf_addstr(errmsg, "proc-receive reported 'option' without a matching 'ok/ng' directive\n");
1017 code = -1;
1018 continue;
1020 if (new_report) {
1021 if (!hint->report) {
1022 CALLOC_ARRAY(hint->report, 1);
1023 report = hint->report;
1024 } else {
1025 report = hint->report;
1026 while (report->next)
1027 report = report->next;
1028 report->next = xcalloc(1, sizeof(struct ref_push_report));
1029 report = report->next;
1031 new_report = 0;
1033 key = p;
1034 p = strchr(key, ' ');
1035 if (p)
1036 *p++ = '\0';
1037 val = p;
1038 if (!strcmp(key, "refname"))
1039 report->ref_name = xstrdup_or_null(val);
1040 else if (!strcmp(key, "old-oid") && val &&
1041 !parse_oid_hex(val, &old_oid, &val))
1042 report->old_oid = oiddup(&old_oid);
1043 else if (!strcmp(key, "new-oid") && val &&
1044 !parse_oid_hex(val, &new_oid, &val))
1045 report->new_oid = oiddup(&new_oid);
1046 else if (!strcmp(key, "forced-update"))
1047 report->forced_update = 1;
1048 else if (!strcmp(key, "fall-through"))
1049 /* Fall through, let 'receive-pack' to execute it. */
1050 hint->run_proc_receive = 0;
1051 continue;
1054 report = NULL;
1055 new_report = 0;
1056 refname = p;
1057 p = strchr(refname, ' ');
1058 if (p)
1059 *p++ = '\0';
1060 if (strcmp(head, "ok") && strcmp(head, "ng")) {
1061 strbuf_addf(errmsg, "proc-receive reported bad status '%s' on ref '%s'\n",
1062 head, refname);
1063 code = -1;
1064 continue;
1067 /* first try searching at our hint, falling back to all refs */
1068 if (hint)
1069 hint = find_command_by_refname(hint, refname);
1070 if (!hint)
1071 hint = find_command_by_refname(commands, refname);
1072 if (!hint) {
1073 strbuf_addf(errmsg, "proc-receive reported status on unknown ref: %s\n",
1074 refname);
1075 code = -1;
1076 continue;
1078 if (!hint->run_proc_receive) {
1079 strbuf_addf(errmsg, "proc-receive reported status on unexpected ref: %s\n",
1080 refname);
1081 code = -1;
1082 continue;
1084 hint->run_proc_receive |= RUN_PROC_RECEIVE_RETURNED;
1085 if (!strcmp(head, "ng")) {
1086 if (p)
1087 hint->error_string = hint->error_string_owned = xstrdup(p);
1088 else
1089 hint->error_string = "failed";
1090 code = -1;
1091 continue;
1093 new_report = 1;
1096 for (cmd = commands; cmd; cmd = cmd->next)
1097 if (cmd->run_proc_receive && !cmd->error_string &&
1098 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED)) {
1099 cmd->error_string = "proc-receive failed to report status";
1100 code = -1;
1102 return code;
1105 static int run_proc_receive_hook(struct command *commands,
1106 const struct string_list *push_options)
1108 struct child_process proc = CHILD_PROCESS_INIT;
1109 struct async muxer;
1110 struct command *cmd;
1111 struct packet_reader reader;
1112 struct strbuf cap = STRBUF_INIT;
1113 struct strbuf errmsg = STRBUF_INIT;
1114 int hook_use_push_options = 0;
1115 int version = 0;
1116 int code;
1117 const char *hook_path = find_hook(the_repository, "proc-receive");
1119 if (!hook_path) {
1120 rp_error("cannot find hook 'proc-receive'");
1121 return -1;
1124 strvec_push(&proc.args, hook_path);
1125 proc.in = -1;
1126 proc.out = -1;
1127 proc.trace2_hook_name = "proc-receive";
1129 if (use_sideband) {
1130 memset(&muxer, 0, sizeof(muxer));
1131 muxer.proc = copy_to_sideband;
1132 muxer.in = -1;
1133 code = start_async(&muxer);
1134 if (code)
1135 return code;
1136 proc.err = muxer.in;
1137 } else {
1138 proc.err = 0;
1141 code = start_command(&proc);
1142 if (code) {
1143 if (use_sideband)
1144 finish_async(&muxer);
1145 return code;
1148 sigchain_push(SIGPIPE, SIG_IGN);
1150 /* Version negotiaton */
1151 packet_reader_init(&reader, proc.out, NULL, 0,
1152 PACKET_READ_CHOMP_NEWLINE |
1153 PACKET_READ_GENTLE_ON_EOF);
1154 if (use_atomic)
1155 strbuf_addstr(&cap, " atomic");
1156 if (use_push_options)
1157 strbuf_addstr(&cap, " push-options");
1158 if (cap.len) {
1159 code = packet_write_fmt_gently(proc.in, "version=1%c%s\n", '\0', cap.buf + 1);
1160 strbuf_release(&cap);
1161 } else {
1162 code = packet_write_fmt_gently(proc.in, "version=1\n");
1164 if (!code)
1165 code = packet_flush_gently(proc.in);
1167 if (!code)
1168 for (;;) {
1169 int linelen;
1170 enum packet_read_status status;
1172 status = packet_reader_read(&reader);
1173 if (status != PACKET_READ_NORMAL) {
1174 /* Check whether proc-receive exited abnormally */
1175 if (status == PACKET_READ_EOF)
1176 code = -1;
1177 break;
1180 if (reader.pktlen > 8 && starts_with(reader.line, "version=")) {
1181 version = atoi(reader.line + 8);
1182 linelen = strlen(reader.line);
1183 if (linelen < reader.pktlen) {
1184 const char *feature_list = reader.line + linelen + 1;
1185 if (parse_feature_request(feature_list, "push-options"))
1186 hook_use_push_options = 1;
1191 if (code) {
1192 strbuf_addstr(&errmsg, "fail to negotiate version with proc-receive hook");
1193 goto cleanup;
1196 switch (version) {
1197 case 0:
1198 /* fallthrough */
1199 case 1:
1200 break;
1201 default:
1202 strbuf_addf(&errmsg, "proc-receive version '%d' is not supported",
1203 version);
1204 code = -1;
1205 goto cleanup;
1208 /* Send commands */
1209 for (cmd = commands; cmd; cmd = cmd->next) {
1210 if (!cmd->run_proc_receive || cmd->skip_update || cmd->error_string)
1211 continue;
1212 code = packet_write_fmt_gently(proc.in, "%s %s %s",
1213 oid_to_hex(&cmd->old_oid),
1214 oid_to_hex(&cmd->new_oid),
1215 cmd->ref_name);
1216 if (code)
1217 break;
1219 if (!code)
1220 code = packet_flush_gently(proc.in);
1221 if (code) {
1222 strbuf_addstr(&errmsg, "fail to write commands to proc-receive hook");
1223 goto cleanup;
1226 /* Send push options */
1227 if (hook_use_push_options) {
1228 struct string_list_item *item;
1230 for_each_string_list_item(item, push_options) {
1231 code = packet_write_fmt_gently(proc.in, "%s", item->string);
1232 if (code)
1233 break;
1235 if (!code)
1236 code = packet_flush_gently(proc.in);
1237 if (code) {
1238 strbuf_addstr(&errmsg,
1239 "fail to write push-options to proc-receive hook");
1240 goto cleanup;
1244 /* Read result from proc-receive */
1245 code = read_proc_receive_report(&reader, commands, &errmsg);
1247 cleanup:
1248 close(proc.in);
1249 close(proc.out);
1250 if (use_sideband)
1251 finish_async(&muxer);
1252 if (finish_command(&proc))
1253 code = -1;
1254 if (errmsg.len >0) {
1255 char *p = errmsg.buf;
1257 p += errmsg.len - 1;
1258 if (*p == '\n')
1259 *p = '\0';
1260 rp_error("%s", errmsg.buf);
1261 strbuf_release(&errmsg);
1263 sigchain_pop(SIGPIPE);
1265 return code;
1268 static const char *refuse_unconfigured_deny_msg =
1269 N_("By default, updating the current branch in a non-bare repository\n"
1270 "is denied, because it will make the index and work tree inconsistent\n"
1271 "with what you pushed, and will require 'git reset --hard' to match\n"
1272 "the work tree to HEAD.\n"
1273 "\n"
1274 "You can set the 'receive.denyCurrentBranch' configuration variable\n"
1275 "to 'ignore' or 'warn' in the remote repository to allow pushing into\n"
1276 "its current branch; however, this is not recommended unless you\n"
1277 "arranged to update its work tree to match what you pushed in some\n"
1278 "other way.\n"
1279 "\n"
1280 "To squelch this message and still keep the default behaviour, set\n"
1281 "'receive.denyCurrentBranch' configuration variable to 'refuse'.");
1283 static void refuse_unconfigured_deny(void)
1285 rp_error("%s", _(refuse_unconfigured_deny_msg));
1288 static const char *refuse_unconfigured_deny_delete_current_msg =
1289 N_("By default, deleting the current branch is denied, because the next\n"
1290 "'git clone' won't result in any file checked out, causing confusion.\n"
1291 "\n"
1292 "You can set 'receive.denyDeleteCurrent' configuration variable to\n"
1293 "'warn' or 'ignore' in the remote repository to allow deleting the\n"
1294 "current branch, with or without a warning message.\n"
1295 "\n"
1296 "To squelch this message, you can set it to 'refuse'.");
1298 static void refuse_unconfigured_deny_delete_current(void)
1300 rp_error("%s", _(refuse_unconfigured_deny_delete_current_msg));
1303 static const struct object_id *command_singleton_iterator(void *cb_data);
1304 static int update_shallow_ref(struct command *cmd, struct shallow_info *si)
1306 struct shallow_lock shallow_lock = SHALLOW_LOCK_INIT;
1307 struct oid_array extra = OID_ARRAY_INIT;
1308 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1309 uint32_t mask = 1 << (cmd->index % 32);
1310 int i;
1312 trace_printf_key(&trace_shallow,
1313 "shallow: update_shallow_ref %s\n", cmd->ref_name);
1314 for (i = 0; i < si->shallow->nr; i++)
1315 if (si->used_shallow[i] &&
1316 (si->used_shallow[i][cmd->index / 32] & mask) &&
1317 !delayed_reachability_test(si, i))
1318 oid_array_append(&extra, &si->shallow->oid[i]);
1320 opt.env = tmp_objdir_env(tmp_objdir);
1321 setup_alternate_shallow(&shallow_lock, &opt.shallow_file, &extra);
1322 if (check_connected(command_singleton_iterator, cmd, &opt)) {
1323 rollback_shallow_file(the_repository, &shallow_lock);
1324 oid_array_clear(&extra);
1325 return -1;
1328 commit_shallow_file(the_repository, &shallow_lock);
1331 * Make sure setup_alternate_shallow() for the next ref does
1332 * not lose these new roots..
1334 for (i = 0; i < extra.nr; i++)
1335 register_shallow(the_repository, &extra.oid[i]);
1337 si->shallow_ref[cmd->index] = 0;
1338 oid_array_clear(&extra);
1339 return 0;
1343 * NEEDSWORK: we should consolidate various implementations of "are we
1344 * on an unborn branch?" test into one, and make the unified one more
1345 * robust. !get_sha1() based check used here and elsewhere would not
1346 * allow us to tell an unborn branch from corrupt ref, for example.
1347 * For the purpose of fixing "deploy-to-update does not work when
1348 * pushing into an empty repository" issue, this should suffice for
1349 * now.
1351 static int head_has_history(void)
1353 struct object_id oid;
1355 return !repo_get_oid(the_repository, "HEAD", &oid);
1358 static const char *push_to_deploy(unsigned char *sha1,
1359 struct strvec *env,
1360 const char *work_tree)
1362 struct child_process child = CHILD_PROCESS_INIT;
1364 strvec_pushl(&child.args, "update-index", "-q", "--ignore-submodules",
1365 "--refresh", NULL);
1366 strvec_pushv(&child.env, env->v);
1367 child.dir = work_tree;
1368 child.no_stdin = 1;
1369 child.stdout_to_stderr = 1;
1370 child.git_cmd = 1;
1371 if (run_command(&child))
1372 return "Up-to-date check failed";
1374 /* run_command() does not clean up completely; reinitialize */
1375 child_process_init(&child);
1376 strvec_pushl(&child.args, "diff-files", "--quiet",
1377 "--ignore-submodules", "--", NULL);
1378 strvec_pushv(&child.env, env->v);
1379 child.dir = work_tree;
1380 child.no_stdin = 1;
1381 child.stdout_to_stderr = 1;
1382 child.git_cmd = 1;
1383 if (run_command(&child))
1384 return "Working directory has unstaged changes";
1386 child_process_init(&child);
1387 strvec_pushl(&child.args, "diff-index", "--quiet", "--cached",
1388 "--ignore-submodules",
1389 /* diff-index with either HEAD or an empty tree */
1390 head_has_history() ? "HEAD" : empty_tree_oid_hex(the_repository->hash_algo),
1391 "--", NULL);
1392 strvec_pushv(&child.env, env->v);
1393 child.no_stdin = 1;
1394 child.no_stdout = 1;
1395 child.stdout_to_stderr = 0;
1396 child.git_cmd = 1;
1397 if (run_command(&child))
1398 return "Working directory has staged changes";
1400 child_process_init(&child);
1401 strvec_pushl(&child.args, "read-tree", "-u", "-m", hash_to_hex(sha1),
1402 NULL);
1403 strvec_pushv(&child.env, env->v);
1404 child.dir = work_tree;
1405 child.no_stdin = 1;
1406 child.no_stdout = 1;
1407 child.stdout_to_stderr = 0;
1408 child.git_cmd = 1;
1409 if (run_command(&child))
1410 return "Could not update working tree to new HEAD";
1412 return NULL;
1415 static const char *push_to_checkout_hook = "push-to-checkout";
1417 static const char *push_to_checkout(unsigned char *hash,
1418 int *invoked_hook,
1419 struct strvec *env,
1420 const char *work_tree)
1422 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1423 opt.invoked_hook = invoked_hook;
1425 strvec_pushf(env, "GIT_WORK_TREE=%s", absolute_path(work_tree));
1426 strvec_pushv(&opt.env, env->v);
1427 strvec_push(&opt.args, hash_to_hex(hash));
1428 if (run_hooks_opt(the_repository, push_to_checkout_hook, &opt))
1429 return "push-to-checkout hook declined";
1430 else
1431 return NULL;
1434 static const char *update_worktree(unsigned char *sha1, const struct worktree *worktree)
1436 const char *retval, *git_dir;
1437 struct strvec env = STRVEC_INIT;
1438 int invoked_hook;
1440 if (!worktree || !worktree->path)
1441 BUG("worktree->path must be non-NULL");
1443 if (worktree->is_bare)
1444 return "denyCurrentBranch = updateInstead needs a worktree";
1445 git_dir = get_worktree_git_dir(worktree);
1447 strvec_pushf(&env, "GIT_DIR=%s", absolute_path(git_dir));
1449 retval = push_to_checkout(sha1, &invoked_hook, &env, worktree->path);
1450 if (!invoked_hook)
1451 retval = push_to_deploy(sha1, &env, worktree->path);
1453 strvec_clear(&env);
1454 return retval;
1457 static const char *update(struct command *cmd, struct shallow_info *si)
1459 const char *name = cmd->ref_name;
1460 struct strbuf namespaced_name_buf = STRBUF_INIT;
1461 static char *namespaced_name;
1462 const char *ret;
1463 struct object_id *old_oid = &cmd->old_oid;
1464 struct object_id *new_oid = &cmd->new_oid;
1465 int do_update_worktree = 0;
1466 struct worktree **worktrees = get_worktrees();
1467 const struct worktree *worktree =
1468 find_shared_symref(worktrees, "HEAD", name);
1470 /* only refs/... are allowed */
1471 if (!starts_with(name, "refs/") ||
1472 check_refname_format(name + 5, is_null_oid(new_oid) ?
1473 REFNAME_ALLOW_ONELEVEL : 0)) {
1474 rp_error("refusing to update funny ref '%s' remotely", name);
1475 ret = "funny refname";
1476 goto out;
1479 strbuf_addf(&namespaced_name_buf, "%s%s", get_git_namespace(), name);
1480 free(namespaced_name);
1481 namespaced_name = strbuf_detach(&namespaced_name_buf, NULL);
1483 if (worktree && !worktree->is_bare) {
1484 switch (deny_current_branch) {
1485 case DENY_IGNORE:
1486 break;
1487 case DENY_WARN:
1488 rp_warning("updating the current branch");
1489 break;
1490 case DENY_REFUSE:
1491 case DENY_UNCONFIGURED:
1492 rp_error("refusing to update checked out branch: %s", name);
1493 if (deny_current_branch == DENY_UNCONFIGURED)
1494 refuse_unconfigured_deny();
1495 ret = "branch is currently checked out";
1496 goto out;
1497 case DENY_UPDATE_INSTEAD:
1498 /* pass -- let other checks intervene first */
1499 do_update_worktree = 1;
1500 break;
1504 if (!is_null_oid(new_oid) && !repo_has_object_file(the_repository, new_oid)) {
1505 error("unpack should have generated %s, "
1506 "but I can't find it!", oid_to_hex(new_oid));
1507 ret = "bad pack";
1508 goto out;
1511 if (!is_null_oid(old_oid) && is_null_oid(new_oid)) {
1512 if (deny_deletes && starts_with(name, "refs/heads/")) {
1513 rp_error("denying ref deletion for %s", name);
1514 ret = "deletion prohibited";
1515 goto out;
1518 if (worktree || (head_name && !strcmp(namespaced_name, head_name))) {
1519 switch (deny_delete_current) {
1520 case DENY_IGNORE:
1521 break;
1522 case DENY_WARN:
1523 rp_warning("deleting the current branch");
1524 break;
1525 case DENY_REFUSE:
1526 case DENY_UNCONFIGURED:
1527 case DENY_UPDATE_INSTEAD:
1528 if (deny_delete_current == DENY_UNCONFIGURED)
1529 refuse_unconfigured_deny_delete_current();
1530 rp_error("refusing to delete the current branch: %s", name);
1531 ret = "deletion of the current branch prohibited";
1532 goto out;
1533 default:
1534 ret = "Invalid denyDeleteCurrent setting";
1535 goto out;
1540 if (deny_non_fast_forwards && !is_null_oid(new_oid) &&
1541 !is_null_oid(old_oid) &&
1542 starts_with(name, "refs/heads/")) {
1543 struct object *old_object, *new_object;
1544 struct commit *old_commit, *new_commit;
1545 int ret2;
1547 old_object = parse_object(the_repository, old_oid);
1548 new_object = parse_object(the_repository, new_oid);
1550 if (!old_object || !new_object ||
1551 old_object->type != OBJ_COMMIT ||
1552 new_object->type != OBJ_COMMIT) {
1553 error("bad sha1 objects for %s", name);
1554 ret = "bad ref";
1555 goto out;
1557 old_commit = (struct commit *)old_object;
1558 new_commit = (struct commit *)new_object;
1559 ret2 = repo_in_merge_bases(the_repository, old_commit, new_commit);
1560 if (ret2 < 0)
1561 exit(128);
1562 if (!ret2) {
1563 rp_error("denying non-fast-forward %s"
1564 " (you should pull first)", name);
1565 ret = "non-fast-forward";
1566 goto out;
1569 if (run_update_hook(cmd)) {
1570 rp_error("hook declined to update %s", name);
1571 ret = "hook declined";
1572 goto out;
1575 if (do_update_worktree) {
1576 ret = update_worktree(new_oid->hash, worktree);
1577 if (ret)
1578 goto out;
1581 if (is_null_oid(new_oid)) {
1582 struct strbuf err = STRBUF_INIT;
1583 if (!parse_object(the_repository, old_oid)) {
1584 old_oid = NULL;
1585 if (refs_ref_exists(get_main_ref_store(the_repository), name)) {
1586 rp_warning("allowing deletion of corrupt ref");
1587 } else {
1588 rp_warning("deleting a non-existent ref");
1589 cmd->did_not_exist = 1;
1592 if (ref_transaction_delete(transaction,
1593 namespaced_name,
1594 old_oid,
1595 NULL, 0,
1596 "push", &err)) {
1597 rp_error("%s", err.buf);
1598 ret = "failed to delete";
1599 } else {
1600 ret = NULL; /* good */
1602 strbuf_release(&err);
1604 else {
1605 struct strbuf err = STRBUF_INIT;
1606 if (shallow_update && si->shallow_ref[cmd->index] &&
1607 update_shallow_ref(cmd, si)) {
1608 ret = "shallow error";
1609 goto out;
1612 if (ref_transaction_update(transaction,
1613 namespaced_name,
1614 new_oid, old_oid,
1615 NULL, NULL,
1616 0, "push",
1617 &err)) {
1618 rp_error("%s", err.buf);
1619 ret = "failed to update ref";
1620 } else {
1621 ret = NULL; /* good */
1623 strbuf_release(&err);
1626 out:
1627 free_worktrees(worktrees);
1628 return ret;
1631 static void run_update_post_hook(struct command *commands)
1633 struct command *cmd;
1634 struct child_process proc = CHILD_PROCESS_INIT;
1635 const char *hook;
1637 hook = find_hook(the_repository, "post-update");
1638 if (!hook)
1639 return;
1641 for (cmd = commands; cmd; cmd = cmd->next) {
1642 if (cmd->error_string || cmd->did_not_exist)
1643 continue;
1644 if (!proc.args.nr)
1645 strvec_push(&proc.args, hook);
1646 strvec_push(&proc.args, cmd->ref_name);
1648 if (!proc.args.nr)
1649 return;
1651 proc.no_stdin = 1;
1652 proc.stdout_to_stderr = 1;
1653 proc.err = use_sideband ? -1 : 0;
1654 proc.trace2_hook_name = "post-update";
1656 if (!start_command(&proc)) {
1657 if (use_sideband)
1658 copy_to_sideband(proc.err, -1, NULL);
1659 finish_command(&proc);
1663 static void check_aliased_update_internal(struct command *cmd,
1664 struct string_list *list,
1665 const char *dst_name, int flag)
1667 struct string_list_item *item;
1668 struct command *dst_cmd;
1670 if (!(flag & REF_ISSYMREF))
1671 return;
1673 if (!dst_name) {
1674 rp_error("refusing update to broken symref '%s'", cmd->ref_name);
1675 cmd->skip_update = 1;
1676 cmd->error_string = "broken symref";
1677 return;
1679 dst_name = strip_namespace(dst_name);
1681 if (!(item = string_list_lookup(list, dst_name)))
1682 return;
1684 cmd->skip_update = 1;
1686 dst_cmd = (struct command *) item->util;
1688 if (oideq(&cmd->old_oid, &dst_cmd->old_oid) &&
1689 oideq(&cmd->new_oid, &dst_cmd->new_oid))
1690 return;
1692 dst_cmd->skip_update = 1;
1694 rp_error("refusing inconsistent update between symref '%s' (%s..%s) and"
1695 " its target '%s' (%s..%s)",
1696 cmd->ref_name,
1697 repo_find_unique_abbrev(the_repository, &cmd->old_oid, DEFAULT_ABBREV),
1698 repo_find_unique_abbrev(the_repository, &cmd->new_oid, DEFAULT_ABBREV),
1699 dst_cmd->ref_name,
1700 repo_find_unique_abbrev(the_repository, &dst_cmd->old_oid, DEFAULT_ABBREV),
1701 repo_find_unique_abbrev(the_repository, &dst_cmd->new_oid, DEFAULT_ABBREV));
1703 cmd->error_string = dst_cmd->error_string =
1704 "inconsistent aliased update";
1707 static void check_aliased_update(struct command *cmd, struct string_list *list)
1709 struct strbuf buf = STRBUF_INIT;
1710 const char *dst_name;
1711 int flag;
1713 strbuf_addf(&buf, "%s%s", get_git_namespace(), cmd->ref_name);
1714 dst_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1715 buf.buf, 0, NULL, &flag);
1716 check_aliased_update_internal(cmd, list, dst_name, flag);
1717 strbuf_release(&buf);
1720 static void check_aliased_updates(struct command *commands)
1722 struct command *cmd;
1723 struct string_list ref_list = STRING_LIST_INIT_NODUP;
1725 for (cmd = commands; cmd; cmd = cmd->next) {
1726 struct string_list_item *item =
1727 string_list_append(&ref_list, cmd->ref_name);
1728 item->util = (void *)cmd;
1730 string_list_sort(&ref_list);
1732 for (cmd = commands; cmd; cmd = cmd->next) {
1733 if (!cmd->error_string)
1734 check_aliased_update(cmd, &ref_list);
1737 string_list_clear(&ref_list, 0);
1740 static const struct object_id *command_singleton_iterator(void *cb_data)
1742 struct command **cmd_list = cb_data;
1743 struct command *cmd = *cmd_list;
1745 if (!cmd || is_null_oid(&cmd->new_oid))
1746 return NULL;
1747 *cmd_list = NULL; /* this returns only one */
1748 return &cmd->new_oid;
1751 static void set_connectivity_errors(struct command *commands,
1752 struct shallow_info *si)
1754 struct command *cmd;
1756 for (cmd = commands; cmd; cmd = cmd->next) {
1757 struct command *singleton = cmd;
1758 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1760 if (shallow_update && si->shallow_ref[cmd->index])
1761 /* to be checked in update_shallow_ref() */
1762 continue;
1764 opt.env = tmp_objdir_env(tmp_objdir);
1765 if (!check_connected(command_singleton_iterator, &singleton,
1766 &opt))
1767 continue;
1769 cmd->error_string = "missing necessary objects";
1773 struct iterate_data {
1774 struct command *cmds;
1775 struct shallow_info *si;
1778 static const struct object_id *iterate_receive_command_list(void *cb_data)
1780 struct iterate_data *data = cb_data;
1781 struct command **cmd_list = &data->cmds;
1782 struct command *cmd = *cmd_list;
1784 for (; cmd; cmd = cmd->next) {
1785 if (shallow_update && data->si->shallow_ref[cmd->index])
1786 /* to be checked in update_shallow_ref() */
1787 continue;
1788 if (!is_null_oid(&cmd->new_oid) && !cmd->skip_update) {
1789 *cmd_list = cmd->next;
1790 return &cmd->new_oid;
1793 return NULL;
1796 static void reject_updates_to_hidden(struct command *commands)
1798 struct strbuf refname_full = STRBUF_INIT;
1799 size_t prefix_len;
1800 struct command *cmd;
1802 strbuf_addstr(&refname_full, get_git_namespace());
1803 prefix_len = refname_full.len;
1805 for (cmd = commands; cmd; cmd = cmd->next) {
1806 if (cmd->error_string)
1807 continue;
1809 strbuf_setlen(&refname_full, prefix_len);
1810 strbuf_addstr(&refname_full, cmd->ref_name);
1812 if (!ref_is_hidden(cmd->ref_name, refname_full.buf, &hidden_refs))
1813 continue;
1814 if (is_null_oid(&cmd->new_oid))
1815 cmd->error_string = "deny deleting a hidden ref";
1816 else
1817 cmd->error_string = "deny updating a hidden ref";
1820 strbuf_release(&refname_full);
1823 static int should_process_cmd(struct command *cmd)
1825 return !cmd->error_string && !cmd->skip_update;
1828 static void BUG_if_skipped_connectivity_check(struct command *commands,
1829 struct shallow_info *si)
1831 struct command *cmd;
1833 for (cmd = commands; cmd; cmd = cmd->next) {
1834 if (should_process_cmd(cmd) && si->shallow_ref[cmd->index])
1835 bug("connectivity check has not been run on ref %s",
1836 cmd->ref_name);
1838 BUG_if_bug("connectivity check skipped???");
1841 static void execute_commands_non_atomic(struct command *commands,
1842 struct shallow_info *si)
1844 struct command *cmd;
1845 struct strbuf err = STRBUF_INIT;
1847 for (cmd = commands; cmd; cmd = cmd->next) {
1848 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1849 continue;
1851 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1852 &err);
1853 if (!transaction) {
1854 rp_error("%s", err.buf);
1855 strbuf_reset(&err);
1856 cmd->error_string = "transaction failed to start";
1857 continue;
1860 cmd->error_string = update(cmd, si);
1862 if (!cmd->error_string
1863 && ref_transaction_commit(transaction, &err)) {
1864 rp_error("%s", err.buf);
1865 strbuf_reset(&err);
1866 cmd->error_string = "failed to update ref";
1868 ref_transaction_free(transaction);
1870 strbuf_release(&err);
1873 static void execute_commands_atomic(struct command *commands,
1874 struct shallow_info *si)
1876 struct command *cmd;
1877 struct strbuf err = STRBUF_INIT;
1878 const char *reported_error = "atomic push failure";
1880 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1881 &err);
1882 if (!transaction) {
1883 rp_error("%s", err.buf);
1884 strbuf_reset(&err);
1885 reported_error = "transaction failed to start";
1886 goto failure;
1889 for (cmd = commands; cmd; cmd = cmd->next) {
1890 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1891 continue;
1893 cmd->error_string = update(cmd, si);
1895 if (cmd->error_string)
1896 goto failure;
1899 if (ref_transaction_commit(transaction, &err)) {
1900 rp_error("%s", err.buf);
1901 reported_error = "atomic transaction failed";
1902 goto failure;
1904 goto cleanup;
1906 failure:
1907 for (cmd = commands; cmd; cmd = cmd->next)
1908 if (!cmd->error_string)
1909 cmd->error_string = reported_error;
1911 cleanup:
1912 ref_transaction_free(transaction);
1913 strbuf_release(&err);
1916 static void execute_commands(struct command *commands,
1917 const char *unpacker_error,
1918 struct shallow_info *si,
1919 const struct string_list *push_options)
1921 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1922 struct command *cmd;
1923 struct iterate_data data;
1924 struct async muxer;
1925 int err_fd = 0;
1926 int run_proc_receive = 0;
1928 if (unpacker_error) {
1929 for (cmd = commands; cmd; cmd = cmd->next)
1930 cmd->error_string = "unpacker error";
1931 return;
1934 if (use_sideband) {
1935 memset(&muxer, 0, sizeof(muxer));
1936 muxer.proc = copy_to_sideband;
1937 muxer.in = -1;
1938 if (!start_async(&muxer))
1939 err_fd = muxer.in;
1940 /* ...else, continue without relaying sideband */
1943 data.cmds = commands;
1944 data.si = si;
1945 opt.err_fd = err_fd;
1946 opt.progress = err_fd && !quiet;
1947 opt.env = tmp_objdir_env(tmp_objdir);
1948 opt.exclude_hidden_refs_section = "receive";
1950 if (check_connected(iterate_receive_command_list, &data, &opt))
1951 set_connectivity_errors(commands, si);
1953 if (use_sideband)
1954 finish_async(&muxer);
1956 reject_updates_to_hidden(commands);
1959 * Try to find commands that have special prefix in their reference names,
1960 * and mark them to run an external "proc-receive" hook later.
1962 if (proc_receive_ref) {
1963 for (cmd = commands; cmd; cmd = cmd->next) {
1964 if (!should_process_cmd(cmd))
1965 continue;
1967 if (proc_receive_ref_matches(cmd)) {
1968 cmd->run_proc_receive = RUN_PROC_RECEIVE_SCHEDULED;
1969 run_proc_receive = 1;
1974 if (run_receive_hook(commands, "pre-receive", 0, push_options)) {
1975 for (cmd = commands; cmd; cmd = cmd->next) {
1976 if (!cmd->error_string)
1977 cmd->error_string = "pre-receive hook declined";
1979 return;
1983 * If there is no command ready to run, should return directly to destroy
1984 * temporary data in the quarantine area.
1986 for (cmd = commands; cmd && cmd->error_string; cmd = cmd->next)
1987 ; /* nothing */
1988 if (!cmd)
1989 return;
1992 * Now we'll start writing out refs, which means the objects need
1993 * to be in their final positions so that other processes can see them.
1995 if (tmp_objdir_migrate(tmp_objdir) < 0) {
1996 for (cmd = commands; cmd; cmd = cmd->next) {
1997 if (!cmd->error_string)
1998 cmd->error_string = "unable to migrate objects to permanent storage";
2000 return;
2002 tmp_objdir = NULL;
2004 check_aliased_updates(commands);
2006 free(head_name_to_free);
2007 head_name = head_name_to_free = refs_resolve_refdup(get_main_ref_store(the_repository),
2008 "HEAD", 0, NULL,
2009 NULL);
2011 if (run_proc_receive &&
2012 run_proc_receive_hook(commands, push_options))
2013 for (cmd = commands; cmd; cmd = cmd->next)
2014 if (!cmd->error_string &&
2015 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED) &&
2016 (cmd->run_proc_receive || use_atomic))
2017 cmd->error_string = "fail to run proc-receive hook";
2019 if (use_atomic)
2020 execute_commands_atomic(commands, si);
2021 else
2022 execute_commands_non_atomic(commands, si);
2024 if (shallow_update)
2025 BUG_if_skipped_connectivity_check(commands, si);
2028 static struct command **queue_command(struct command **tail,
2029 const char *line,
2030 int linelen)
2032 struct object_id old_oid, new_oid;
2033 struct command *cmd;
2034 const char *refname;
2035 int reflen;
2036 const char *p;
2038 if (parse_oid_hex(line, &old_oid, &p) ||
2039 *p++ != ' ' ||
2040 parse_oid_hex(p, &new_oid, &p) ||
2041 *p++ != ' ')
2042 die("protocol error: expected old/new/ref, got '%s'", line);
2044 refname = p;
2045 reflen = linelen - (p - line);
2046 FLEX_ALLOC_MEM(cmd, ref_name, refname, reflen);
2047 oidcpy(&cmd->old_oid, &old_oid);
2048 oidcpy(&cmd->new_oid, &new_oid);
2049 *tail = cmd;
2050 return &cmd->next;
2053 static void free_commands(struct command *commands)
2055 while (commands) {
2056 struct command *next = commands->next;
2058 ref_push_report_free(commands->report);
2059 free(commands->error_string_owned);
2060 free(commands);
2061 commands = next;
2065 static void queue_commands_from_cert(struct command **tail,
2066 struct strbuf *push_cert)
2068 const char *boc, *eoc;
2070 if (*tail)
2071 die("protocol error: got both push certificate and unsigned commands");
2073 boc = strstr(push_cert->buf, "\n\n");
2074 if (!boc)
2075 die("malformed push certificate %.*s", 100, push_cert->buf);
2076 else
2077 boc += 2;
2078 eoc = push_cert->buf + parse_signed_buffer(push_cert->buf, push_cert->len);
2080 while (boc < eoc) {
2081 const char *eol = memchr(boc, '\n', eoc - boc);
2082 tail = queue_command(tail, boc, eol ? eol - boc : eoc - boc);
2083 boc = eol ? eol + 1 : eoc;
2087 static struct command *read_head_info(struct packet_reader *reader,
2088 struct oid_array *shallow)
2090 struct command *commands = NULL;
2091 struct command **p = &commands;
2092 for (;;) {
2093 int linelen;
2095 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2096 break;
2098 if (reader->pktlen > 8 && starts_with(reader->line, "shallow ")) {
2099 struct object_id oid;
2100 if (get_oid_hex(reader->line + 8, &oid))
2101 die("protocol error: expected shallow sha, got '%s'",
2102 reader->line + 8);
2103 oid_array_append(shallow, &oid);
2104 continue;
2107 linelen = strlen(reader->line);
2108 if (linelen < reader->pktlen) {
2109 const char *feature_list = reader->line + linelen + 1;
2110 const char *hash = NULL;
2111 const char *client_sid;
2112 size_t len = 0;
2113 if (parse_feature_request(feature_list, "report-status"))
2114 report_status = 1;
2115 if (parse_feature_request(feature_list, "report-status-v2"))
2116 report_status_v2 = 1;
2117 if (parse_feature_request(feature_list, "side-band-64k"))
2118 use_sideband = LARGE_PACKET_MAX;
2119 if (parse_feature_request(feature_list, "quiet"))
2120 quiet = 1;
2121 if (advertise_atomic_push
2122 && parse_feature_request(feature_list, "atomic"))
2123 use_atomic = 1;
2124 if (advertise_push_options
2125 && parse_feature_request(feature_list, "push-options"))
2126 use_push_options = 1;
2127 hash = parse_feature_value(feature_list, "object-format", &len, NULL);
2128 if (!hash) {
2129 hash = hash_algos[GIT_HASH_SHA1].name;
2130 len = strlen(hash);
2132 if (xstrncmpz(the_hash_algo->name, hash, len))
2133 die("error: unsupported object format '%s'", hash);
2134 client_sid = parse_feature_value(feature_list, "session-id", &len, NULL);
2135 if (client_sid) {
2136 char *sid = xstrndup(client_sid, len);
2137 trace2_data_string("transfer", NULL, "client-sid", client_sid);
2138 free(sid);
2142 if (!strcmp(reader->line, "push-cert")) {
2143 int true_flush = 0;
2144 int saved_options = reader->options;
2145 reader->options &= ~PACKET_READ_CHOMP_NEWLINE;
2147 for (;;) {
2148 packet_reader_read(reader);
2149 if (reader->status == PACKET_READ_FLUSH) {
2150 true_flush = 1;
2151 break;
2153 if (reader->status != PACKET_READ_NORMAL) {
2154 die("protocol error: got an unexpected packet");
2156 if (!strcmp(reader->line, "push-cert-end\n"))
2157 break; /* end of cert */
2158 strbuf_addstr(&push_cert, reader->line);
2160 reader->options = saved_options;
2162 if (true_flush)
2163 break;
2164 continue;
2167 p = queue_command(p, reader->line, linelen);
2170 if (push_cert.len)
2171 queue_commands_from_cert(p, &push_cert);
2173 return commands;
2176 static void read_push_options(struct packet_reader *reader,
2177 struct string_list *options)
2179 while (1) {
2180 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2181 break;
2183 string_list_append(options, reader->line);
2187 static const char *parse_pack_header(struct pack_header *hdr)
2189 switch (read_pack_header(0, hdr)) {
2190 case PH_ERROR_EOF:
2191 return "eof before pack header was fully read";
2193 case PH_ERROR_PACK_SIGNATURE:
2194 return "protocol error (pack signature mismatch detected)";
2196 case PH_ERROR_PROTOCOL:
2197 return "protocol error (pack version unsupported)";
2199 default:
2200 return "unknown error in parse_pack_header";
2202 case 0:
2203 return NULL;
2207 static struct tempfile *pack_lockfile;
2209 static void push_header_arg(struct strvec *args, struct pack_header *hdr)
2211 strvec_pushf(args, "--pack_header=%"PRIu32",%"PRIu32,
2212 ntohl(hdr->hdr_version), ntohl(hdr->hdr_entries));
2215 static const char *unpack(int err_fd, struct shallow_info *si)
2217 struct pack_header hdr;
2218 const char *hdr_err;
2219 int status;
2220 struct child_process child = CHILD_PROCESS_INIT;
2221 int fsck_objects = (receive_fsck_objects >= 0
2222 ? receive_fsck_objects
2223 : transfer_fsck_objects >= 0
2224 ? transfer_fsck_objects
2225 : 0);
2227 hdr_err = parse_pack_header(&hdr);
2228 if (hdr_err) {
2229 if (err_fd > 0)
2230 close(err_fd);
2231 return hdr_err;
2234 if (si->nr_ours || si->nr_theirs) {
2235 alt_shallow_file = setup_temporary_shallow(si->shallow);
2236 strvec_push(&child.args, "--shallow-file");
2237 strvec_push(&child.args, alt_shallow_file);
2240 tmp_objdir = tmp_objdir_create("incoming");
2241 if (!tmp_objdir) {
2242 if (err_fd > 0)
2243 close(err_fd);
2244 return "unable to create temporary object directory";
2246 strvec_pushv(&child.env, tmp_objdir_env(tmp_objdir));
2249 * Normally we just pass the tmp_objdir environment to the child
2250 * processes that do the heavy lifting, but we may need to see these
2251 * objects ourselves to set up shallow information.
2253 tmp_objdir_add_as_alternate(tmp_objdir);
2255 if (ntohl(hdr.hdr_entries) < unpack_limit) {
2256 strvec_push(&child.args, "unpack-objects");
2257 push_header_arg(&child.args, &hdr);
2258 if (quiet)
2259 strvec_push(&child.args, "-q");
2260 if (fsck_objects)
2261 strvec_pushf(&child.args, "--strict%s",
2262 fsck_msg_types.buf);
2263 if (max_input_size)
2264 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2265 (uintmax_t)max_input_size);
2266 child.no_stdout = 1;
2267 child.err = err_fd;
2268 child.git_cmd = 1;
2269 status = run_command(&child);
2270 if (status)
2271 return "unpack-objects abnormal exit";
2272 } else {
2273 char hostname[HOST_NAME_MAX + 1];
2274 char *lockfile;
2276 strvec_pushl(&child.args, "index-pack", "--stdin", NULL);
2277 push_header_arg(&child.args, &hdr);
2279 if (xgethostname(hostname, sizeof(hostname)))
2280 xsnprintf(hostname, sizeof(hostname), "localhost");
2281 strvec_pushf(&child.args,
2282 "--keep=receive-pack %"PRIuMAX" on %s",
2283 (uintmax_t)getpid(),
2284 hostname);
2286 if (!quiet && err_fd)
2287 strvec_push(&child.args, "--show-resolving-progress");
2288 if (use_sideband)
2289 strvec_push(&child.args, "--report-end-of-input");
2290 if (fsck_objects)
2291 strvec_pushf(&child.args, "--strict%s",
2292 fsck_msg_types.buf);
2293 if (!reject_thin)
2294 strvec_push(&child.args, "--fix-thin");
2295 if (max_input_size)
2296 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2297 (uintmax_t)max_input_size);
2298 child.out = -1;
2299 child.err = err_fd;
2300 child.git_cmd = 1;
2301 status = start_command(&child);
2302 if (status)
2303 return "index-pack fork failed";
2305 lockfile = index_pack_lockfile(child.out, NULL);
2306 if (lockfile) {
2307 pack_lockfile = register_tempfile(lockfile);
2308 free(lockfile);
2310 close(child.out);
2312 status = finish_command(&child);
2313 if (status)
2314 return "index-pack abnormal exit";
2315 reprepare_packed_git(the_repository);
2317 return NULL;
2320 static const char *unpack_with_sideband(struct shallow_info *si)
2322 struct async muxer;
2323 const char *ret;
2325 if (!use_sideband)
2326 return unpack(0, si);
2328 use_keepalive = KEEPALIVE_AFTER_NUL;
2329 memset(&muxer, 0, sizeof(muxer));
2330 muxer.proc = copy_to_sideband;
2331 muxer.in = -1;
2332 if (start_async(&muxer))
2333 return NULL;
2335 ret = unpack(muxer.in, si);
2337 finish_async(&muxer);
2338 return ret;
2341 static void prepare_shallow_update(struct shallow_info *si)
2343 int i, j, k, bitmap_size = DIV_ROUND_UP(si->ref->nr, 32);
2345 ALLOC_ARRAY(si->used_shallow, si->shallow->nr);
2346 assign_shallow_commits_to_refs(si, si->used_shallow, NULL);
2348 CALLOC_ARRAY(si->need_reachability_test, si->shallow->nr);
2349 CALLOC_ARRAY(si->reachable, si->shallow->nr);
2350 CALLOC_ARRAY(si->shallow_ref, si->ref->nr);
2352 for (i = 0; i < si->nr_ours; i++)
2353 si->need_reachability_test[si->ours[i]] = 1;
2355 for (i = 0; i < si->shallow->nr; i++) {
2356 if (!si->used_shallow[i])
2357 continue;
2358 for (j = 0; j < bitmap_size; j++) {
2359 if (!si->used_shallow[i][j])
2360 continue;
2361 si->need_reachability_test[i]++;
2362 for (k = 0; k < 32; k++)
2363 if (si->used_shallow[i][j] & (1U << k))
2364 si->shallow_ref[j * 32 + k]++;
2368 * true for those associated with some refs and belong
2369 * in "ours" list aka "step 7 not done yet"
2371 si->need_reachability_test[i] =
2372 si->need_reachability_test[i] > 1;
2376 * keep hooks happy by forcing a temporary shallow file via
2377 * env variable because we can't add --shallow-file to every
2378 * command. check_connected() will be done with
2379 * true .git/shallow though.
2381 setenv(GIT_SHALLOW_FILE_ENVIRONMENT, alt_shallow_file, 1);
2384 static void update_shallow_info(struct command *commands,
2385 struct shallow_info *si,
2386 struct oid_array *ref)
2388 struct command *cmd;
2389 int *ref_status;
2390 remove_nonexistent_theirs_shallow(si);
2391 if (!si->nr_ours && !si->nr_theirs) {
2392 shallow_update = 0;
2393 return;
2396 for (cmd = commands; cmd; cmd = cmd->next) {
2397 if (is_null_oid(&cmd->new_oid))
2398 continue;
2399 oid_array_append(ref, &cmd->new_oid);
2400 cmd->index = ref->nr - 1;
2402 si->ref = ref;
2404 if (shallow_update) {
2405 prepare_shallow_update(si);
2406 return;
2409 ALLOC_ARRAY(ref_status, ref->nr);
2410 assign_shallow_commits_to_refs(si, NULL, ref_status);
2411 for (cmd = commands; cmd; cmd = cmd->next) {
2412 if (is_null_oid(&cmd->new_oid))
2413 continue;
2414 if (ref_status[cmd->index]) {
2415 cmd->error_string = "shallow update not allowed";
2416 cmd->skip_update = 1;
2419 free(ref_status);
2422 static void report(struct command *commands, const char *unpack_status)
2424 struct command *cmd;
2425 struct strbuf buf = STRBUF_INIT;
2427 packet_buf_write(&buf, "unpack %s\n",
2428 unpack_status ? unpack_status : "ok");
2429 for (cmd = commands; cmd; cmd = cmd->next) {
2430 if (!cmd->error_string)
2431 packet_buf_write(&buf, "ok %s\n",
2432 cmd->ref_name);
2433 else
2434 packet_buf_write(&buf, "ng %s %s\n",
2435 cmd->ref_name, cmd->error_string);
2437 packet_buf_flush(&buf);
2439 if (use_sideband)
2440 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2441 else
2442 write_or_die(1, buf.buf, buf.len);
2443 strbuf_release(&buf);
2446 static void report_v2(struct command *commands, const char *unpack_status)
2448 struct command *cmd;
2449 struct strbuf buf = STRBUF_INIT;
2450 struct ref_push_report *report;
2452 packet_buf_write(&buf, "unpack %s\n",
2453 unpack_status ? unpack_status : "ok");
2454 for (cmd = commands; cmd; cmd = cmd->next) {
2455 int count = 0;
2457 if (cmd->error_string) {
2458 packet_buf_write(&buf, "ng %s %s\n",
2459 cmd->ref_name,
2460 cmd->error_string);
2461 continue;
2463 packet_buf_write(&buf, "ok %s\n",
2464 cmd->ref_name);
2465 for (report = cmd->report; report; report = report->next) {
2466 if (count++ > 0)
2467 packet_buf_write(&buf, "ok %s\n",
2468 cmd->ref_name);
2469 if (report->ref_name)
2470 packet_buf_write(&buf, "option refname %s\n",
2471 report->ref_name);
2472 if (report->old_oid)
2473 packet_buf_write(&buf, "option old-oid %s\n",
2474 oid_to_hex(report->old_oid));
2475 if (report->new_oid)
2476 packet_buf_write(&buf, "option new-oid %s\n",
2477 oid_to_hex(report->new_oid));
2478 if (report->forced_update)
2479 packet_buf_write(&buf, "option forced-update\n");
2482 packet_buf_flush(&buf);
2484 if (use_sideband)
2485 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2486 else
2487 write_or_die(1, buf.buf, buf.len);
2488 strbuf_release(&buf);
2491 static int delete_only(struct command *commands)
2493 struct command *cmd;
2494 for (cmd = commands; cmd; cmd = cmd->next) {
2495 if (!is_null_oid(&cmd->new_oid))
2496 return 0;
2498 return 1;
2501 int cmd_receive_pack(int argc,
2502 const char **argv,
2503 const char *prefix,
2504 struct repository *repo UNUSED)
2506 int advertise_refs = 0;
2507 struct command *commands;
2508 struct oid_array shallow = OID_ARRAY_INIT;
2509 struct oid_array ref = OID_ARRAY_INIT;
2510 struct shallow_info si;
2511 struct packet_reader reader;
2513 struct option options[] = {
2514 OPT__QUIET(&quiet, N_("quiet")),
2515 OPT_HIDDEN_BOOL(0, "stateless-rpc", &stateless_rpc, NULL),
2516 OPT_HIDDEN_BOOL(0, "http-backend-info-refs", &advertise_refs, NULL),
2517 OPT_ALIAS(0, "advertise-refs", "http-backend-info-refs"),
2518 OPT_HIDDEN_BOOL(0, "reject-thin-pack-for-testing", &reject_thin, NULL),
2519 OPT_END()
2522 packet_trace_identity("receive-pack");
2524 argc = parse_options(argc, argv, prefix, options, receive_pack_usage, 0);
2526 if (argc > 1)
2527 usage_msg_opt(_("too many arguments"), receive_pack_usage, options);
2528 if (argc == 0)
2529 usage_msg_opt(_("you must specify a directory"), receive_pack_usage, options);
2531 service_dir = argv[0];
2533 setup_path();
2535 if (!enter_repo(service_dir, 0))
2536 die("'%s' does not appear to be a git repository", service_dir);
2538 git_config(receive_pack_config, NULL);
2539 if (cert_nonce_seed)
2540 push_cert_nonce = prepare_push_cert_nonce(service_dir, time(NULL));
2542 if (0 <= receive_unpack_limit)
2543 unpack_limit = receive_unpack_limit;
2544 else if (0 <= transfer_unpack_limit)
2545 unpack_limit = transfer_unpack_limit;
2547 switch (determine_protocol_version_server()) {
2548 case protocol_v2:
2550 * push support for protocol v2 has not been implemented yet,
2551 * so ignore the request to use v2 and fallback to using v0.
2553 break;
2554 case protocol_v1:
2556 * v1 is just the original protocol with a version string,
2557 * so just fall through after writing the version string.
2559 if (advertise_refs || !stateless_rpc)
2560 packet_write_fmt(1, "version 1\n");
2562 /* fallthrough */
2563 case protocol_v0:
2564 break;
2565 case protocol_unknown_version:
2566 BUG("unknown protocol version");
2569 if (advertise_refs || !stateless_rpc) {
2570 write_head_info();
2572 if (advertise_refs)
2573 return 0;
2575 packet_reader_init(&reader, 0, NULL, 0,
2576 PACKET_READ_CHOMP_NEWLINE |
2577 PACKET_READ_DIE_ON_ERR_PACKET);
2579 if ((commands = read_head_info(&reader, &shallow))) {
2580 const char *unpack_status = NULL;
2581 struct string_list push_options = STRING_LIST_INIT_DUP;
2583 if (use_push_options)
2584 read_push_options(&reader, &push_options);
2585 if (!check_cert_push_options(&push_options)) {
2586 struct command *cmd;
2587 for (cmd = commands; cmd; cmd = cmd->next)
2588 cmd->error_string = "inconsistent push options";
2591 prepare_shallow_info(&si, &shallow);
2592 if (!si.nr_ours && !si.nr_theirs)
2593 shallow_update = 0;
2594 if (!delete_only(commands)) {
2595 unpack_status = unpack_with_sideband(&si);
2596 update_shallow_info(commands, &si, &ref);
2598 use_keepalive = KEEPALIVE_ALWAYS;
2599 execute_commands(commands, unpack_status, &si,
2600 &push_options);
2601 delete_tempfile(&pack_lockfile);
2602 sigchain_push(SIGPIPE, SIG_IGN);
2603 if (report_status_v2)
2604 report_v2(commands, unpack_status);
2605 else if (report_status)
2606 report(commands, unpack_status);
2607 sigchain_pop(SIGPIPE);
2608 run_receive_hook(commands, "post-receive", 1,
2609 &push_options);
2610 run_update_post_hook(commands);
2611 free_commands(commands);
2612 string_list_clear(&push_options, 0);
2613 if (auto_gc) {
2614 struct child_process proc = CHILD_PROCESS_INIT;
2616 if (prepare_auto_maintenance(1, &proc)) {
2617 proc.no_stdin = 1;
2618 proc.stdout_to_stderr = 1;
2619 proc.err = use_sideband ? -1 : 0;
2621 if (!start_command(&proc)) {
2622 if (use_sideband)
2623 copy_to_sideband(proc.err, -1, NULL);
2624 finish_command(&proc);
2628 if (auto_update_server_info)
2629 update_server_info(0);
2630 clear_shallow_info(&si);
2632 if (use_sideband)
2633 packet_flush(1);
2634 oid_array_clear(&shallow);
2635 oid_array_clear(&ref);
2636 strvec_clear(&hidden_refs);
2637 free((void *)push_cert_nonce);
2638 return 0;