at commit a0189536

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