clone_submodule: avoid using `access()` on directories
[git/gitster.git] / builtin / receive-pack.c
bloba90af3036303f1c6d8261559c7309fe9934874c7
1 #include "builtin.h"
2 #include "repository.h"
3 #include "config.h"
4 #include "lockfile.h"
5 #include "pack.h"
6 #include "refs.h"
7 #include "pkt-line.h"
8 #include "sideband.h"
9 #include "run-command.h"
10 #include "hook.h"
11 #include "exec-cmd.h"
12 #include "commit.h"
13 #include "object.h"
14 #include "remote.h"
15 #include "connect.h"
16 #include "string-list.h"
17 #include "oid-array.h"
18 #include "connected.h"
19 #include "strvec.h"
20 #include "version.h"
21 #include "tag.h"
22 #include "gpg-interface.h"
23 #include "sigchain.h"
24 #include "fsck.h"
25 #include "tmp-objdir.h"
26 #include "oidset.h"
27 #include "packfile.h"
28 #include "object-store.h"
29 #include "protocol.h"
30 #include "commit-reach.h"
31 #include "worktree.h"
32 #include "shallow.h"
34 static const char * const receive_pack_usage[] = {
35 N_("git receive-pack <git-dir>"),
36 NULL
39 enum deny_action {
40 DENY_UNCONFIGURED,
41 DENY_IGNORE,
42 DENY_WARN,
43 DENY_REFUSE,
44 DENY_UPDATE_INSTEAD
47 static int deny_deletes;
48 static int deny_non_fast_forwards;
49 static enum deny_action deny_current_branch = DENY_UNCONFIGURED;
50 static enum deny_action deny_delete_current = DENY_UNCONFIGURED;
51 static int receive_fsck_objects = -1;
52 static int transfer_fsck_objects = -1;
53 static struct strbuf fsck_msg_types = STRBUF_INIT;
54 static int receive_unpack_limit = -1;
55 static int transfer_unpack_limit = -1;
56 static int advertise_atomic_push = 1;
57 static int advertise_push_options;
58 static int advertise_sid;
59 static int unpack_limit = 100;
60 static off_t max_input_size;
61 static int report_status;
62 static int report_status_v2;
63 static int use_sideband;
64 static int use_atomic;
65 static int use_push_options;
66 static int quiet;
67 static int prefer_ofs_delta = 1;
68 static int auto_update_server_info;
69 static int auto_gc = 1;
70 static int reject_thin;
71 static int stateless_rpc;
72 static const char *service_dir;
73 static const char *head_name;
74 static void *head_name_to_free;
75 static int sent_capabilities;
76 static int shallow_update;
77 static const char *alt_shallow_file;
78 static struct strbuf push_cert = STRBUF_INIT;
79 static struct object_id push_cert_oid;
80 static struct signature_check sigcheck;
81 static const char *push_cert_nonce;
82 static const char *cert_nonce_seed;
83 static struct string_list hidden_refs = STRING_LIST_INIT_DUP;
85 static const char *NONCE_UNSOLICITED = "UNSOLICITED";
86 static const char *NONCE_BAD = "BAD";
87 static const char *NONCE_MISSING = "MISSING";
88 static const char *NONCE_OK = "OK";
89 static const char *NONCE_SLOP = "SLOP";
90 static const char *nonce_status;
91 static long nonce_stamp_slop;
92 static timestamp_t nonce_stamp_slop_limit;
93 static struct ref_transaction *transaction;
95 static enum {
96 KEEPALIVE_NEVER = 0,
97 KEEPALIVE_AFTER_NUL,
98 KEEPALIVE_ALWAYS
99 } use_keepalive;
100 static int keepalive_in_sec = 5;
102 static struct tmp_objdir *tmp_objdir;
104 static struct proc_receive_ref {
105 unsigned int want_add:1,
106 want_delete:1,
107 want_modify:1,
108 negative_ref:1;
109 char *ref_prefix;
110 struct proc_receive_ref *next;
111 } *proc_receive_ref;
113 static void proc_receive_ref_append(const char *prefix);
115 static enum deny_action parse_deny_action(const char *var, const char *value)
117 if (value) {
118 if (!strcasecmp(value, "ignore"))
119 return DENY_IGNORE;
120 if (!strcasecmp(value, "warn"))
121 return DENY_WARN;
122 if (!strcasecmp(value, "refuse"))
123 return DENY_REFUSE;
124 if (!strcasecmp(value, "updateinstead"))
125 return DENY_UPDATE_INSTEAD;
127 if (git_config_bool(var, value))
128 return DENY_REFUSE;
129 return DENY_IGNORE;
132 static int receive_pack_config(const char *var, const char *value, void *cb)
134 int status = parse_hide_refs_config(var, value, "receive", &hidden_refs);
136 if (status)
137 return status;
139 status = git_gpg_config(var, value, NULL);
140 if (status)
141 return status;
143 if (strcmp(var, "receive.denydeletes") == 0) {
144 deny_deletes = git_config_bool(var, value);
145 return 0;
148 if (strcmp(var, "receive.denynonfastforwards") == 0) {
149 deny_non_fast_forwards = git_config_bool(var, value);
150 return 0;
153 if (strcmp(var, "receive.unpacklimit") == 0) {
154 receive_unpack_limit = git_config_int(var, value);
155 return 0;
158 if (strcmp(var, "transfer.unpacklimit") == 0) {
159 transfer_unpack_limit = git_config_int(var, value);
160 return 0;
163 if (strcmp(var, "receive.fsck.skiplist") == 0) {
164 const char *path;
166 if (git_config_pathname(&path, var, value))
167 return 1;
168 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
169 fsck_msg_types.len ? ',' : '=', path);
170 free((char *)path);
171 return 0;
174 if (skip_prefix(var, "receive.fsck.", &var)) {
175 if (is_valid_msg_type(var, value))
176 strbuf_addf(&fsck_msg_types, "%c%s=%s",
177 fsck_msg_types.len ? ',' : '=', var, value);
178 else
179 warning("skipping unknown msg id '%s'", var);
180 return 0;
183 if (strcmp(var, "receive.fsckobjects") == 0) {
184 receive_fsck_objects = git_config_bool(var, value);
185 return 0;
188 if (strcmp(var, "transfer.fsckobjects") == 0) {
189 transfer_fsck_objects = git_config_bool(var, value);
190 return 0;
193 if (!strcmp(var, "receive.denycurrentbranch")) {
194 deny_current_branch = parse_deny_action(var, value);
195 return 0;
198 if (strcmp(var, "receive.denydeletecurrent") == 0) {
199 deny_delete_current = parse_deny_action(var, value);
200 return 0;
203 if (strcmp(var, "repack.usedeltabaseoffset") == 0) {
204 prefer_ofs_delta = git_config_bool(var, value);
205 return 0;
208 if (strcmp(var, "receive.updateserverinfo") == 0) {
209 auto_update_server_info = git_config_bool(var, value);
210 return 0;
213 if (strcmp(var, "receive.autogc") == 0) {
214 auto_gc = git_config_bool(var, value);
215 return 0;
218 if (strcmp(var, "receive.shallowupdate") == 0) {
219 shallow_update = git_config_bool(var, value);
220 return 0;
223 if (strcmp(var, "receive.certnonceseed") == 0)
224 return git_config_string(&cert_nonce_seed, var, value);
226 if (strcmp(var, "receive.certnonceslop") == 0) {
227 nonce_stamp_slop_limit = git_config_ulong(var, value);
228 return 0;
231 if (strcmp(var, "receive.advertiseatomic") == 0) {
232 advertise_atomic_push = git_config_bool(var, value);
233 return 0;
236 if (strcmp(var, "receive.advertisepushoptions") == 0) {
237 advertise_push_options = git_config_bool(var, value);
238 return 0;
241 if (strcmp(var, "receive.keepalive") == 0) {
242 keepalive_in_sec = git_config_int(var, value);
243 return 0;
246 if (strcmp(var, "receive.maxinputsize") == 0) {
247 max_input_size = git_config_int64(var, value);
248 return 0;
251 if (strcmp(var, "receive.procreceiverefs") == 0) {
252 if (!value)
253 return config_error_nonbool(var);
254 proc_receive_ref_append(value);
255 return 0;
258 if (strcmp(var, "transfer.advertisesid") == 0) {
259 advertise_sid = git_config_bool(var, value);
260 return 0;
263 return git_default_config(var, value, cb);
266 static void show_ref(const char *path, const struct object_id *oid)
268 if (sent_capabilities) {
269 packet_write_fmt(1, "%s %s\n", oid_to_hex(oid), path);
270 } else {
271 struct strbuf cap = STRBUF_INIT;
273 strbuf_addstr(&cap,
274 "report-status report-status-v2 delete-refs side-band-64k quiet");
275 if (advertise_atomic_push)
276 strbuf_addstr(&cap, " atomic");
277 if (prefer_ofs_delta)
278 strbuf_addstr(&cap, " ofs-delta");
279 if (push_cert_nonce)
280 strbuf_addf(&cap, " push-cert=%s", push_cert_nonce);
281 if (advertise_push_options)
282 strbuf_addstr(&cap, " push-options");
283 if (advertise_sid)
284 strbuf_addf(&cap, " session-id=%s", trace2_session_id());
285 strbuf_addf(&cap, " object-format=%s", the_hash_algo->name);
286 strbuf_addf(&cap, " agent=%s", git_user_agent_sanitized());
287 packet_write_fmt(1, "%s %s%c%s\n",
288 oid_to_hex(oid), path, 0, cap.buf);
289 strbuf_release(&cap);
290 sent_capabilities = 1;
294 static int show_ref_cb(const char *path_full, const struct object_id *oid,
295 int flag UNUSED, void *data)
297 struct oidset *seen = data;
298 const char *path = strip_namespace(path_full);
300 if (ref_is_hidden(path, path_full, &hidden_refs))
301 return 0;
304 * Advertise refs outside our current namespace as ".have"
305 * refs, so that the client can use them to minimize data
306 * transfer but will otherwise ignore them.
308 if (!path) {
309 if (oidset_insert(seen, oid))
310 return 0;
311 path = ".have";
312 } else {
313 oidset_insert(seen, oid);
315 show_ref(path, oid);
316 return 0;
319 static void show_one_alternate_ref(const struct object_id *oid,
320 void *data)
322 struct oidset *seen = data;
324 if (oidset_insert(seen, oid))
325 return;
327 show_ref(".have", oid);
330 static void write_head_info(void)
332 static struct oidset seen = OIDSET_INIT;
334 for_each_ref(show_ref_cb, &seen);
335 for_each_alternate_ref(show_one_alternate_ref, &seen);
336 oidset_clear(&seen);
337 if (!sent_capabilities)
338 show_ref("capabilities^{}", null_oid());
340 advertise_shallow_grafts(1);
342 /* EOF */
343 packet_flush(1);
346 #define RUN_PROC_RECEIVE_SCHEDULED 1
347 #define RUN_PROC_RECEIVE_RETURNED 2
348 struct command {
349 struct command *next;
350 const char *error_string;
351 struct ref_push_report *report;
352 unsigned int skip_update:1,
353 did_not_exist:1,
354 run_proc_receive:2;
355 int index;
356 struct object_id old_oid;
357 struct object_id new_oid;
358 char ref_name[FLEX_ARRAY]; /* more */
361 static void proc_receive_ref_append(const char *prefix)
363 struct proc_receive_ref *ref_pattern;
364 char *p;
365 int len;
367 CALLOC_ARRAY(ref_pattern, 1);
368 p = strchr(prefix, ':');
369 if (p) {
370 while (prefix < p) {
371 if (*prefix == 'a')
372 ref_pattern->want_add = 1;
373 else if (*prefix == 'd')
374 ref_pattern->want_delete = 1;
375 else if (*prefix == 'm')
376 ref_pattern->want_modify = 1;
377 else if (*prefix == '!')
378 ref_pattern->negative_ref = 1;
379 prefix++;
381 prefix++;
382 } else {
383 ref_pattern->want_add = 1;
384 ref_pattern->want_delete = 1;
385 ref_pattern->want_modify = 1;
387 len = strlen(prefix);
388 while (len && prefix[len - 1] == '/')
389 len--;
390 ref_pattern->ref_prefix = xmemdupz(prefix, len);
391 if (!proc_receive_ref) {
392 proc_receive_ref = ref_pattern;
393 } else {
394 struct proc_receive_ref *end;
396 end = proc_receive_ref;
397 while (end->next)
398 end = end->next;
399 end->next = ref_pattern;
403 static int proc_receive_ref_matches(struct command *cmd)
405 struct proc_receive_ref *p;
407 if (!proc_receive_ref)
408 return 0;
410 for (p = proc_receive_ref; p; p = p->next) {
411 const char *match = p->ref_prefix;
412 const char *remains;
414 if (!p->want_add && is_null_oid(&cmd->old_oid))
415 continue;
416 else if (!p->want_delete && is_null_oid(&cmd->new_oid))
417 continue;
418 else if (!p->want_modify &&
419 !is_null_oid(&cmd->old_oid) &&
420 !is_null_oid(&cmd->new_oid))
421 continue;
423 if (skip_prefix(cmd->ref_name, match, &remains) &&
424 (!*remains || *remains == '/')) {
425 if (!p->negative_ref)
426 return 1;
427 } else if (p->negative_ref) {
428 return 1;
431 return 0;
434 static void report_message(const char *prefix, const char *err, va_list params)
436 int sz;
437 char msg[4096];
439 sz = xsnprintf(msg, sizeof(msg), "%s", prefix);
440 sz += vsnprintf(msg + sz, sizeof(msg) - sz, err, params);
441 if (sz > (sizeof(msg) - 1))
442 sz = sizeof(msg) - 1;
443 msg[sz++] = '\n';
445 if (use_sideband)
446 send_sideband(1, 2, msg, sz, use_sideband);
447 else
448 xwrite(2, msg, sz);
451 __attribute__((format (printf, 1, 2)))
452 static void rp_warning(const char *err, ...)
454 va_list params;
455 va_start(params, err);
456 report_message("warning: ", err, params);
457 va_end(params);
460 __attribute__((format (printf, 1, 2)))
461 static void rp_error(const char *err, ...)
463 va_list params;
464 va_start(params, err);
465 report_message("error: ", err, params);
466 va_end(params);
469 static int copy_to_sideband(int in, int out UNUSED, void *arg UNUSED)
471 char data[128];
472 int keepalive_active = 0;
474 if (keepalive_in_sec <= 0)
475 use_keepalive = KEEPALIVE_NEVER;
476 if (use_keepalive == KEEPALIVE_ALWAYS)
477 keepalive_active = 1;
479 while (1) {
480 ssize_t sz;
482 if (keepalive_active) {
483 struct pollfd pfd;
484 int ret;
486 pfd.fd = in;
487 pfd.events = POLLIN;
488 ret = poll(&pfd, 1, 1000 * keepalive_in_sec);
490 if (ret < 0) {
491 if (errno == EINTR)
492 continue;
493 else
494 break;
495 } else if (ret == 0) {
496 /* no data; send a keepalive packet */
497 static const char buf[] = "0005\1";
498 write_or_die(1, buf, sizeof(buf) - 1);
499 continue;
500 } /* else there is actual data to read */
503 sz = xread(in, data, sizeof(data));
504 if (sz <= 0)
505 break;
507 if (use_keepalive == KEEPALIVE_AFTER_NUL && !keepalive_active) {
508 const char *p = memchr(data, '\0', sz);
509 if (p) {
511 * The NUL tells us to start sending keepalives. Make
512 * sure we send any other data we read along
513 * with it.
515 keepalive_active = 1;
516 send_sideband(1, 2, data, p - data, use_sideband);
517 send_sideband(1, 2, p + 1, sz - (p - data + 1), use_sideband);
518 continue;
523 * Either we're not looking for a NUL signal, or we didn't see
524 * it yet; just pass along the data.
526 send_sideband(1, 2, data, sz, use_sideband);
528 close(in);
529 return 0;
532 static void hmac_hash(unsigned char *out,
533 const char *key_in, size_t key_len,
534 const char *text, size_t text_len)
536 unsigned char key[GIT_MAX_BLKSZ];
537 unsigned char k_ipad[GIT_MAX_BLKSZ];
538 unsigned char k_opad[GIT_MAX_BLKSZ];
539 int i;
540 git_hash_ctx ctx;
542 /* RFC 2104 2. (1) */
543 memset(key, '\0', GIT_MAX_BLKSZ);
544 if (the_hash_algo->blksz < key_len) {
545 the_hash_algo->init_fn(&ctx);
546 the_hash_algo->update_fn(&ctx, key_in, key_len);
547 the_hash_algo->final_fn(key, &ctx);
548 } else {
549 memcpy(key, key_in, key_len);
552 /* RFC 2104 2. (2) & (5) */
553 for (i = 0; i < sizeof(key); i++) {
554 k_ipad[i] = key[i] ^ 0x36;
555 k_opad[i] = key[i] ^ 0x5c;
558 /* RFC 2104 2. (3) & (4) */
559 the_hash_algo->init_fn(&ctx);
560 the_hash_algo->update_fn(&ctx, k_ipad, sizeof(k_ipad));
561 the_hash_algo->update_fn(&ctx, text, text_len);
562 the_hash_algo->final_fn(out, &ctx);
564 /* RFC 2104 2. (6) & (7) */
565 the_hash_algo->init_fn(&ctx);
566 the_hash_algo->update_fn(&ctx, k_opad, sizeof(k_opad));
567 the_hash_algo->update_fn(&ctx, out, the_hash_algo->rawsz);
568 the_hash_algo->final_fn(out, &ctx);
571 static char *prepare_push_cert_nonce(const char *path, timestamp_t stamp)
573 struct strbuf buf = STRBUF_INIT;
574 unsigned char hash[GIT_MAX_RAWSZ];
576 strbuf_addf(&buf, "%s:%"PRItime, path, stamp);
577 hmac_hash(hash, buf.buf, buf.len, cert_nonce_seed, strlen(cert_nonce_seed));
578 strbuf_release(&buf);
580 /* RFC 2104 5. HMAC-SHA1 or HMAC-SHA256 */
581 strbuf_addf(&buf, "%"PRItime"-%.*s", stamp, (int)the_hash_algo->hexsz, hash_to_hex(hash));
582 return strbuf_detach(&buf, NULL);
585 static char *find_header(const char *msg, size_t len, const char *key,
586 const char **next_line)
588 size_t out_len;
589 const char *val = find_header_mem(msg, len, key, &out_len);
591 if (!val)
592 return NULL;
594 if (next_line)
595 *next_line = val + out_len + 1;
597 return xmemdupz(val, out_len);
601 * Return zero if a and b are equal up to n bytes and nonzero if they are not.
602 * This operation is guaranteed to run in constant time to avoid leaking data.
604 static int constant_memequal(const char *a, const char *b, size_t n)
606 int res = 0;
607 size_t i;
609 for (i = 0; i < n; i++)
610 res |= a[i] ^ b[i];
611 return res;
614 static const char *check_nonce(const char *buf, size_t len)
616 char *nonce = find_header(buf, len, "nonce", NULL);
617 timestamp_t stamp, ostamp;
618 char *bohmac, *expect = NULL;
619 const char *retval = NONCE_BAD;
620 size_t noncelen;
622 if (!nonce) {
623 retval = NONCE_MISSING;
624 goto leave;
625 } else if (!push_cert_nonce) {
626 retval = NONCE_UNSOLICITED;
627 goto leave;
628 } else if (!strcmp(push_cert_nonce, nonce)) {
629 retval = NONCE_OK;
630 goto leave;
633 if (!stateless_rpc) {
634 /* returned nonce MUST match what we gave out earlier */
635 retval = NONCE_BAD;
636 goto leave;
640 * In stateless mode, we may be receiving a nonce issued by
641 * another instance of the server that serving the same
642 * repository, and the timestamps may not match, but the
643 * nonce-seed and dir should match, so we can recompute and
644 * report the time slop.
646 * In addition, when a nonce issued by another instance has
647 * timestamp within receive.certnonceslop seconds, we pretend
648 * as if we issued that nonce when reporting to the hook.
651 /* nonce is concat(<seconds-since-epoch>, "-", <hmac>) */
652 if (*nonce <= '0' || '9' < *nonce) {
653 retval = NONCE_BAD;
654 goto leave;
656 stamp = parse_timestamp(nonce, &bohmac, 10);
657 if (bohmac == nonce || bohmac[0] != '-') {
658 retval = NONCE_BAD;
659 goto leave;
662 noncelen = strlen(nonce);
663 expect = prepare_push_cert_nonce(service_dir, stamp);
664 if (noncelen != strlen(expect)) {
665 /* This is not even the right size. */
666 retval = NONCE_BAD;
667 goto leave;
669 if (constant_memequal(expect, nonce, noncelen)) {
670 /* Not what we would have signed earlier */
671 retval = NONCE_BAD;
672 goto leave;
676 * By how many seconds is this nonce stale? Negative value
677 * would mean it was issued by another server with its clock
678 * skewed in the future.
680 ostamp = parse_timestamp(push_cert_nonce, NULL, 10);
681 nonce_stamp_slop = (long)ostamp - (long)stamp;
683 if (nonce_stamp_slop_limit &&
684 labs(nonce_stamp_slop) <= nonce_stamp_slop_limit) {
686 * Pretend as if the received nonce (which passes the
687 * HMAC check, so it is not a forged by third-party)
688 * is what we issued.
690 free((void *)push_cert_nonce);
691 push_cert_nonce = xstrdup(nonce);
692 retval = NONCE_OK;
693 } else {
694 retval = NONCE_SLOP;
697 leave:
698 free(nonce);
699 free(expect);
700 return retval;
704 * Return 1 if there is no push_cert or if the push options in push_cert are
705 * the same as those in the argument; 0 otherwise.
707 static int check_cert_push_options(const struct string_list *push_options)
709 const char *buf = push_cert.buf;
710 int len = push_cert.len;
712 char *option;
713 const char *next_line;
714 int options_seen = 0;
716 int retval = 1;
718 if (!len)
719 return 1;
721 while ((option = find_header(buf, len, "push-option", &next_line))) {
722 len -= (next_line - buf);
723 buf = next_line;
724 options_seen++;
725 if (options_seen > push_options->nr
726 || strcmp(option,
727 push_options->items[options_seen - 1].string)) {
728 retval = 0;
729 goto leave;
731 free(option);
734 if (options_seen != push_options->nr)
735 retval = 0;
737 leave:
738 free(option);
739 return retval;
742 static void prepare_push_cert_sha1(struct child_process *proc)
744 static int already_done;
746 if (!push_cert.len)
747 return;
749 if (!already_done) {
750 int bogs /* beginning_of_gpg_sig */;
752 already_done = 1;
753 if (write_object_file(push_cert.buf, push_cert.len, OBJ_BLOB,
754 &push_cert_oid))
755 oidclr(&push_cert_oid);
757 memset(&sigcheck, '\0', sizeof(sigcheck));
759 bogs = parse_signed_buffer(push_cert.buf, push_cert.len);
760 sigcheck.payload = xmemdupz(push_cert.buf, bogs);
761 sigcheck.payload_len = bogs;
762 check_signature(&sigcheck, push_cert.buf + bogs,
763 push_cert.len - bogs);
765 nonce_status = check_nonce(push_cert.buf, bogs);
767 if (!is_null_oid(&push_cert_oid)) {
768 strvec_pushf(&proc->env, "GIT_PUSH_CERT=%s",
769 oid_to_hex(&push_cert_oid));
770 strvec_pushf(&proc->env, "GIT_PUSH_CERT_SIGNER=%s",
771 sigcheck.signer ? sigcheck.signer : "");
772 strvec_pushf(&proc->env, "GIT_PUSH_CERT_KEY=%s",
773 sigcheck.key ? sigcheck.key : "");
774 strvec_pushf(&proc->env, "GIT_PUSH_CERT_STATUS=%c",
775 sigcheck.result);
776 if (push_cert_nonce) {
777 strvec_pushf(&proc->env,
778 "GIT_PUSH_CERT_NONCE=%s",
779 push_cert_nonce);
780 strvec_pushf(&proc->env,
781 "GIT_PUSH_CERT_NONCE_STATUS=%s",
782 nonce_status);
783 if (nonce_status == NONCE_SLOP)
784 strvec_pushf(&proc->env,
785 "GIT_PUSH_CERT_NONCE_SLOP=%ld",
786 nonce_stamp_slop);
791 struct receive_hook_feed_state {
792 struct command *cmd;
793 struct ref_push_report *report;
794 int skip_broken;
795 struct strbuf buf;
796 const struct string_list *push_options;
799 typedef int (*feed_fn)(void *, const char **, size_t *);
800 static int run_and_feed_hook(const char *hook_name, feed_fn feed,
801 struct receive_hook_feed_state *feed_state)
803 struct child_process proc = CHILD_PROCESS_INIT;
804 struct async muxer;
805 int code;
806 const char *hook_path = find_hook(hook_name);
808 if (!hook_path)
809 return 0;
811 strvec_push(&proc.args, hook_path);
812 proc.in = -1;
813 proc.stdout_to_stderr = 1;
814 proc.trace2_hook_name = hook_name;
816 if (feed_state->push_options) {
817 size_t i;
818 for (i = 0; i < feed_state->push_options->nr; i++)
819 strvec_pushf(&proc.env,
820 "GIT_PUSH_OPTION_%"PRIuMAX"=%s",
821 (uintmax_t)i,
822 feed_state->push_options->items[i].string);
823 strvec_pushf(&proc.env, "GIT_PUSH_OPTION_COUNT=%"PRIuMAX"",
824 (uintmax_t)feed_state->push_options->nr);
825 } else
826 strvec_pushf(&proc.env, "GIT_PUSH_OPTION_COUNT");
828 if (tmp_objdir)
829 strvec_pushv(&proc.env, tmp_objdir_env(tmp_objdir));
831 if (use_sideband) {
832 memset(&muxer, 0, sizeof(muxer));
833 muxer.proc = copy_to_sideband;
834 muxer.in = -1;
835 code = start_async(&muxer);
836 if (code)
837 return code;
838 proc.err = muxer.in;
841 prepare_push_cert_sha1(&proc);
843 code = start_command(&proc);
844 if (code) {
845 if (use_sideband)
846 finish_async(&muxer);
847 return code;
850 sigchain_push(SIGPIPE, SIG_IGN);
852 while (1) {
853 const char *buf;
854 size_t n;
855 if (feed(feed_state, &buf, &n))
856 break;
857 if (write_in_full(proc.in, buf, n) < 0)
858 break;
860 close(proc.in);
861 if (use_sideband)
862 finish_async(&muxer);
864 sigchain_pop(SIGPIPE);
866 return finish_command(&proc);
869 static int feed_receive_hook(void *state_, const char **bufp, size_t *sizep)
871 struct receive_hook_feed_state *state = state_;
872 struct command *cmd = state->cmd;
874 while (cmd &&
875 state->skip_broken && (cmd->error_string || cmd->did_not_exist))
876 cmd = cmd->next;
877 if (!cmd)
878 return -1; /* EOF */
879 if (!bufp)
880 return 0; /* OK, can feed something. */
881 strbuf_reset(&state->buf);
882 if (!state->report)
883 state->report = cmd->report;
884 if (state->report) {
885 struct object_id *old_oid;
886 struct object_id *new_oid;
887 const char *ref_name;
889 old_oid = state->report->old_oid ? state->report->old_oid : &cmd->old_oid;
890 new_oid = state->report->new_oid ? state->report->new_oid : &cmd->new_oid;
891 ref_name = state->report->ref_name ? state->report->ref_name : cmd->ref_name;
892 strbuf_addf(&state->buf, "%s %s %s\n",
893 oid_to_hex(old_oid), oid_to_hex(new_oid),
894 ref_name);
895 state->report = state->report->next;
896 if (!state->report)
897 state->cmd = cmd->next;
898 } else {
899 strbuf_addf(&state->buf, "%s %s %s\n",
900 oid_to_hex(&cmd->old_oid), oid_to_hex(&cmd->new_oid),
901 cmd->ref_name);
902 state->cmd = cmd->next;
904 if (bufp) {
905 *bufp = state->buf.buf;
906 *sizep = state->buf.len;
908 return 0;
911 static int run_receive_hook(struct command *commands,
912 const char *hook_name,
913 int skip_broken,
914 const struct string_list *push_options)
916 struct receive_hook_feed_state state;
917 int status;
919 strbuf_init(&state.buf, 0);
920 state.cmd = commands;
921 state.skip_broken = skip_broken;
922 state.report = NULL;
923 if (feed_receive_hook(&state, NULL, NULL))
924 return 0;
925 state.cmd = commands;
926 state.push_options = push_options;
927 status = run_and_feed_hook(hook_name, feed_receive_hook, &state);
928 strbuf_release(&state.buf);
929 return status;
932 static int run_update_hook(struct command *cmd)
934 struct child_process proc = CHILD_PROCESS_INIT;
935 int code;
936 const char *hook_path = find_hook("update");
938 if (!hook_path)
939 return 0;
941 strvec_push(&proc.args, hook_path);
942 strvec_push(&proc.args, cmd->ref_name);
943 strvec_push(&proc.args, oid_to_hex(&cmd->old_oid));
944 strvec_push(&proc.args, oid_to_hex(&cmd->new_oid));
946 proc.no_stdin = 1;
947 proc.stdout_to_stderr = 1;
948 proc.err = use_sideband ? -1 : 0;
949 proc.trace2_hook_name = "update";
951 code = start_command(&proc);
952 if (code)
953 return code;
954 if (use_sideband)
955 copy_to_sideband(proc.err, -1, NULL);
956 return finish_command(&proc);
959 static struct command *find_command_by_refname(struct command *list,
960 const char *refname)
962 for (; list; list = list->next)
963 if (!strcmp(list->ref_name, refname))
964 return list;
965 return NULL;
968 static int read_proc_receive_report(struct packet_reader *reader,
969 struct command *commands,
970 struct strbuf *errmsg)
972 struct command *cmd;
973 struct command *hint = NULL;
974 struct ref_push_report *report = NULL;
975 int new_report = 0;
976 int code = 0;
977 int once = 0;
978 int response = 0;
980 for (;;) {
981 struct object_id old_oid, new_oid;
982 const char *head;
983 const char *refname;
984 char *p;
985 enum packet_read_status status;
987 status = packet_reader_read(reader);
988 if (status != PACKET_READ_NORMAL) {
989 /* Check whether proc-receive exited abnormally */
990 if (status == PACKET_READ_EOF && !response) {
991 strbuf_addstr(errmsg, "proc-receive exited abnormally");
992 return -1;
994 break;
996 response++;
998 head = reader->line;
999 p = strchr(head, ' ');
1000 if (!p) {
1001 strbuf_addf(errmsg, "proc-receive reported incomplete status line: '%s'\n", head);
1002 code = -1;
1003 continue;
1005 *p++ = '\0';
1006 if (!strcmp(head, "option")) {
1007 const char *key, *val;
1009 if (!hint || !(report || new_report)) {
1010 if (!once++)
1011 strbuf_addstr(errmsg, "proc-receive reported 'option' without a matching 'ok/ng' directive\n");
1012 code = -1;
1013 continue;
1015 if (new_report) {
1016 if (!hint->report) {
1017 CALLOC_ARRAY(hint->report, 1);
1018 report = hint->report;
1019 } else {
1020 report = hint->report;
1021 while (report->next)
1022 report = report->next;
1023 report->next = xcalloc(1, sizeof(struct ref_push_report));
1024 report = report->next;
1026 new_report = 0;
1028 key = p;
1029 p = strchr(key, ' ');
1030 if (p)
1031 *p++ = '\0';
1032 val = p;
1033 if (!strcmp(key, "refname"))
1034 report->ref_name = xstrdup_or_null(val);
1035 else if (!strcmp(key, "old-oid") && val &&
1036 !parse_oid_hex(val, &old_oid, &val))
1037 report->old_oid = oiddup(&old_oid);
1038 else if (!strcmp(key, "new-oid") && val &&
1039 !parse_oid_hex(val, &new_oid, &val))
1040 report->new_oid = oiddup(&new_oid);
1041 else if (!strcmp(key, "forced-update"))
1042 report->forced_update = 1;
1043 else if (!strcmp(key, "fall-through"))
1044 /* Fall through, let 'receive-pack' to execute it. */
1045 hint->run_proc_receive = 0;
1046 continue;
1049 report = NULL;
1050 new_report = 0;
1051 refname = p;
1052 p = strchr(refname, ' ');
1053 if (p)
1054 *p++ = '\0';
1055 if (strcmp(head, "ok") && strcmp(head, "ng")) {
1056 strbuf_addf(errmsg, "proc-receive reported bad status '%s' on ref '%s'\n",
1057 head, refname);
1058 code = -1;
1059 continue;
1062 /* first try searching at our hint, falling back to all refs */
1063 if (hint)
1064 hint = find_command_by_refname(hint, refname);
1065 if (!hint)
1066 hint = find_command_by_refname(commands, refname);
1067 if (!hint) {
1068 strbuf_addf(errmsg, "proc-receive reported status on unknown ref: %s\n",
1069 refname);
1070 code = -1;
1071 continue;
1073 if (!hint->run_proc_receive) {
1074 strbuf_addf(errmsg, "proc-receive reported status on unexpected ref: %s\n",
1075 refname);
1076 code = -1;
1077 continue;
1079 hint->run_proc_receive |= RUN_PROC_RECEIVE_RETURNED;
1080 if (!strcmp(head, "ng")) {
1081 if (p)
1082 hint->error_string = xstrdup(p);
1083 else
1084 hint->error_string = "failed";
1085 code = -1;
1086 continue;
1088 new_report = 1;
1091 for (cmd = commands; cmd; cmd = cmd->next)
1092 if (cmd->run_proc_receive && !cmd->error_string &&
1093 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED)) {
1094 cmd->error_string = "proc-receive failed to report status";
1095 code = -1;
1097 return code;
1100 static int run_proc_receive_hook(struct command *commands,
1101 const struct string_list *push_options)
1103 struct child_process proc = CHILD_PROCESS_INIT;
1104 struct async muxer;
1105 struct command *cmd;
1106 struct packet_reader reader;
1107 struct strbuf cap = STRBUF_INIT;
1108 struct strbuf errmsg = STRBUF_INIT;
1109 int hook_use_push_options = 0;
1110 int version = 0;
1111 int code;
1112 const char *hook_path = find_hook("proc-receive");
1114 if (!hook_path) {
1115 rp_error("cannot find hook 'proc-receive'");
1116 return -1;
1119 strvec_push(&proc.args, hook_path);
1120 proc.in = -1;
1121 proc.out = -1;
1122 proc.trace2_hook_name = "proc-receive";
1124 if (use_sideband) {
1125 memset(&muxer, 0, sizeof(muxer));
1126 muxer.proc = copy_to_sideband;
1127 muxer.in = -1;
1128 code = start_async(&muxer);
1129 if (code)
1130 return code;
1131 proc.err = muxer.in;
1132 } else {
1133 proc.err = 0;
1136 code = start_command(&proc);
1137 if (code) {
1138 if (use_sideband)
1139 finish_async(&muxer);
1140 return code;
1143 sigchain_push(SIGPIPE, SIG_IGN);
1145 /* Version negotiaton */
1146 packet_reader_init(&reader, proc.out, NULL, 0,
1147 PACKET_READ_CHOMP_NEWLINE |
1148 PACKET_READ_GENTLE_ON_EOF);
1149 if (use_atomic)
1150 strbuf_addstr(&cap, " atomic");
1151 if (use_push_options)
1152 strbuf_addstr(&cap, " push-options");
1153 if (cap.len) {
1154 code = packet_write_fmt_gently(proc.in, "version=1%c%s\n", '\0', cap.buf + 1);
1155 strbuf_release(&cap);
1156 } else {
1157 code = packet_write_fmt_gently(proc.in, "version=1\n");
1159 if (!code)
1160 code = packet_flush_gently(proc.in);
1162 if (!code)
1163 for (;;) {
1164 int linelen;
1165 enum packet_read_status status;
1167 status = packet_reader_read(&reader);
1168 if (status != PACKET_READ_NORMAL) {
1169 /* Check whether proc-receive exited abnormally */
1170 if (status == PACKET_READ_EOF)
1171 code = -1;
1172 break;
1175 if (reader.pktlen > 8 && starts_with(reader.line, "version=")) {
1176 version = atoi(reader.line + 8);
1177 linelen = strlen(reader.line);
1178 if (linelen < reader.pktlen) {
1179 const char *feature_list = reader.line + linelen + 1;
1180 if (parse_feature_request(feature_list, "push-options"))
1181 hook_use_push_options = 1;
1186 if (code) {
1187 strbuf_addstr(&errmsg, "fail to negotiate version with proc-receive hook");
1188 goto cleanup;
1191 switch (version) {
1192 case 0:
1193 /* fallthrough */
1194 case 1:
1195 break;
1196 default:
1197 strbuf_addf(&errmsg, "proc-receive version '%d' is not supported",
1198 version);
1199 code = -1;
1200 goto cleanup;
1203 /* Send commands */
1204 for (cmd = commands; cmd; cmd = cmd->next) {
1205 if (!cmd->run_proc_receive || cmd->skip_update || cmd->error_string)
1206 continue;
1207 code = packet_write_fmt_gently(proc.in, "%s %s %s",
1208 oid_to_hex(&cmd->old_oid),
1209 oid_to_hex(&cmd->new_oid),
1210 cmd->ref_name);
1211 if (code)
1212 break;
1214 if (!code)
1215 code = packet_flush_gently(proc.in);
1216 if (code) {
1217 strbuf_addstr(&errmsg, "fail to write commands to proc-receive hook");
1218 goto cleanup;
1221 /* Send push options */
1222 if (hook_use_push_options) {
1223 struct string_list_item *item;
1225 for_each_string_list_item(item, push_options) {
1226 code = packet_write_fmt_gently(proc.in, "%s", item->string);
1227 if (code)
1228 break;
1230 if (!code)
1231 code = packet_flush_gently(proc.in);
1232 if (code) {
1233 strbuf_addstr(&errmsg,
1234 "fail to write push-options to proc-receive hook");
1235 goto cleanup;
1239 /* Read result from proc-receive */
1240 code = read_proc_receive_report(&reader, commands, &errmsg);
1242 cleanup:
1243 close(proc.in);
1244 close(proc.out);
1245 if (use_sideband)
1246 finish_async(&muxer);
1247 if (finish_command(&proc))
1248 code = -1;
1249 if (errmsg.len >0) {
1250 char *p = errmsg.buf;
1252 p += errmsg.len - 1;
1253 if (*p == '\n')
1254 *p = '\0';
1255 rp_error("%s", errmsg.buf);
1256 strbuf_release(&errmsg);
1258 sigchain_pop(SIGPIPE);
1260 return code;
1263 static char *refuse_unconfigured_deny_msg =
1264 N_("By default, updating the current branch in a non-bare repository\n"
1265 "is denied, because it will make the index and work tree inconsistent\n"
1266 "with what you pushed, and will require 'git reset --hard' to match\n"
1267 "the work tree to HEAD.\n"
1268 "\n"
1269 "You can set the 'receive.denyCurrentBranch' configuration variable\n"
1270 "to 'ignore' or 'warn' in the remote repository to allow pushing into\n"
1271 "its current branch; however, this is not recommended unless you\n"
1272 "arranged to update its work tree to match what you pushed in some\n"
1273 "other way.\n"
1274 "\n"
1275 "To squelch this message and still keep the default behaviour, set\n"
1276 "'receive.denyCurrentBranch' configuration variable to 'refuse'.");
1278 static void refuse_unconfigured_deny(void)
1280 rp_error("%s", _(refuse_unconfigured_deny_msg));
1283 static char *refuse_unconfigured_deny_delete_current_msg =
1284 N_("By default, deleting the current branch is denied, because the next\n"
1285 "'git clone' won't result in any file checked out, causing confusion.\n"
1286 "\n"
1287 "You can set 'receive.denyDeleteCurrent' configuration variable to\n"
1288 "'warn' or 'ignore' in the remote repository to allow deleting the\n"
1289 "current branch, with or without a warning message.\n"
1290 "\n"
1291 "To squelch this message, you can set it to 'refuse'.");
1293 static void refuse_unconfigured_deny_delete_current(void)
1295 rp_error("%s", _(refuse_unconfigured_deny_delete_current_msg));
1298 static const struct object_id *command_singleton_iterator(void *cb_data);
1299 static int update_shallow_ref(struct command *cmd, struct shallow_info *si)
1301 struct shallow_lock shallow_lock = SHALLOW_LOCK_INIT;
1302 struct oid_array extra = OID_ARRAY_INIT;
1303 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1304 uint32_t mask = 1 << (cmd->index % 32);
1305 int i;
1307 trace_printf_key(&trace_shallow,
1308 "shallow: update_shallow_ref %s\n", cmd->ref_name);
1309 for (i = 0; i < si->shallow->nr; i++)
1310 if (si->used_shallow[i] &&
1311 (si->used_shallow[i][cmd->index / 32] & mask) &&
1312 !delayed_reachability_test(si, i))
1313 oid_array_append(&extra, &si->shallow->oid[i]);
1315 opt.env = tmp_objdir_env(tmp_objdir);
1316 setup_alternate_shallow(&shallow_lock, &opt.shallow_file, &extra);
1317 if (check_connected(command_singleton_iterator, cmd, &opt)) {
1318 rollback_shallow_file(the_repository, &shallow_lock);
1319 oid_array_clear(&extra);
1320 return -1;
1323 commit_shallow_file(the_repository, &shallow_lock);
1326 * Make sure setup_alternate_shallow() for the next ref does
1327 * not lose these new roots..
1329 for (i = 0; i < extra.nr; i++)
1330 register_shallow(the_repository, &extra.oid[i]);
1332 si->shallow_ref[cmd->index] = 0;
1333 oid_array_clear(&extra);
1334 return 0;
1338 * NEEDSWORK: we should consolidate various implementions of "are we
1339 * on an unborn branch?" test into one, and make the unified one more
1340 * robust. !get_sha1() based check used here and elsewhere would not
1341 * allow us to tell an unborn branch from corrupt ref, for example.
1342 * For the purpose of fixing "deploy-to-update does not work when
1343 * pushing into an empty repository" issue, this should suffice for
1344 * now.
1346 static int head_has_history(void)
1348 struct object_id oid;
1350 return !get_oid("HEAD", &oid);
1353 static const char *push_to_deploy(unsigned char *sha1,
1354 struct strvec *env,
1355 const char *work_tree)
1357 struct child_process child = CHILD_PROCESS_INIT;
1359 strvec_pushl(&child.args, "update-index", "-q", "--ignore-submodules",
1360 "--refresh", NULL);
1361 strvec_pushv(&child.env, env->v);
1362 child.dir = work_tree;
1363 child.no_stdin = 1;
1364 child.stdout_to_stderr = 1;
1365 child.git_cmd = 1;
1366 if (run_command(&child))
1367 return "Up-to-date check failed";
1369 /* run_command() does not clean up completely; reinitialize */
1370 child_process_init(&child);
1371 strvec_pushl(&child.args, "diff-files", "--quiet",
1372 "--ignore-submodules", "--", NULL);
1373 strvec_pushv(&child.env, env->v);
1374 child.dir = work_tree;
1375 child.no_stdin = 1;
1376 child.stdout_to_stderr = 1;
1377 child.git_cmd = 1;
1378 if (run_command(&child))
1379 return "Working directory has unstaged changes";
1381 child_process_init(&child);
1382 strvec_pushl(&child.args, "diff-index", "--quiet", "--cached",
1383 "--ignore-submodules",
1384 /* diff-index with either HEAD or an empty tree */
1385 head_has_history() ? "HEAD" : empty_tree_oid_hex(),
1386 "--", NULL);
1387 strvec_pushv(&child.env, env->v);
1388 child.no_stdin = 1;
1389 child.no_stdout = 1;
1390 child.stdout_to_stderr = 0;
1391 child.git_cmd = 1;
1392 if (run_command(&child))
1393 return "Working directory has staged changes";
1395 child_process_init(&child);
1396 strvec_pushl(&child.args, "read-tree", "-u", "-m", hash_to_hex(sha1),
1397 NULL);
1398 strvec_pushv(&child.env, env->v);
1399 child.dir = work_tree;
1400 child.no_stdin = 1;
1401 child.no_stdout = 1;
1402 child.stdout_to_stderr = 0;
1403 child.git_cmd = 1;
1404 if (run_command(&child))
1405 return "Could not update working tree to new HEAD";
1407 return NULL;
1410 static const char *push_to_checkout_hook = "push-to-checkout";
1412 static const char *push_to_checkout(unsigned char *hash,
1413 int *invoked_hook,
1414 struct strvec *env,
1415 const char *work_tree)
1417 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1418 opt.invoked_hook = invoked_hook;
1420 strvec_pushf(env, "GIT_WORK_TREE=%s", absolute_path(work_tree));
1421 strvec_pushv(&opt.env, env->v);
1422 strvec_push(&opt.args, hash_to_hex(hash));
1423 if (run_hooks_opt(push_to_checkout_hook, &opt))
1424 return "push-to-checkout hook declined";
1425 else
1426 return NULL;
1429 static const char *update_worktree(unsigned char *sha1, const struct worktree *worktree)
1431 const char *retval, *git_dir;
1432 struct strvec env = STRVEC_INIT;
1433 int invoked_hook;
1435 if (!worktree || !worktree->path)
1436 BUG("worktree->path must be non-NULL");
1438 if (worktree->is_bare)
1439 return "denyCurrentBranch = updateInstead needs a worktree";
1440 git_dir = get_worktree_git_dir(worktree);
1442 strvec_pushf(&env, "GIT_DIR=%s", absolute_path(git_dir));
1444 retval = push_to_checkout(sha1, &invoked_hook, &env, worktree->path);
1445 if (!invoked_hook)
1446 retval = push_to_deploy(sha1, &env, worktree->path);
1448 strvec_clear(&env);
1449 return retval;
1452 static const char *update(struct command *cmd, struct shallow_info *si)
1454 const char *name = cmd->ref_name;
1455 struct strbuf namespaced_name_buf = STRBUF_INIT;
1456 static char *namespaced_name;
1457 const char *ret;
1458 struct object_id *old_oid = &cmd->old_oid;
1459 struct object_id *new_oid = &cmd->new_oid;
1460 int do_update_worktree = 0;
1461 struct worktree **worktrees = get_worktrees();
1462 const struct worktree *worktree =
1463 find_shared_symref(worktrees, "HEAD", name);
1465 /* only refs/... are allowed */
1466 if (!starts_with(name, "refs/") || check_refname_format(name + 5, 0)) {
1467 rp_error("refusing to create funny ref '%s' remotely", name);
1468 ret = "funny refname";
1469 goto out;
1472 strbuf_addf(&namespaced_name_buf, "%s%s", get_git_namespace(), name);
1473 free(namespaced_name);
1474 namespaced_name = strbuf_detach(&namespaced_name_buf, NULL);
1476 if (worktree && !worktree->is_bare) {
1477 switch (deny_current_branch) {
1478 case DENY_IGNORE:
1479 break;
1480 case DENY_WARN:
1481 rp_warning("updating the current branch");
1482 break;
1483 case DENY_REFUSE:
1484 case DENY_UNCONFIGURED:
1485 rp_error("refusing to update checked out branch: %s", name);
1486 if (deny_current_branch == DENY_UNCONFIGURED)
1487 refuse_unconfigured_deny();
1488 ret = "branch is currently checked out";
1489 goto out;
1490 case DENY_UPDATE_INSTEAD:
1491 /* pass -- let other checks intervene first */
1492 do_update_worktree = 1;
1493 break;
1497 if (!is_null_oid(new_oid) && !has_object_file(new_oid)) {
1498 error("unpack should have generated %s, "
1499 "but I can't find it!", oid_to_hex(new_oid));
1500 ret = "bad pack";
1501 goto out;
1504 if (!is_null_oid(old_oid) && is_null_oid(new_oid)) {
1505 if (deny_deletes && starts_with(name, "refs/heads/")) {
1506 rp_error("denying ref deletion for %s", name);
1507 ret = "deletion prohibited";
1508 goto out;
1511 if (worktree || (head_name && !strcmp(namespaced_name, head_name))) {
1512 switch (deny_delete_current) {
1513 case DENY_IGNORE:
1514 break;
1515 case DENY_WARN:
1516 rp_warning("deleting the current branch");
1517 break;
1518 case DENY_REFUSE:
1519 case DENY_UNCONFIGURED:
1520 case DENY_UPDATE_INSTEAD:
1521 if (deny_delete_current == DENY_UNCONFIGURED)
1522 refuse_unconfigured_deny_delete_current();
1523 rp_error("refusing to delete the current branch: %s", name);
1524 ret = "deletion of the current branch prohibited";
1525 goto out;
1526 default:
1527 ret = "Invalid denyDeleteCurrent setting";
1528 goto out;
1533 if (deny_non_fast_forwards && !is_null_oid(new_oid) &&
1534 !is_null_oid(old_oid) &&
1535 starts_with(name, "refs/heads/")) {
1536 struct object *old_object, *new_object;
1537 struct commit *old_commit, *new_commit;
1539 old_object = parse_object(the_repository, old_oid);
1540 new_object = parse_object(the_repository, new_oid);
1542 if (!old_object || !new_object ||
1543 old_object->type != OBJ_COMMIT ||
1544 new_object->type != OBJ_COMMIT) {
1545 error("bad sha1 objects for %s", name);
1546 ret = "bad ref";
1547 goto out;
1549 old_commit = (struct commit *)old_object;
1550 new_commit = (struct commit *)new_object;
1551 if (!in_merge_bases(old_commit, new_commit)) {
1552 rp_error("denying non-fast-forward %s"
1553 " (you should pull first)", name);
1554 ret = "non-fast-forward";
1555 goto out;
1558 if (run_update_hook(cmd)) {
1559 rp_error("hook declined to update %s", name);
1560 ret = "hook declined";
1561 goto out;
1564 if (do_update_worktree) {
1565 ret = update_worktree(new_oid->hash, worktree);
1566 if (ret)
1567 goto out;
1570 if (is_null_oid(new_oid)) {
1571 struct strbuf err = STRBUF_INIT;
1572 if (!parse_object(the_repository, old_oid)) {
1573 old_oid = NULL;
1574 if (ref_exists(name)) {
1575 rp_warning("allowing deletion of corrupt ref");
1576 } else {
1577 rp_warning("deleting a non-existent ref");
1578 cmd->did_not_exist = 1;
1581 if (ref_transaction_delete(transaction,
1582 namespaced_name,
1583 old_oid,
1584 0, "push", &err)) {
1585 rp_error("%s", err.buf);
1586 ret = "failed to delete";
1587 } else {
1588 ret = NULL; /* good */
1590 strbuf_release(&err);
1592 else {
1593 struct strbuf err = STRBUF_INIT;
1594 if (shallow_update && si->shallow_ref[cmd->index] &&
1595 update_shallow_ref(cmd, si)) {
1596 ret = "shallow error";
1597 goto out;
1600 if (ref_transaction_update(transaction,
1601 namespaced_name,
1602 new_oid, old_oid,
1603 0, "push",
1604 &err)) {
1605 rp_error("%s", err.buf);
1606 ret = "failed to update ref";
1607 } else {
1608 ret = NULL; /* good */
1610 strbuf_release(&err);
1613 out:
1614 free_worktrees(worktrees);
1615 return ret;
1618 static void run_update_post_hook(struct command *commands)
1620 struct command *cmd;
1621 struct child_process proc = CHILD_PROCESS_INIT;
1622 const char *hook;
1624 hook = find_hook("post-update");
1625 if (!hook)
1626 return;
1628 for (cmd = commands; cmd; cmd = cmd->next) {
1629 if (cmd->error_string || cmd->did_not_exist)
1630 continue;
1631 if (!proc.args.nr)
1632 strvec_push(&proc.args, hook);
1633 strvec_push(&proc.args, cmd->ref_name);
1635 if (!proc.args.nr)
1636 return;
1638 proc.no_stdin = 1;
1639 proc.stdout_to_stderr = 1;
1640 proc.err = use_sideband ? -1 : 0;
1641 proc.trace2_hook_name = "post-update";
1643 if (!start_command(&proc)) {
1644 if (use_sideband)
1645 copy_to_sideband(proc.err, -1, NULL);
1646 finish_command(&proc);
1650 static void check_aliased_update_internal(struct command *cmd,
1651 struct string_list *list,
1652 const char *dst_name, int flag)
1654 struct string_list_item *item;
1655 struct command *dst_cmd;
1657 if (!(flag & REF_ISSYMREF))
1658 return;
1660 if (!dst_name) {
1661 rp_error("refusing update to broken symref '%s'", cmd->ref_name);
1662 cmd->skip_update = 1;
1663 cmd->error_string = "broken symref";
1664 return;
1666 dst_name = strip_namespace(dst_name);
1668 if (!(item = string_list_lookup(list, dst_name)))
1669 return;
1671 cmd->skip_update = 1;
1673 dst_cmd = (struct command *) item->util;
1675 if (oideq(&cmd->old_oid, &dst_cmd->old_oid) &&
1676 oideq(&cmd->new_oid, &dst_cmd->new_oid))
1677 return;
1679 dst_cmd->skip_update = 1;
1681 rp_error("refusing inconsistent update between symref '%s' (%s..%s) and"
1682 " its target '%s' (%s..%s)",
1683 cmd->ref_name,
1684 find_unique_abbrev(&cmd->old_oid, DEFAULT_ABBREV),
1685 find_unique_abbrev(&cmd->new_oid, DEFAULT_ABBREV),
1686 dst_cmd->ref_name,
1687 find_unique_abbrev(&dst_cmd->old_oid, DEFAULT_ABBREV),
1688 find_unique_abbrev(&dst_cmd->new_oid, DEFAULT_ABBREV));
1690 cmd->error_string = dst_cmd->error_string =
1691 "inconsistent aliased update";
1694 static void check_aliased_update(struct command *cmd, struct string_list *list)
1696 struct strbuf buf = STRBUF_INIT;
1697 const char *dst_name;
1698 int flag;
1700 strbuf_addf(&buf, "%s%s", get_git_namespace(), cmd->ref_name);
1701 dst_name = resolve_ref_unsafe(buf.buf, 0, NULL, &flag);
1702 check_aliased_update_internal(cmd, list, dst_name, flag);
1703 strbuf_release(&buf);
1706 static void check_aliased_updates(struct command *commands)
1708 struct command *cmd;
1709 struct string_list ref_list = STRING_LIST_INIT_NODUP;
1711 for (cmd = commands; cmd; cmd = cmd->next) {
1712 struct string_list_item *item =
1713 string_list_append(&ref_list, cmd->ref_name);
1714 item->util = (void *)cmd;
1716 string_list_sort(&ref_list);
1718 for (cmd = commands; cmd; cmd = cmd->next) {
1719 if (!cmd->error_string)
1720 check_aliased_update(cmd, &ref_list);
1723 string_list_clear(&ref_list, 0);
1726 static const struct object_id *command_singleton_iterator(void *cb_data)
1728 struct command **cmd_list = cb_data;
1729 struct command *cmd = *cmd_list;
1731 if (!cmd || is_null_oid(&cmd->new_oid))
1732 return NULL;
1733 *cmd_list = NULL; /* this returns only one */
1734 return &cmd->new_oid;
1737 static void set_connectivity_errors(struct command *commands,
1738 struct shallow_info *si)
1740 struct command *cmd;
1742 for (cmd = commands; cmd; cmd = cmd->next) {
1743 struct command *singleton = cmd;
1744 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1746 if (shallow_update && si->shallow_ref[cmd->index])
1747 /* to be checked in update_shallow_ref() */
1748 continue;
1750 opt.env = tmp_objdir_env(tmp_objdir);
1751 if (!check_connected(command_singleton_iterator, &singleton,
1752 &opt))
1753 continue;
1755 cmd->error_string = "missing necessary objects";
1759 struct iterate_data {
1760 struct command *cmds;
1761 struct shallow_info *si;
1764 static const struct object_id *iterate_receive_command_list(void *cb_data)
1766 struct iterate_data *data = cb_data;
1767 struct command **cmd_list = &data->cmds;
1768 struct command *cmd = *cmd_list;
1770 for (; cmd; cmd = cmd->next) {
1771 if (shallow_update && data->si->shallow_ref[cmd->index])
1772 /* to be checked in update_shallow_ref() */
1773 continue;
1774 if (!is_null_oid(&cmd->new_oid) && !cmd->skip_update) {
1775 *cmd_list = cmd->next;
1776 return &cmd->new_oid;
1779 return NULL;
1782 static void reject_updates_to_hidden(struct command *commands)
1784 struct strbuf refname_full = STRBUF_INIT;
1785 size_t prefix_len;
1786 struct command *cmd;
1788 strbuf_addstr(&refname_full, get_git_namespace());
1789 prefix_len = refname_full.len;
1791 for (cmd = commands; cmd; cmd = cmd->next) {
1792 if (cmd->error_string)
1793 continue;
1795 strbuf_setlen(&refname_full, prefix_len);
1796 strbuf_addstr(&refname_full, cmd->ref_name);
1798 if (!ref_is_hidden(cmd->ref_name, refname_full.buf, &hidden_refs))
1799 continue;
1800 if (is_null_oid(&cmd->new_oid))
1801 cmd->error_string = "deny deleting a hidden ref";
1802 else
1803 cmd->error_string = "deny updating a hidden ref";
1806 strbuf_release(&refname_full);
1809 static int should_process_cmd(struct command *cmd)
1811 return !cmd->error_string && !cmd->skip_update;
1814 static void BUG_if_skipped_connectivity_check(struct command *commands,
1815 struct shallow_info *si)
1817 struct command *cmd;
1819 for (cmd = commands; cmd; cmd = cmd->next) {
1820 if (should_process_cmd(cmd) && si->shallow_ref[cmd->index])
1821 bug("connectivity check has not been run on ref %s",
1822 cmd->ref_name);
1824 BUG_if_bug("connectivity check skipped???");
1827 static void execute_commands_non_atomic(struct command *commands,
1828 struct shallow_info *si)
1830 struct command *cmd;
1831 struct strbuf err = STRBUF_INIT;
1833 for (cmd = commands; cmd; cmd = cmd->next) {
1834 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1835 continue;
1837 transaction = ref_transaction_begin(&err);
1838 if (!transaction) {
1839 rp_error("%s", err.buf);
1840 strbuf_reset(&err);
1841 cmd->error_string = "transaction failed to start";
1842 continue;
1845 cmd->error_string = update(cmd, si);
1847 if (!cmd->error_string
1848 && ref_transaction_commit(transaction, &err)) {
1849 rp_error("%s", err.buf);
1850 strbuf_reset(&err);
1851 cmd->error_string = "failed to update ref";
1853 ref_transaction_free(transaction);
1855 strbuf_release(&err);
1858 static void execute_commands_atomic(struct command *commands,
1859 struct shallow_info *si)
1861 struct command *cmd;
1862 struct strbuf err = STRBUF_INIT;
1863 const char *reported_error = "atomic push failure";
1865 transaction = ref_transaction_begin(&err);
1866 if (!transaction) {
1867 rp_error("%s", err.buf);
1868 strbuf_reset(&err);
1869 reported_error = "transaction failed to start";
1870 goto failure;
1873 for (cmd = commands; cmd; cmd = cmd->next) {
1874 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1875 continue;
1877 cmd->error_string = update(cmd, si);
1879 if (cmd->error_string)
1880 goto failure;
1883 if (ref_transaction_commit(transaction, &err)) {
1884 rp_error("%s", err.buf);
1885 reported_error = "atomic transaction failed";
1886 goto failure;
1888 goto cleanup;
1890 failure:
1891 for (cmd = commands; cmd; cmd = cmd->next)
1892 if (!cmd->error_string)
1893 cmd->error_string = reported_error;
1895 cleanup:
1896 ref_transaction_free(transaction);
1897 strbuf_release(&err);
1900 static void execute_commands(struct command *commands,
1901 const char *unpacker_error,
1902 struct shallow_info *si,
1903 const struct string_list *push_options)
1905 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1906 struct command *cmd;
1907 struct iterate_data data;
1908 struct async muxer;
1909 int err_fd = 0;
1910 int run_proc_receive = 0;
1912 if (unpacker_error) {
1913 for (cmd = commands; cmd; cmd = cmd->next)
1914 cmd->error_string = "unpacker error";
1915 return;
1918 if (use_sideband) {
1919 memset(&muxer, 0, sizeof(muxer));
1920 muxer.proc = copy_to_sideband;
1921 muxer.in = -1;
1922 if (!start_async(&muxer))
1923 err_fd = muxer.in;
1924 /* ...else, continue without relaying sideband */
1927 data.cmds = commands;
1928 data.si = si;
1929 opt.err_fd = err_fd;
1930 opt.progress = err_fd && !quiet;
1931 opt.env = tmp_objdir_env(tmp_objdir);
1932 opt.exclude_hidden_refs_section = "receive";
1934 if (check_connected(iterate_receive_command_list, &data, &opt))
1935 set_connectivity_errors(commands, si);
1937 if (use_sideband)
1938 finish_async(&muxer);
1940 reject_updates_to_hidden(commands);
1943 * Try to find commands that have special prefix in their reference names,
1944 * and mark them to run an external "proc-receive" hook later.
1946 if (proc_receive_ref) {
1947 for (cmd = commands; cmd; cmd = cmd->next) {
1948 if (!should_process_cmd(cmd))
1949 continue;
1951 if (proc_receive_ref_matches(cmd)) {
1952 cmd->run_proc_receive = RUN_PROC_RECEIVE_SCHEDULED;
1953 run_proc_receive = 1;
1958 if (run_receive_hook(commands, "pre-receive", 0, push_options)) {
1959 for (cmd = commands; cmd; cmd = cmd->next) {
1960 if (!cmd->error_string)
1961 cmd->error_string = "pre-receive hook declined";
1963 return;
1967 * If there is no command ready to run, should return directly to destroy
1968 * temporary data in the quarantine area.
1970 for (cmd = commands; cmd && cmd->error_string; cmd = cmd->next)
1971 ; /* nothing */
1972 if (!cmd)
1973 return;
1976 * Now we'll start writing out refs, which means the objects need
1977 * to be in their final positions so that other processes can see them.
1979 if (tmp_objdir_migrate(tmp_objdir) < 0) {
1980 for (cmd = commands; cmd; cmd = cmd->next) {
1981 if (!cmd->error_string)
1982 cmd->error_string = "unable to migrate objects to permanent storage";
1984 return;
1986 tmp_objdir = NULL;
1988 check_aliased_updates(commands);
1990 free(head_name_to_free);
1991 head_name = head_name_to_free = resolve_refdup("HEAD", 0, NULL, NULL);
1993 if (run_proc_receive &&
1994 run_proc_receive_hook(commands, push_options))
1995 for (cmd = commands; cmd; cmd = cmd->next)
1996 if (!cmd->error_string &&
1997 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED) &&
1998 (cmd->run_proc_receive || use_atomic))
1999 cmd->error_string = "fail to run proc-receive hook";
2001 if (use_atomic)
2002 execute_commands_atomic(commands, si);
2003 else
2004 execute_commands_non_atomic(commands, si);
2006 if (shallow_update)
2007 BUG_if_skipped_connectivity_check(commands, si);
2010 static struct command **queue_command(struct command **tail,
2011 const char *line,
2012 int linelen)
2014 struct object_id old_oid, new_oid;
2015 struct command *cmd;
2016 const char *refname;
2017 int reflen;
2018 const char *p;
2020 if (parse_oid_hex(line, &old_oid, &p) ||
2021 *p++ != ' ' ||
2022 parse_oid_hex(p, &new_oid, &p) ||
2023 *p++ != ' ')
2024 die("protocol error: expected old/new/ref, got '%s'", line);
2026 refname = p;
2027 reflen = linelen - (p - line);
2028 FLEX_ALLOC_MEM(cmd, ref_name, refname, reflen);
2029 oidcpy(&cmd->old_oid, &old_oid);
2030 oidcpy(&cmd->new_oid, &new_oid);
2031 *tail = cmd;
2032 return &cmd->next;
2035 static void queue_commands_from_cert(struct command **tail,
2036 struct strbuf *push_cert)
2038 const char *boc, *eoc;
2040 if (*tail)
2041 die("protocol error: got both push certificate and unsigned commands");
2043 boc = strstr(push_cert->buf, "\n\n");
2044 if (!boc)
2045 die("malformed push certificate %.*s", 100, push_cert->buf);
2046 else
2047 boc += 2;
2048 eoc = push_cert->buf + parse_signed_buffer(push_cert->buf, push_cert->len);
2050 while (boc < eoc) {
2051 const char *eol = memchr(boc, '\n', eoc - boc);
2052 tail = queue_command(tail, boc, eol ? eol - boc : eoc - boc);
2053 boc = eol ? eol + 1 : eoc;
2057 static struct command *read_head_info(struct packet_reader *reader,
2058 struct oid_array *shallow)
2060 struct command *commands = NULL;
2061 struct command **p = &commands;
2062 for (;;) {
2063 int linelen;
2065 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2066 break;
2068 if (reader->pktlen > 8 && starts_with(reader->line, "shallow ")) {
2069 struct object_id oid;
2070 if (get_oid_hex(reader->line + 8, &oid))
2071 die("protocol error: expected shallow sha, got '%s'",
2072 reader->line + 8);
2073 oid_array_append(shallow, &oid);
2074 continue;
2077 linelen = strlen(reader->line);
2078 if (linelen < reader->pktlen) {
2079 const char *feature_list = reader->line + linelen + 1;
2080 const char *hash = NULL;
2081 const char *client_sid;
2082 int len = 0;
2083 if (parse_feature_request(feature_list, "report-status"))
2084 report_status = 1;
2085 if (parse_feature_request(feature_list, "report-status-v2"))
2086 report_status_v2 = 1;
2087 if (parse_feature_request(feature_list, "side-band-64k"))
2088 use_sideband = LARGE_PACKET_MAX;
2089 if (parse_feature_request(feature_list, "quiet"))
2090 quiet = 1;
2091 if (advertise_atomic_push
2092 && parse_feature_request(feature_list, "atomic"))
2093 use_atomic = 1;
2094 if (advertise_push_options
2095 && parse_feature_request(feature_list, "push-options"))
2096 use_push_options = 1;
2097 hash = parse_feature_value(feature_list, "object-format", &len, NULL);
2098 if (!hash) {
2099 hash = hash_algos[GIT_HASH_SHA1].name;
2100 len = strlen(hash);
2102 if (xstrncmpz(the_hash_algo->name, hash, len))
2103 die("error: unsupported object format '%s'", hash);
2104 client_sid = parse_feature_value(feature_list, "session-id", &len, NULL);
2105 if (client_sid) {
2106 char *sid = xstrndup(client_sid, len);
2107 trace2_data_string("transfer", NULL, "client-sid", client_sid);
2108 free(sid);
2112 if (!strcmp(reader->line, "push-cert")) {
2113 int true_flush = 0;
2114 int saved_options = reader->options;
2115 reader->options &= ~PACKET_READ_CHOMP_NEWLINE;
2117 for (;;) {
2118 packet_reader_read(reader);
2119 if (reader->status == PACKET_READ_FLUSH) {
2120 true_flush = 1;
2121 break;
2123 if (reader->status != PACKET_READ_NORMAL) {
2124 die("protocol error: got an unexpected packet");
2126 if (!strcmp(reader->line, "push-cert-end\n"))
2127 break; /* end of cert */
2128 strbuf_addstr(&push_cert, reader->line);
2130 reader->options = saved_options;
2132 if (true_flush)
2133 break;
2134 continue;
2137 p = queue_command(p, reader->line, linelen);
2140 if (push_cert.len)
2141 queue_commands_from_cert(p, &push_cert);
2143 return commands;
2146 static void read_push_options(struct packet_reader *reader,
2147 struct string_list *options)
2149 while (1) {
2150 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2151 break;
2153 string_list_append(options, reader->line);
2157 static const char *parse_pack_header(struct pack_header *hdr)
2159 switch (read_pack_header(0, hdr)) {
2160 case PH_ERROR_EOF:
2161 return "eof before pack header was fully read";
2163 case PH_ERROR_PACK_SIGNATURE:
2164 return "protocol error (pack signature mismatch detected)";
2166 case PH_ERROR_PROTOCOL:
2167 return "protocol error (pack version unsupported)";
2169 default:
2170 return "unknown error in parse_pack_header";
2172 case 0:
2173 return NULL;
2177 static const char *pack_lockfile;
2179 static void push_header_arg(struct strvec *args, struct pack_header *hdr)
2181 strvec_pushf(args, "--pack_header=%"PRIu32",%"PRIu32,
2182 ntohl(hdr->hdr_version), ntohl(hdr->hdr_entries));
2185 static const char *unpack(int err_fd, struct shallow_info *si)
2187 struct pack_header hdr;
2188 const char *hdr_err;
2189 int status;
2190 struct child_process child = CHILD_PROCESS_INIT;
2191 int fsck_objects = (receive_fsck_objects >= 0
2192 ? receive_fsck_objects
2193 : transfer_fsck_objects >= 0
2194 ? transfer_fsck_objects
2195 : 0);
2197 hdr_err = parse_pack_header(&hdr);
2198 if (hdr_err) {
2199 if (err_fd > 0)
2200 close(err_fd);
2201 return hdr_err;
2204 if (si->nr_ours || si->nr_theirs) {
2205 alt_shallow_file = setup_temporary_shallow(si->shallow);
2206 strvec_push(&child.args, "--shallow-file");
2207 strvec_push(&child.args, alt_shallow_file);
2210 tmp_objdir = tmp_objdir_create("incoming");
2211 if (!tmp_objdir) {
2212 if (err_fd > 0)
2213 close(err_fd);
2214 return "unable to create temporary object directory";
2216 strvec_pushv(&child.env, tmp_objdir_env(tmp_objdir));
2219 * Normally we just pass the tmp_objdir environment to the child
2220 * processes that do the heavy lifting, but we may need to see these
2221 * objects ourselves to set up shallow information.
2223 tmp_objdir_add_as_alternate(tmp_objdir);
2225 if (ntohl(hdr.hdr_entries) < unpack_limit) {
2226 strvec_push(&child.args, "unpack-objects");
2227 push_header_arg(&child.args, &hdr);
2228 if (quiet)
2229 strvec_push(&child.args, "-q");
2230 if (fsck_objects)
2231 strvec_pushf(&child.args, "--strict%s",
2232 fsck_msg_types.buf);
2233 if (max_input_size)
2234 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2235 (uintmax_t)max_input_size);
2236 child.no_stdout = 1;
2237 child.err = err_fd;
2238 child.git_cmd = 1;
2239 status = run_command(&child);
2240 if (status)
2241 return "unpack-objects abnormal exit";
2242 } else {
2243 char hostname[HOST_NAME_MAX + 1];
2245 strvec_pushl(&child.args, "index-pack", "--stdin", NULL);
2246 push_header_arg(&child.args, &hdr);
2248 if (xgethostname(hostname, sizeof(hostname)))
2249 xsnprintf(hostname, sizeof(hostname), "localhost");
2250 strvec_pushf(&child.args,
2251 "--keep=receive-pack %"PRIuMAX" on %s",
2252 (uintmax_t)getpid(),
2253 hostname);
2255 if (!quiet && err_fd)
2256 strvec_push(&child.args, "--show-resolving-progress");
2257 if (use_sideband)
2258 strvec_push(&child.args, "--report-end-of-input");
2259 if (fsck_objects)
2260 strvec_pushf(&child.args, "--strict%s",
2261 fsck_msg_types.buf);
2262 if (!reject_thin)
2263 strvec_push(&child.args, "--fix-thin");
2264 if (max_input_size)
2265 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2266 (uintmax_t)max_input_size);
2267 child.out = -1;
2268 child.err = err_fd;
2269 child.git_cmd = 1;
2270 status = start_command(&child);
2271 if (status)
2272 return "index-pack fork failed";
2273 pack_lockfile = index_pack_lockfile(child.out, NULL);
2274 close(child.out);
2275 status = finish_command(&child);
2276 if (status)
2277 return "index-pack abnormal exit";
2278 reprepare_packed_git(the_repository);
2280 return NULL;
2283 static const char *unpack_with_sideband(struct shallow_info *si)
2285 struct async muxer;
2286 const char *ret;
2288 if (!use_sideband)
2289 return unpack(0, si);
2291 use_keepalive = KEEPALIVE_AFTER_NUL;
2292 memset(&muxer, 0, sizeof(muxer));
2293 muxer.proc = copy_to_sideband;
2294 muxer.in = -1;
2295 if (start_async(&muxer))
2296 return NULL;
2298 ret = unpack(muxer.in, si);
2300 finish_async(&muxer);
2301 return ret;
2304 static void prepare_shallow_update(struct shallow_info *si)
2306 int i, j, k, bitmap_size = DIV_ROUND_UP(si->ref->nr, 32);
2308 ALLOC_ARRAY(si->used_shallow, si->shallow->nr);
2309 assign_shallow_commits_to_refs(si, si->used_shallow, NULL);
2311 CALLOC_ARRAY(si->need_reachability_test, si->shallow->nr);
2312 CALLOC_ARRAY(si->reachable, si->shallow->nr);
2313 CALLOC_ARRAY(si->shallow_ref, si->ref->nr);
2315 for (i = 0; i < si->nr_ours; i++)
2316 si->need_reachability_test[si->ours[i]] = 1;
2318 for (i = 0; i < si->shallow->nr; i++) {
2319 if (!si->used_shallow[i])
2320 continue;
2321 for (j = 0; j < bitmap_size; j++) {
2322 if (!si->used_shallow[i][j])
2323 continue;
2324 si->need_reachability_test[i]++;
2325 for (k = 0; k < 32; k++)
2326 if (si->used_shallow[i][j] & (1U << k))
2327 si->shallow_ref[j * 32 + k]++;
2331 * true for those associated with some refs and belong
2332 * in "ours" list aka "step 7 not done yet"
2334 si->need_reachability_test[i] =
2335 si->need_reachability_test[i] > 1;
2339 * keep hooks happy by forcing a temporary shallow file via
2340 * env variable because we can't add --shallow-file to every
2341 * command. check_connected() will be done with
2342 * true .git/shallow though.
2344 setenv(GIT_SHALLOW_FILE_ENVIRONMENT, alt_shallow_file, 1);
2347 static void update_shallow_info(struct command *commands,
2348 struct shallow_info *si,
2349 struct oid_array *ref)
2351 struct command *cmd;
2352 int *ref_status;
2353 remove_nonexistent_theirs_shallow(si);
2354 if (!si->nr_ours && !si->nr_theirs) {
2355 shallow_update = 0;
2356 return;
2359 for (cmd = commands; cmd; cmd = cmd->next) {
2360 if (is_null_oid(&cmd->new_oid))
2361 continue;
2362 oid_array_append(ref, &cmd->new_oid);
2363 cmd->index = ref->nr - 1;
2365 si->ref = ref;
2367 if (shallow_update) {
2368 prepare_shallow_update(si);
2369 return;
2372 ALLOC_ARRAY(ref_status, ref->nr);
2373 assign_shallow_commits_to_refs(si, NULL, ref_status);
2374 for (cmd = commands; cmd; cmd = cmd->next) {
2375 if (is_null_oid(&cmd->new_oid))
2376 continue;
2377 if (ref_status[cmd->index]) {
2378 cmd->error_string = "shallow update not allowed";
2379 cmd->skip_update = 1;
2382 free(ref_status);
2385 static void report(struct command *commands, const char *unpack_status)
2387 struct command *cmd;
2388 struct strbuf buf = STRBUF_INIT;
2390 packet_buf_write(&buf, "unpack %s\n",
2391 unpack_status ? unpack_status : "ok");
2392 for (cmd = commands; cmd; cmd = cmd->next) {
2393 if (!cmd->error_string)
2394 packet_buf_write(&buf, "ok %s\n",
2395 cmd->ref_name);
2396 else
2397 packet_buf_write(&buf, "ng %s %s\n",
2398 cmd->ref_name, cmd->error_string);
2400 packet_buf_flush(&buf);
2402 if (use_sideband)
2403 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2404 else
2405 write_or_die(1, buf.buf, buf.len);
2406 strbuf_release(&buf);
2409 static void report_v2(struct command *commands, const char *unpack_status)
2411 struct command *cmd;
2412 struct strbuf buf = STRBUF_INIT;
2413 struct ref_push_report *report;
2415 packet_buf_write(&buf, "unpack %s\n",
2416 unpack_status ? unpack_status : "ok");
2417 for (cmd = commands; cmd; cmd = cmd->next) {
2418 int count = 0;
2420 if (cmd->error_string) {
2421 packet_buf_write(&buf, "ng %s %s\n",
2422 cmd->ref_name,
2423 cmd->error_string);
2424 continue;
2426 packet_buf_write(&buf, "ok %s\n",
2427 cmd->ref_name);
2428 for (report = cmd->report; report; report = report->next) {
2429 if (count++ > 0)
2430 packet_buf_write(&buf, "ok %s\n",
2431 cmd->ref_name);
2432 if (report->ref_name)
2433 packet_buf_write(&buf, "option refname %s\n",
2434 report->ref_name);
2435 if (report->old_oid)
2436 packet_buf_write(&buf, "option old-oid %s\n",
2437 oid_to_hex(report->old_oid));
2438 if (report->new_oid)
2439 packet_buf_write(&buf, "option new-oid %s\n",
2440 oid_to_hex(report->new_oid));
2441 if (report->forced_update)
2442 packet_buf_write(&buf, "option forced-update\n");
2445 packet_buf_flush(&buf);
2447 if (use_sideband)
2448 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2449 else
2450 write_or_die(1, buf.buf, buf.len);
2451 strbuf_release(&buf);
2454 static int delete_only(struct command *commands)
2456 struct command *cmd;
2457 for (cmd = commands; cmd; cmd = cmd->next) {
2458 if (!is_null_oid(&cmd->new_oid))
2459 return 0;
2461 return 1;
2464 int cmd_receive_pack(int argc, const char **argv, const char *prefix)
2466 int advertise_refs = 0;
2467 struct command *commands;
2468 struct oid_array shallow = OID_ARRAY_INIT;
2469 struct oid_array ref = OID_ARRAY_INIT;
2470 struct shallow_info si;
2471 struct packet_reader reader;
2473 struct option options[] = {
2474 OPT__QUIET(&quiet, N_("quiet")),
2475 OPT_HIDDEN_BOOL(0, "stateless-rpc", &stateless_rpc, NULL),
2476 OPT_HIDDEN_BOOL(0, "http-backend-info-refs", &advertise_refs, NULL),
2477 OPT_ALIAS(0, "advertise-refs", "http-backend-info-refs"),
2478 OPT_HIDDEN_BOOL(0, "reject-thin-pack-for-testing", &reject_thin, NULL),
2479 OPT_END()
2482 packet_trace_identity("receive-pack");
2484 argc = parse_options(argc, argv, prefix, options, receive_pack_usage, 0);
2486 if (argc > 1)
2487 usage_msg_opt(_("too many arguments"), receive_pack_usage, options);
2488 if (argc == 0)
2489 usage_msg_opt(_("you must specify a directory"), receive_pack_usage, options);
2491 service_dir = argv[0];
2493 setup_path();
2495 if (!enter_repo(service_dir, 0))
2496 die("'%s' does not appear to be a git repository", service_dir);
2498 git_config(receive_pack_config, NULL);
2499 if (cert_nonce_seed)
2500 push_cert_nonce = prepare_push_cert_nonce(service_dir, time(NULL));
2502 if (0 <= transfer_unpack_limit)
2503 unpack_limit = transfer_unpack_limit;
2504 else if (0 <= receive_unpack_limit)
2505 unpack_limit = receive_unpack_limit;
2507 switch (determine_protocol_version_server()) {
2508 case protocol_v2:
2510 * push support for protocol v2 has not been implemented yet,
2511 * so ignore the request to use v2 and fallback to using v0.
2513 break;
2514 case protocol_v1:
2516 * v1 is just the original protocol with a version string,
2517 * so just fall through after writing the version string.
2519 if (advertise_refs || !stateless_rpc)
2520 packet_write_fmt(1, "version 1\n");
2522 /* fallthrough */
2523 case protocol_v0:
2524 break;
2525 case protocol_unknown_version:
2526 BUG("unknown protocol version");
2529 if (advertise_refs || !stateless_rpc) {
2530 write_head_info();
2532 if (advertise_refs)
2533 return 0;
2535 packet_reader_init(&reader, 0, NULL, 0,
2536 PACKET_READ_CHOMP_NEWLINE |
2537 PACKET_READ_DIE_ON_ERR_PACKET);
2539 if ((commands = read_head_info(&reader, &shallow))) {
2540 const char *unpack_status = NULL;
2541 struct string_list push_options = STRING_LIST_INIT_DUP;
2543 if (use_push_options)
2544 read_push_options(&reader, &push_options);
2545 if (!check_cert_push_options(&push_options)) {
2546 struct command *cmd;
2547 for (cmd = commands; cmd; cmd = cmd->next)
2548 cmd->error_string = "inconsistent push options";
2551 prepare_shallow_info(&si, &shallow);
2552 if (!si.nr_ours && !si.nr_theirs)
2553 shallow_update = 0;
2554 if (!delete_only(commands)) {
2555 unpack_status = unpack_with_sideband(&si);
2556 update_shallow_info(commands, &si, &ref);
2558 use_keepalive = KEEPALIVE_ALWAYS;
2559 execute_commands(commands, unpack_status, &si,
2560 &push_options);
2561 if (pack_lockfile)
2562 unlink_or_warn(pack_lockfile);
2563 sigchain_push(SIGPIPE, SIG_IGN);
2564 if (report_status_v2)
2565 report_v2(commands, unpack_status);
2566 else if (report_status)
2567 report(commands, unpack_status);
2568 sigchain_pop(SIGPIPE);
2569 run_receive_hook(commands, "post-receive", 1,
2570 &push_options);
2571 run_update_post_hook(commands);
2572 string_list_clear(&push_options, 0);
2573 if (auto_gc) {
2574 struct child_process proc = CHILD_PROCESS_INIT;
2576 proc.no_stdin = 1;
2577 proc.stdout_to_stderr = 1;
2578 proc.err = use_sideband ? -1 : 0;
2579 proc.git_cmd = proc.close_object_store = 1;
2580 strvec_pushl(&proc.args, "gc", "--auto", "--quiet",
2581 NULL);
2583 if (!start_command(&proc)) {
2584 if (use_sideband)
2585 copy_to_sideband(proc.err, -1, NULL);
2586 finish_command(&proc);
2589 if (auto_update_server_info)
2590 update_server_info(0);
2591 clear_shallow_info(&si);
2593 if (use_sideband)
2594 packet_flush(1);
2595 oid_array_clear(&shallow);
2596 oid_array_clear(&ref);
2597 string_list_clear(&hidden_refs, 0);
2598 free((void *)push_cert_nonce);
2599 return 0;