]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/receive-pack.c
Merge branch 'rj/send-email-validate-hook-count-messages'
[thirdparty/git.git] / builtin / receive-pack.c
1 #include "builtin.h"
2 #include "abspath.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "lockfile.h"
9 #include "pack.h"
10 #include "refs.h"
11 #include "pkt-line.h"
12 #include "sideband.h"
13 #include "run-command.h"
14 #include "hook.h"
15 #include "exec-cmd.h"
16 #include "commit.h"
17 #include "object.h"
18 #include "remote.h"
19 #include "connect.h"
20 #include "string-list.h"
21 #include "oid-array.h"
22 #include "connected.h"
23 #include "strvec.h"
24 #include "version.h"
25 #include "tag.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.h"
34 #include "protocol.h"
35 #include "commit-reach.h"
36 #include "trace.h"
37 #include "trace2.h"
38 #include "worktree.h"
39 #include "shallow.h"
40 #include "parse-options.h"
41 #include "wrapper.h"
42
43 static const char * const receive_pack_usage[] = {
44 N_("git receive-pack <git-dir>"),
45 NULL
46 };
47
48 enum deny_action {
49 DENY_UNCONFIGURED,
50 DENY_IGNORE,
51 DENY_WARN,
52 DENY_REFUSE,
53 DENY_UPDATE_INSTEAD
54 };
55
56 static int deny_deletes;
57 static int deny_non_fast_forwards;
58 static enum deny_action deny_current_branch = DENY_UNCONFIGURED;
59 static enum deny_action deny_delete_current = DENY_UNCONFIGURED;
60 static int receive_fsck_objects = -1;
61 static int transfer_fsck_objects = -1;
62 static struct strbuf fsck_msg_types = STRBUF_INIT;
63 static int receive_unpack_limit = -1;
64 static int transfer_unpack_limit = -1;
65 static int advertise_atomic_push = 1;
66 static int advertise_push_options;
67 static int advertise_sid;
68 static int unpack_limit = 100;
69 static off_t max_input_size;
70 static int report_status;
71 static int report_status_v2;
72 static int use_sideband;
73 static int use_atomic;
74 static int use_push_options;
75 static int quiet;
76 static int prefer_ofs_delta = 1;
77 static int auto_update_server_info;
78 static int auto_gc = 1;
79 static int reject_thin;
80 static int stateless_rpc;
81 static const char *service_dir;
82 static const char *head_name;
83 static void *head_name_to_free;
84 static int sent_capabilities;
85 static int shallow_update;
86 static const char *alt_shallow_file;
87 static struct strbuf push_cert = STRBUF_INIT;
88 static struct object_id push_cert_oid;
89 static struct signature_check sigcheck;
90 static const char *push_cert_nonce;
91 static const char *cert_nonce_seed;
92 static struct string_list hidden_refs = STRING_LIST_INIT_DUP;
93
94 static const char *NONCE_UNSOLICITED = "UNSOLICITED";
95 static const char *NONCE_BAD = "BAD";
96 static const char *NONCE_MISSING = "MISSING";
97 static const char *NONCE_OK = "OK";
98 static const char *NONCE_SLOP = "SLOP";
99 static const char *nonce_status;
100 static long nonce_stamp_slop;
101 static timestamp_t nonce_stamp_slop_limit;
102 static struct ref_transaction *transaction;
103
104 static enum {
105 KEEPALIVE_NEVER = 0,
106 KEEPALIVE_AFTER_NUL,
107 KEEPALIVE_ALWAYS
108 } use_keepalive;
109 static int keepalive_in_sec = 5;
110
111 static struct tmp_objdir *tmp_objdir;
112
113 static struct proc_receive_ref {
114 unsigned int want_add:1,
115 want_delete:1,
116 want_modify:1,
117 negative_ref:1;
118 char *ref_prefix;
119 struct proc_receive_ref *next;
120 } *proc_receive_ref;
121
122 static void proc_receive_ref_append(const char *prefix);
123
124 static enum deny_action parse_deny_action(const char *var, const char *value)
125 {
126 if (value) {
127 if (!strcasecmp(value, "ignore"))
128 return DENY_IGNORE;
129 if (!strcasecmp(value, "warn"))
130 return DENY_WARN;
131 if (!strcasecmp(value, "refuse"))
132 return DENY_REFUSE;
133 if (!strcasecmp(value, "updateinstead"))
134 return DENY_UPDATE_INSTEAD;
135 }
136 if (git_config_bool(var, value))
137 return DENY_REFUSE;
138 return DENY_IGNORE;
139 }
140
141 static int receive_pack_config(const char *var, const char *value, void *cb)
142 {
143 int status = parse_hide_refs_config(var, value, "receive", &hidden_refs);
144
145 if (status)
146 return status;
147
148 if (strcmp(var, "receive.denydeletes") == 0) {
149 deny_deletes = git_config_bool(var, value);
150 return 0;
151 }
152
153 if (strcmp(var, "receive.denynonfastforwards") == 0) {
154 deny_non_fast_forwards = git_config_bool(var, value);
155 return 0;
156 }
157
158 if (strcmp(var, "receive.unpacklimit") == 0) {
159 receive_unpack_limit = git_config_int(var, value);
160 return 0;
161 }
162
163 if (strcmp(var, "transfer.unpacklimit") == 0) {
164 transfer_unpack_limit = git_config_int(var, value);
165 return 0;
166 }
167
168 if (strcmp(var, "receive.fsck.skiplist") == 0) {
169 const char *path;
170
171 if (git_config_pathname(&path, var, value))
172 return 1;
173 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
174 fsck_msg_types.len ? ',' : '=', path);
175 free((char *)path);
176 return 0;
177 }
178
179 if (skip_prefix(var, "receive.fsck.", &var)) {
180 if (is_valid_msg_type(var, value))
181 strbuf_addf(&fsck_msg_types, "%c%s=%s",
182 fsck_msg_types.len ? ',' : '=', var, value);
183 else
184 warning("skipping unknown msg id '%s'", var);
185 return 0;
186 }
187
188 if (strcmp(var, "receive.fsckobjects") == 0) {
189 receive_fsck_objects = git_config_bool(var, value);
190 return 0;
191 }
192
193 if (strcmp(var, "transfer.fsckobjects") == 0) {
194 transfer_fsck_objects = git_config_bool(var, value);
195 return 0;
196 }
197
198 if (!strcmp(var, "receive.denycurrentbranch")) {
199 deny_current_branch = parse_deny_action(var, value);
200 return 0;
201 }
202
203 if (strcmp(var, "receive.denydeletecurrent") == 0) {
204 deny_delete_current = parse_deny_action(var, value);
205 return 0;
206 }
207
208 if (strcmp(var, "repack.usedeltabaseoffset") == 0) {
209 prefer_ofs_delta = git_config_bool(var, value);
210 return 0;
211 }
212
213 if (strcmp(var, "receive.updateserverinfo") == 0) {
214 auto_update_server_info = git_config_bool(var, value);
215 return 0;
216 }
217
218 if (strcmp(var, "receive.autogc") == 0) {
219 auto_gc = git_config_bool(var, value);
220 return 0;
221 }
222
223 if (strcmp(var, "receive.shallowupdate") == 0) {
224 shallow_update = git_config_bool(var, value);
225 return 0;
226 }
227
228 if (strcmp(var, "receive.certnonceseed") == 0)
229 return git_config_string(&cert_nonce_seed, var, value);
230
231 if (strcmp(var, "receive.certnonceslop") == 0) {
232 nonce_stamp_slop_limit = git_config_ulong(var, value);
233 return 0;
234 }
235
236 if (strcmp(var, "receive.advertiseatomic") == 0) {
237 advertise_atomic_push = git_config_bool(var, value);
238 return 0;
239 }
240
241 if (strcmp(var, "receive.advertisepushoptions") == 0) {
242 advertise_push_options = git_config_bool(var, value);
243 return 0;
244 }
245
246 if (strcmp(var, "receive.keepalive") == 0) {
247 keepalive_in_sec = git_config_int(var, value);
248 return 0;
249 }
250
251 if (strcmp(var, "receive.maxinputsize") == 0) {
252 max_input_size = git_config_int64(var, value);
253 return 0;
254 }
255
256 if (strcmp(var, "receive.procreceiverefs") == 0) {
257 if (!value)
258 return config_error_nonbool(var);
259 proc_receive_ref_append(value);
260 return 0;
261 }
262
263 if (strcmp(var, "transfer.advertisesid") == 0) {
264 advertise_sid = git_config_bool(var, value);
265 return 0;
266 }
267
268 return git_default_config(var, value, cb);
269 }
270
271 static void show_ref(const char *path, const struct object_id *oid)
272 {
273 if (sent_capabilities) {
274 packet_write_fmt(1, "%s %s\n", oid_to_hex(oid), path);
275 } else {
276 struct strbuf cap = STRBUF_INIT;
277
278 strbuf_addstr(&cap,
279 "report-status report-status-v2 delete-refs side-band-64k quiet");
280 if (advertise_atomic_push)
281 strbuf_addstr(&cap, " atomic");
282 if (prefer_ofs_delta)
283 strbuf_addstr(&cap, " ofs-delta");
284 if (push_cert_nonce)
285 strbuf_addf(&cap, " push-cert=%s", push_cert_nonce);
286 if (advertise_push_options)
287 strbuf_addstr(&cap, " push-options");
288 if (advertise_sid)
289 strbuf_addf(&cap, " session-id=%s", trace2_session_id());
290 strbuf_addf(&cap, " object-format=%s", the_hash_algo->name);
291 strbuf_addf(&cap, " agent=%s", git_user_agent_sanitized());
292 packet_write_fmt(1, "%s %s%c%s\n",
293 oid_to_hex(oid), path, 0, cap.buf);
294 strbuf_release(&cap);
295 sent_capabilities = 1;
296 }
297 }
298
299 static int show_ref_cb(const char *path_full, const struct object_id *oid,
300 int flag UNUSED, void *data)
301 {
302 struct oidset *seen = data;
303 const char *path = strip_namespace(path_full);
304
305 if (ref_is_hidden(path, path_full, &hidden_refs))
306 return 0;
307
308 /*
309 * Advertise refs outside our current namespace as ".have"
310 * refs, so that the client can use them to minimize data
311 * transfer but will otherwise ignore them.
312 */
313 if (!path) {
314 if (oidset_insert(seen, oid))
315 return 0;
316 path = ".have";
317 } else {
318 oidset_insert(seen, oid);
319 }
320 show_ref(path, oid);
321 return 0;
322 }
323
324 static void show_one_alternate_ref(const struct object_id *oid,
325 void *data)
326 {
327 struct oidset *seen = data;
328
329 if (oidset_insert(seen, oid))
330 return;
331
332 show_ref(".have", oid);
333 }
334
335 static void write_head_info(void)
336 {
337 static struct oidset seen = OIDSET_INIT;
338
339 for_each_ref(show_ref_cb, &seen);
340 for_each_alternate_ref(show_one_alternate_ref, &seen);
341 oidset_clear(&seen);
342 if (!sent_capabilities)
343 show_ref("capabilities^{}", null_oid());
344
345 advertise_shallow_grafts(1);
346
347 /* EOF */
348 packet_flush(1);
349 }
350
351 #define RUN_PROC_RECEIVE_SCHEDULED 1
352 #define RUN_PROC_RECEIVE_RETURNED 2
353 struct command {
354 struct command *next;
355 const char *error_string;
356 struct ref_push_report *report;
357 unsigned int skip_update:1,
358 did_not_exist:1,
359 run_proc_receive:2;
360 int index;
361 struct object_id old_oid;
362 struct object_id new_oid;
363 char ref_name[FLEX_ARRAY]; /* more */
364 };
365
366 static void proc_receive_ref_append(const char *prefix)
367 {
368 struct proc_receive_ref *ref_pattern;
369 char *p;
370 int len;
371
372 CALLOC_ARRAY(ref_pattern, 1);
373 p = strchr(prefix, ':');
374 if (p) {
375 while (prefix < p) {
376 if (*prefix == 'a')
377 ref_pattern->want_add = 1;
378 else if (*prefix == 'd')
379 ref_pattern->want_delete = 1;
380 else if (*prefix == 'm')
381 ref_pattern->want_modify = 1;
382 else if (*prefix == '!')
383 ref_pattern->negative_ref = 1;
384 prefix++;
385 }
386 prefix++;
387 } else {
388 ref_pattern->want_add = 1;
389 ref_pattern->want_delete = 1;
390 ref_pattern->want_modify = 1;
391 }
392 len = strlen(prefix);
393 while (len && prefix[len - 1] == '/')
394 len--;
395 ref_pattern->ref_prefix = xmemdupz(prefix, len);
396 if (!proc_receive_ref) {
397 proc_receive_ref = ref_pattern;
398 } else {
399 struct proc_receive_ref *end;
400
401 end = proc_receive_ref;
402 while (end->next)
403 end = end->next;
404 end->next = ref_pattern;
405 }
406 }
407
408 static int proc_receive_ref_matches(struct command *cmd)
409 {
410 struct proc_receive_ref *p;
411
412 if (!proc_receive_ref)
413 return 0;
414
415 for (p = proc_receive_ref; p; p = p->next) {
416 const char *match = p->ref_prefix;
417 const char *remains;
418
419 if (!p->want_add && is_null_oid(&cmd->old_oid))
420 continue;
421 else if (!p->want_delete && is_null_oid(&cmd->new_oid))
422 continue;
423 else if (!p->want_modify &&
424 !is_null_oid(&cmd->old_oid) &&
425 !is_null_oid(&cmd->new_oid))
426 continue;
427
428 if (skip_prefix(cmd->ref_name, match, &remains) &&
429 (!*remains || *remains == '/')) {
430 if (!p->negative_ref)
431 return 1;
432 } else if (p->negative_ref) {
433 return 1;
434 }
435 }
436 return 0;
437 }
438
439 static void report_message(const char *prefix, const char *err, va_list params)
440 {
441 int sz;
442 char msg[4096];
443
444 sz = xsnprintf(msg, sizeof(msg), "%s", prefix);
445 sz += vsnprintf(msg + sz, sizeof(msg) - sz, err, params);
446 if (sz > (sizeof(msg) - 1))
447 sz = sizeof(msg) - 1;
448 msg[sz++] = '\n';
449
450 if (use_sideband)
451 send_sideband(1, 2, msg, sz, use_sideband);
452 else
453 xwrite(2, msg, sz);
454 }
455
456 __attribute__((format (printf, 1, 2)))
457 static void rp_warning(const char *err, ...)
458 {
459 va_list params;
460 va_start(params, err);
461 report_message("warning: ", err, params);
462 va_end(params);
463 }
464
465 __attribute__((format (printf, 1, 2)))
466 static void rp_error(const char *err, ...)
467 {
468 va_list params;
469 va_start(params, err);
470 report_message("error: ", err, params);
471 va_end(params);
472 }
473
474 static int copy_to_sideband(int in, int out UNUSED, void *arg UNUSED)
475 {
476 char data[128];
477 int keepalive_active = 0;
478
479 if (keepalive_in_sec <= 0)
480 use_keepalive = KEEPALIVE_NEVER;
481 if (use_keepalive == KEEPALIVE_ALWAYS)
482 keepalive_active = 1;
483
484 while (1) {
485 ssize_t sz;
486
487 if (keepalive_active) {
488 struct pollfd pfd;
489 int ret;
490
491 pfd.fd = in;
492 pfd.events = POLLIN;
493 ret = poll(&pfd, 1, 1000 * keepalive_in_sec);
494
495 if (ret < 0) {
496 if (errno == EINTR)
497 continue;
498 else
499 break;
500 } else if (ret == 0) {
501 /* no data; send a keepalive packet */
502 static const char buf[] = "0005\1";
503 write_or_die(1, buf, sizeof(buf) - 1);
504 continue;
505 } /* else there is actual data to read */
506 }
507
508 sz = xread(in, data, sizeof(data));
509 if (sz <= 0)
510 break;
511
512 if (use_keepalive == KEEPALIVE_AFTER_NUL && !keepalive_active) {
513 const char *p = memchr(data, '\0', sz);
514 if (p) {
515 /*
516 * The NUL tells us to start sending keepalives. Make
517 * sure we send any other data we read along
518 * with it.
519 */
520 keepalive_active = 1;
521 send_sideband(1, 2, data, p - data, use_sideband);
522 send_sideband(1, 2, p + 1, sz - (p - data + 1), use_sideband);
523 continue;
524 }
525 }
526
527 /*
528 * Either we're not looking for a NUL signal, or we didn't see
529 * it yet; just pass along the data.
530 */
531 send_sideband(1, 2, data, sz, use_sideband);
532 }
533 close(in);
534 return 0;
535 }
536
537 static void hmac_hash(unsigned char *out,
538 const char *key_in, size_t key_len,
539 const char *text, size_t text_len)
540 {
541 unsigned char key[GIT_MAX_BLKSZ];
542 unsigned char k_ipad[GIT_MAX_BLKSZ];
543 unsigned char k_opad[GIT_MAX_BLKSZ];
544 int i;
545 git_hash_ctx ctx;
546
547 /* RFC 2104 2. (1) */
548 memset(key, '\0', GIT_MAX_BLKSZ);
549 if (the_hash_algo->blksz < key_len) {
550 the_hash_algo->init_fn(&ctx);
551 the_hash_algo->update_fn(&ctx, key_in, key_len);
552 the_hash_algo->final_fn(key, &ctx);
553 } else {
554 memcpy(key, key_in, key_len);
555 }
556
557 /* RFC 2104 2. (2) & (5) */
558 for (i = 0; i < sizeof(key); i++) {
559 k_ipad[i] = key[i] ^ 0x36;
560 k_opad[i] = key[i] ^ 0x5c;
561 }
562
563 /* RFC 2104 2. (3) & (4) */
564 the_hash_algo->init_fn(&ctx);
565 the_hash_algo->update_fn(&ctx, k_ipad, sizeof(k_ipad));
566 the_hash_algo->update_fn(&ctx, text, text_len);
567 the_hash_algo->final_fn(out, &ctx);
568
569 /* RFC 2104 2. (6) & (7) */
570 the_hash_algo->init_fn(&ctx);
571 the_hash_algo->update_fn(&ctx, k_opad, sizeof(k_opad));
572 the_hash_algo->update_fn(&ctx, out, the_hash_algo->rawsz);
573 the_hash_algo->final_fn(out, &ctx);
574 }
575
576 static char *prepare_push_cert_nonce(const char *path, timestamp_t stamp)
577 {
578 struct strbuf buf = STRBUF_INIT;
579 unsigned char hash[GIT_MAX_RAWSZ];
580
581 strbuf_addf(&buf, "%s:%"PRItime, path, stamp);
582 hmac_hash(hash, buf.buf, buf.len, cert_nonce_seed, strlen(cert_nonce_seed));
583 strbuf_release(&buf);
584
585 /* RFC 2104 5. HMAC-SHA1 or HMAC-SHA256 */
586 strbuf_addf(&buf, "%"PRItime"-%.*s", stamp, (int)the_hash_algo->hexsz, hash_to_hex(hash));
587 return strbuf_detach(&buf, NULL);
588 }
589
590 static char *find_header(const char *msg, size_t len, const char *key,
591 const char **next_line)
592 {
593 size_t out_len;
594 const char *val = find_header_mem(msg, len, key, &out_len);
595
596 if (!val)
597 return NULL;
598
599 if (next_line)
600 *next_line = val + out_len + 1;
601
602 return xmemdupz(val, out_len);
603 }
604
605 /*
606 * Return zero if a and b are equal up to n bytes and nonzero if they are not.
607 * This operation is guaranteed to run in constant time to avoid leaking data.
608 */
609 static int constant_memequal(const char *a, const char *b, size_t n)
610 {
611 int res = 0;
612 size_t i;
613
614 for (i = 0; i < n; i++)
615 res |= a[i] ^ b[i];
616 return res;
617 }
618
619 static const char *check_nonce(const char *buf, size_t len)
620 {
621 char *nonce = find_header(buf, len, "nonce", NULL);
622 timestamp_t stamp, ostamp;
623 char *bohmac, *expect = NULL;
624 const char *retval = NONCE_BAD;
625 size_t noncelen;
626
627 if (!nonce) {
628 retval = NONCE_MISSING;
629 goto leave;
630 } else if (!push_cert_nonce) {
631 retval = NONCE_UNSOLICITED;
632 goto leave;
633 } else if (!strcmp(push_cert_nonce, nonce)) {
634 retval = NONCE_OK;
635 goto leave;
636 }
637
638 if (!stateless_rpc) {
639 /* returned nonce MUST match what we gave out earlier */
640 retval = NONCE_BAD;
641 goto leave;
642 }
643
644 /*
645 * In stateless mode, we may be receiving a nonce issued by
646 * another instance of the server that serving the same
647 * repository, and the timestamps may not match, but the
648 * nonce-seed and dir should match, so we can recompute and
649 * report the time slop.
650 *
651 * In addition, when a nonce issued by another instance has
652 * timestamp within receive.certnonceslop seconds, we pretend
653 * as if we issued that nonce when reporting to the hook.
654 */
655
656 /* nonce is concat(<seconds-since-epoch>, "-", <hmac>) */
657 if (*nonce <= '0' || '9' < *nonce) {
658 retval = NONCE_BAD;
659 goto leave;
660 }
661 stamp = parse_timestamp(nonce, &bohmac, 10);
662 if (bohmac == nonce || bohmac[0] != '-') {
663 retval = NONCE_BAD;
664 goto leave;
665 }
666
667 noncelen = strlen(nonce);
668 expect = prepare_push_cert_nonce(service_dir, stamp);
669 if (noncelen != strlen(expect)) {
670 /* This is not even the right size. */
671 retval = NONCE_BAD;
672 goto leave;
673 }
674 if (constant_memequal(expect, nonce, noncelen)) {
675 /* Not what we would have signed earlier */
676 retval = NONCE_BAD;
677 goto leave;
678 }
679
680 /*
681 * By how many seconds is this nonce stale? Negative value
682 * would mean it was issued by another server with its clock
683 * skewed in the future.
684 */
685 ostamp = parse_timestamp(push_cert_nonce, NULL, 10);
686 nonce_stamp_slop = (long)ostamp - (long)stamp;
687
688 if (nonce_stamp_slop_limit &&
689 labs(nonce_stamp_slop) <= nonce_stamp_slop_limit) {
690 /*
691 * Pretend as if the received nonce (which passes the
692 * HMAC check, so it is not a forged by third-party)
693 * is what we issued.
694 */
695 free((void *)push_cert_nonce);
696 push_cert_nonce = xstrdup(nonce);
697 retval = NONCE_OK;
698 } else {
699 retval = NONCE_SLOP;
700 }
701
702 leave:
703 free(nonce);
704 free(expect);
705 return retval;
706 }
707
708 /*
709 * Return 1 if there is no push_cert or if the push options in push_cert are
710 * the same as those in the argument; 0 otherwise.
711 */
712 static int check_cert_push_options(const struct string_list *push_options)
713 {
714 const char *buf = push_cert.buf;
715 int len = push_cert.len;
716
717 char *option;
718 const char *next_line;
719 int options_seen = 0;
720
721 int retval = 1;
722
723 if (!len)
724 return 1;
725
726 while ((option = find_header(buf, len, "push-option", &next_line))) {
727 len -= (next_line - buf);
728 buf = next_line;
729 options_seen++;
730 if (options_seen > push_options->nr
731 || strcmp(option,
732 push_options->items[options_seen - 1].string)) {
733 retval = 0;
734 goto leave;
735 }
736 free(option);
737 }
738
739 if (options_seen != push_options->nr)
740 retval = 0;
741
742 leave:
743 free(option);
744 return retval;
745 }
746
747 static void prepare_push_cert_sha1(struct child_process *proc)
748 {
749 static int already_done;
750
751 if (!push_cert.len)
752 return;
753
754 if (!already_done) {
755 int bogs /* beginning_of_gpg_sig */;
756
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);
761
762 memset(&sigcheck, '\0', sizeof(sigcheck));
763
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);
769
770 nonce_status = check_nonce(push_cert.buf, bogs);
771 }
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);
792 }
793 }
794 }
795
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;
802 };
803
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)
807 {
808 struct child_process proc = CHILD_PROCESS_INIT;
809 struct async muxer;
810 int code;
811 const char *hook_path = find_hook(hook_name);
812
813 if (!hook_path)
814 return 0;
815
816 strvec_push(&proc.args, hook_path);
817 proc.in = -1;
818 proc.stdout_to_stderr = 1;
819 proc.trace2_hook_name = hook_name;
820
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");
832
833 if (tmp_objdir)
834 strvec_pushv(&proc.env, tmp_objdir_env(tmp_objdir));
835
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;
844 }
845
846 prepare_push_cert_sha1(&proc);
847
848 code = start_command(&proc);
849 if (code) {
850 if (use_sideband)
851 finish_async(&muxer);
852 return code;
853 }
854
855 sigchain_push(SIGPIPE, SIG_IGN);
856
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;
864 }
865 close(proc.in);
866 if (use_sideband)
867 finish_async(&muxer);
868
869 sigchain_pop(SIGPIPE);
870
871 return finish_command(&proc);
872 }
873
874 static int feed_receive_hook(void *state_, const char **bufp, size_t *sizep)
875 {
876 struct receive_hook_feed_state *state = state_;
877 struct command *cmd = state->cmd;
878
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;
893
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;
908 }
909 if (bufp) {
910 *bufp = state->buf.buf;
911 *sizep = state->buf.len;
912 }
913 return 0;
914 }
915
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)
920 {
921 struct receive_hook_feed_state state;
922 int status;
923
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;
935 }
936
937 static int run_update_hook(struct command *cmd)
938 {
939 struct child_process proc = CHILD_PROCESS_INIT;
940 int code;
941 const char *hook_path = find_hook("update");
942
943 if (!hook_path)
944 return 0;
945
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));
950
951 proc.no_stdin = 1;
952 proc.stdout_to_stderr = 1;
953 proc.err = use_sideband ? -1 : 0;
954 proc.trace2_hook_name = "update";
955
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);
962 }
963
964 static struct command *find_command_by_refname(struct command *list,
965 const char *refname)
966 {
967 for (; list; list = list->next)
968 if (!strcmp(list->ref_name, refname))
969 return list;
970 return NULL;
971 }
972
973 static int read_proc_receive_report(struct packet_reader *reader,
974 struct command *commands,
975 struct strbuf *errmsg)
976 {
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;
984
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;
991
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;
998 }
999 break;
1000 }
1001 response++;
1002
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;
1009 }
1010 *p++ = '\0';
1011 if (!strcmp(head, "option")) {
1012 const char *key, *val;
1013
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;
1019 }
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;
1030 }
1031 new_report = 0;
1032 }
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;
1052 }
1053
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;
1065 }
1066
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;
1077 }
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;
1083 }
1084 hint->run_proc_receive |= RUN_PROC_RECEIVE_RETURNED;
1085 if (!strcmp(head, "ng")) {
1086 if (p)
1087 hint->error_string = xstrdup(p);
1088 else
1089 hint->error_string = "failed";
1090 code = -1;
1091 continue;
1092 }
1093 new_report = 1;
1094 }
1095
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;
1101 }
1102 return code;
1103 }
1104
1105 static int run_proc_receive_hook(struct command *commands,
1106 const struct string_list *push_options)
1107 {
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("proc-receive");
1118
1119 if (!hook_path) {
1120 rp_error("cannot find hook 'proc-receive'");
1121 return -1;
1122 }
1123
1124 strvec_push(&proc.args, hook_path);
1125 proc.in = -1;
1126 proc.out = -1;
1127 proc.trace2_hook_name = "proc-receive";
1128
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;
1139 }
1140
1141 code = start_command(&proc);
1142 if (code) {
1143 if (use_sideband)
1144 finish_async(&muxer);
1145 return code;
1146 }
1147
1148 sigchain_push(SIGPIPE, SIG_IGN);
1149
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");
1163 }
1164 if (!code)
1165 code = packet_flush_gently(proc.in);
1166
1167 if (!code)
1168 for (;;) {
1169 int linelen;
1170 enum packet_read_status status;
1171
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;
1178 }
1179
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;
1187 }
1188 }
1189 }
1190
1191 if (code) {
1192 strbuf_addstr(&errmsg, "fail to negotiate version with proc-receive hook");
1193 goto cleanup;
1194 }
1195
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;
1206 }
1207
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;
1218 }
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;
1224 }
1225
1226 /* Send push options */
1227 if (hook_use_push_options) {
1228 struct string_list_item *item;
1229
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;
1234 }
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;
1241 }
1242 }
1243
1244 /* Read result from proc-receive */
1245 code = read_proc_receive_report(&reader, commands, &errmsg);
1246
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;
1256
1257 p += errmsg.len - 1;
1258 if (*p == '\n')
1259 *p = '\0';
1260 rp_error("%s", errmsg.buf);
1261 strbuf_release(&errmsg);
1262 }
1263 sigchain_pop(SIGPIPE);
1264
1265 return code;
1266 }
1267
1268 static 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'.");
1282
1283 static void refuse_unconfigured_deny(void)
1284 {
1285 rp_error("%s", _(refuse_unconfigured_deny_msg));
1286 }
1287
1288 static 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'.");
1297
1298 static void refuse_unconfigured_deny_delete_current(void)
1299 {
1300 rp_error("%s", _(refuse_unconfigured_deny_delete_current_msg));
1301 }
1302
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)
1305 {
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;
1311
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]);
1319
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;
1326 }
1327
1328 commit_shallow_file(the_repository, &shallow_lock);
1329
1330 /*
1331 * Make sure setup_alternate_shallow() for the next ref does
1332 * not lose these new roots..
1333 */
1334 for (i = 0; i < extra.nr; i++)
1335 register_shallow(the_repository, &extra.oid[i]);
1336
1337 si->shallow_ref[cmd->index] = 0;
1338 oid_array_clear(&extra);
1339 return 0;
1340 }
1341
1342 /*
1343 * NEEDSWORK: we should consolidate various implementions 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.
1350 */
1351 static int head_has_history(void)
1352 {
1353 struct object_id oid;
1354
1355 return !repo_get_oid(the_repository, "HEAD", &oid);
1356 }
1357
1358 static const char *push_to_deploy(unsigned char *sha1,
1359 struct strvec *env,
1360 const char *work_tree)
1361 {
1362 struct child_process child = CHILD_PROCESS_INIT;
1363
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";
1373
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";
1385
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(),
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";
1399
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";
1411
1412 return NULL;
1413 }
1414
1415 static const char *push_to_checkout_hook = "push-to-checkout";
1416
1417 static const char *push_to_checkout(unsigned char *hash,
1418 int *invoked_hook,
1419 struct strvec *env,
1420 const char *work_tree)
1421 {
1422 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1423 opt.invoked_hook = invoked_hook;
1424
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(push_to_checkout_hook, &opt))
1429 return "push-to-checkout hook declined";
1430 else
1431 return NULL;
1432 }
1433
1434 static const char *update_worktree(unsigned char *sha1, const struct worktree *worktree)
1435 {
1436 const char *retval, *git_dir;
1437 struct strvec env = STRVEC_INIT;
1438 int invoked_hook;
1439
1440 if (!worktree || !worktree->path)
1441 BUG("worktree->path must be non-NULL");
1442
1443 if (worktree->is_bare)
1444 return "denyCurrentBranch = updateInstead needs a worktree";
1445 git_dir = get_worktree_git_dir(worktree);
1446
1447 strvec_pushf(&env, "GIT_DIR=%s", absolute_path(git_dir));
1448
1449 retval = push_to_checkout(sha1, &invoked_hook, &env, worktree->path);
1450 if (!invoked_hook)
1451 retval = push_to_deploy(sha1, &env, worktree->path);
1452
1453 strvec_clear(&env);
1454 return retval;
1455 }
1456
1457 static const char *update(struct command *cmd, struct shallow_info *si)
1458 {
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);
1469
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;
1477 }
1478
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);
1482
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;
1501 }
1502 }
1503
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;
1509 }
1510
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;
1516 }
1517
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;
1536 }
1537 }
1538 }
1539
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
1546 old_object = parse_object(the_repository, old_oid);
1547 new_object = parse_object(the_repository, new_oid);
1548
1549 if (!old_object || !new_object ||
1550 old_object->type != OBJ_COMMIT ||
1551 new_object->type != OBJ_COMMIT) {
1552 error("bad sha1 objects for %s", name);
1553 ret = "bad ref";
1554 goto out;
1555 }
1556 old_commit = (struct commit *)old_object;
1557 new_commit = (struct commit *)new_object;
1558 if (!repo_in_merge_bases(the_repository, old_commit, new_commit)) {
1559 rp_error("denying non-fast-forward %s"
1560 " (you should pull first)", name);
1561 ret = "non-fast-forward";
1562 goto out;
1563 }
1564 }
1565 if (run_update_hook(cmd)) {
1566 rp_error("hook declined to update %s", name);
1567 ret = "hook declined";
1568 goto out;
1569 }
1570
1571 if (do_update_worktree) {
1572 ret = update_worktree(new_oid->hash, worktree);
1573 if (ret)
1574 goto out;
1575 }
1576
1577 if (is_null_oid(new_oid)) {
1578 struct strbuf err = STRBUF_INIT;
1579 if (!parse_object(the_repository, old_oid)) {
1580 old_oid = NULL;
1581 if (ref_exists(name)) {
1582 rp_warning("allowing deletion of corrupt ref");
1583 } else {
1584 rp_warning("deleting a non-existent ref");
1585 cmd->did_not_exist = 1;
1586 }
1587 }
1588 if (ref_transaction_delete(transaction,
1589 namespaced_name,
1590 old_oid,
1591 0, "push", &err)) {
1592 rp_error("%s", err.buf);
1593 ret = "failed to delete";
1594 } else {
1595 ret = NULL; /* good */
1596 }
1597 strbuf_release(&err);
1598 }
1599 else {
1600 struct strbuf err = STRBUF_INIT;
1601 if (shallow_update && si->shallow_ref[cmd->index] &&
1602 update_shallow_ref(cmd, si)) {
1603 ret = "shallow error";
1604 goto out;
1605 }
1606
1607 if (ref_transaction_update(transaction,
1608 namespaced_name,
1609 new_oid, old_oid,
1610 0, "push",
1611 &err)) {
1612 rp_error("%s", err.buf);
1613 ret = "failed to update ref";
1614 } else {
1615 ret = NULL; /* good */
1616 }
1617 strbuf_release(&err);
1618 }
1619
1620 out:
1621 free_worktrees(worktrees);
1622 return ret;
1623 }
1624
1625 static void run_update_post_hook(struct command *commands)
1626 {
1627 struct command *cmd;
1628 struct child_process proc = CHILD_PROCESS_INIT;
1629 const char *hook;
1630
1631 hook = find_hook("post-update");
1632 if (!hook)
1633 return;
1634
1635 for (cmd = commands; cmd; cmd = cmd->next) {
1636 if (cmd->error_string || cmd->did_not_exist)
1637 continue;
1638 if (!proc.args.nr)
1639 strvec_push(&proc.args, hook);
1640 strvec_push(&proc.args, cmd->ref_name);
1641 }
1642 if (!proc.args.nr)
1643 return;
1644
1645 proc.no_stdin = 1;
1646 proc.stdout_to_stderr = 1;
1647 proc.err = use_sideband ? -1 : 0;
1648 proc.trace2_hook_name = "post-update";
1649
1650 if (!start_command(&proc)) {
1651 if (use_sideband)
1652 copy_to_sideband(proc.err, -1, NULL);
1653 finish_command(&proc);
1654 }
1655 }
1656
1657 static void check_aliased_update_internal(struct command *cmd,
1658 struct string_list *list,
1659 const char *dst_name, int flag)
1660 {
1661 struct string_list_item *item;
1662 struct command *dst_cmd;
1663
1664 if (!(flag & REF_ISSYMREF))
1665 return;
1666
1667 if (!dst_name) {
1668 rp_error("refusing update to broken symref '%s'", cmd->ref_name);
1669 cmd->skip_update = 1;
1670 cmd->error_string = "broken symref";
1671 return;
1672 }
1673 dst_name = strip_namespace(dst_name);
1674
1675 if (!(item = string_list_lookup(list, dst_name)))
1676 return;
1677
1678 cmd->skip_update = 1;
1679
1680 dst_cmd = (struct command *) item->util;
1681
1682 if (oideq(&cmd->old_oid, &dst_cmd->old_oid) &&
1683 oideq(&cmd->new_oid, &dst_cmd->new_oid))
1684 return;
1685
1686 dst_cmd->skip_update = 1;
1687
1688 rp_error("refusing inconsistent update between symref '%s' (%s..%s) and"
1689 " its target '%s' (%s..%s)",
1690 cmd->ref_name,
1691 repo_find_unique_abbrev(the_repository, &cmd->old_oid, DEFAULT_ABBREV),
1692 repo_find_unique_abbrev(the_repository, &cmd->new_oid, DEFAULT_ABBREV),
1693 dst_cmd->ref_name,
1694 repo_find_unique_abbrev(the_repository, &dst_cmd->old_oid, DEFAULT_ABBREV),
1695 repo_find_unique_abbrev(the_repository, &dst_cmd->new_oid, DEFAULT_ABBREV));
1696
1697 cmd->error_string = dst_cmd->error_string =
1698 "inconsistent aliased update";
1699 }
1700
1701 static void check_aliased_update(struct command *cmd, struct string_list *list)
1702 {
1703 struct strbuf buf = STRBUF_INIT;
1704 const char *dst_name;
1705 int flag;
1706
1707 strbuf_addf(&buf, "%s%s", get_git_namespace(), cmd->ref_name);
1708 dst_name = resolve_ref_unsafe(buf.buf, 0, NULL, &flag);
1709 check_aliased_update_internal(cmd, list, dst_name, flag);
1710 strbuf_release(&buf);
1711 }
1712
1713 static void check_aliased_updates(struct command *commands)
1714 {
1715 struct command *cmd;
1716 struct string_list ref_list = STRING_LIST_INIT_NODUP;
1717
1718 for (cmd = commands; cmd; cmd = cmd->next) {
1719 struct string_list_item *item =
1720 string_list_append(&ref_list, cmd->ref_name);
1721 item->util = (void *)cmd;
1722 }
1723 string_list_sort(&ref_list);
1724
1725 for (cmd = commands; cmd; cmd = cmd->next) {
1726 if (!cmd->error_string)
1727 check_aliased_update(cmd, &ref_list);
1728 }
1729
1730 string_list_clear(&ref_list, 0);
1731 }
1732
1733 static const struct object_id *command_singleton_iterator(void *cb_data)
1734 {
1735 struct command **cmd_list = cb_data;
1736 struct command *cmd = *cmd_list;
1737
1738 if (!cmd || is_null_oid(&cmd->new_oid))
1739 return NULL;
1740 *cmd_list = NULL; /* this returns only one */
1741 return &cmd->new_oid;
1742 }
1743
1744 static void set_connectivity_errors(struct command *commands,
1745 struct shallow_info *si)
1746 {
1747 struct command *cmd;
1748
1749 for (cmd = commands; cmd; cmd = cmd->next) {
1750 struct command *singleton = cmd;
1751 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1752
1753 if (shallow_update && si->shallow_ref[cmd->index])
1754 /* to be checked in update_shallow_ref() */
1755 continue;
1756
1757 opt.env = tmp_objdir_env(tmp_objdir);
1758 if (!check_connected(command_singleton_iterator, &singleton,
1759 &opt))
1760 continue;
1761
1762 cmd->error_string = "missing necessary objects";
1763 }
1764 }
1765
1766 struct iterate_data {
1767 struct command *cmds;
1768 struct shallow_info *si;
1769 };
1770
1771 static const struct object_id *iterate_receive_command_list(void *cb_data)
1772 {
1773 struct iterate_data *data = cb_data;
1774 struct command **cmd_list = &data->cmds;
1775 struct command *cmd = *cmd_list;
1776
1777 for (; cmd; cmd = cmd->next) {
1778 if (shallow_update && data->si->shallow_ref[cmd->index])
1779 /* to be checked in update_shallow_ref() */
1780 continue;
1781 if (!is_null_oid(&cmd->new_oid) && !cmd->skip_update) {
1782 *cmd_list = cmd->next;
1783 return &cmd->new_oid;
1784 }
1785 }
1786 return NULL;
1787 }
1788
1789 static void reject_updates_to_hidden(struct command *commands)
1790 {
1791 struct strbuf refname_full = STRBUF_INIT;
1792 size_t prefix_len;
1793 struct command *cmd;
1794
1795 strbuf_addstr(&refname_full, get_git_namespace());
1796 prefix_len = refname_full.len;
1797
1798 for (cmd = commands; cmd; cmd = cmd->next) {
1799 if (cmd->error_string)
1800 continue;
1801
1802 strbuf_setlen(&refname_full, prefix_len);
1803 strbuf_addstr(&refname_full, cmd->ref_name);
1804
1805 if (!ref_is_hidden(cmd->ref_name, refname_full.buf, &hidden_refs))
1806 continue;
1807 if (is_null_oid(&cmd->new_oid))
1808 cmd->error_string = "deny deleting a hidden ref";
1809 else
1810 cmd->error_string = "deny updating a hidden ref";
1811 }
1812
1813 strbuf_release(&refname_full);
1814 }
1815
1816 static int should_process_cmd(struct command *cmd)
1817 {
1818 return !cmd->error_string && !cmd->skip_update;
1819 }
1820
1821 static void BUG_if_skipped_connectivity_check(struct command *commands,
1822 struct shallow_info *si)
1823 {
1824 struct command *cmd;
1825
1826 for (cmd = commands; cmd; cmd = cmd->next) {
1827 if (should_process_cmd(cmd) && si->shallow_ref[cmd->index])
1828 bug("connectivity check has not been run on ref %s",
1829 cmd->ref_name);
1830 }
1831 BUG_if_bug("connectivity check skipped???");
1832 }
1833
1834 static void execute_commands_non_atomic(struct command *commands,
1835 struct shallow_info *si)
1836 {
1837 struct command *cmd;
1838 struct strbuf err = STRBUF_INIT;
1839
1840 for (cmd = commands; cmd; cmd = cmd->next) {
1841 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1842 continue;
1843
1844 transaction = ref_transaction_begin(&err);
1845 if (!transaction) {
1846 rp_error("%s", err.buf);
1847 strbuf_reset(&err);
1848 cmd->error_string = "transaction failed to start";
1849 continue;
1850 }
1851
1852 cmd->error_string = update(cmd, si);
1853
1854 if (!cmd->error_string
1855 && ref_transaction_commit(transaction, &err)) {
1856 rp_error("%s", err.buf);
1857 strbuf_reset(&err);
1858 cmd->error_string = "failed to update ref";
1859 }
1860 ref_transaction_free(transaction);
1861 }
1862 strbuf_release(&err);
1863 }
1864
1865 static void execute_commands_atomic(struct command *commands,
1866 struct shallow_info *si)
1867 {
1868 struct command *cmd;
1869 struct strbuf err = STRBUF_INIT;
1870 const char *reported_error = "atomic push failure";
1871
1872 transaction = ref_transaction_begin(&err);
1873 if (!transaction) {
1874 rp_error("%s", err.buf);
1875 strbuf_reset(&err);
1876 reported_error = "transaction failed to start";
1877 goto failure;
1878 }
1879
1880 for (cmd = commands; cmd; cmd = cmd->next) {
1881 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1882 continue;
1883
1884 cmd->error_string = update(cmd, si);
1885
1886 if (cmd->error_string)
1887 goto failure;
1888 }
1889
1890 if (ref_transaction_commit(transaction, &err)) {
1891 rp_error("%s", err.buf);
1892 reported_error = "atomic transaction failed";
1893 goto failure;
1894 }
1895 goto cleanup;
1896
1897 failure:
1898 for (cmd = commands; cmd; cmd = cmd->next)
1899 if (!cmd->error_string)
1900 cmd->error_string = reported_error;
1901
1902 cleanup:
1903 ref_transaction_free(transaction);
1904 strbuf_release(&err);
1905 }
1906
1907 static void execute_commands(struct command *commands,
1908 const char *unpacker_error,
1909 struct shallow_info *si,
1910 const struct string_list *push_options)
1911 {
1912 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1913 struct command *cmd;
1914 struct iterate_data data;
1915 struct async muxer;
1916 int err_fd = 0;
1917 int run_proc_receive = 0;
1918
1919 if (unpacker_error) {
1920 for (cmd = commands; cmd; cmd = cmd->next)
1921 cmd->error_string = "unpacker error";
1922 return;
1923 }
1924
1925 if (use_sideband) {
1926 memset(&muxer, 0, sizeof(muxer));
1927 muxer.proc = copy_to_sideband;
1928 muxer.in = -1;
1929 if (!start_async(&muxer))
1930 err_fd = muxer.in;
1931 /* ...else, continue without relaying sideband */
1932 }
1933
1934 data.cmds = commands;
1935 data.si = si;
1936 opt.err_fd = err_fd;
1937 opt.progress = err_fd && !quiet;
1938 opt.env = tmp_objdir_env(tmp_objdir);
1939 opt.exclude_hidden_refs_section = "receive";
1940
1941 if (check_connected(iterate_receive_command_list, &data, &opt))
1942 set_connectivity_errors(commands, si);
1943
1944 if (use_sideband)
1945 finish_async(&muxer);
1946
1947 reject_updates_to_hidden(commands);
1948
1949 /*
1950 * Try to find commands that have special prefix in their reference names,
1951 * and mark them to run an external "proc-receive" hook later.
1952 */
1953 if (proc_receive_ref) {
1954 for (cmd = commands; cmd; cmd = cmd->next) {
1955 if (!should_process_cmd(cmd))
1956 continue;
1957
1958 if (proc_receive_ref_matches(cmd)) {
1959 cmd->run_proc_receive = RUN_PROC_RECEIVE_SCHEDULED;
1960 run_proc_receive = 1;
1961 }
1962 }
1963 }
1964
1965 if (run_receive_hook(commands, "pre-receive", 0, push_options)) {
1966 for (cmd = commands; cmd; cmd = cmd->next) {
1967 if (!cmd->error_string)
1968 cmd->error_string = "pre-receive hook declined";
1969 }
1970 return;
1971 }
1972
1973 /*
1974 * If there is no command ready to run, should return directly to destroy
1975 * temporary data in the quarantine area.
1976 */
1977 for (cmd = commands; cmd && cmd->error_string; cmd = cmd->next)
1978 ; /* nothing */
1979 if (!cmd)
1980 return;
1981
1982 /*
1983 * Now we'll start writing out refs, which means the objects need
1984 * to be in their final positions so that other processes can see them.
1985 */
1986 if (tmp_objdir_migrate(tmp_objdir) < 0) {
1987 for (cmd = commands; cmd; cmd = cmd->next) {
1988 if (!cmd->error_string)
1989 cmd->error_string = "unable to migrate objects to permanent storage";
1990 }
1991 return;
1992 }
1993 tmp_objdir = NULL;
1994
1995 check_aliased_updates(commands);
1996
1997 free(head_name_to_free);
1998 head_name = head_name_to_free = resolve_refdup("HEAD", 0, NULL, NULL);
1999
2000 if (run_proc_receive &&
2001 run_proc_receive_hook(commands, push_options))
2002 for (cmd = commands; cmd; cmd = cmd->next)
2003 if (!cmd->error_string &&
2004 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED) &&
2005 (cmd->run_proc_receive || use_atomic))
2006 cmd->error_string = "fail to run proc-receive hook";
2007
2008 if (use_atomic)
2009 execute_commands_atomic(commands, si);
2010 else
2011 execute_commands_non_atomic(commands, si);
2012
2013 if (shallow_update)
2014 BUG_if_skipped_connectivity_check(commands, si);
2015 }
2016
2017 static struct command **queue_command(struct command **tail,
2018 const char *line,
2019 int linelen)
2020 {
2021 struct object_id old_oid, new_oid;
2022 struct command *cmd;
2023 const char *refname;
2024 int reflen;
2025 const char *p;
2026
2027 if (parse_oid_hex(line, &old_oid, &p) ||
2028 *p++ != ' ' ||
2029 parse_oid_hex(p, &new_oid, &p) ||
2030 *p++ != ' ')
2031 die("protocol error: expected old/new/ref, got '%s'", line);
2032
2033 refname = p;
2034 reflen = linelen - (p - line);
2035 FLEX_ALLOC_MEM(cmd, ref_name, refname, reflen);
2036 oidcpy(&cmd->old_oid, &old_oid);
2037 oidcpy(&cmd->new_oid, &new_oid);
2038 *tail = cmd;
2039 return &cmd->next;
2040 }
2041
2042 static void free_commands(struct command *commands)
2043 {
2044 while (commands) {
2045 struct command *next = commands->next;
2046
2047 free(commands);
2048 commands = next;
2049 }
2050 }
2051
2052 static void queue_commands_from_cert(struct command **tail,
2053 struct strbuf *push_cert)
2054 {
2055 const char *boc, *eoc;
2056
2057 if (*tail)
2058 die("protocol error: got both push certificate and unsigned commands");
2059
2060 boc = strstr(push_cert->buf, "\n\n");
2061 if (!boc)
2062 die("malformed push certificate %.*s", 100, push_cert->buf);
2063 else
2064 boc += 2;
2065 eoc = push_cert->buf + parse_signed_buffer(push_cert->buf, push_cert->len);
2066
2067 while (boc < eoc) {
2068 const char *eol = memchr(boc, '\n', eoc - boc);
2069 tail = queue_command(tail, boc, eol ? eol - boc : eoc - boc);
2070 boc = eol ? eol + 1 : eoc;
2071 }
2072 }
2073
2074 static struct command *read_head_info(struct packet_reader *reader,
2075 struct oid_array *shallow)
2076 {
2077 struct command *commands = NULL;
2078 struct command **p = &commands;
2079 for (;;) {
2080 int linelen;
2081
2082 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2083 break;
2084
2085 if (reader->pktlen > 8 && starts_with(reader->line, "shallow ")) {
2086 struct object_id oid;
2087 if (get_oid_hex(reader->line + 8, &oid))
2088 die("protocol error: expected shallow sha, got '%s'",
2089 reader->line + 8);
2090 oid_array_append(shallow, &oid);
2091 continue;
2092 }
2093
2094 linelen = strlen(reader->line);
2095 if (linelen < reader->pktlen) {
2096 const char *feature_list = reader->line + linelen + 1;
2097 const char *hash = NULL;
2098 const char *client_sid;
2099 size_t len = 0;
2100 if (parse_feature_request(feature_list, "report-status"))
2101 report_status = 1;
2102 if (parse_feature_request(feature_list, "report-status-v2"))
2103 report_status_v2 = 1;
2104 if (parse_feature_request(feature_list, "side-band-64k"))
2105 use_sideband = LARGE_PACKET_MAX;
2106 if (parse_feature_request(feature_list, "quiet"))
2107 quiet = 1;
2108 if (advertise_atomic_push
2109 && parse_feature_request(feature_list, "atomic"))
2110 use_atomic = 1;
2111 if (advertise_push_options
2112 && parse_feature_request(feature_list, "push-options"))
2113 use_push_options = 1;
2114 hash = parse_feature_value(feature_list, "object-format", &len, NULL);
2115 if (!hash) {
2116 hash = hash_algos[GIT_HASH_SHA1].name;
2117 len = strlen(hash);
2118 }
2119 if (xstrncmpz(the_hash_algo->name, hash, len))
2120 die("error: unsupported object format '%s'", hash);
2121 client_sid = parse_feature_value(feature_list, "session-id", &len, NULL);
2122 if (client_sid) {
2123 char *sid = xstrndup(client_sid, len);
2124 trace2_data_string("transfer", NULL, "client-sid", client_sid);
2125 free(sid);
2126 }
2127 }
2128
2129 if (!strcmp(reader->line, "push-cert")) {
2130 int true_flush = 0;
2131 int saved_options = reader->options;
2132 reader->options &= ~PACKET_READ_CHOMP_NEWLINE;
2133
2134 for (;;) {
2135 packet_reader_read(reader);
2136 if (reader->status == PACKET_READ_FLUSH) {
2137 true_flush = 1;
2138 break;
2139 }
2140 if (reader->status != PACKET_READ_NORMAL) {
2141 die("protocol error: got an unexpected packet");
2142 }
2143 if (!strcmp(reader->line, "push-cert-end\n"))
2144 break; /* end of cert */
2145 strbuf_addstr(&push_cert, reader->line);
2146 }
2147 reader->options = saved_options;
2148
2149 if (true_flush)
2150 break;
2151 continue;
2152 }
2153
2154 p = queue_command(p, reader->line, linelen);
2155 }
2156
2157 if (push_cert.len)
2158 queue_commands_from_cert(p, &push_cert);
2159
2160 return commands;
2161 }
2162
2163 static void read_push_options(struct packet_reader *reader,
2164 struct string_list *options)
2165 {
2166 while (1) {
2167 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2168 break;
2169
2170 string_list_append(options, reader->line);
2171 }
2172 }
2173
2174 static const char *parse_pack_header(struct pack_header *hdr)
2175 {
2176 switch (read_pack_header(0, hdr)) {
2177 case PH_ERROR_EOF:
2178 return "eof before pack header was fully read";
2179
2180 case PH_ERROR_PACK_SIGNATURE:
2181 return "protocol error (pack signature mismatch detected)";
2182
2183 case PH_ERROR_PROTOCOL:
2184 return "protocol error (pack version unsupported)";
2185
2186 default:
2187 return "unknown error in parse_pack_header";
2188
2189 case 0:
2190 return NULL;
2191 }
2192 }
2193
2194 static struct tempfile *pack_lockfile;
2195
2196 static void push_header_arg(struct strvec *args, struct pack_header *hdr)
2197 {
2198 strvec_pushf(args, "--pack_header=%"PRIu32",%"PRIu32,
2199 ntohl(hdr->hdr_version), ntohl(hdr->hdr_entries));
2200 }
2201
2202 static const char *unpack(int err_fd, struct shallow_info *si)
2203 {
2204 struct pack_header hdr;
2205 const char *hdr_err;
2206 int status;
2207 struct child_process child = CHILD_PROCESS_INIT;
2208 int fsck_objects = (receive_fsck_objects >= 0
2209 ? receive_fsck_objects
2210 : transfer_fsck_objects >= 0
2211 ? transfer_fsck_objects
2212 : 0);
2213
2214 hdr_err = parse_pack_header(&hdr);
2215 if (hdr_err) {
2216 if (err_fd > 0)
2217 close(err_fd);
2218 return hdr_err;
2219 }
2220
2221 if (si->nr_ours || si->nr_theirs) {
2222 alt_shallow_file = setup_temporary_shallow(si->shallow);
2223 strvec_push(&child.args, "--shallow-file");
2224 strvec_push(&child.args, alt_shallow_file);
2225 }
2226
2227 tmp_objdir = tmp_objdir_create("incoming");
2228 if (!tmp_objdir) {
2229 if (err_fd > 0)
2230 close(err_fd);
2231 return "unable to create temporary object directory";
2232 }
2233 strvec_pushv(&child.env, tmp_objdir_env(tmp_objdir));
2234
2235 /*
2236 * Normally we just pass the tmp_objdir environment to the child
2237 * processes that do the heavy lifting, but we may need to see these
2238 * objects ourselves to set up shallow information.
2239 */
2240 tmp_objdir_add_as_alternate(tmp_objdir);
2241
2242 if (ntohl(hdr.hdr_entries) < unpack_limit) {
2243 strvec_push(&child.args, "unpack-objects");
2244 push_header_arg(&child.args, &hdr);
2245 if (quiet)
2246 strvec_push(&child.args, "-q");
2247 if (fsck_objects)
2248 strvec_pushf(&child.args, "--strict%s",
2249 fsck_msg_types.buf);
2250 if (max_input_size)
2251 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2252 (uintmax_t)max_input_size);
2253 child.no_stdout = 1;
2254 child.err = err_fd;
2255 child.git_cmd = 1;
2256 status = run_command(&child);
2257 if (status)
2258 return "unpack-objects abnormal exit";
2259 } else {
2260 char hostname[HOST_NAME_MAX + 1];
2261 char *lockfile;
2262
2263 strvec_pushl(&child.args, "index-pack", "--stdin", NULL);
2264 push_header_arg(&child.args, &hdr);
2265
2266 if (xgethostname(hostname, sizeof(hostname)))
2267 xsnprintf(hostname, sizeof(hostname), "localhost");
2268 strvec_pushf(&child.args,
2269 "--keep=receive-pack %"PRIuMAX" on %s",
2270 (uintmax_t)getpid(),
2271 hostname);
2272
2273 if (!quiet && err_fd)
2274 strvec_push(&child.args, "--show-resolving-progress");
2275 if (use_sideband)
2276 strvec_push(&child.args, "--report-end-of-input");
2277 if (fsck_objects)
2278 strvec_pushf(&child.args, "--strict%s",
2279 fsck_msg_types.buf);
2280 if (!reject_thin)
2281 strvec_push(&child.args, "--fix-thin");
2282 if (max_input_size)
2283 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2284 (uintmax_t)max_input_size);
2285 child.out = -1;
2286 child.err = err_fd;
2287 child.git_cmd = 1;
2288 status = start_command(&child);
2289 if (status)
2290 return "index-pack fork failed";
2291
2292 lockfile = index_pack_lockfile(child.out, NULL);
2293 if (lockfile) {
2294 pack_lockfile = register_tempfile(lockfile);
2295 free(lockfile);
2296 }
2297 close(child.out);
2298
2299 status = finish_command(&child);
2300 if (status)
2301 return "index-pack abnormal exit";
2302 reprepare_packed_git(the_repository);
2303 }
2304 return NULL;
2305 }
2306
2307 static const char *unpack_with_sideband(struct shallow_info *si)
2308 {
2309 struct async muxer;
2310 const char *ret;
2311
2312 if (!use_sideband)
2313 return unpack(0, si);
2314
2315 use_keepalive = KEEPALIVE_AFTER_NUL;
2316 memset(&muxer, 0, sizeof(muxer));
2317 muxer.proc = copy_to_sideband;
2318 muxer.in = -1;
2319 if (start_async(&muxer))
2320 return NULL;
2321
2322 ret = unpack(muxer.in, si);
2323
2324 finish_async(&muxer);
2325 return ret;
2326 }
2327
2328 static void prepare_shallow_update(struct shallow_info *si)
2329 {
2330 int i, j, k, bitmap_size = DIV_ROUND_UP(si->ref->nr, 32);
2331
2332 ALLOC_ARRAY(si->used_shallow, si->shallow->nr);
2333 assign_shallow_commits_to_refs(si, si->used_shallow, NULL);
2334
2335 CALLOC_ARRAY(si->need_reachability_test, si->shallow->nr);
2336 CALLOC_ARRAY(si->reachable, si->shallow->nr);
2337 CALLOC_ARRAY(si->shallow_ref, si->ref->nr);
2338
2339 for (i = 0; i < si->nr_ours; i++)
2340 si->need_reachability_test[si->ours[i]] = 1;
2341
2342 for (i = 0; i < si->shallow->nr; i++) {
2343 if (!si->used_shallow[i])
2344 continue;
2345 for (j = 0; j < bitmap_size; j++) {
2346 if (!si->used_shallow[i][j])
2347 continue;
2348 si->need_reachability_test[i]++;
2349 for (k = 0; k < 32; k++)
2350 if (si->used_shallow[i][j] & (1U << k))
2351 si->shallow_ref[j * 32 + k]++;
2352 }
2353
2354 /*
2355 * true for those associated with some refs and belong
2356 * in "ours" list aka "step 7 not done yet"
2357 */
2358 si->need_reachability_test[i] =
2359 si->need_reachability_test[i] > 1;
2360 }
2361
2362 /*
2363 * keep hooks happy by forcing a temporary shallow file via
2364 * env variable because we can't add --shallow-file to every
2365 * command. check_connected() will be done with
2366 * true .git/shallow though.
2367 */
2368 setenv(GIT_SHALLOW_FILE_ENVIRONMENT, alt_shallow_file, 1);
2369 }
2370
2371 static void update_shallow_info(struct command *commands,
2372 struct shallow_info *si,
2373 struct oid_array *ref)
2374 {
2375 struct command *cmd;
2376 int *ref_status;
2377 remove_nonexistent_theirs_shallow(si);
2378 if (!si->nr_ours && !si->nr_theirs) {
2379 shallow_update = 0;
2380 return;
2381 }
2382
2383 for (cmd = commands; cmd; cmd = cmd->next) {
2384 if (is_null_oid(&cmd->new_oid))
2385 continue;
2386 oid_array_append(ref, &cmd->new_oid);
2387 cmd->index = ref->nr - 1;
2388 }
2389 si->ref = ref;
2390
2391 if (shallow_update) {
2392 prepare_shallow_update(si);
2393 return;
2394 }
2395
2396 ALLOC_ARRAY(ref_status, ref->nr);
2397 assign_shallow_commits_to_refs(si, NULL, ref_status);
2398 for (cmd = commands; cmd; cmd = cmd->next) {
2399 if (is_null_oid(&cmd->new_oid))
2400 continue;
2401 if (ref_status[cmd->index]) {
2402 cmd->error_string = "shallow update not allowed";
2403 cmd->skip_update = 1;
2404 }
2405 }
2406 free(ref_status);
2407 }
2408
2409 static void report(struct command *commands, const char *unpack_status)
2410 {
2411 struct command *cmd;
2412 struct strbuf buf = STRBUF_INIT;
2413
2414 packet_buf_write(&buf, "unpack %s\n",
2415 unpack_status ? unpack_status : "ok");
2416 for (cmd = commands; cmd; cmd = cmd->next) {
2417 if (!cmd->error_string)
2418 packet_buf_write(&buf, "ok %s\n",
2419 cmd->ref_name);
2420 else
2421 packet_buf_write(&buf, "ng %s %s\n",
2422 cmd->ref_name, cmd->error_string);
2423 }
2424 packet_buf_flush(&buf);
2425
2426 if (use_sideband)
2427 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2428 else
2429 write_or_die(1, buf.buf, buf.len);
2430 strbuf_release(&buf);
2431 }
2432
2433 static void report_v2(struct command *commands, const char *unpack_status)
2434 {
2435 struct command *cmd;
2436 struct strbuf buf = STRBUF_INIT;
2437 struct ref_push_report *report;
2438
2439 packet_buf_write(&buf, "unpack %s\n",
2440 unpack_status ? unpack_status : "ok");
2441 for (cmd = commands; cmd; cmd = cmd->next) {
2442 int count = 0;
2443
2444 if (cmd->error_string) {
2445 packet_buf_write(&buf, "ng %s %s\n",
2446 cmd->ref_name,
2447 cmd->error_string);
2448 continue;
2449 }
2450 packet_buf_write(&buf, "ok %s\n",
2451 cmd->ref_name);
2452 for (report = cmd->report; report; report = report->next) {
2453 if (count++ > 0)
2454 packet_buf_write(&buf, "ok %s\n",
2455 cmd->ref_name);
2456 if (report->ref_name)
2457 packet_buf_write(&buf, "option refname %s\n",
2458 report->ref_name);
2459 if (report->old_oid)
2460 packet_buf_write(&buf, "option old-oid %s\n",
2461 oid_to_hex(report->old_oid));
2462 if (report->new_oid)
2463 packet_buf_write(&buf, "option new-oid %s\n",
2464 oid_to_hex(report->new_oid));
2465 if (report->forced_update)
2466 packet_buf_write(&buf, "option forced-update\n");
2467 }
2468 }
2469 packet_buf_flush(&buf);
2470
2471 if (use_sideband)
2472 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2473 else
2474 write_or_die(1, buf.buf, buf.len);
2475 strbuf_release(&buf);
2476 }
2477
2478 static int delete_only(struct command *commands)
2479 {
2480 struct command *cmd;
2481 for (cmd = commands; cmd; cmd = cmd->next) {
2482 if (!is_null_oid(&cmd->new_oid))
2483 return 0;
2484 }
2485 return 1;
2486 }
2487
2488 int cmd_receive_pack(int argc, const char **argv, const char *prefix)
2489 {
2490 int advertise_refs = 0;
2491 struct command *commands;
2492 struct oid_array shallow = OID_ARRAY_INIT;
2493 struct oid_array ref = OID_ARRAY_INIT;
2494 struct shallow_info si;
2495 struct packet_reader reader;
2496
2497 struct option options[] = {
2498 OPT__QUIET(&quiet, N_("quiet")),
2499 OPT_HIDDEN_BOOL(0, "stateless-rpc", &stateless_rpc, NULL),
2500 OPT_HIDDEN_BOOL(0, "http-backend-info-refs", &advertise_refs, NULL),
2501 OPT_ALIAS(0, "advertise-refs", "http-backend-info-refs"),
2502 OPT_HIDDEN_BOOL(0, "reject-thin-pack-for-testing", &reject_thin, NULL),
2503 OPT_END()
2504 };
2505
2506 packet_trace_identity("receive-pack");
2507
2508 argc = parse_options(argc, argv, prefix, options, receive_pack_usage, 0);
2509
2510 if (argc > 1)
2511 usage_msg_opt(_("too many arguments"), receive_pack_usage, options);
2512 if (argc == 0)
2513 usage_msg_opt(_("you must specify a directory"), receive_pack_usage, options);
2514
2515 service_dir = argv[0];
2516
2517 setup_path();
2518
2519 if (!enter_repo(service_dir, 0))
2520 die("'%s' does not appear to be a git repository", service_dir);
2521
2522 git_config(receive_pack_config, NULL);
2523 if (cert_nonce_seed)
2524 push_cert_nonce = prepare_push_cert_nonce(service_dir, time(NULL));
2525
2526 if (0 <= transfer_unpack_limit)
2527 unpack_limit = transfer_unpack_limit;
2528 else if (0 <= receive_unpack_limit)
2529 unpack_limit = receive_unpack_limit;
2530
2531 switch (determine_protocol_version_server()) {
2532 case protocol_v2:
2533 /*
2534 * push support for protocol v2 has not been implemented yet,
2535 * so ignore the request to use v2 and fallback to using v0.
2536 */
2537 break;
2538 case protocol_v1:
2539 /*
2540 * v1 is just the original protocol with a version string,
2541 * so just fall through after writing the version string.
2542 */
2543 if (advertise_refs || !stateless_rpc)
2544 packet_write_fmt(1, "version 1\n");
2545
2546 /* fallthrough */
2547 case protocol_v0:
2548 break;
2549 case protocol_unknown_version:
2550 BUG("unknown protocol version");
2551 }
2552
2553 if (advertise_refs || !stateless_rpc) {
2554 write_head_info();
2555 }
2556 if (advertise_refs)
2557 return 0;
2558
2559 packet_reader_init(&reader, 0, NULL, 0,
2560 PACKET_READ_CHOMP_NEWLINE |
2561 PACKET_READ_DIE_ON_ERR_PACKET);
2562
2563 if ((commands = read_head_info(&reader, &shallow))) {
2564 const char *unpack_status = NULL;
2565 struct string_list push_options = STRING_LIST_INIT_DUP;
2566
2567 if (use_push_options)
2568 read_push_options(&reader, &push_options);
2569 if (!check_cert_push_options(&push_options)) {
2570 struct command *cmd;
2571 for (cmd = commands; cmd; cmd = cmd->next)
2572 cmd->error_string = "inconsistent push options";
2573 }
2574
2575 prepare_shallow_info(&si, &shallow);
2576 if (!si.nr_ours && !si.nr_theirs)
2577 shallow_update = 0;
2578 if (!delete_only(commands)) {
2579 unpack_status = unpack_with_sideband(&si);
2580 update_shallow_info(commands, &si, &ref);
2581 }
2582 use_keepalive = KEEPALIVE_ALWAYS;
2583 execute_commands(commands, unpack_status, &si,
2584 &push_options);
2585 delete_tempfile(&pack_lockfile);
2586 sigchain_push(SIGPIPE, SIG_IGN);
2587 if (report_status_v2)
2588 report_v2(commands, unpack_status);
2589 else if (report_status)
2590 report(commands, unpack_status);
2591 sigchain_pop(SIGPIPE);
2592 run_receive_hook(commands, "post-receive", 1,
2593 &push_options);
2594 run_update_post_hook(commands);
2595 free_commands(commands);
2596 string_list_clear(&push_options, 0);
2597 if (auto_gc) {
2598 struct child_process proc = CHILD_PROCESS_INIT;
2599
2600 proc.no_stdin = 1;
2601 proc.stdout_to_stderr = 1;
2602 proc.err = use_sideband ? -1 : 0;
2603 proc.git_cmd = proc.close_object_store = 1;
2604 strvec_pushl(&proc.args, "gc", "--auto", "--quiet",
2605 NULL);
2606
2607 if (!start_command(&proc)) {
2608 if (use_sideband)
2609 copy_to_sideband(proc.err, -1, NULL);
2610 finish_command(&proc);
2611 }
2612 }
2613 if (auto_update_server_info)
2614 update_server_info(0);
2615 clear_shallow_info(&si);
2616 }
2617 if (use_sideband)
2618 packet_flush(1);
2619 oid_array_clear(&shallow);
2620 oid_array_clear(&ref);
2621 string_list_clear(&hidden_refs, 0);
2622 free((void *)push_cert_nonce);
2623 return 0;
2624 }