Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
3
4 #include "builtin.h"
5 #include "abspath.h"
6 #include "commit.h"
7 #include "commit-reach.h"
8 #include "config.h"
9 #include "connect.h"
10 #include "connected.h"
11 #include "environment.h"
12 #include "exec-cmd.h"
13 #include "fsck.h"
14 #include "gettext.h"
15 #include "gpg-interface.h"
16 #include "hex.h"
17 #include "hook.h"
18 #include "lockfile.h"
19 #include "object.h"
20 #include "object-file.h"
21 #include "object-name.h"
22 #include "odb.h"
23 #include "oid-array.h"
24 #include "oidset.h"
25 #include "pack.h"
26 #include "packfile.h"
27 #include "parse-options.h"
28 #include "pkt-line.h"
29 #include "protocol.h"
30 #include "refs.h"
31 #include "remote.h"
32 #include "run-command.h"
33 #include "server-info.h"
34 #include "setup.h"
35 #include "shallow.h"
36 #include "sideband.h"
37 #include "sigchain.h"
38 #include "string-list.h"
39 #include "strvec.h"
40 #include "tmp-objdir.h"
41 #include "trace.h"
42 #include "trace2.h"
43 #include "version.h"
44 #include "worktree.h"
45
46 static const char * const receive_pack_usage[] = {
47 N_("git receive-pack <git-dir>"),
48 NULL
49 };
50
51 enum deny_action {
52 DENY_UNCONFIGURED,
53 DENY_IGNORE,
54 DENY_WARN,
55 DENY_REFUSE,
56 DENY_UPDATE_INSTEAD
57 };
58
59 static int deny_deletes;
60 static int deny_non_fast_forwards;
61 static enum deny_action deny_current_branch = DENY_UNCONFIGURED;
62 static enum deny_action deny_delete_current = DENY_UNCONFIGURED;
63 static int receive_fsck_objects = -1;
64 static int transfer_fsck_objects = -1;
65 static struct strbuf fsck_msg_types = STRBUF_INIT;
66 static int receive_unpack_limit = -1;
67 static int transfer_unpack_limit = -1;
68 static int advertise_atomic_push = 1;
69 static int advertise_push_options;
70 static int advertise_sid;
71 static int unpack_limit = 100;
72 static off_t max_input_size;
73 static int report_status;
74 static int report_status_v2;
75 static int use_sideband;
76 static int use_atomic;
77 static int use_push_options;
78 static int quiet;
79 static int prefer_ofs_delta = 1;
80 static int auto_update_server_info;
81 static int auto_gc = 1;
82 static int reject_thin;
83 static int skip_connectivity_check;
84 static int stateless_rpc;
85 static const char *service_dir;
86 static const char *head_name;
87 static void *head_name_to_free;
88 static int sent_capabilities;
89 static int shallow_update;
90 static const char *alt_shallow_file;
91 static struct strbuf push_cert = STRBUF_INIT;
92 static struct object_id push_cert_oid;
93 static struct signature_check sigcheck;
94 static const char *push_cert_nonce;
95 static char *cert_nonce_seed;
96 static struct strvec hidden_refs = STRVEC_INIT;
97
98 static const char *NONCE_UNSOLICITED = "UNSOLICITED";
99 static const char *NONCE_BAD = "BAD";
100 static const char *NONCE_MISSING = "MISSING";
101 static const char *NONCE_OK = "OK";
102 static const char *NONCE_SLOP = "SLOP";
103 static const char *nonce_status;
104 static long nonce_stamp_slop;
105 static timestamp_t nonce_stamp_slop_limit;
106 static struct ref_transaction *transaction;
107
108 static enum {
109 KEEPALIVE_NEVER = 0,
110 KEEPALIVE_AFTER_NUL,
111 KEEPALIVE_ALWAYS
112 } use_keepalive;
113 static int keepalive_in_sec = 5;
114
115 static struct tmp_objdir *tmp_objdir;
116
117 static struct proc_receive_ref {
118 unsigned int want_add:1,
119 want_delete:1,
120 want_modify:1,
121 negative_ref:1;
122 char *ref_prefix;
123 struct proc_receive_ref *next;
124 } *proc_receive_ref;
125
126 static void proc_receive_ref_append(const char *prefix);
127
128 static enum deny_action parse_deny_action(const char *var, const char *value)
129 {
130 if (value) {
131 if (!strcasecmp(value, "ignore"))
132 return DENY_IGNORE;
133 if (!strcasecmp(value, "warn"))
134 return DENY_WARN;
135 if (!strcasecmp(value, "refuse"))
136 return DENY_REFUSE;
137 if (!strcasecmp(value, "updateinstead"))
138 return DENY_UPDATE_INSTEAD;
139 }
140 if (git_config_bool(var, value))
141 return DENY_REFUSE;
142 return DENY_IGNORE;
143 }
144
145 static int receive_pack_config(const char *var, const char *value,
146 const struct config_context *ctx, void *cb)
147 {
148 const char *msg_id;
149 int status = parse_hide_refs_config(var, value, "receive", &hidden_refs);
150
151 if (status)
152 return status;
153
154 if (strcmp(var, "receive.denydeletes") == 0) {
155 deny_deletes = git_config_bool(var, value);
156 return 0;
157 }
158
159 if (strcmp(var, "receive.denynonfastforwards") == 0) {
160 deny_non_fast_forwards = git_config_bool(var, value);
161 return 0;
162 }
163
164 if (strcmp(var, "receive.unpacklimit") == 0) {
165 receive_unpack_limit = git_config_int(var, value, ctx->kvi);
166 return 0;
167 }
168
169 if (strcmp(var, "transfer.unpacklimit") == 0) {
170 transfer_unpack_limit = git_config_int(var, value, ctx->kvi);
171 return 0;
172 }
173
174 if (strcmp(var, "receive.fsck.skiplist") == 0) {
175 char *path;
176
177 if (git_config_pathname(&path, var, value))
178 return -1;
179 if (path)
180 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
181 fsck_msg_types.len ? ',' : '=', path);
182 free(path);
183 return 0;
184 }
185
186 if (skip_prefix(var, "receive.fsck.", &msg_id)) {
187 if (!value)
188 return config_error_nonbool(var);
189 if (is_valid_msg_type(msg_id, value))
190 strbuf_addf(&fsck_msg_types, "%c%s=%s",
191 fsck_msg_types.len ? ',' : '=', msg_id, value);
192 else
193 warning("skipping unknown msg id '%s'", msg_id);
194 return 0;
195 }
196
197 if (strcmp(var, "receive.fsckobjects") == 0) {
198 receive_fsck_objects = git_config_bool(var, value);
199 return 0;
200 }
201
202 if (strcmp(var, "transfer.fsckobjects") == 0) {
203 transfer_fsck_objects = git_config_bool(var, value);
204 return 0;
205 }
206
207 if (!strcmp(var, "receive.denycurrentbranch")) {
208 deny_current_branch = parse_deny_action(var, value);
209 return 0;
210 }
211
212 if (strcmp(var, "receive.denydeletecurrent") == 0) {
213 deny_delete_current = parse_deny_action(var, value);
214 return 0;
215 }
216
217 if (strcmp(var, "repack.usedeltabaseoffset") == 0) {
218 prefer_ofs_delta = git_config_bool(var, value);
219 return 0;
220 }
221
222 if (strcmp(var, "receive.updateserverinfo") == 0) {
223 auto_update_server_info = git_config_bool(var, value);
224 return 0;
225 }
226
227 if (strcmp(var, "receive.autogc") == 0) {
228 auto_gc = git_config_bool(var, value);
229 return 0;
230 }
231
232 if (strcmp(var, "receive.shallowupdate") == 0) {
233 shallow_update = git_config_bool(var, value);
234 return 0;
235 }
236
237 if (strcmp(var, "receive.certnonceseed") == 0)
238 return git_config_string(&cert_nonce_seed, var, value);
239
240 if (strcmp(var, "receive.certnonceslop") == 0) {
241 nonce_stamp_slop_limit = git_config_ulong(var, value, ctx->kvi);
242 return 0;
243 }
244
245 if (strcmp(var, "receive.advertiseatomic") == 0) {
246 advertise_atomic_push = git_config_bool(var, value);
247 return 0;
248 }
249
250 if (strcmp(var, "receive.advertisepushoptions") == 0) {
251 advertise_push_options = git_config_bool(var, value);
252 return 0;
253 }
254
255 if (strcmp(var, "receive.keepalive") == 0) {
256 keepalive_in_sec = git_config_int(var, value, ctx->kvi);
257 return 0;
258 }
259
260 if (strcmp(var, "receive.maxinputsize") == 0) {
261 max_input_size = git_config_int64(var, value, ctx->kvi);
262 return 0;
263 }
264
265 if (strcmp(var, "receive.procreceiverefs") == 0) {
266 if (!value)
267 return config_error_nonbool(var);
268 proc_receive_ref_append(value);
269 return 0;
270 }
271
272 if (strcmp(var, "transfer.advertisesid") == 0) {
273 advertise_sid = git_config_bool(var, value);
274 return 0;
275 }
276
277 return git_default_config(var, value, ctx, cb);
278 }
279
280 static void show_ref(const char *path, const struct object_id *oid)
281 {
282 if (sent_capabilities) {
283 packet_write_fmt(1, "%s %s\n", oid_to_hex(oid), path);
284 } else {
285 struct strbuf cap = STRBUF_INIT;
286
287 strbuf_addstr(&cap,
288 "report-status report-status-v2 delete-refs side-band-64k quiet");
289 if (advertise_atomic_push)
290 strbuf_addstr(&cap, " atomic");
291 if (prefer_ofs_delta)
292 strbuf_addstr(&cap, " ofs-delta");
293 if (push_cert_nonce)
294 strbuf_addf(&cap, " push-cert=%s", push_cert_nonce);
295 if (advertise_push_options)
296 strbuf_addstr(&cap, " push-options");
297 if (advertise_sid)
298 strbuf_addf(&cap, " session-id=%s", trace2_session_id());
299 strbuf_addf(&cap, " object-format=%s", the_hash_algo->name);
300 strbuf_addf(&cap, " agent=%s", git_user_agent_sanitized());
301 packet_write_fmt(1, "%s %s%c%s\n",
302 oid_to_hex(oid), path, 0, cap.buf);
303 strbuf_release(&cap);
304 sent_capabilities = 1;
305 }
306 }
307
308 static int show_ref_cb(const struct reference *ref, void *data)
309 {
310 struct oidset *seen = data;
311 const char *path = strip_namespace(ref->name);
312
313 if (ref_is_hidden(path, ref->name, &hidden_refs))
314 return 0;
315
316 /*
317 * Advertise refs outside our current namespace as ".have"
318 * refs, so that the client can use them to minimize data
319 * transfer but will otherwise ignore them.
320 */
321 if (!path) {
322 if (oidset_insert(seen, ref->oid))
323 return 0;
324 path = ".have";
325 } else {
326 oidset_insert(seen, ref->oid);
327 }
328 show_ref(path, ref->oid);
329 return 0;
330 }
331
332 static void show_one_alternate_ref(const struct object_id *oid,
333 void *data)
334 {
335 struct oidset *seen = data;
336
337 if (oidset_insert(seen, oid))
338 return;
339
340 show_ref(".have", oid);
341 }
342
343 static void write_head_info(void)
344 {
345 struct refs_for_each_ref_options opts = { 0 };
346 static struct oidset seen = OIDSET_INIT;
347 struct strvec excludes_vector = STRVEC_INIT;
348
349 /*
350 * We need access to the reference names both with and without their
351 * namespace and thus cannot use `refs_for_each_namespaced_ref()`. We
352 * thus have to adapt exclude patterns to carry the namespace prefix
353 * ourselves.
354 */
355 opts.exclude_patterns = get_namespaced_exclude_patterns(
356 hidden_refs_to_excludes(&hidden_refs),
357 get_git_namespace(), &excludes_vector);
358
359 refs_for_each_ref_ext(get_main_ref_store(the_repository),
360 show_ref_cb, &seen, &opts);
361 odb_for_each_alternate_ref(the_repository->objects,
362 show_one_alternate_ref, &seen);
363
364 oidset_clear(&seen);
365 strvec_clear(&excludes_vector);
366
367 if (!sent_capabilities)
368 show_ref("capabilities^{}", null_oid(the_hash_algo));
369
370 advertise_shallow_grafts(1);
371
372 /* EOF */
373 packet_flush(1);
374 }
375
376 #define RUN_PROC_RECEIVE_SCHEDULED 1
377 #define RUN_PROC_RECEIVE_RETURNED 2
378 struct command {
379 struct command *next;
380 const char *error_string;
381 char *error_string_owned;
382 struct ref_push_report *report;
383 unsigned int skip_update:1,
384 did_not_exist:1,
385 run_proc_receive:2;
386 int index;
387 struct object_id old_oid;
388 struct object_id new_oid;
389 char ref_name[FLEX_ARRAY]; /* more */
390 };
391
392 static void proc_receive_ref_append(const char *prefix)
393 {
394 struct proc_receive_ref *ref_pattern;
395 const char *p;
396 int len;
397
398 CALLOC_ARRAY(ref_pattern, 1);
399 p = strchr(prefix, ':');
400 if (p) {
401 while (prefix < p) {
402 if (*prefix == 'a')
403 ref_pattern->want_add = 1;
404 else if (*prefix == 'd')
405 ref_pattern->want_delete = 1;
406 else if (*prefix == 'm')
407 ref_pattern->want_modify = 1;
408 else if (*prefix == '!')
409 ref_pattern->negative_ref = 1;
410 prefix++;
411 }
412 prefix++;
413 } else {
414 ref_pattern->want_add = 1;
415 ref_pattern->want_delete = 1;
416 ref_pattern->want_modify = 1;
417 }
418 len = strlen(prefix);
419 while (len && prefix[len - 1] == '/')
420 len--;
421 ref_pattern->ref_prefix = xmemdupz(prefix, len);
422 if (!proc_receive_ref) {
423 proc_receive_ref = ref_pattern;
424 } else {
425 struct proc_receive_ref *end;
426
427 end = proc_receive_ref;
428 while (end->next)
429 end = end->next;
430 end->next = ref_pattern;
431 }
432 }
433
434 static int proc_receive_ref_matches(struct command *cmd)
435 {
436 struct proc_receive_ref *p;
437
438 if (!proc_receive_ref)
439 return 0;
440
441 for (p = proc_receive_ref; p; p = p->next) {
442 const char *match = p->ref_prefix;
443 const char *remains;
444
445 if (!p->want_add && is_null_oid(&cmd->old_oid))
446 continue;
447 else if (!p->want_delete && is_null_oid(&cmd->new_oid))
448 continue;
449 else if (!p->want_modify &&
450 !is_null_oid(&cmd->old_oid) &&
451 !is_null_oid(&cmd->new_oid))
452 continue;
453
454 if (skip_prefix(cmd->ref_name, match, &remains) &&
455 (!*remains || *remains == '/')) {
456 if (!p->negative_ref)
457 return 1;
458 } else if (p->negative_ref) {
459 return 1;
460 }
461 }
462 return 0;
463 }
464
465 static void report_message(const char *prefix, const char *err, va_list params)
466 {
467 int sz;
468 char msg[4096];
469
470 sz = xsnprintf(msg, sizeof(msg), "%s", prefix);
471 sz += vsnprintf(msg + sz, sizeof(msg) - sz, err, params);
472 if (sz > (sizeof(msg) - 1))
473 sz = sizeof(msg) - 1;
474 msg[sz++] = '\n';
475
476 if (use_sideband)
477 send_sideband(1, 2, msg, sz, use_sideband);
478 else
479 xwrite(2, msg, sz);
480 }
481
482 __attribute__((format (printf, 1, 2)))
483 static void rp_warning(const char *err, ...)
484 {
485 va_list params;
486 va_start(params, err);
487 report_message("warning: ", err, params);
488 va_end(params);
489 }
490
491 __attribute__((format (printf, 1, 2)))
492 static void rp_error(const char *err, ...)
493 {
494 va_list params;
495 va_start(params, err);
496 report_message("error: ", err, params);
497 va_end(params);
498 }
499
500 static int copy_to_sideband(int in, int out UNUSED, void *arg UNUSED)
501 {
502 char data[128];
503 int keepalive_active = 0;
504
505 if (keepalive_in_sec <= 0)
506 use_keepalive = KEEPALIVE_NEVER;
507 if (use_keepalive == KEEPALIVE_ALWAYS)
508 keepalive_active = 1;
509
510 while (1) {
511 ssize_t sz;
512
513 if (keepalive_active) {
514 struct pollfd pfd;
515 int ret;
516
517 pfd.fd = in;
518 pfd.events = POLLIN;
519 ret = poll(&pfd, 1, 1000 * keepalive_in_sec);
520
521 if (ret < 0) {
522 if (errno == EINTR)
523 continue;
524 else
525 break;
526 } else if (ret == 0) {
527 /* no data; send a keepalive packet */
528 static const char buf[] = "0005\1";
529 write_or_die(1, buf, sizeof(buf) - 1);
530 continue;
531 } /* else there is actual data to read */
532 }
533
534 sz = xread(in, data, sizeof(data));
535 if (sz <= 0)
536 break;
537
538 if (use_keepalive == KEEPALIVE_AFTER_NUL && !keepalive_active) {
539 const char *p = memchr(data, '\0', sz);
540 if (p) {
541 /*
542 * The NUL tells us to start sending keepalives. Make
543 * sure we send any other data we read along
544 * with it.
545 */
546 keepalive_active = 1;
547 send_sideband(1, 2, data, p - data, use_sideband);
548 send_sideband(1, 2, p + 1, sz - (p - data + 1), use_sideband);
549 continue;
550 }
551 }
552
553 /*
554 * Either we're not looking for a NUL signal, or we didn't see
555 * it yet; just pass along the data.
556 */
557 send_sideband(1, 2, data, sz, use_sideband);
558 }
559 close(in);
560 return 0;
561 }
562
563 /*
564 * Start an async thread which redirects hook stderr over the sideband.
565 * The original stderr fd is saved to `saved_stderr` and STDERR_FILENO is
566 * redirected to the async's input pipe.
567 */
568 static void prepare_sideband_async(struct async *sideband_async, int *saved_stderr, int *started)
569 {
570 *started = 0;
571
572 if (!use_sideband)
573 return;
574
575 memset(sideband_async, 0, sizeof(*sideband_async));
576 sideband_async->proc = copy_to_sideband;
577 sideband_async->in = -1;
578
579 if (!start_async(sideband_async)) {
580 *started = 1;
581 *saved_stderr = dup(STDERR_FILENO);
582 if (*saved_stderr >= 0)
583 dup2(sideband_async->in, STDERR_FILENO);
584 close(sideband_async->in);
585 }
586 }
587
588 /*
589 * Restore the original stderr and wait for the async sideband thread to finish.
590 */
591 static void finish_sideband_async(struct async *sideband_async, int saved_stderr, int started)
592 {
593 if (!use_sideband)
594 return;
595
596 if (saved_stderr >= 0) {
597 dup2(saved_stderr, STDERR_FILENO);
598 close(saved_stderr);
599 }
600
601 if (started)
602 finish_async(sideband_async);
603 }
604
605 static void hmac_hash(unsigned char *out,
606 const char *key_in, size_t key_len,
607 const char *text, size_t text_len)
608 {
609 unsigned char key[GIT_MAX_BLKSZ];
610 unsigned char k_ipad[GIT_MAX_BLKSZ];
611 unsigned char k_opad[GIT_MAX_BLKSZ];
612 int i;
613 struct git_hash_ctx ctx;
614
615 /* RFC 2104 2. (1) */
616 memset(key, '\0', GIT_MAX_BLKSZ);
617 if (the_hash_algo->blksz < key_len) {
618 the_hash_algo->init_fn(&ctx);
619 git_hash_update(&ctx, key_in, key_len);
620 git_hash_final(key, &ctx);
621 } else {
622 memcpy(key, key_in, key_len);
623 }
624
625 /* RFC 2104 2. (2) & (5) */
626 for (i = 0; i < sizeof(key); i++) {
627 k_ipad[i] = key[i] ^ 0x36;
628 k_opad[i] = key[i] ^ 0x5c;
629 }
630
631 /* RFC 2104 2. (3) & (4) */
632 the_hash_algo->init_fn(&ctx);
633 git_hash_update(&ctx, k_ipad, sizeof(k_ipad));
634 git_hash_update(&ctx, text, text_len);
635 git_hash_final(out, &ctx);
636
637 /* RFC 2104 2. (6) & (7) */
638 the_hash_algo->init_fn(&ctx);
639 git_hash_update(&ctx, k_opad, sizeof(k_opad));
640 git_hash_update(&ctx, out, the_hash_algo->rawsz);
641 git_hash_final(out, &ctx);
642 }
643
644 static char *prepare_push_cert_nonce(const char *path, timestamp_t stamp)
645 {
646 struct strbuf buf = STRBUF_INIT;
647 unsigned char hash[GIT_MAX_RAWSZ];
648
649 strbuf_addf(&buf, "%s:%"PRItime, path, stamp);
650 hmac_hash(hash, buf.buf, buf.len, cert_nonce_seed, strlen(cert_nonce_seed));
651 strbuf_release(&buf);
652
653 /* RFC 2104 5. HMAC-SHA1 or HMAC-SHA256 */
654 strbuf_addf(&buf, "%"PRItime"-%.*s", stamp, (int)the_hash_algo->hexsz, hash_to_hex(hash));
655 return strbuf_detach(&buf, NULL);
656 }
657
658 /*
659 * Return zero if a and b are equal up to n bytes and nonzero if they are not.
660 * This operation is guaranteed to run in constant time to avoid leaking data.
661 */
662 static int constant_memequal(const char *a, const char *b, size_t n)
663 {
664 int res = 0;
665 size_t i;
666
667 for (i = 0; i < n; i++)
668 res |= a[i] ^ b[i];
669 return res;
670 }
671
672 static const char *check_nonce(const char *buf)
673 {
674 size_t noncelen;
675 const char *found = find_commit_header(buf, "nonce", &noncelen);
676 char *nonce = found ? xmemdupz(found, noncelen) : NULL;
677 timestamp_t stamp, ostamp;
678 char *bohmac, *expect = NULL;
679 const char *retval = NONCE_BAD;
680
681 if (!nonce) {
682 retval = NONCE_MISSING;
683 goto leave;
684 } else if (!push_cert_nonce) {
685 retval = NONCE_UNSOLICITED;
686 goto leave;
687 } else if (!strcmp(push_cert_nonce, nonce)) {
688 retval = NONCE_OK;
689 goto leave;
690 }
691
692 if (!stateless_rpc) {
693 /* returned nonce MUST match what we gave out earlier */
694 retval = NONCE_BAD;
695 goto leave;
696 }
697
698 /*
699 * In stateless mode, we may be receiving a nonce issued by
700 * another instance of the server that serving the same
701 * repository, and the timestamps may not match, but the
702 * nonce-seed and dir should match, so we can recompute and
703 * report the time slop.
704 *
705 * In addition, when a nonce issued by another instance has
706 * timestamp within receive.certnonceslop seconds, we pretend
707 * as if we issued that nonce when reporting to the hook.
708 */
709
710 /* nonce is concat(<seconds-since-epoch>, "-", <hmac>) */
711 if (*nonce <= '0' || '9' < *nonce) {
712 retval = NONCE_BAD;
713 goto leave;
714 }
715 stamp = parse_timestamp(nonce, &bohmac, 10);
716 if (bohmac == nonce || bohmac[0] != '-') {
717 retval = NONCE_BAD;
718 goto leave;
719 }
720
721 expect = prepare_push_cert_nonce(service_dir, stamp);
722 if (noncelen != strlen(expect)) {
723 /* This is not even the right size. */
724 retval = NONCE_BAD;
725 goto leave;
726 }
727 if (constant_memequal(expect, nonce, noncelen)) {
728 /* Not what we would have signed earlier */
729 retval = NONCE_BAD;
730 goto leave;
731 }
732
733 /*
734 * By how many seconds is this nonce stale? Negative value
735 * would mean it was issued by another server with its clock
736 * skewed in the future.
737 */
738 ostamp = parse_timestamp(push_cert_nonce, NULL, 10);
739 nonce_stamp_slop = (long)ostamp - (long)stamp;
740
741 if (nonce_stamp_slop_limit &&
742 labs(nonce_stamp_slop) <= nonce_stamp_slop_limit) {
743 /*
744 * Pretend as if the received nonce (which passes the
745 * HMAC check, so it is not a forged by third-party)
746 * is what we issued.
747 */
748 free((void *)push_cert_nonce);
749 push_cert_nonce = xstrdup(nonce);
750 retval = NONCE_OK;
751 } else {
752 retval = NONCE_SLOP;
753 }
754
755 leave:
756 free(nonce);
757 free(expect);
758 return retval;
759 }
760
761 /*
762 * Return 1 if there is no push_cert or if the push options in push_cert are
763 * the same as those in the argument; 0 otherwise.
764 */
765 static int check_cert_push_options(const struct string_list *push_options)
766 {
767 const char *buf = push_cert.buf;
768
769 const char *option;
770 size_t optionlen;
771 int options_seen = 0;
772
773 int retval = 1;
774
775 if (!*buf)
776 return 1;
777
778 while ((option = find_commit_header(buf, "push-option", &optionlen))) {
779 buf = option + optionlen + 1;
780 options_seen++;
781 if (options_seen > push_options->nr
782 || xstrncmpz(push_options->items[options_seen - 1].string,
783 option, optionlen))
784 return 0;
785 }
786
787 if (options_seen != push_options->nr)
788 retval = 0;
789
790 return retval;
791 }
792
793 static void prepare_push_cert_sha1(struct run_hooks_opt *opt)
794 {
795 static int already_done;
796
797 if (!push_cert.len)
798 return;
799
800 if (!already_done) {
801 int bogs /* beginning_of_gpg_sig */;
802
803 already_done = 1;
804 if (odb_write_object(the_repository->objects, push_cert.buf,
805 push_cert.len, OBJ_BLOB, &push_cert_oid))
806 oidclr(&push_cert_oid, the_repository->hash_algo);
807
808 memset(&sigcheck, '\0', sizeof(sigcheck));
809
810 bogs = parse_signed_buffer(push_cert.buf, push_cert.len);
811 sigcheck.payload = xmemdupz(push_cert.buf, bogs);
812 sigcheck.payload_len = bogs;
813 check_signature(&sigcheck, push_cert.buf + bogs,
814 push_cert.len - bogs);
815
816 nonce_status = check_nonce(sigcheck.payload);
817 }
818 if (!is_null_oid(&push_cert_oid)) {
819 strvec_pushf(&opt->env, "GIT_PUSH_CERT=%s",
820 oid_to_hex(&push_cert_oid));
821 strvec_pushf(&opt->env, "GIT_PUSH_CERT_SIGNER=%s",
822 sigcheck.signer ? sigcheck.signer : "");
823 strvec_pushf(&opt->env, "GIT_PUSH_CERT_KEY=%s",
824 sigcheck.key ? sigcheck.key : "");
825 strvec_pushf(&opt->env, "GIT_PUSH_CERT_STATUS=%c",
826 sigcheck.result);
827 if (push_cert_nonce) {
828 strvec_pushf(&opt->env,
829 "GIT_PUSH_CERT_NONCE=%s",
830 push_cert_nonce);
831 strvec_pushf(&opt->env,
832 "GIT_PUSH_CERT_NONCE_STATUS=%s",
833 nonce_status);
834 if (nonce_status == NONCE_SLOP)
835 strvec_pushf(&opt->env,
836 "GIT_PUSH_CERT_NONCE_SLOP=%ld",
837 nonce_stamp_slop);
838 }
839 }
840 }
841
842 struct receive_hook_feed_state {
843 struct command *cmd;
844 struct ref_push_report *report;
845 int skip_broken;
846 struct strbuf buf;
847 };
848
849 static int feed_receive_hook_cb(int hook_stdin_fd, void *pp_cb UNUSED, void *pp_task_cb)
850 {
851 struct receive_hook_feed_state *state = pp_task_cb;
852 struct command *cmd = state->cmd;
853
854 strbuf_reset(&state->buf);
855
856 while (cmd &&
857 state->skip_broken && (cmd->error_string || cmd->did_not_exist))
858 cmd = cmd->next;
859
860 if (!cmd)
861 return 1; /* no more commands left */
862
863 if (!state->report)
864 state->report = cmd->report;
865
866 if (state->report) {
867 struct object_id *old_oid;
868 struct object_id *new_oid;
869 const char *ref_name;
870
871 old_oid = state->report->old_oid ? state->report->old_oid : &cmd->old_oid;
872 new_oid = state->report->new_oid ? state->report->new_oid : &cmd->new_oid;
873 ref_name = state->report->ref_name ? state->report->ref_name : cmd->ref_name;
874
875 strbuf_addf(&state->buf, "%s %s %s\n",
876 oid_to_hex(old_oid), oid_to_hex(new_oid),
877 ref_name);
878
879 state->report = state->report->next;
880 if (!state->report)
881 cmd = cmd->next;
882 } else {
883 strbuf_addf(&state->buf, "%s %s %s\n",
884 oid_to_hex(&cmd->old_oid), oid_to_hex(&cmd->new_oid),
885 cmd->ref_name);
886 cmd = cmd->next;
887 }
888
889 state->cmd = cmd;
890
891 if (state->buf.len > 0) {
892 int ret = write_in_full(hook_stdin_fd, state->buf.buf, state->buf.len);
893 if (ret < 0) {
894 if (errno == EPIPE)
895 return 1; /* child closed pipe */
896 return ret;
897 }
898 }
899
900 return state->cmd ? 0 : 1; /* 0 = more to come, 1 = EOF */
901 }
902
903 static void *receive_hook_feed_state_alloc(void *feed_pipe_ctx)
904 {
905 struct receive_hook_feed_state *init_state = feed_pipe_ctx;
906 struct receive_hook_feed_state *data;
907
908 CALLOC_ARRAY(data, 1);
909 data->report = init_state->report;
910 data->cmd = init_state->cmd;
911 data->skip_broken = init_state->skip_broken;
912 strbuf_init(&data->buf, 0);
913
914 return data;
915 }
916
917 static void receive_hook_feed_state_free(void *data)
918 {
919 struct receive_hook_feed_state *d = data;
920 if (!d)
921 return;
922 strbuf_release(&d->buf);
923 free(d);
924 }
925
926 static int run_receive_hook(struct command *commands,
927 const char *hook_name,
928 int skip_broken,
929 const struct string_list *push_options)
930 {
931 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
932 struct command *iter = commands;
933 struct receive_hook_feed_state feed_init_state = {
934 .cmd = commands,
935 .skip_broken = skip_broken,
936 .buf = STRBUF_INIT,
937 };
938 struct async sideband_async;
939 int sideband_async_started = 0;
940 int saved_stderr = -1;
941 int ret;
942
943 if (!hook_exists(the_repository, hook_name))
944 return 0;
945
946 /* if there are no valid commands, don't invoke the hook at all. */
947 while (iter && skip_broken && (iter->error_string || iter->did_not_exist))
948 iter = iter->next;
949 if (!iter)
950 return 0;
951
952 if (push_options) {
953 for (int i = 0; i < push_options->nr; i++)
954 strvec_pushf(&opt.env, "GIT_PUSH_OPTION_%d=%s", i,
955 push_options->items[i].string);
956 strvec_pushf(&opt.env, "GIT_PUSH_OPTION_COUNT=%"PRIuMAX"",
957 (uintmax_t)push_options->nr);
958 } else {
959 strvec_push(&opt.env, "GIT_PUSH_OPTION_COUNT");
960 }
961
962 if (tmp_objdir)
963 strvec_pushv(&opt.env, tmp_objdir_env(tmp_objdir));
964
965 prepare_push_cert_sha1(&opt);
966
967 prepare_sideband_async(&sideband_async, &saved_stderr, &sideband_async_started);
968
969 /* set up stdin callback */
970 opt.feed_pipe_ctx = &feed_init_state;
971 opt.feed_pipe = feed_receive_hook_cb;
972 opt.feed_pipe_cb_data_alloc = receive_hook_feed_state_alloc;
973 opt.feed_pipe_cb_data_free = receive_hook_feed_state_free;
974
975 ret = run_hooks_opt(the_repository, hook_name, &opt);
976
977 finish_sideband_async(&sideband_async, saved_stderr, sideband_async_started);
978
979 return ret;
980 }
981
982 static int run_update_hook(struct command *cmd)
983 {
984 static const char hook_name[] = "update";
985 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
986 struct async sideband_async;
987 int sideband_async_started = 0;
988 int saved_stderr = -1;
989 int code;
990
991 if (!hook_exists(the_repository, hook_name))
992 return 0;
993
994 strvec_pushl(&opt.args,
995 cmd->ref_name,
996 oid_to_hex(&cmd->old_oid),
997 oid_to_hex(&cmd->new_oid),
998 NULL);
999
1000 prepare_sideband_async(&sideband_async, &saved_stderr, &sideband_async_started);
1001
1002 code = run_hooks_opt(the_repository, hook_name, &opt);
1003
1004 finish_sideband_async(&sideband_async, saved_stderr, sideband_async_started);
1005
1006 return code;
1007 }
1008
1009 static struct command *find_command_by_refname(struct command *list,
1010 const char *refname)
1011 {
1012 for (; list; list = list->next)
1013 if (!strcmp(list->ref_name, refname))
1014 return list;
1015 return NULL;
1016 }
1017
1018 static int read_proc_receive_report(struct packet_reader *reader,
1019 struct command *commands,
1020 struct strbuf *errmsg)
1021 {
1022 struct command *cmd;
1023 struct command *hint = NULL;
1024 struct ref_push_report *report = NULL;
1025 int new_report = 0;
1026 int code = 0;
1027 int once = 0;
1028 int response = 0;
1029
1030 for (;;) {
1031 struct object_id old_oid, new_oid;
1032 char *head;
1033 char *refname;
1034 char *p;
1035 enum packet_read_status status;
1036
1037 status = packet_reader_read(reader);
1038 if (status != PACKET_READ_NORMAL) {
1039 /* Check whether proc-receive exited abnormally */
1040 if (status == PACKET_READ_EOF && !response) {
1041 strbuf_addstr(errmsg, "proc-receive exited abnormally");
1042 return -1;
1043 }
1044 break;
1045 }
1046 response++;
1047
1048 head = reader->line;
1049 p = strchr(head, ' ');
1050 if (!p) {
1051 strbuf_addf(errmsg, "proc-receive reported incomplete status line: '%s'\n", head);
1052 code = -1;
1053 continue;
1054 }
1055 *p++ = '\0';
1056 if (!strcmp(head, "option")) {
1057 char *key;
1058 const char *val;
1059
1060 if (!hint || !(report || new_report)) {
1061 if (!once++)
1062 strbuf_addstr(errmsg, "proc-receive reported 'option' without a matching 'ok/ng' directive\n");
1063 code = -1;
1064 continue;
1065 }
1066 if (new_report) {
1067 if (!hint->report) {
1068 CALLOC_ARRAY(hint->report, 1);
1069 report = hint->report;
1070 } else {
1071 report = hint->report;
1072 while (report->next)
1073 report = report->next;
1074 report->next = xcalloc(1, sizeof(struct ref_push_report));
1075 report = report->next;
1076 }
1077 new_report = 0;
1078 }
1079 key = p;
1080 p = strchr(key, ' ');
1081 if (p)
1082 *p++ = '\0';
1083 val = p;
1084 if (!strcmp(key, "refname"))
1085 report->ref_name = xstrdup_or_null(val);
1086 else if (!strcmp(key, "old-oid") && val &&
1087 !parse_oid_hex(val, &old_oid, &val))
1088 report->old_oid = oiddup(&old_oid);
1089 else if (!strcmp(key, "new-oid") && val &&
1090 !parse_oid_hex(val, &new_oid, &val))
1091 report->new_oid = oiddup(&new_oid);
1092 else if (!strcmp(key, "forced-update"))
1093 report->forced_update = 1;
1094 else if (!strcmp(key, "fall-through"))
1095 /* Fall through, let 'receive-pack' to execute it. */
1096 hint->run_proc_receive = 0;
1097 continue;
1098 }
1099
1100 report = NULL;
1101 new_report = 0;
1102 refname = p;
1103 p = strchr(refname, ' ');
1104 if (p)
1105 *p++ = '\0';
1106 if (strcmp(head, "ok") && strcmp(head, "ng")) {
1107 strbuf_addf(errmsg, "proc-receive reported bad status '%s' on ref '%s'\n",
1108 head, refname);
1109 code = -1;
1110 continue;
1111 }
1112
1113 /* first try searching at our hint, falling back to all refs */
1114 if (hint)
1115 hint = find_command_by_refname(hint, refname);
1116 if (!hint)
1117 hint = find_command_by_refname(commands, refname);
1118 if (!hint) {
1119 strbuf_addf(errmsg, "proc-receive reported status on unknown ref: %s\n",
1120 refname);
1121 code = -1;
1122 continue;
1123 }
1124 if (!hint->run_proc_receive) {
1125 strbuf_addf(errmsg, "proc-receive reported status on unexpected ref: %s\n",
1126 refname);
1127 code = -1;
1128 continue;
1129 }
1130 hint->run_proc_receive |= RUN_PROC_RECEIVE_RETURNED;
1131 if (!strcmp(head, "ng")) {
1132 if (p)
1133 hint->error_string = hint->error_string_owned = xstrdup(p);
1134 else
1135 hint->error_string = "failed";
1136 code = -1;
1137 continue;
1138 }
1139 new_report = 1;
1140 }
1141
1142 for (cmd = commands; cmd; cmd = cmd->next)
1143 if (cmd->run_proc_receive && !cmd->error_string &&
1144 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED)) {
1145 cmd->error_string = "proc-receive failed to report status";
1146 code = -1;
1147 }
1148 return code;
1149 }
1150
1151 static int run_proc_receive_hook(struct command *commands,
1152 const struct string_list *push_options)
1153 {
1154 struct child_process proc = CHILD_PROCESS_INIT;
1155 struct async muxer;
1156 struct command *cmd;
1157 struct packet_reader reader;
1158 struct strbuf cap = STRBUF_INIT;
1159 struct strbuf errmsg = STRBUF_INIT;
1160 int hook_use_push_options = 0;
1161 int version = 0;
1162 int code;
1163 const char *hook_path = find_hook(the_repository, "proc-receive");
1164
1165 if (!hook_path) {
1166 rp_error("cannot find hook 'proc-receive'");
1167 return -1;
1168 }
1169
1170 strvec_push(&proc.args, hook_path);
1171 proc.in = -1;
1172 proc.out = -1;
1173 proc.trace2_hook_name = "proc-receive";
1174
1175 if (use_sideband) {
1176 memset(&muxer, 0, sizeof(muxer));
1177 muxer.proc = copy_to_sideband;
1178 muxer.in = -1;
1179 code = start_async(&muxer);
1180 if (code)
1181 return code;
1182 proc.err = muxer.in;
1183 } else {
1184 proc.err = 0;
1185 }
1186
1187 code = start_command(&proc);
1188 if (code) {
1189 if (use_sideband)
1190 finish_async(&muxer);
1191 return code;
1192 }
1193
1194 sigchain_push(SIGPIPE, SIG_IGN);
1195
1196 /* Version negotiaton */
1197 packet_reader_init(&reader, proc.out, NULL, 0,
1198 PACKET_READ_CHOMP_NEWLINE |
1199 PACKET_READ_GENTLE_ON_EOF);
1200 if (use_atomic)
1201 strbuf_addstr(&cap, " atomic");
1202 if (use_push_options)
1203 strbuf_addstr(&cap, " push-options");
1204 if (cap.len) {
1205 code = packet_write_fmt_gently(proc.in, "version=1%c%s\n", '\0', cap.buf + 1);
1206 strbuf_release(&cap);
1207 } else {
1208 code = packet_write_fmt_gently(proc.in, "version=1\n");
1209 }
1210 if (!code)
1211 code = packet_flush_gently(proc.in);
1212
1213 if (!code)
1214 for (;;) {
1215 int linelen;
1216 enum packet_read_status status;
1217
1218 status = packet_reader_read(&reader);
1219 if (status != PACKET_READ_NORMAL) {
1220 /* Check whether proc-receive exited abnormally */
1221 if (status == PACKET_READ_EOF)
1222 code = -1;
1223 break;
1224 }
1225
1226 if (reader.pktlen > 8 && starts_with(reader.line, "version=")) {
1227 version = atoi(reader.line + 8);
1228 linelen = strlen(reader.line);
1229 if (linelen < reader.pktlen) {
1230 const char *feature_list = reader.line + linelen + 1;
1231 if (parse_feature_request(feature_list, "push-options"))
1232 hook_use_push_options = 1;
1233 }
1234 }
1235 }
1236
1237 if (code) {
1238 strbuf_addstr(&errmsg, "fail to negotiate version with proc-receive hook");
1239 goto cleanup;
1240 }
1241
1242 switch (version) {
1243 case 0:
1244 /* fallthrough */
1245 case 1:
1246 break;
1247 default:
1248 strbuf_addf(&errmsg, "proc-receive version '%d' is not supported",
1249 version);
1250 code = -1;
1251 goto cleanup;
1252 }
1253
1254 /* Send commands */
1255 for (cmd = commands; cmd; cmd = cmd->next) {
1256 if (!cmd->run_proc_receive || cmd->skip_update || cmd->error_string)
1257 continue;
1258 code = packet_write_fmt_gently(proc.in, "%s %s %s",
1259 oid_to_hex(&cmd->old_oid),
1260 oid_to_hex(&cmd->new_oid),
1261 cmd->ref_name);
1262 if (code)
1263 break;
1264 }
1265 if (!code)
1266 code = packet_flush_gently(proc.in);
1267 if (code) {
1268 strbuf_addstr(&errmsg, "fail to write commands to proc-receive hook");
1269 goto cleanup;
1270 }
1271
1272 /* Send push options */
1273 if (hook_use_push_options) {
1274 struct string_list_item *item;
1275
1276 for_each_string_list_item(item, push_options) {
1277 code = packet_write_fmt_gently(proc.in, "%s", item->string);
1278 if (code)
1279 break;
1280 }
1281 if (!code)
1282 code = packet_flush_gently(proc.in);
1283 if (code) {
1284 strbuf_addstr(&errmsg,
1285 "fail to write push-options to proc-receive hook");
1286 goto cleanup;
1287 }
1288 }
1289
1290 /* Read result from proc-receive */
1291 code = read_proc_receive_report(&reader, commands, &errmsg);
1292
1293 cleanup:
1294 close(proc.in);
1295 close(proc.out);
1296 if (use_sideband)
1297 finish_async(&muxer);
1298 if (finish_command(&proc))
1299 code = -1;
1300 if (errmsg.len >0) {
1301 char *p = errmsg.buf;
1302
1303 p += errmsg.len - 1;
1304 if (*p == '\n')
1305 *p = '\0';
1306 rp_error("%s", errmsg.buf);
1307 strbuf_release(&errmsg);
1308 }
1309 sigchain_pop(SIGPIPE);
1310
1311 return code;
1312 }
1313
1314 static const char *refuse_unconfigured_deny_msg =
1315 N_("By default, updating the current branch in a non-bare repository\n"
1316 "is denied, because it will make the index and work tree inconsistent\n"
1317 "with what you pushed, and will require 'git reset --hard' to match\n"
1318 "the work tree to HEAD.\n"
1319 "\n"
1320 "You can set the 'receive.denyCurrentBranch' configuration variable\n"
1321 "to 'ignore' or 'warn' in the remote repository to allow pushing into\n"
1322 "its current branch; however, this is not recommended unless you\n"
1323 "arranged to update its work tree to match what you pushed in some\n"
1324 "other way.\n"
1325 "\n"
1326 "To squelch this message and still keep the default behaviour, set\n"
1327 "'receive.denyCurrentBranch' configuration variable to 'refuse'.");
1328
1329 static void refuse_unconfigured_deny(void)
1330 {
1331 rp_error("%s", _(refuse_unconfigured_deny_msg));
1332 }
1333
1334 static const char *refuse_unconfigured_deny_delete_current_msg =
1335 N_("By default, deleting the current branch is denied, because the next\n"
1336 "'git clone' won't result in any file checked out, causing confusion.\n"
1337 "\n"
1338 "You can set 'receive.denyDeleteCurrent' configuration variable to\n"
1339 "'warn' or 'ignore' in the remote repository to allow deleting the\n"
1340 "current branch, with or without a warning message.\n"
1341 "\n"
1342 "To squelch this message, you can set it to 'refuse'.");
1343
1344 static void refuse_unconfigured_deny_delete_current(void)
1345 {
1346 rp_error("%s", _(refuse_unconfigured_deny_delete_current_msg));
1347 }
1348
1349 static const struct object_id *command_singleton_iterator(void *cb_data);
1350 static int update_shallow_ref(struct command *cmd, struct shallow_info *si)
1351 {
1352 struct shallow_lock shallow_lock = SHALLOW_LOCK_INIT;
1353 struct oid_array extra = OID_ARRAY_INIT;
1354 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1355 uint32_t mask = 1 << (cmd->index % 32);
1356 int i;
1357
1358 trace_printf_key(&trace_shallow,
1359 "shallow: update_shallow_ref %s\n", cmd->ref_name);
1360 for (i = 0; i < si->shallow->nr; i++)
1361 if (si->used_shallow[i] &&
1362 (si->used_shallow[i][cmd->index / 32] & mask) &&
1363 !delayed_reachability_test(si, i))
1364 oid_array_append(&extra, &si->shallow->oid[i]);
1365
1366 opt.env = tmp_objdir_env(tmp_objdir);
1367 setup_alternate_shallow(&shallow_lock, &opt.shallow_file, &extra);
1368 if (check_connected(command_singleton_iterator, cmd, &opt)) {
1369 rollback_shallow_file(the_repository, &shallow_lock);
1370 oid_array_clear(&extra);
1371 return -1;
1372 }
1373
1374 commit_shallow_file(the_repository, &shallow_lock);
1375
1376 /*
1377 * Make sure setup_alternate_shallow() for the next ref does
1378 * not lose these new roots..
1379 */
1380 for (i = 0; i < extra.nr; i++)
1381 register_shallow(the_repository, &extra.oid[i]);
1382
1383 si->shallow_ref[cmd->index] = 0;
1384 oid_array_clear(&extra);
1385 return 0;
1386 }
1387
1388 static const char *push_to_deploy(unsigned char *sha1,
1389 struct strvec *env,
1390 const struct worktree *worktree)
1391 {
1392 struct child_process child = CHILD_PROCESS_INIT;
1393
1394 strvec_pushl(&child.args, "update-index", "-q", "--ignore-submodules",
1395 "--refresh", NULL);
1396 strvec_pushv(&child.env, env->v);
1397 child.dir = worktree->path;
1398 child.no_stdin = 1;
1399 child.stdout_to_stderr = 1;
1400 child.git_cmd = 1;
1401 if (run_command(&child))
1402 return "Up-to-date check failed";
1403
1404 /* run_command() does not clean up completely; reinitialize */
1405 child_process_init(&child);
1406 strvec_pushl(&child.args, "diff-files", "--quiet",
1407 "--ignore-submodules", "--", NULL);
1408 strvec_pushv(&child.env, env->v);
1409 child.dir = worktree->path;
1410 child.no_stdin = 1;
1411 child.stdout_to_stderr = 1;
1412 child.git_cmd = 1;
1413 if (run_command(&child))
1414 return "Working directory has unstaged changes";
1415
1416 child_process_init(&child);
1417 strvec_pushl(&child.args, "diff-index", "--quiet", "--cached",
1418 "--ignore-submodules",
1419 /*
1420 * diff-index with either HEAD or an empty tree
1421 *
1422 * NEEDSWORK: is_null_oid() cannot know whether it's an
1423 * unborn HEAD or a corrupt ref. It works for now because
1424 * it's only needed to know if we are comparing HEAD or an
1425 * empty tree.
1426 */
1427 !is_null_oid(&worktree->head_oid) ? "HEAD" :
1428 empty_tree_oid_hex(the_repository->hash_algo), "--", NULL);
1429 strvec_pushv(&child.env, env->v);
1430 child.no_stdin = 1;
1431 child.no_stdout = 1;
1432 child.stdout_to_stderr = 0;
1433 child.git_cmd = 1;
1434 if (run_command(&child))
1435 return "Working directory has staged changes";
1436
1437 child_process_init(&child);
1438 strvec_pushl(&child.args, "read-tree", "-u", "-m", hash_to_hex(sha1),
1439 NULL);
1440 strvec_pushv(&child.env, env->v);
1441 child.dir = worktree->path;
1442 child.no_stdin = 1;
1443 child.no_stdout = 1;
1444 child.stdout_to_stderr = 0;
1445 child.git_cmd = 1;
1446 if (run_command(&child))
1447 return "Could not update working tree to new HEAD";
1448
1449 return NULL;
1450 }
1451
1452 static const char *push_to_checkout_hook = "push-to-checkout";
1453
1454 static const char *push_to_checkout(unsigned char *hash,
1455 int *invoked_hook,
1456 struct strvec *env,
1457 const char *work_tree)
1458 {
1459 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT_FORCE_SERIAL;
1460
1461 opt.invoked_hook = invoked_hook;
1462
1463 strvec_pushv(&opt.env, env->v);
1464 strvec_pushf(&opt.env, "GIT_WORK_TREE=%s", absolute_path(work_tree));
1465 strvec_push(&opt.args, hash_to_hex(hash));
1466 if (run_hooks_opt(the_repository, push_to_checkout_hook, &opt))
1467 return "push-to-checkout hook declined";
1468 else
1469 return NULL;
1470 }
1471
1472 static const char *update_worktree(unsigned char *sha1, const struct worktree *worktree)
1473 {
1474 const char *retval;
1475 char *git_dir;
1476 struct strvec env = STRVEC_INIT;
1477 int invoked_hook;
1478
1479 if (!worktree || !worktree->path)
1480 BUG("worktree->path must be non-NULL");
1481
1482 if (worktree->is_bare)
1483 return "denyCurrentBranch = updateInstead needs a worktree";
1484 git_dir = get_worktree_git_dir(worktree);
1485
1486 strvec_pushf(&env, "GIT_DIR=%s", absolute_path(git_dir));
1487
1488 retval = push_to_checkout(sha1, &invoked_hook, &env, worktree->path);
1489 if (!invoked_hook)
1490 retval = push_to_deploy(sha1, &env, worktree);
1491
1492 strvec_clear(&env);
1493 free(git_dir);
1494 return retval;
1495 }
1496
1497 static const char *update(struct command *cmd, struct shallow_info *si)
1498 {
1499 const char *name = cmd->ref_name;
1500 struct strbuf namespaced_name_buf = STRBUF_INIT;
1501 static char *namespaced_name;
1502 const char *ret;
1503 struct object_id *old_oid = &cmd->old_oid;
1504 struct object_id *new_oid = &cmd->new_oid;
1505 int do_update_worktree = 0;
1506 struct worktree **worktrees = get_worktrees();
1507 const struct worktree *worktree =
1508 find_shared_symref(worktrees, "HEAD", name);
1509
1510 /* only refs/... are allowed */
1511 if (!starts_with(name, "refs/") ||
1512 check_refname_format(name + 5, is_null_oid(new_oid) ?
1513 REFNAME_ALLOW_ONELEVEL : 0)) {
1514 rp_error("refusing to update funny ref '%s' remotely", name);
1515 ret = "funny refname";
1516 goto out;
1517 }
1518
1519 strbuf_addf(&namespaced_name_buf, "%s%s", get_git_namespace(), name);
1520 free(namespaced_name);
1521 namespaced_name = strbuf_detach(&namespaced_name_buf, NULL);
1522
1523 if (worktree && !worktree->is_bare) {
1524 switch (deny_current_branch) {
1525 case DENY_IGNORE:
1526 break;
1527 case DENY_WARN:
1528 rp_warning("updating the current branch");
1529 break;
1530 case DENY_REFUSE:
1531 case DENY_UNCONFIGURED:
1532 rp_error("refusing to update checked out branch: %s", name);
1533 if (deny_current_branch == DENY_UNCONFIGURED)
1534 refuse_unconfigured_deny();
1535 ret = "branch is currently checked out";
1536 goto out;
1537 case DENY_UPDATE_INSTEAD:
1538 /* pass -- let other checks intervene first */
1539 do_update_worktree = 1;
1540 break;
1541 }
1542 }
1543
1544 if (!is_null_oid(new_oid) &&
1545 !odb_has_object(the_repository->objects, new_oid,
1546 ODB_HAS_OBJECT_RECHECK_PACKED | ODB_HAS_OBJECT_FETCH_PROMISOR)) {
1547 error("unpack should have generated %s, "
1548 "but I can't find it!", oid_to_hex(new_oid));
1549 ret = "bad pack";
1550 goto out;
1551 }
1552
1553 if (!is_null_oid(old_oid) && is_null_oid(new_oid)) {
1554 if (deny_deletes && starts_with(name, "refs/heads/")) {
1555 rp_error("denying ref deletion for %s", name);
1556 ret = "deletion prohibited";
1557 goto out;
1558 }
1559
1560 if (worktree || (head_name && !strcmp(namespaced_name, head_name))) {
1561 switch (deny_delete_current) {
1562 case DENY_IGNORE:
1563 break;
1564 case DENY_WARN:
1565 rp_warning("deleting the current branch");
1566 break;
1567 case DENY_REFUSE:
1568 case DENY_UNCONFIGURED:
1569 case DENY_UPDATE_INSTEAD:
1570 if (deny_delete_current == DENY_UNCONFIGURED)
1571 refuse_unconfigured_deny_delete_current();
1572 rp_error("refusing to delete the current branch: %s", name);
1573 ret = "deletion of the current branch prohibited";
1574 goto out;
1575 default:
1576 ret = "Invalid denyDeleteCurrent setting";
1577 goto out;
1578 }
1579 }
1580 }
1581
1582 if (deny_non_fast_forwards && !is_null_oid(new_oid) &&
1583 !is_null_oid(old_oid) &&
1584 starts_with(name, "refs/heads/")) {
1585 struct object *old_object, *new_object;
1586 struct commit *old_commit, *new_commit;
1587 int ret2;
1588
1589 old_object = parse_object(the_repository, old_oid);
1590 new_object = parse_object(the_repository, new_oid);
1591
1592 if (!old_object || !new_object ||
1593 old_object->type != OBJ_COMMIT ||
1594 new_object->type != OBJ_COMMIT) {
1595 error("bad sha1 objects for %s", name);
1596 ret = "bad ref";
1597 goto out;
1598 }
1599 old_commit = (struct commit *)old_object;
1600 new_commit = (struct commit *)new_object;
1601 ret2 = repo_in_merge_bases(the_repository, old_commit, new_commit);
1602 if (ret2 < 0)
1603 exit(128);
1604 if (!ret2) {
1605 rp_error("denying non-fast-forward %s"
1606 " (you should pull first)", name);
1607 ret = "non-fast-forward";
1608 goto out;
1609 }
1610 }
1611 if (run_update_hook(cmd)) {
1612 rp_error("hook declined to update %s", name);
1613 ret = "hook declined";
1614 goto out;
1615 }
1616
1617 if (do_update_worktree) {
1618 ret = update_worktree(new_oid->hash, worktree);
1619 if (ret)
1620 goto out;
1621 }
1622
1623 if (is_null_oid(new_oid)) {
1624 struct strbuf err = STRBUF_INIT;
1625 if (!parse_object(the_repository, old_oid)) {
1626 old_oid = NULL;
1627 if (refs_ref_exists(get_main_ref_store(the_repository), name)) {
1628 rp_warning("allowing deletion of corrupt ref");
1629 } else {
1630 rp_warning("deleting a non-existent ref");
1631 cmd->did_not_exist = 1;
1632 }
1633 }
1634 if (ref_transaction_delete(transaction,
1635 namespaced_name,
1636 old_oid,
1637 NULL, 0,
1638 "push", &err)) {
1639 rp_error("%s", err.buf);
1640 ret = "failed to delete";
1641 } else {
1642 ret = NULL; /* good */
1643 }
1644 strbuf_release(&err);
1645 } else {
1646 enum ref_transaction_error tx_err;
1647 struct strbuf err = STRBUF_INIT;
1648 if (shallow_update && si->shallow_ref[cmd->index] &&
1649 update_shallow_ref(cmd, si)) {
1650 ret = "shallow error";
1651 goto out;
1652 }
1653
1654 tx_err = ref_transaction_update(transaction,
1655 namespaced_name,
1656 new_oid, old_oid,
1657 NULL, NULL,
1658 0, "push",
1659 &err);
1660 if (tx_err) {
1661 rp_error("%s", err.buf);
1662 if (tx_err == REF_TRANSACTION_ERROR_GENERIC)
1663 ret = "failed to update ref";
1664 else
1665 ret = ref_transaction_error_msg(tx_err);
1666 } else {
1667 ret = NULL; /* good */
1668 }
1669 strbuf_release(&err);
1670 }
1671
1672 out:
1673 free_worktrees(worktrees);
1674 return ret;
1675 }
1676
1677 static void run_update_post_hook(struct command *commands)
1678 {
1679 static const char hook_name[] = "post-update";
1680 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1681 struct async sideband_async;
1682 struct command *cmd;
1683 int sideband_async_started = 0;
1684 int saved_stderr = -1;
1685
1686 if (!hook_exists(the_repository, hook_name))
1687 return;
1688
1689 for (cmd = commands; cmd; cmd = cmd->next) {
1690 if (cmd->error_string || cmd->did_not_exist)
1691 continue;
1692 strvec_push(&opt.args, cmd->ref_name);
1693 }
1694 if (!opt.args.nr)
1695 return;
1696
1697 prepare_sideband_async(&sideband_async, &saved_stderr, &sideband_async_started);
1698
1699 run_hooks_opt(the_repository, hook_name, &opt);
1700
1701 finish_sideband_async(&sideband_async, saved_stderr, sideband_async_started);
1702 }
1703
1704 static void check_aliased_update_internal(struct command *cmd,
1705 struct string_list *list,
1706 const char *dst_name, int flag)
1707 {
1708 struct string_list_item *item;
1709 struct command *dst_cmd;
1710
1711 if (!(flag & REF_ISSYMREF))
1712 return;
1713
1714 if (!dst_name) {
1715 rp_error("refusing update to broken symref '%s'", cmd->ref_name);
1716 cmd->skip_update = 1;
1717 cmd->error_string = "broken symref";
1718 return;
1719 }
1720 dst_name = strip_namespace(dst_name);
1721
1722 if (!(item = string_list_lookup(list, dst_name)))
1723 return;
1724
1725 cmd->skip_update = 1;
1726
1727 dst_cmd = (struct command *) item->util;
1728
1729 if (oideq(&cmd->old_oid, &dst_cmd->old_oid) &&
1730 oideq(&cmd->new_oid, &dst_cmd->new_oid))
1731 return;
1732
1733 dst_cmd->skip_update = 1;
1734
1735 rp_error("refusing inconsistent update between symref '%s' (%s..%s) and"
1736 " its target '%s' (%s..%s)",
1737 cmd->ref_name,
1738 repo_find_unique_abbrev(the_repository, &cmd->old_oid, DEFAULT_ABBREV),
1739 repo_find_unique_abbrev(the_repository, &cmd->new_oid, DEFAULT_ABBREV),
1740 dst_cmd->ref_name,
1741 repo_find_unique_abbrev(the_repository, &dst_cmd->old_oid, DEFAULT_ABBREV),
1742 repo_find_unique_abbrev(the_repository, &dst_cmd->new_oid, DEFAULT_ABBREV));
1743
1744 cmd->error_string = dst_cmd->error_string =
1745 "inconsistent aliased update";
1746 }
1747
1748 static void check_aliased_update(struct command *cmd, struct string_list *list)
1749 {
1750 struct strbuf buf = STRBUF_INIT;
1751 const char *dst_name;
1752 int flag;
1753
1754 strbuf_addf(&buf, "%s%s", get_git_namespace(), cmd->ref_name);
1755 dst_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1756 buf.buf, 0, NULL, &flag);
1757 check_aliased_update_internal(cmd, list, dst_name, flag);
1758 strbuf_release(&buf);
1759 }
1760
1761 static void check_aliased_updates(struct command *commands)
1762 {
1763 struct command *cmd;
1764 struct string_list ref_list = STRING_LIST_INIT_NODUP;
1765
1766 for (cmd = commands; cmd; cmd = cmd->next) {
1767 struct string_list_item *item =
1768 string_list_append(&ref_list, cmd->ref_name);
1769 item->util = (void *)cmd;
1770 }
1771 string_list_sort(&ref_list);
1772
1773 for (cmd = commands; cmd; cmd = cmd->next) {
1774 if (!cmd->error_string)
1775 check_aliased_update(cmd, &ref_list);
1776 }
1777
1778 string_list_clear(&ref_list, 0);
1779 }
1780
1781 static const struct object_id *command_singleton_iterator(void *cb_data)
1782 {
1783 struct command **cmd_list = cb_data;
1784 struct command *cmd = *cmd_list;
1785
1786 if (!cmd || is_null_oid(&cmd->new_oid))
1787 return NULL;
1788 *cmd_list = NULL; /* this returns only one */
1789 return &cmd->new_oid;
1790 }
1791
1792 static void set_connectivity_errors(struct command *commands,
1793 struct shallow_info *si)
1794 {
1795 struct command *cmd;
1796
1797 for (cmd = commands; cmd; cmd = cmd->next) {
1798 struct command *singleton = cmd;
1799 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1800
1801 if (shallow_update && si->shallow_ref[cmd->index])
1802 /* to be checked in update_shallow_ref() */
1803 continue;
1804
1805 opt.env = tmp_objdir_env(tmp_objdir);
1806 if (!check_connected(command_singleton_iterator, &singleton,
1807 &opt))
1808 continue;
1809
1810 cmd->error_string = "missing necessary objects";
1811 }
1812 }
1813
1814 struct iterate_data {
1815 struct command *cmds;
1816 struct shallow_info *si;
1817 };
1818
1819 static const struct object_id *iterate_receive_command_list(void *cb_data)
1820 {
1821 struct iterate_data *data = cb_data;
1822 struct command **cmd_list = &data->cmds;
1823 struct command *cmd = *cmd_list;
1824
1825 for (; cmd; cmd = cmd->next) {
1826 if (shallow_update && data->si->shallow_ref[cmd->index])
1827 /* to be checked in update_shallow_ref() */
1828 continue;
1829 if (!is_null_oid(&cmd->new_oid) && !cmd->skip_update) {
1830 *cmd_list = cmd->next;
1831 return &cmd->new_oid;
1832 }
1833 }
1834 return NULL;
1835 }
1836
1837 static void reject_updates_to_hidden(struct command *commands)
1838 {
1839 struct strbuf refname_full = STRBUF_INIT;
1840 size_t prefix_len;
1841 struct command *cmd;
1842
1843 strbuf_addstr(&refname_full, get_git_namespace());
1844 prefix_len = refname_full.len;
1845
1846 for (cmd = commands; cmd; cmd = cmd->next) {
1847 if (cmd->error_string)
1848 continue;
1849
1850 strbuf_setlen(&refname_full, prefix_len);
1851 strbuf_addstr(&refname_full, cmd->ref_name);
1852
1853 if (!ref_is_hidden(cmd->ref_name, refname_full.buf, &hidden_refs))
1854 continue;
1855 if (is_null_oid(&cmd->new_oid))
1856 cmd->error_string = "deny deleting a hidden ref";
1857 else
1858 cmd->error_string = "deny updating a hidden ref";
1859 }
1860
1861 strbuf_release(&refname_full);
1862 }
1863
1864 static int should_process_cmd(struct command *cmd)
1865 {
1866 return !cmd->error_string && !cmd->skip_update;
1867 }
1868
1869 static void BUG_if_skipped_connectivity_check(struct command *commands,
1870 struct shallow_info *si)
1871 {
1872 struct command *cmd;
1873
1874 for (cmd = commands; cmd; cmd = cmd->next) {
1875 if (should_process_cmd(cmd) && si->shallow_ref[cmd->index])
1876 bug("connectivity check has not been run on ref %s",
1877 cmd->ref_name);
1878 }
1879 BUG_if_bug("connectivity check skipped???");
1880 }
1881
1882 static void ref_transaction_rejection_handler(const char *refname,
1883 const struct object_id *old_oid UNUSED,
1884 const struct object_id *new_oid UNUSED,
1885 const char *old_target UNUSED,
1886 const char *new_target UNUSED,
1887 enum ref_transaction_error err,
1888 const char *details,
1889 void *cb_data)
1890 {
1891 struct strmap *failed_refs = cb_data;
1892
1893 if (details)
1894 rp_error("%s", details);
1895
1896 strmap_put(failed_refs, refname, (char *)ref_transaction_error_msg(err));
1897 }
1898
1899 static void execute_commands_non_atomic(struct command *commands,
1900 struct shallow_info *si)
1901 {
1902 struct command *cmd;
1903 struct strbuf err = STRBUF_INIT;
1904 const char *reported_error = NULL;
1905 struct strmap failed_refs = STRMAP_INIT;
1906
1907 /*
1908 * Reference updates, where D/F conflicts shouldn't arise due to
1909 * one reference being deleted, while the other being created
1910 * are treated as conflicts in batched updates. This is because
1911 * we don't do conflict resolution inside a transaction. To
1912 * mitigate this, delete references in a separate batch.
1913 *
1914 * NEEDSWORK: Add conflict resolution between deletion and creation
1915 * of reference updates within a transaction. With that, we can
1916 * combine the two phases.
1917 */
1918 enum processing_phase {
1919 PHASE_DELETIONS,
1920 PHASE_OTHERS
1921 };
1922
1923 for (enum processing_phase phase = PHASE_DELETIONS; phase <= PHASE_OTHERS; phase++) {
1924 for (cmd = commands; cmd; cmd = cmd->next) {
1925 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1926 continue;
1927
1928 if (phase == PHASE_DELETIONS && !is_null_oid(&cmd->new_oid))
1929 continue;
1930 else if (phase == PHASE_OTHERS && is_null_oid(&cmd->new_oid))
1931 continue;
1932
1933 /*
1934 * Lazily create a transaction only when we know there are
1935 * updates to be added.
1936 */
1937 if (!transaction) {
1938 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1939 REF_TRANSACTION_ALLOW_FAILURE, &err);
1940 if (!transaction) {
1941 rp_error("%s", err.buf);
1942 strbuf_reset(&err);
1943 reported_error = "transaction failed to start";
1944 goto failure;
1945 }
1946 }
1947
1948 cmd->error_string = update(cmd, si);
1949 }
1950
1951 /* No transaction, so nothing to commit */
1952 if (!transaction)
1953 goto cleanup;
1954
1955 if (ref_transaction_commit(transaction, &err)) {
1956 rp_error("%s", err.buf);
1957 reported_error = "failed to update refs";
1958 goto failure;
1959 }
1960
1961 ref_transaction_for_each_rejected_update(transaction,
1962
1963 ref_transaction_rejection_handler,
1964 &failed_refs);
1965
1966 if (strmap_empty(&failed_refs))
1967 goto cleanup;
1968
1969 failure:
1970 for (cmd = commands; cmd; cmd = cmd->next) {
1971 if (reported_error)
1972 cmd->error_string = reported_error;
1973 else if (strmap_contains(&failed_refs, cmd->ref_name))
1974 cmd->error_string = cmd->error_string_owned = xstrdup(strmap_get(&failed_refs, cmd->ref_name));
1975 }
1976
1977 cleanup:
1978 ref_transaction_free(transaction);
1979 transaction = NULL;
1980 strmap_clear(&failed_refs, 0);
1981 strbuf_release(&err);
1982 }
1983 }
1984
1985 static void execute_commands_atomic(struct command *commands,
1986 struct shallow_info *si)
1987 {
1988 struct command *cmd;
1989 struct strbuf err = STRBUF_INIT;
1990 const char *reported_error = "atomic push failure";
1991
1992 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1993 0, &err);
1994 if (!transaction) {
1995 rp_error("%s", err.buf);
1996 strbuf_reset(&err);
1997 reported_error = "transaction failed to start";
1998 goto failure;
1999 }
2000
2001 for (cmd = commands; cmd; cmd = cmd->next) {
2002 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
2003 continue;
2004
2005 cmd->error_string = update(cmd, si);
2006
2007 if (cmd->error_string)
2008 goto failure;
2009 }
2010
2011 if (ref_transaction_commit(transaction, &err)) {
2012 rp_error("%s", err.buf);
2013 reported_error = "atomic transaction failed";
2014 goto failure;
2015 }
2016 goto cleanup;
2017
2018 failure:
2019 for (cmd = commands; cmd; cmd = cmd->next)
2020 if (!cmd->error_string)
2021 cmd->error_string = reported_error;
2022
2023 cleanup:
2024 ref_transaction_free(transaction);
2025 strbuf_release(&err);
2026 }
2027
2028 static void execute_commands(struct command *commands,
2029 const char *unpacker_error,
2030 struct shallow_info *si,
2031 const struct string_list *push_options)
2032 {
2033 struct check_connected_options opt = CHECK_CONNECTED_INIT;
2034 struct command *cmd;
2035 struct iterate_data data;
2036 struct async muxer;
2037 int err_fd = 0;
2038 int run_proc_receive = 0;
2039
2040 if (unpacker_error) {
2041 for (cmd = commands; cmd; cmd = cmd->next)
2042 cmd->error_string = "unpacker error";
2043 return;
2044 }
2045
2046 if (!skip_connectivity_check) {
2047 if (use_sideband) {
2048 memset(&muxer, 0, sizeof(muxer));
2049 muxer.proc = copy_to_sideband;
2050 muxer.in = -1;
2051 if (!start_async(&muxer))
2052 err_fd = muxer.in;
2053 /* ...else, continue without relaying sideband */
2054 }
2055
2056 data.cmds = commands;
2057 data.si = si;
2058 opt.err_fd = err_fd;
2059 opt.progress = err_fd && !quiet;
2060 opt.env = tmp_objdir_env(tmp_objdir);
2061 opt.exclude_hidden_refs_section = "receive";
2062
2063 if (check_connected(iterate_receive_command_list, &data, &opt))
2064 set_connectivity_errors(commands, si);
2065
2066 if (use_sideband)
2067 finish_async(&muxer);
2068 }
2069
2070 reject_updates_to_hidden(commands);
2071
2072 /*
2073 * Try to find commands that have special prefix in their reference names,
2074 * and mark them to run an external "proc-receive" hook later.
2075 */
2076 if (proc_receive_ref) {
2077 for (cmd = commands; cmd; cmd = cmd->next) {
2078 if (!should_process_cmd(cmd))
2079 continue;
2080
2081 if (proc_receive_ref_matches(cmd)) {
2082 cmd->run_proc_receive = RUN_PROC_RECEIVE_SCHEDULED;
2083 run_proc_receive = 1;
2084 }
2085 }
2086 }
2087
2088 if (run_receive_hook(commands, "pre-receive", 0, push_options)) {
2089 for (cmd = commands; cmd; cmd = cmd->next) {
2090 if (!cmd->error_string)
2091 cmd->error_string = "pre-receive hook declined";
2092 }
2093 return;
2094 }
2095
2096 /*
2097 * If there is no command ready to run, should return directly to destroy
2098 * temporary data in the quarantine area.
2099 */
2100 for (cmd = commands; cmd && cmd->error_string; cmd = cmd->next)
2101 ; /* nothing */
2102 if (!cmd)
2103 return;
2104
2105 /*
2106 * Now we'll start writing out refs, which means the objects need
2107 * to be in their final positions so that other processes can see them.
2108 */
2109 if (tmp_objdir_migrate(tmp_objdir) < 0) {
2110 for (cmd = commands; cmd; cmd = cmd->next) {
2111 if (!cmd->error_string)
2112 cmd->error_string = "unable to migrate objects to permanent storage";
2113 }
2114 return;
2115 }
2116 tmp_objdir = NULL;
2117
2118 check_aliased_updates(commands);
2119
2120 free(head_name_to_free);
2121 head_name = head_name_to_free = refs_resolve_refdup(get_main_ref_store(the_repository),
2122 "HEAD", 0, NULL,
2123 NULL);
2124
2125 if (run_proc_receive &&
2126 run_proc_receive_hook(commands, push_options))
2127 for (cmd = commands; cmd; cmd = cmd->next)
2128 if (!cmd->error_string &&
2129 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED) &&
2130 (cmd->run_proc_receive || use_atomic))
2131 cmd->error_string = "fail to run proc-receive hook";
2132
2133 if (use_atomic)
2134 execute_commands_atomic(commands, si);
2135 else
2136 execute_commands_non_atomic(commands, si);
2137
2138 if (shallow_update)
2139 BUG_if_skipped_connectivity_check(commands, si);
2140 }
2141
2142 static struct command **queue_command(struct command **tail,
2143 const char *line,
2144 int linelen)
2145 {
2146 struct object_id old_oid, new_oid;
2147 struct command *cmd;
2148 const char *refname;
2149 int reflen;
2150 const char *p;
2151
2152 if (parse_oid_hex(line, &old_oid, &p) ||
2153 *p++ != ' ' ||
2154 parse_oid_hex(p, &new_oid, &p) ||
2155 *p++ != ' ')
2156 die("protocol error: expected old/new/ref, got '%s'", line);
2157
2158 refname = p;
2159 reflen = linelen - (p - line);
2160 FLEX_ALLOC_MEM(cmd, ref_name, refname, reflen);
2161 oidcpy(&cmd->old_oid, &old_oid);
2162 oidcpy(&cmd->new_oid, &new_oid);
2163 *tail = cmd;
2164 return &cmd->next;
2165 }
2166
2167 static void free_commands(struct command *commands)
2168 {
2169 while (commands) {
2170 struct command *next = commands->next;
2171
2172 ref_push_report_free(commands->report);
2173 free(commands->error_string_owned);
2174 free(commands);
2175 commands = next;
2176 }
2177 }
2178
2179 static void queue_commands_from_cert(struct command **tail,
2180 struct strbuf *push_cert)
2181 {
2182 const char *boc, *eoc;
2183
2184 if (*tail)
2185 die("protocol error: got both push certificate and unsigned commands");
2186
2187 boc = strstr(push_cert->buf, "\n\n");
2188 if (!boc)
2189 die("malformed push certificate %.*s", 100, push_cert->buf);
2190 else
2191 boc += 2;
2192 eoc = push_cert->buf + parse_signed_buffer(push_cert->buf, push_cert->len);
2193
2194 while (boc < eoc) {
2195 const char *eol = memchr(boc, '\n', eoc - boc);
2196 tail = queue_command(tail, boc, eol ? eol - boc : eoc - boc);
2197 boc = eol ? eol + 1 : eoc;
2198 }
2199 }
2200
2201 static struct command *read_head_info(struct packet_reader *reader,
2202 struct oid_array *shallow)
2203 {
2204 struct command *commands = NULL;
2205 struct command **p = &commands;
2206 for (;;) {
2207 int linelen;
2208
2209 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2210 break;
2211
2212 if (reader->pktlen > 8 && starts_with(reader->line, "shallow ")) {
2213 struct object_id oid;
2214 if (get_oid_hex(reader->line + 8, &oid))
2215 die("protocol error: expected shallow sha, got '%s'",
2216 reader->line + 8);
2217 oid_array_append(shallow, &oid);
2218 continue;
2219 }
2220
2221 linelen = strlen(reader->line);
2222 if (linelen < reader->pktlen) {
2223 const char *feature_list = reader->line + linelen + 1;
2224 const char *hash = NULL;
2225 const char *client_sid;
2226 size_t len = 0;
2227 if (parse_feature_request(feature_list, "report-status"))
2228 report_status = 1;
2229 if (parse_feature_request(feature_list, "report-status-v2"))
2230 report_status_v2 = 1;
2231 if (parse_feature_request(feature_list, "side-band-64k"))
2232 use_sideband = LARGE_PACKET_MAX;
2233 if (parse_feature_request(feature_list, "quiet"))
2234 quiet = 1;
2235 if (advertise_atomic_push
2236 && parse_feature_request(feature_list, "atomic"))
2237 use_atomic = 1;
2238 if (advertise_push_options
2239 && parse_feature_request(feature_list, "push-options"))
2240 use_push_options = 1;
2241 hash = parse_feature_value(feature_list, "object-format", &len, NULL);
2242 if (!hash) {
2243 hash = hash_algos[GIT_HASH_SHA1_LEGACY].name;
2244 len = strlen(hash);
2245 }
2246 if (xstrncmpz(the_hash_algo->name, hash, len))
2247 die("error: unsupported object format '%s'", hash);
2248 client_sid = parse_feature_value(feature_list, "session-id", &len, NULL);
2249 if (client_sid) {
2250 char *sid = xstrndup(client_sid, len);
2251 trace2_data_string("transfer", NULL, "client-sid", client_sid);
2252 free(sid);
2253 }
2254 }
2255
2256 if (!strcmp(reader->line, "push-cert")) {
2257 int true_flush = 0;
2258 int saved_options = reader->options;
2259 reader->options &= ~PACKET_READ_CHOMP_NEWLINE;
2260
2261 for (;;) {
2262 packet_reader_read(reader);
2263 if (reader->status == PACKET_READ_FLUSH) {
2264 true_flush = 1;
2265 break;
2266 }
2267 if (reader->status != PACKET_READ_NORMAL) {
2268 die("protocol error: got an unexpected packet");
2269 }
2270 if (!strcmp(reader->line, "push-cert-end\n"))
2271 break; /* end of cert */
2272 strbuf_addstr(&push_cert, reader->line);
2273 }
2274 reader->options = saved_options;
2275
2276 if (true_flush)
2277 break;
2278 continue;
2279 }
2280
2281 p = queue_command(p, reader->line, linelen);
2282 }
2283
2284 if (push_cert.len)
2285 queue_commands_from_cert(p, &push_cert);
2286
2287 return commands;
2288 }
2289
2290 static void read_push_options(struct packet_reader *reader,
2291 struct string_list *options)
2292 {
2293 while (1) {
2294 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2295 break;
2296
2297 string_list_append(options, reader->line);
2298 }
2299 }
2300
2301 static const char *parse_pack_header(struct pack_header *hdr)
2302 {
2303 switch (read_pack_header(0, hdr)) {
2304 case PH_ERROR_EOF:
2305 return "eof before pack header was fully read";
2306
2307 case PH_ERROR_PACK_SIGNATURE:
2308 return "protocol error (pack signature mismatch detected)";
2309
2310 case PH_ERROR_PROTOCOL:
2311 return "protocol error (pack version unsupported)";
2312
2313 default:
2314 return "unknown error in parse_pack_header";
2315
2316 case 0:
2317 return NULL;
2318 }
2319 }
2320
2321 static struct tempfile *pack_lockfile;
2322
2323 static void push_header_arg(struct strvec *args, struct pack_header *hdr)
2324 {
2325 strvec_pushf(args, "--pack_header=%"PRIu32",%"PRIu32,
2326 ntohl(hdr->hdr_version), ntohl(hdr->hdr_entries));
2327 }
2328
2329 static const char *unpack(int err_fd, struct shallow_info *si)
2330 {
2331 struct pack_header hdr;
2332 const char *hdr_err;
2333 int status;
2334 struct child_process child = CHILD_PROCESS_INIT;
2335 int fsck_objects = (receive_fsck_objects >= 0
2336 ? receive_fsck_objects
2337 : transfer_fsck_objects >= 0
2338 ? transfer_fsck_objects
2339 : 0);
2340
2341 hdr_err = parse_pack_header(&hdr);
2342 if (hdr_err) {
2343 if (err_fd > 0)
2344 close(err_fd);
2345 return hdr_err;
2346 }
2347
2348 if (si->nr_ours || si->nr_theirs) {
2349 alt_shallow_file = setup_temporary_shallow(si->shallow);
2350 strvec_push(&child.args, "--shallow-file");
2351 strvec_push(&child.args, alt_shallow_file);
2352 }
2353
2354 tmp_objdir = tmp_objdir_create(the_repository, "incoming");
2355 if (!tmp_objdir) {
2356 if (err_fd > 0)
2357 close(err_fd);
2358 return "unable to create temporary object directory";
2359 }
2360 strvec_pushv(&child.env, tmp_objdir_env(tmp_objdir));
2361
2362 /*
2363 * Normally we just pass the tmp_objdir environment to the child
2364 * processes that do the heavy lifting, but we may need to see these
2365 * objects ourselves to set up shallow information.
2366 */
2367 tmp_objdir_add_as_alternate(tmp_objdir);
2368
2369 if (ntohl(hdr.hdr_entries) < unpack_limit) {
2370 strvec_push(&child.args, "unpack-objects");
2371 push_header_arg(&child.args, &hdr);
2372 if (quiet)
2373 strvec_push(&child.args, "-q");
2374 if (fsck_objects)
2375 strvec_pushf(&child.args, "--strict%s",
2376 fsck_msg_types.buf);
2377 if (max_input_size)
2378 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2379 (uintmax_t)max_input_size);
2380 child.no_stdout = 1;
2381 child.err = err_fd;
2382 child.git_cmd = 1;
2383 status = run_command(&child);
2384 if (status)
2385 return "unpack-objects abnormal exit";
2386 } else {
2387 char hostname[HOST_NAME_MAX + 1];
2388 char *lockfile;
2389
2390 strvec_pushl(&child.args, "index-pack", "--stdin", NULL);
2391 push_header_arg(&child.args, &hdr);
2392
2393 if (xgethostname(hostname, sizeof(hostname)))
2394 xsnprintf(hostname, sizeof(hostname), "localhost");
2395 strvec_pushf(&child.args,
2396 "--keep=receive-pack %"PRIuMAX" on %s",
2397 (uintmax_t)getpid(),
2398 hostname);
2399
2400 if (!quiet && err_fd)
2401 strvec_push(&child.args, "--show-resolving-progress");
2402 if (use_sideband)
2403 strvec_push(&child.args, "--report-end-of-input");
2404 if (fsck_objects)
2405 strvec_pushf(&child.args, "--strict%s",
2406 fsck_msg_types.buf);
2407 if (!reject_thin)
2408 strvec_push(&child.args, "--fix-thin");
2409 if (max_input_size)
2410 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2411 (uintmax_t)max_input_size);
2412 child.out = -1;
2413 child.err = err_fd;
2414 child.git_cmd = 1;
2415 status = start_command(&child);
2416 if (status)
2417 return "index-pack fork failed";
2418
2419 lockfile = index_pack_lockfile(the_repository, child.out, NULL);
2420 if (lockfile) {
2421 pack_lockfile = register_tempfile(lockfile);
2422 free(lockfile);
2423 }
2424 close(child.out);
2425
2426 status = finish_command(&child);
2427 if (status)
2428 return "index-pack abnormal exit";
2429 odb_reprepare(the_repository->objects);
2430 }
2431 return NULL;
2432 }
2433
2434 static const char *unpack_with_sideband(struct shallow_info *si)
2435 {
2436 struct async muxer;
2437 const char *ret;
2438
2439 if (!use_sideband)
2440 return unpack(0, si);
2441
2442 use_keepalive = KEEPALIVE_AFTER_NUL;
2443 memset(&muxer, 0, sizeof(muxer));
2444 muxer.proc = copy_to_sideband;
2445 muxer.in = -1;
2446 if (start_async(&muxer))
2447 return NULL;
2448
2449 ret = unpack(muxer.in, si);
2450
2451 finish_async(&muxer);
2452 return ret;
2453 }
2454
2455 static void prepare_shallow_update(struct shallow_info *si)
2456 {
2457 int i, j, k, bitmap_size = DIV_ROUND_UP(si->ref->nr, 32);
2458
2459 ALLOC_ARRAY(si->used_shallow, si->shallow->nr);
2460 assign_shallow_commits_to_refs(si, si->used_shallow, NULL);
2461
2462 CALLOC_ARRAY(si->need_reachability_test, si->shallow->nr);
2463 CALLOC_ARRAY(si->reachable, si->shallow->nr);
2464 CALLOC_ARRAY(si->shallow_ref, si->ref->nr);
2465
2466 for (i = 0; i < si->nr_ours; i++)
2467 si->need_reachability_test[si->ours[i]] = 1;
2468
2469 for (i = 0; i < si->shallow->nr; i++) {
2470 if (!si->used_shallow[i])
2471 continue;
2472 for (j = 0; j < bitmap_size; j++) {
2473 if (!si->used_shallow[i][j])
2474 continue;
2475 si->need_reachability_test[i]++;
2476 for (k = 0; k < 32; k++)
2477 if (si->used_shallow[i][j] & (1U << k))
2478 si->shallow_ref[j * 32 + k]++;
2479 }
2480
2481 /*
2482 * true for those associated with some refs and belong
2483 * in "ours" list aka "step 7 not done yet"
2484 */
2485 si->need_reachability_test[i] =
2486 si->need_reachability_test[i] > 1;
2487 }
2488
2489 /*
2490 * keep hooks happy by forcing a temporary shallow file via
2491 * env variable because we can't add --shallow-file to every
2492 * command. check_connected() will be done with
2493 * true .git/shallow though.
2494 */
2495 setenv(GIT_SHALLOW_FILE_ENVIRONMENT, alt_shallow_file, 1);
2496 }
2497
2498 static void update_shallow_info(struct command *commands,
2499 struct shallow_info *si,
2500 struct oid_array *ref)
2501 {
2502 struct command *cmd;
2503 int *ref_status;
2504 remove_nonexistent_theirs_shallow(si);
2505 if (!si->nr_ours && !si->nr_theirs) {
2506 shallow_update = 0;
2507 return;
2508 }
2509
2510 for (cmd = commands; cmd; cmd = cmd->next) {
2511 if (is_null_oid(&cmd->new_oid))
2512 continue;
2513 oid_array_append(ref, &cmd->new_oid);
2514 cmd->index = ref->nr - 1;
2515 }
2516 si->ref = ref;
2517
2518 if (shallow_update) {
2519 prepare_shallow_update(si);
2520 return;
2521 }
2522
2523 ALLOC_ARRAY(ref_status, ref->nr);
2524 assign_shallow_commits_to_refs(si, NULL, ref_status);
2525 for (cmd = commands; cmd; cmd = cmd->next) {
2526 if (is_null_oid(&cmd->new_oid))
2527 continue;
2528 if (ref_status[cmd->index]) {
2529 cmd->error_string = "shallow update not allowed";
2530 cmd->skip_update = 1;
2531 }
2532 }
2533 free(ref_status);
2534 }
2535
2536 static void report(struct command *commands, const char *unpack_status)
2537 {
2538 struct command *cmd;
2539 struct strbuf buf = STRBUF_INIT;
2540
2541 packet_buf_write(&buf, "unpack %s\n",
2542 unpack_status ? unpack_status : "ok");
2543 for (cmd = commands; cmd; cmd = cmd->next) {
2544 if (!cmd->error_string)
2545 packet_buf_write(&buf, "ok %s\n",
2546 cmd->ref_name);
2547 else
2548 packet_buf_write(&buf, "ng %s %s\n",
2549 cmd->ref_name, cmd->error_string);
2550 }
2551 packet_buf_flush(&buf);
2552
2553 if (use_sideband)
2554 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2555 else
2556 write_or_die(1, buf.buf, buf.len);
2557 strbuf_release(&buf);
2558 }
2559
2560 static void report_v2(struct command *commands, const char *unpack_status)
2561 {
2562 struct command *cmd;
2563 struct strbuf buf = STRBUF_INIT;
2564 struct ref_push_report *report;
2565
2566 packet_buf_write(&buf, "unpack %s\n",
2567 unpack_status ? unpack_status : "ok");
2568 for (cmd = commands; cmd; cmd = cmd->next) {
2569 int count = 0;
2570
2571 if (cmd->error_string) {
2572 packet_buf_write(&buf, "ng %s %s\n",
2573 cmd->ref_name,
2574 cmd->error_string);
2575 continue;
2576 }
2577 packet_buf_write(&buf, "ok %s\n",
2578 cmd->ref_name);
2579 for (report = cmd->report; report; report = report->next) {
2580 if (count++ > 0)
2581 packet_buf_write(&buf, "ok %s\n",
2582 cmd->ref_name);
2583 if (report->ref_name)
2584 packet_buf_write(&buf, "option refname %s\n",
2585 report->ref_name);
2586 if (report->old_oid)
2587 packet_buf_write(&buf, "option old-oid %s\n",
2588 oid_to_hex(report->old_oid));
2589 if (report->new_oid)
2590 packet_buf_write(&buf, "option new-oid %s\n",
2591 oid_to_hex(report->new_oid));
2592 if (report->forced_update)
2593 packet_buf_write(&buf, "option forced-update\n");
2594 }
2595 }
2596 packet_buf_flush(&buf);
2597
2598 if (use_sideband)
2599 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
2600 else
2601 write_or_die(1, buf.buf, buf.len);
2602 strbuf_release(&buf);
2603 }
2604
2605 static int delete_only(struct command *commands)
2606 {
2607 struct command *cmd;
2608 for (cmd = commands; cmd; cmd = cmd->next) {
2609 if (!is_null_oid(&cmd->new_oid))
2610 return 0;
2611 }
2612 return 1;
2613 }
2614
2615 int cmd_receive_pack(int argc,
2616 const char **argv,
2617 const char *prefix,
2618 struct repository *repo UNUSED)
2619 {
2620 int advertise_refs = 0;
2621 struct command *commands;
2622 struct oid_array shallow = OID_ARRAY_INIT;
2623 struct oid_array ref = OID_ARRAY_INIT;
2624 struct shallow_info si;
2625 struct packet_reader reader;
2626
2627 struct option options[] = {
2628 OPT__QUIET(&quiet, N_("quiet")),
2629 OPT_HIDDEN_BOOL(0, "skip-connectivity-check", &skip_connectivity_check, NULL),
2630 OPT_HIDDEN_BOOL(0, "stateless-rpc", &stateless_rpc, NULL),
2631 OPT_HIDDEN_BOOL(0, "http-backend-info-refs", &advertise_refs, NULL),
2632 OPT_ALIAS(0, "advertise-refs", "http-backend-info-refs"),
2633 OPT_HIDDEN_BOOL(0, "reject-thin-pack-for-testing", &reject_thin, NULL),
2634 OPT_END()
2635 };
2636
2637 packet_trace_identity("receive-pack");
2638
2639 argc = parse_options(argc, argv, prefix, options, receive_pack_usage, 0);
2640
2641 if (argc > 1)
2642 usage_msg_opt(_("too many arguments"), receive_pack_usage, options);
2643 if (argc == 0)
2644 usage_msg_opt(_("you must specify a directory"), receive_pack_usage, options);
2645
2646 service_dir = argv[0];
2647
2648 setup_path();
2649
2650 if (!enter_repo(the_repository, service_dir, 0))
2651 die("'%s' does not appear to be a git repository", service_dir);
2652
2653 repo_config(the_repository, receive_pack_config, NULL);
2654 if (cert_nonce_seed)
2655 push_cert_nonce = prepare_push_cert_nonce(service_dir, time(NULL));
2656
2657 if (0 <= receive_unpack_limit)
2658 unpack_limit = receive_unpack_limit;
2659 else if (0 <= transfer_unpack_limit)
2660 unpack_limit = transfer_unpack_limit;
2661
2662 switch (determine_protocol_version_server()) {
2663 case protocol_v2:
2664 /*
2665 * push support for protocol v2 has not been implemented yet,
2666 * so ignore the request to use v2 and fallback to using v0.
2667 */
2668 break;
2669 case protocol_v1:
2670 /*
2671 * v1 is just the original protocol with a version string,
2672 * so just fall through after writing the version string.
2673 */
2674 if (advertise_refs || !stateless_rpc)
2675 packet_write_fmt(1, "version 1\n");
2676
2677 /* fallthrough */
2678 case protocol_v0:
2679 break;
2680 case protocol_unknown_version:
2681 BUG("unknown protocol version");
2682 }
2683
2684 if (advertise_refs || !stateless_rpc) {
2685 write_head_info();
2686 }
2687 if (advertise_refs)
2688 return 0;
2689
2690 packet_reader_init(&reader, 0, NULL, 0,
2691 PACKET_READ_CHOMP_NEWLINE |
2692 PACKET_READ_DIE_ON_ERR_PACKET);
2693
2694 if ((commands = read_head_info(&reader, &shallow))) {
2695 const char *unpack_status = NULL;
2696 struct string_list push_options = STRING_LIST_INIT_DUP;
2697
2698 if (use_push_options)
2699 read_push_options(&reader, &push_options);
2700 if (!check_cert_push_options(&push_options)) {
2701 struct command *cmd;
2702 for (cmd = commands; cmd; cmd = cmd->next)
2703 cmd->error_string = "inconsistent push options";
2704 }
2705
2706 prepare_shallow_info(&si, &shallow);
2707 if (!si.nr_ours && !si.nr_theirs)
2708 shallow_update = 0;
2709 if (!delete_only(commands)) {
2710 unpack_status = unpack_with_sideband(&si);
2711 update_shallow_info(commands, &si, &ref);
2712 }
2713 use_keepalive = KEEPALIVE_ALWAYS;
2714 execute_commands(commands, unpack_status, &si,
2715 &push_options);
2716 delete_tempfile(&pack_lockfile);
2717 sigchain_push(SIGPIPE, SIG_IGN);
2718 if (report_status_v2)
2719 report_v2(commands, unpack_status);
2720 else if (report_status)
2721 report(commands, unpack_status);
2722 sigchain_pop(SIGPIPE);
2723 run_receive_hook(commands, "post-receive", 1,
2724 &push_options);
2725 run_update_post_hook(commands);
2726 free_commands(commands);
2727 string_list_clear(&push_options, 0);
2728 if (auto_gc) {
2729 struct child_process proc = CHILD_PROCESS_INIT;
2730
2731 if (prepare_auto_maintenance(the_repository, 1, &proc)) {
2732 proc.no_stdin = 1;
2733 proc.stdout_to_stderr = 1;
2734 proc.err = use_sideband ? -1 : 0;
2735
2736 if (!start_command(&proc)) {
2737 if (use_sideband)
2738 copy_to_sideband(proc.err, -1, NULL);
2739 finish_command(&proc);
2740 }
2741 }
2742 }
2743 if (auto_update_server_info)
2744 update_server_info(the_repository, 0);
2745 clear_shallow_info(&si);
2746 }
2747 if (use_sideband)
2748 packet_flush(1);
2749 oid_array_clear(&shallow);
2750 oid_array_clear(&ref);
2751 strvec_clear(&hidden_refs);
2752 free((void *)push_cert_nonce);
2753 return 0;
2754 }