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 "trace.h"
41 #include "trace2.h"
42 #include "version.h"
43 #include "worktree.h"
44
45 static const char * const receive_pack_usage[] = {
46 N_("git receive-pack <git-dir>"),
47 NULL
48 };
49
50 enum deny_action {
51 DENY_UNCONFIGURED,
52 DENY_IGNORE,
53 DENY_WARN,
54 DENY_REFUSE,
55 DENY_UPDATE_INSTEAD
56 };
57
58 static int deny_deletes;
59 static int deny_non_fast_forwards;
60 static enum deny_action deny_current_branch = DENY_UNCONFIGURED;
61 static enum deny_action deny_delete_current = DENY_UNCONFIGURED;
62 static int receive_fsck_objects = -1;
63 static int transfer_fsck_objects = -1;
64 static struct strbuf fsck_msg_types = STRBUF_INIT;
65 static int receive_unpack_limit = -1;
66 static int transfer_unpack_limit = -1;
67 static int advertise_atomic_push = 1;
68 static int advertise_no_ref_delta;
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 proc_receive_ref {
116 unsigned int want_add:1,
117 want_delete:1,
118 want_modify:1,
119 negative_ref:1;
120 char *ref_prefix;
121 struct proc_receive_ref *next;
122 } *proc_receive_ref;
123
124 static void proc_receive_ref_append(const char *prefix);
125
126 static enum deny_action parse_deny_action(const char *var, const char *value)
127 {
128 if (value) {
129 if (!strcasecmp(value, "ignore"))
130 return DENY_IGNORE;
131 if (!strcasecmp(value, "warn"))
132 return DENY_WARN;
133 if (!strcasecmp(value, "refuse"))
134 return DENY_REFUSE;
135 if (!strcasecmp(value, "updateinstead"))
136 return DENY_UPDATE_INSTEAD;
137 }
138 if (git_config_bool(var, value))
139 return DENY_REFUSE;
140 return DENY_IGNORE;
141 }
142
143 static int receive_pack_config(const char *var, const char *value,
144 const struct config_context *ctx, void *cb)
145 {
146 const char *msg_id;
147 int status = parse_hide_refs_config(var, value, "receive", &hidden_refs);
148
149 if (status)
150 return status;
151
152 if (strcmp(var, "receive.denydeletes") == 0) {
153 deny_deletes = git_config_bool(var, value);
154 return 0;
155 }
156
157 if (strcmp(var, "receive.denynonfastforwards") == 0) {
158 deny_non_fast_forwards = git_config_bool(var, value);
159 return 0;
160 }
161
162 if (strcmp(var, "receive.unpacklimit") == 0) {
163 receive_unpack_limit = git_config_int(var, value, ctx->kvi);
164 return 0;
165 }
166
167 if (strcmp(var, "transfer.unpacklimit") == 0) {
168 transfer_unpack_limit = git_config_int(var, value, ctx->kvi);
169 return 0;
170 }
171
172 if (strcmp(var, "receive.fsck.skiplist") == 0) {
173 char *path;
174
175 if (git_config_pathname(&path, var, value))
176 return -1;
177 if (path)
178 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
179 fsck_msg_types.len ? ',' : '=', path);
180 free(path);
181 return 0;
182 }
183
184 if (skip_prefix(var, "receive.fsck.", &msg_id)) {
185 if (!value)
186 return config_error_nonbool(var);
187 if (is_valid_msg_type(msg_id, value))
188 strbuf_addf(&fsck_msg_types, "%c%s=%s",
189 fsck_msg_types.len ? ',' : '=', msg_id, value);
190 else
191 warning("skipping unknown msg id '%s'", msg_id);
192 return 0;
193 }
194
195 if (strcmp(var, "receive.fsckobjects") == 0) {
196 receive_fsck_objects = git_config_bool(var, value);
197 return 0;
198 }
199
200 if (strcmp(var, "transfer.fsckobjects") == 0) {
201 transfer_fsck_objects = git_config_bool(var, value);
202 return 0;
203 }
204
205 if (!strcmp(var, "receive.denycurrentbranch")) {
206 deny_current_branch = parse_deny_action(var, value);
207 return 0;
208 }
209
210 if (strcmp(var, "receive.denydeletecurrent") == 0) {
211 deny_delete_current = parse_deny_action(var, value);
212 return 0;
213 }
214
215 if (strcmp(var, "repack.usedeltabaseoffset") == 0) {
216 prefer_ofs_delta = git_config_bool(var, value);
217 return 0;
218 }
219
220 if (strcmp(var, "receive.updateserverinfo") == 0) {
221 auto_update_server_info = git_config_bool(var, value);
222 return 0;
223 }
224
225 if (strcmp(var, "receive.autogc") == 0) {
226 auto_gc = git_config_bool(var, value);
227 return 0;
228 }
229
230 if (strcmp(var, "receive.shallowupdate") == 0) {
231 shallow_update = git_config_bool(var, value);
232 return 0;
233 }
234
235 if (strcmp(var, "receive.certnonceseed") == 0)
236 return git_config_string(&cert_nonce_seed, var, value);
237
238 if (strcmp(var, "receive.certnonceslop") == 0) {
239 nonce_stamp_slop_limit = git_config_ulong(var, value, ctx->kvi);
240 return 0;
241 }
242
243 if (strcmp(var, "receive.advertiseatomic") == 0) {
244 advertise_atomic_push = git_config_bool(var, value);
245 return 0;
246 }
247
248 if (strcmp(var, "receive.advertisepushoptions") == 0) {
249 advertise_push_options = git_config_bool(var, value);
250 return 0;
251 }
252
253 if (strcmp(var, "receive.keepalive") == 0) {
254 keepalive_in_sec = git_config_int(var, value, ctx->kvi);
255 return 0;
256 }
257
258 if (strcmp(var, "receive.maxinputsize") == 0) {
259 max_input_size = git_config_int64(var, value, ctx->kvi);
260 return 0;
261 }
262
263 if (strcmp(var, "receive.procreceiverefs") == 0) {
264 if (!value)
265 return config_error_nonbool(var);
266 proc_receive_ref_append(value);
267 return 0;
268 }
269
270 if (strcmp(var, "transfer.advertisesid") == 0) {
271 advertise_sid = git_config_bool(var, value);
272 return 0;
273 }
274
275 return git_default_config(var, value, ctx, cb);
276 }
277
278 static void show_ref(const char *path, const struct object_id *oid)
279 {
280 if (sent_capabilities) {
281 packet_write_fmt(1, "%s %s\n", oid_to_hex(oid), path);
282 } else {
283 struct strbuf cap = STRBUF_INIT;
284
285 strbuf_addstr(&cap,
286 "report-status report-status-v2 delete-refs side-band-64k quiet");
287 if (advertise_atomic_push)
288 strbuf_addstr(&cap, " atomic");
289 if (prefer_ofs_delta)
290 strbuf_addstr(&cap, " ofs-delta");
291 if (advertise_no_ref_delta)
292 strbuf_addstr(&cap, " no-ref-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 git_hash_init(&ctx, the_hash_algo);
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 git_hash_init(&ctx, the_hash_algo);
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 git_hash_init(&ctx, the_hash_algo);
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 struct odb_transaction *transaction,
930 const struct string_list *push_options)
931 {
932 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
933 struct command *iter = commands;
934 struct receive_hook_feed_state feed_init_state = {
935 .cmd = commands,
936 .skip_broken = skip_broken,
937 .buf = STRBUF_INIT,
938 };
939 struct async sideband_async;
940 int sideband_async_started = 0;
941 int saved_stderr = -1;
942 int ret;
943
944 if (!hook_exists(the_repository, hook_name))
945 return 0;
946
947 /* if there are no valid commands, don't invoke the hook at all. */
948 while (iter && skip_broken && (iter->error_string || iter->did_not_exist))
949 iter = iter->next;
950 if (!iter)
951 return 0;
952
953 if (push_options) {
954 for (int i = 0; i < push_options->nr; i++)
955 strvec_pushf(&opt.env, "GIT_PUSH_OPTION_%d=%s", i,
956 push_options->items[i].string);
957 strvec_pushf(&opt.env, "GIT_PUSH_OPTION_COUNT=%"PRIuMAX"",
958 (uintmax_t)push_options->nr);
959 } else {
960 strvec_push(&opt.env, "GIT_PUSH_OPTION_COUNT");
961 }
962
963 if (transaction)
964 odb_transaction_env(transaction, &opt.env);
965
966 prepare_push_cert_sha1(&opt);
967
968 prepare_sideband_async(&sideband_async, &saved_stderr, &sideband_async_started);
969
970 /* set up stdin callback */
971 opt.feed_pipe_ctx = &feed_init_state;
972 opt.feed_pipe = feed_receive_hook_cb;
973 opt.feed_pipe_cb_data_alloc = receive_hook_feed_state_alloc;
974 opt.feed_pipe_cb_data_free = receive_hook_feed_state_free;
975
976 ret = run_hooks_opt(the_repository, hook_name, &opt);
977
978 finish_sideband_async(&sideband_async, saved_stderr, sideband_async_started);
979
980 return ret;
981 }
982
983 static int run_update_hook(struct command *cmd)
984 {
985 static const char hook_name[] = "update";
986 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
987 struct async sideband_async;
988 int sideband_async_started = 0;
989 int saved_stderr = -1;
990 int code;
991
992 if (!hook_exists(the_repository, hook_name))
993 return 0;
994
995 strvec_pushl(&opt.args,
996 cmd->ref_name,
997 oid_to_hex(&cmd->old_oid),
998 oid_to_hex(&cmd->new_oid),
999 NULL);
1000
1001 prepare_sideband_async(&sideband_async, &saved_stderr, &sideband_async_started);
1002
1003 code = run_hooks_opt(the_repository, hook_name, &opt);
1004
1005 finish_sideband_async(&sideband_async, saved_stderr, sideband_async_started);
1006
1007 return code;
1008 }
1009
1010 static struct command *find_command_by_refname(struct command *list,
1011 const char *refname)
1012 {
1013 for (; list; list = list->next)
1014 if (!strcmp(list->ref_name, refname))
1015 return list;
1016 return NULL;
1017 }
1018
1019 static int read_proc_receive_report(struct packet_reader *reader,
1020 struct command *commands,
1021 struct strbuf *errmsg)
1022 {
1023 struct command *cmd;
1024 struct command *hint = NULL;
1025 struct ref_push_report *report = NULL;
1026 int new_report = 0;
1027 int code = 0;
1028 int once = 0;
1029 int response = 0;
1030
1031 for (;;) {
1032 struct object_id old_oid, new_oid;
1033 char *head;
1034 char *refname;
1035 char *p;
1036 enum packet_read_status status;
1037
1038 status = packet_reader_read(reader);
1039 if (status != PACKET_READ_NORMAL) {
1040 /* Check whether proc-receive exited abnormally */
1041 if (status == PACKET_READ_EOF && !response) {
1042 strbuf_addstr(errmsg, "proc-receive exited abnormally");
1043 return -1;
1044 }
1045 break;
1046 }
1047 response++;
1048
1049 head = reader->line;
1050 p = strchr(head, ' ');
1051 if (!p) {
1052 strbuf_addf(errmsg, "proc-receive reported incomplete status line: '%s'\n", head);
1053 code = -1;
1054 continue;
1055 }
1056 *p++ = '\0';
1057 if (!strcmp(head, "option")) {
1058 char *key;
1059 const char *val;
1060
1061 if (!hint || !(report || new_report)) {
1062 if (!once++)
1063 strbuf_addstr(errmsg, "proc-receive reported 'option' without a matching 'ok/ng' directive\n");
1064 code = -1;
1065 continue;
1066 }
1067 if (new_report) {
1068 if (!hint->report) {
1069 CALLOC_ARRAY(hint->report, 1);
1070 report = hint->report;
1071 } else {
1072 report = hint->report;
1073 while (report->next)
1074 report = report->next;
1075 report->next = xcalloc(1, sizeof(struct ref_push_report));
1076 report = report->next;
1077 }
1078 new_report = 0;
1079 }
1080 key = p;
1081 p = strchr(key, ' ');
1082 if (p)
1083 *p++ = '\0';
1084 val = p;
1085 if (!strcmp(key, "refname"))
1086 report->ref_name = xstrdup_or_null(val);
1087 else if (!strcmp(key, "old-oid") && val &&
1088 !parse_oid_hex(val, &old_oid, &val))
1089 report->old_oid = oiddup(&old_oid);
1090 else if (!strcmp(key, "new-oid") && val &&
1091 !parse_oid_hex(val, &new_oid, &val))
1092 report->new_oid = oiddup(&new_oid);
1093 else if (!strcmp(key, "forced-update"))
1094 report->forced_update = 1;
1095 else if (!strcmp(key, "fall-through"))
1096 /* Fall through, let 'receive-pack' to execute it. */
1097 hint->run_proc_receive = 0;
1098 continue;
1099 }
1100
1101 report = NULL;
1102 new_report = 0;
1103 refname = p;
1104 p = strchr(refname, ' ');
1105 if (p)
1106 *p++ = '\0';
1107 if (strcmp(head, "ok") && strcmp(head, "ng")) {
1108 strbuf_addf(errmsg, "proc-receive reported bad status '%s' on ref '%s'\n",
1109 head, refname);
1110 code = -1;
1111 continue;
1112 }
1113
1114 /* first try searching at our hint, falling back to all refs */
1115 if (hint)
1116 hint = find_command_by_refname(hint, refname);
1117 if (!hint)
1118 hint = find_command_by_refname(commands, refname);
1119 if (!hint) {
1120 strbuf_addf(errmsg, "proc-receive reported status on unknown ref: %s\n",
1121 refname);
1122 code = -1;
1123 continue;
1124 }
1125 if (!hint->run_proc_receive) {
1126 strbuf_addf(errmsg, "proc-receive reported status on unexpected ref: %s\n",
1127 refname);
1128 code = -1;
1129 continue;
1130 }
1131 hint->run_proc_receive |= RUN_PROC_RECEIVE_RETURNED;
1132 if (!strcmp(head, "ng")) {
1133 if (p)
1134 hint->error_string = hint->error_string_owned = xstrdup(p);
1135 else
1136 hint->error_string = "failed";
1137 code = -1;
1138 continue;
1139 }
1140 new_report = 1;
1141 }
1142
1143 for (cmd = commands; cmd; cmd = cmd->next)
1144 if (cmd->run_proc_receive && !cmd->error_string &&
1145 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED)) {
1146 cmd->error_string = "proc-receive failed to report status";
1147 code = -1;
1148 }
1149 return code;
1150 }
1151
1152 static int run_proc_receive_hook(struct command *commands,
1153 const struct string_list *push_options)
1154 {
1155 struct child_process proc = CHILD_PROCESS_INIT;
1156 struct async muxer;
1157 struct command *cmd;
1158 struct packet_reader reader;
1159 struct strbuf cap = STRBUF_INIT;
1160 struct strbuf errmsg = STRBUF_INIT;
1161 int hook_use_push_options = 0;
1162 int version = 0;
1163 int code;
1164 const char *hook_path = find_hook(the_repository, "proc-receive");
1165
1166 if (!hook_path) {
1167 rp_error("cannot find hook 'proc-receive'");
1168 return -1;
1169 }
1170
1171 strvec_push(&proc.args, hook_path);
1172 proc.in = -1;
1173 proc.out = -1;
1174 proc.trace2_hook_name = "proc-receive";
1175
1176 if (use_sideband) {
1177 memset(&muxer, 0, sizeof(muxer));
1178 muxer.proc = copy_to_sideband;
1179 muxer.in = -1;
1180 code = start_async(&muxer);
1181 if (code)
1182 return code;
1183 proc.err = muxer.in;
1184 } else {
1185 proc.err = 0;
1186 }
1187
1188 code = start_command(&proc);
1189 if (code) {
1190 if (use_sideband)
1191 finish_async(&muxer);
1192 return code;
1193 }
1194
1195 sigchain_push(SIGPIPE, SIG_IGN);
1196
1197 /* Version negotiaton */
1198 packet_reader_init(&reader, proc.out, NULL, 0,
1199 PACKET_READ_CHOMP_NEWLINE |
1200 PACKET_READ_GENTLE_ON_EOF);
1201 if (use_atomic)
1202 strbuf_addstr(&cap, " atomic");
1203 if (use_push_options)
1204 strbuf_addstr(&cap, " push-options");
1205 if (cap.len) {
1206 code = packet_write_fmt_gently(proc.in, "version=1%c%s\n", '\0', cap.buf + 1);
1207 strbuf_release(&cap);
1208 } else {
1209 code = packet_write_fmt_gently(proc.in, "version=1\n");
1210 }
1211 if (!code)
1212 code = packet_flush_gently(proc.in);
1213
1214 if (!code)
1215 for (;;) {
1216 int linelen;
1217 enum packet_read_status status;
1218
1219 status = packet_reader_read(&reader);
1220 if (status != PACKET_READ_NORMAL) {
1221 /* Check whether proc-receive exited abnormally */
1222 if (status == PACKET_READ_EOF)
1223 code = -1;
1224 break;
1225 }
1226
1227 if (reader.pktlen > 8 && starts_with(reader.line, "version=")) {
1228 version = atoi(reader.line + 8);
1229 linelen = strlen(reader.line);
1230 if (linelen < reader.pktlen) {
1231 const char *feature_list = reader.line + linelen + 1;
1232 if (parse_feature_request(feature_list, "push-options"))
1233 hook_use_push_options = 1;
1234 }
1235 }
1236 }
1237
1238 if (code) {
1239 strbuf_addstr(&errmsg, "fail to negotiate version with proc-receive hook");
1240 goto cleanup;
1241 }
1242
1243 switch (version) {
1244 case 0:
1245 /* fallthrough */
1246 case 1:
1247 break;
1248 default:
1249 strbuf_addf(&errmsg, "proc-receive version '%d' is not supported",
1250 version);
1251 code = -1;
1252 goto cleanup;
1253 }
1254
1255 /* Send commands */
1256 for (cmd = commands; cmd; cmd = cmd->next) {
1257 if (!cmd->run_proc_receive || cmd->skip_update || cmd->error_string)
1258 continue;
1259 code = packet_write_fmt_gently(proc.in, "%s %s %s",
1260 oid_to_hex(&cmd->old_oid),
1261 oid_to_hex(&cmd->new_oid),
1262 cmd->ref_name);
1263 if (code)
1264 break;
1265 }
1266 if (!code)
1267 code = packet_flush_gently(proc.in);
1268 if (code) {
1269 strbuf_addstr(&errmsg, "fail to write commands to proc-receive hook");
1270 goto cleanup;
1271 }
1272
1273 /* Send push options */
1274 if (hook_use_push_options) {
1275 struct string_list_item *item;
1276
1277 for_each_string_list_item(item, push_options) {
1278 code = packet_write_fmt_gently(proc.in, "%s", item->string);
1279 if (code)
1280 break;
1281 }
1282 if (!code)
1283 code = packet_flush_gently(proc.in);
1284 if (code) {
1285 strbuf_addstr(&errmsg,
1286 "fail to write push-options to proc-receive hook");
1287 goto cleanup;
1288 }
1289 }
1290
1291 /* Read result from proc-receive */
1292 code = read_proc_receive_report(&reader, commands, &errmsg);
1293
1294 cleanup:
1295 close(proc.in);
1296 close(proc.out);
1297 if (use_sideband)
1298 finish_async(&muxer);
1299 if (finish_command(&proc))
1300 code = -1;
1301 if (errmsg.len >0) {
1302 char *p = errmsg.buf;
1303
1304 p += errmsg.len - 1;
1305 if (*p == '\n')
1306 *p = '\0';
1307 rp_error("%s", errmsg.buf);
1308 strbuf_release(&errmsg);
1309 }
1310 sigchain_pop(SIGPIPE);
1311
1312 return code;
1313 }
1314
1315 static const char *refuse_unconfigured_deny_msg =
1316 N_("By default, updating the current branch in a non-bare repository\n"
1317 "is denied, because it will make the index and work tree inconsistent\n"
1318 "with what you pushed, and will require 'git reset --hard' to match\n"
1319 "the work tree to HEAD.\n"
1320 "\n"
1321 "You can set the 'receive.denyCurrentBranch' configuration variable\n"
1322 "to 'ignore' or 'warn' in the remote repository to allow pushing into\n"
1323 "its current branch; however, this is not recommended unless you\n"
1324 "arranged to update its work tree to match what you pushed in some\n"
1325 "other way.\n"
1326 "\n"
1327 "To squelch this message and still keep the default behaviour, set\n"
1328 "'receive.denyCurrentBranch' configuration variable to 'refuse'.");
1329
1330 static void refuse_unconfigured_deny(void)
1331 {
1332 rp_error("%s", _(refuse_unconfigured_deny_msg));
1333 }
1334
1335 static const char *refuse_unconfigured_deny_delete_current_msg =
1336 N_("By default, deleting the current branch is denied, because the next\n"
1337 "'git clone' won't result in any file checked out, causing confusion.\n"
1338 "\n"
1339 "You can set 'receive.denyDeleteCurrent' configuration variable to\n"
1340 "'warn' or 'ignore' in the remote repository to allow deleting the\n"
1341 "current branch, with or without a warning message.\n"
1342 "\n"
1343 "To squelch this message, you can set it to 'refuse'.");
1344
1345 static void refuse_unconfigured_deny_delete_current(void)
1346 {
1347 rp_error("%s", _(refuse_unconfigured_deny_delete_current_msg));
1348 }
1349
1350 static const struct object_id *command_singleton_iterator(void *cb_data);
1351 static int update_shallow_ref(struct command *cmd, struct shallow_info *si)
1352 {
1353 struct shallow_lock shallow_lock = SHALLOW_LOCK_INIT;
1354 struct oid_array extra = OID_ARRAY_INIT;
1355 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1356 uint32_t mask = 1 << (cmd->index % 32);
1357 int i;
1358
1359 trace_printf_key(&trace_shallow,
1360 "shallow: update_shallow_ref %s\n", cmd->ref_name);
1361 for (i = 0; i < si->shallow->nr; i++)
1362 if (si->used_shallow[i] &&
1363 (si->used_shallow[i][cmd->index / 32] & mask) &&
1364 !delayed_reachability_test(si, i))
1365 oid_array_append(&extra, &si->shallow->oid[i]);
1366
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(the_repository);
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 struct odb_transaction *transaction)
1795 {
1796 struct command *cmd;
1797
1798 for (cmd = commands; cmd; cmd = cmd->next) {
1799 struct command *singleton = cmd;
1800 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1801 struct strvec env = STRVEC_INIT;
1802
1803 if (shallow_update && si->shallow_ref[cmd->index])
1804 /* to be checked in update_shallow_ref() */
1805 continue;
1806
1807 odb_transaction_env(transaction, &env);
1808 opt.env = env.v;
1809
1810 if (!check_connected(command_singleton_iterator, &singleton,
1811 &opt))
1812 continue;
1813
1814 cmd->error_string = "missing necessary objects";
1815
1816 strvec_clear(&env);
1817 }
1818 }
1819
1820 struct iterate_data {
1821 struct command *cmds;
1822 struct shallow_info *si;
1823 };
1824
1825 static const struct object_id *iterate_receive_command_list(void *cb_data)
1826 {
1827 struct iterate_data *data = cb_data;
1828 struct command **cmd_list = &data->cmds;
1829 struct command *cmd = *cmd_list;
1830
1831 for (; cmd; cmd = cmd->next) {
1832 if (shallow_update && data->si->shallow_ref[cmd->index])
1833 /* to be checked in update_shallow_ref() */
1834 continue;
1835 if (!is_null_oid(&cmd->new_oid) && !cmd->skip_update) {
1836 *cmd_list = cmd->next;
1837 return &cmd->new_oid;
1838 }
1839 }
1840 return NULL;
1841 }
1842
1843 static void reject_updates_to_hidden(struct command *commands)
1844 {
1845 struct strbuf refname_full = STRBUF_INIT;
1846 size_t prefix_len;
1847 struct command *cmd;
1848
1849 strbuf_addstr(&refname_full, get_git_namespace());
1850 prefix_len = refname_full.len;
1851
1852 for (cmd = commands; cmd; cmd = cmd->next) {
1853 if (cmd->error_string)
1854 continue;
1855
1856 strbuf_setlen(&refname_full, prefix_len);
1857 strbuf_addstr(&refname_full, cmd->ref_name);
1858
1859 if (!ref_is_hidden(cmd->ref_name, refname_full.buf, &hidden_refs))
1860 continue;
1861 if (is_null_oid(&cmd->new_oid))
1862 cmd->error_string = "deny deleting a hidden ref";
1863 else
1864 cmd->error_string = "deny updating a hidden ref";
1865 }
1866
1867 strbuf_release(&refname_full);
1868 }
1869
1870 static int should_process_cmd(struct command *cmd)
1871 {
1872 return !cmd->error_string && !cmd->skip_update;
1873 }
1874
1875 static void BUG_if_skipped_connectivity_check(struct command *commands,
1876 struct shallow_info *si)
1877 {
1878 struct command *cmd;
1879
1880 for (cmd = commands; cmd; cmd = cmd->next) {
1881 if (should_process_cmd(cmd) && si->shallow_ref[cmd->index])
1882 bug("connectivity check has not been run on ref %s",
1883 cmd->ref_name);
1884 }
1885 BUG_if_bug("connectivity check skipped???");
1886 }
1887
1888 static void ref_transaction_rejection_handler(const char *refname,
1889 const struct object_id *old_oid UNUSED,
1890 const struct object_id *new_oid UNUSED,
1891 const char *old_target UNUSED,
1892 const char *new_target UNUSED,
1893 enum ref_transaction_error err,
1894 const char *details,
1895 void *cb_data)
1896 {
1897 struct strmap *failed_refs = cb_data;
1898
1899 if (details)
1900 rp_error("%s", details);
1901
1902 strmap_put(failed_refs, refname, (char *)ref_transaction_error_msg(err));
1903 }
1904
1905 static void execute_commands_non_atomic(struct command *commands,
1906 struct shallow_info *si)
1907 {
1908 struct command *cmd;
1909 struct strbuf err = STRBUF_INIT;
1910 const char *reported_error = NULL;
1911 struct strmap failed_refs = STRMAP_INIT;
1912
1913 /*
1914 * Reference updates, where D/F conflicts shouldn't arise due to
1915 * one reference being deleted, while the other being created
1916 * are treated as conflicts in batched updates. This is because
1917 * we don't do conflict resolution inside a transaction. To
1918 * mitigate this, delete references in a separate batch.
1919 *
1920 * NEEDSWORK: Add conflict resolution between deletion and creation
1921 * of reference updates within a transaction. With that, we can
1922 * combine the two phases.
1923 */
1924 enum processing_phase {
1925 PHASE_DELETIONS,
1926 PHASE_OTHERS
1927 };
1928
1929 for (enum processing_phase phase = PHASE_DELETIONS; phase <= PHASE_OTHERS; phase++) {
1930 for (cmd = commands; cmd; cmd = cmd->next) {
1931 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
1932 continue;
1933
1934 if (phase == PHASE_DELETIONS && !is_null_oid(&cmd->new_oid))
1935 continue;
1936 else if (phase == PHASE_OTHERS && is_null_oid(&cmd->new_oid))
1937 continue;
1938
1939 /*
1940 * Lazily create a transaction only when we know there are
1941 * updates to be added.
1942 */
1943 if (!transaction) {
1944 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1945 REF_TRANSACTION_ALLOW_FAILURE, &err);
1946 if (!transaction) {
1947 rp_error("%s", err.buf);
1948 strbuf_reset(&err);
1949 reported_error = "transaction failed to start";
1950 goto failure;
1951 }
1952 }
1953
1954 cmd->error_string = update(cmd, si);
1955 }
1956
1957 /* No transaction, so nothing to commit */
1958 if (!transaction)
1959 goto cleanup;
1960
1961 if (ref_transaction_commit(transaction, &err)) {
1962 rp_error("%s", err.buf);
1963 reported_error = "failed to update refs";
1964 goto failure;
1965 }
1966
1967 ref_transaction_for_each_rejected_update(transaction,
1968
1969 ref_transaction_rejection_handler,
1970 &failed_refs);
1971
1972 if (strmap_empty(&failed_refs))
1973 goto cleanup;
1974
1975 failure:
1976 for (cmd = commands; cmd; cmd = cmd->next) {
1977 if (reported_error)
1978 cmd->error_string = reported_error;
1979 else if (strmap_contains(&failed_refs, cmd->ref_name))
1980 cmd->error_string = cmd->error_string_owned = xstrdup(strmap_get(&failed_refs, cmd->ref_name));
1981 }
1982
1983 cleanup:
1984 ref_transaction_free(transaction);
1985 transaction = NULL;
1986 strmap_clear(&failed_refs, 0);
1987 strbuf_release(&err);
1988 }
1989 }
1990
1991 static void execute_commands_atomic(struct command *commands,
1992 struct shallow_info *si)
1993 {
1994 struct command *cmd;
1995 struct strbuf err = STRBUF_INIT;
1996 const char *reported_error = "atomic push failure";
1997
1998 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1999 0, &err);
2000 if (!transaction) {
2001 rp_error("%s", err.buf);
2002 strbuf_reset(&err);
2003 reported_error = "transaction failed to start";
2004 goto failure;
2005 }
2006
2007 for (cmd = commands; cmd; cmd = cmd->next) {
2008 if (!should_process_cmd(cmd) || cmd->run_proc_receive)
2009 continue;
2010
2011 cmd->error_string = update(cmd, si);
2012
2013 if (cmd->error_string)
2014 goto failure;
2015 }
2016
2017 if (ref_transaction_commit(transaction, &err)) {
2018 rp_error("%s", err.buf);
2019 reported_error = "atomic transaction failed";
2020 goto failure;
2021 }
2022 goto cleanup;
2023
2024 failure:
2025 for (cmd = commands; cmd; cmd = cmd->next)
2026 if (!cmd->error_string)
2027 cmd->error_string = reported_error;
2028
2029 cleanup:
2030 ref_transaction_free(transaction);
2031 strbuf_release(&err);
2032 }
2033
2034 static void execute_commands(struct command *commands,
2035 const char *unpacker_error,
2036 struct shallow_info *si,
2037 struct odb_transaction *transaction,
2038 const struct string_list *push_options)
2039 {
2040 struct check_connected_options opt = CHECK_CONNECTED_INIT;
2041 struct command *cmd;
2042 struct iterate_data data;
2043 struct async muxer;
2044 int err_fd = 0;
2045 int run_proc_receive = 0;
2046
2047 if (unpacker_error) {
2048 for (cmd = commands; cmd; cmd = cmd->next)
2049 cmd->error_string = "unpacker error";
2050 return;
2051 }
2052
2053 if (!skip_connectivity_check) {
2054 struct strvec env = STRVEC_INIT;
2055
2056 if (use_sideband) {
2057 memset(&muxer, 0, sizeof(muxer));
2058 muxer.proc = copy_to_sideband;
2059 muxer.in = -1;
2060 if (!start_async(&muxer))
2061 err_fd = muxer.in;
2062 /* ...else, continue without relaying sideband */
2063 }
2064
2065 data.cmds = commands;
2066 data.si = si;
2067 opt.err_fd = err_fd;
2068 opt.progress = err_fd && !quiet;
2069 odb_transaction_env(transaction, &env);
2070 opt.env = env.v;
2071 opt.exclude_hidden_refs_section = "receive";
2072
2073 if (check_connected(iterate_receive_command_list, &data, &opt))
2074 set_connectivity_errors(commands, si, transaction);
2075
2076 if (use_sideband)
2077 finish_async(&muxer);
2078
2079 strvec_clear(&env);
2080 }
2081
2082 reject_updates_to_hidden(commands);
2083
2084 /*
2085 * Try to find commands that have special prefix in their reference names,
2086 * and mark them to run an external "proc-receive" hook later.
2087 */
2088 if (proc_receive_ref) {
2089 for (cmd = commands; cmd; cmd = cmd->next) {
2090 if (!should_process_cmd(cmd))
2091 continue;
2092
2093 if (proc_receive_ref_matches(cmd)) {
2094 cmd->run_proc_receive = RUN_PROC_RECEIVE_SCHEDULED;
2095 run_proc_receive = 1;
2096 }
2097 }
2098 }
2099
2100 if (run_receive_hook(commands, "pre-receive", 0, transaction, push_options)) {
2101 for (cmd = commands; cmd; cmd = cmd->next) {
2102 if (!cmd->error_string)
2103 cmd->error_string = "pre-receive hook declined";
2104 }
2105 return;
2106 }
2107
2108 /*
2109 * If there is no command ready to run, should return directly to destroy
2110 * temporary data in the quarantine area.
2111 */
2112 for (cmd = commands; cmd && cmd->error_string; cmd = cmd->next)
2113 ; /* nothing */
2114 if (!cmd)
2115 return;
2116
2117 /*
2118 * Now we'll start writing out refs, which means the objects need
2119 * to be in their final positions so that other processes can see them.
2120 */
2121 if (odb_transaction_commit(transaction)) {
2122 for (cmd = commands; cmd; cmd = cmd->next) {
2123 if (!cmd->error_string)
2124 cmd->error_string = "unable to migrate objects to permanent storage";
2125 }
2126 return;
2127 }
2128
2129 check_aliased_updates(commands);
2130
2131 free(head_name_to_free);
2132 head_name = head_name_to_free = refs_resolve_refdup(get_main_ref_store(the_repository),
2133 "HEAD", 0, NULL,
2134 NULL);
2135
2136 if (run_proc_receive &&
2137 run_proc_receive_hook(commands, push_options))
2138 for (cmd = commands; cmd; cmd = cmd->next)
2139 if (!cmd->error_string &&
2140 !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED) &&
2141 (cmd->run_proc_receive || use_atomic))
2142 cmd->error_string = "fail to run proc-receive hook";
2143
2144 if (use_atomic)
2145 execute_commands_atomic(commands, si);
2146 else
2147 execute_commands_non_atomic(commands, si);
2148
2149 if (shallow_update)
2150 BUG_if_skipped_connectivity_check(commands, si);
2151 }
2152
2153 static struct command **queue_command(struct command **tail,
2154 const char *line,
2155 int linelen)
2156 {
2157 struct object_id old_oid, new_oid;
2158 struct command *cmd;
2159 const char *refname;
2160 int reflen;
2161 const char *p;
2162
2163 if (parse_oid_hex(line, &old_oid, &p) ||
2164 *p++ != ' ' ||
2165 parse_oid_hex(p, &new_oid, &p) ||
2166 *p++ != ' ')
2167 die("protocol error: expected old/new/ref, got '%s'", line);
2168
2169 refname = p;
2170 reflen = linelen - (p - line);
2171 FLEX_ALLOC_MEM(cmd, ref_name, refname, reflen);
2172 oidcpy(&cmd->old_oid, &old_oid);
2173 oidcpy(&cmd->new_oid, &new_oid);
2174 *tail = cmd;
2175 return &cmd->next;
2176 }
2177
2178 static void free_commands(struct command *commands)
2179 {
2180 while (commands) {
2181 struct command *next = commands->next;
2182
2183 ref_push_report_free(commands->report);
2184 free(commands->error_string_owned);
2185 free(commands);
2186 commands = next;
2187 }
2188 }
2189
2190 static void queue_commands_from_cert(struct command **tail,
2191 struct strbuf *push_cert)
2192 {
2193 const char *boc, *eoc;
2194
2195 if (*tail)
2196 die("protocol error: got both push certificate and unsigned commands");
2197
2198 boc = strstr(push_cert->buf, "\n\n");
2199 if (!boc)
2200 die("malformed push certificate %.*s", 100, push_cert->buf);
2201 else
2202 boc += 2;
2203 eoc = push_cert->buf + parse_signed_buffer(push_cert->buf, push_cert->len);
2204
2205 while (boc < eoc) {
2206 const char *eol = memchr(boc, '\n', eoc - boc);
2207 tail = queue_command(tail, boc, eol ? eol - boc : eoc - boc);
2208 boc = eol ? eol + 1 : eoc;
2209 }
2210 }
2211
2212 static struct command *read_head_info(struct packet_reader *reader,
2213 struct oid_array *shallow)
2214 {
2215 struct command *commands = NULL;
2216 struct command **p = &commands;
2217 for (;;) {
2218 int linelen;
2219
2220 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2221 break;
2222
2223 if (reader->pktlen > 8 && starts_with(reader->line, "shallow ")) {
2224 struct object_id oid;
2225 if (get_oid_hex(reader->line + 8, &oid))
2226 die("protocol error: expected shallow sha, got '%s'",
2227 reader->line + 8);
2228 oid_array_append(shallow, &oid);
2229 continue;
2230 }
2231
2232 linelen = strlen(reader->line);
2233 if (linelen < reader->pktlen) {
2234 const char *feature_list = reader->line + linelen + 1;
2235 const char *hash = NULL;
2236 const char *client_sid;
2237 size_t len = 0;
2238 if (parse_feature_request(feature_list, "report-status"))
2239 report_status = 1;
2240 if (parse_feature_request(feature_list, "report-status-v2"))
2241 report_status_v2 = 1;
2242 if (parse_feature_request(feature_list, "side-band-64k"))
2243 use_sideband = LARGE_PACKET_MAX;
2244 if (parse_feature_request(feature_list, "quiet"))
2245 quiet = 1;
2246 if (advertise_atomic_push
2247 && parse_feature_request(feature_list, "atomic"))
2248 use_atomic = 1;
2249 if (advertise_push_options
2250 && parse_feature_request(feature_list, "push-options"))
2251 use_push_options = 1;
2252 hash = parse_feature_value(feature_list, "object-format", &len, NULL);
2253 if (!hash) {
2254 hash = hash_algos[GIT_HASH_SHA1_LEGACY].name;
2255 len = strlen(hash);
2256 }
2257 if (xstrncmpz(the_hash_algo->name, hash, len))
2258 die("error: unsupported object format '%s'", hash);
2259 client_sid = parse_feature_value(feature_list, "session-id", &len, NULL);
2260 if (client_sid) {
2261 char *sid = xstrndup(client_sid, len);
2262 trace2_data_string("transfer", NULL, "client-sid", client_sid);
2263 free(sid);
2264 }
2265 }
2266
2267 if (!strcmp(reader->line, "push-cert")) {
2268 int true_flush = 0;
2269 int saved_options = reader->options;
2270 reader->options &= ~PACKET_READ_CHOMP_NEWLINE;
2271
2272 for (;;) {
2273 packet_reader_read(reader);
2274 if (reader->status == PACKET_READ_FLUSH) {
2275 true_flush = 1;
2276 break;
2277 }
2278 if (reader->status != PACKET_READ_NORMAL) {
2279 die("protocol error: got an unexpected packet");
2280 }
2281 if (!strcmp(reader->line, "push-cert-end\n"))
2282 break; /* end of cert */
2283 strbuf_addstr(&push_cert, reader->line);
2284 }
2285 reader->options = saved_options;
2286
2287 if (true_flush)
2288 break;
2289 continue;
2290 }
2291
2292 p = queue_command(p, reader->line, linelen);
2293 }
2294
2295 if (push_cert.len)
2296 queue_commands_from_cert(p, &push_cert);
2297
2298 return commands;
2299 }
2300
2301 static void read_push_options(struct packet_reader *reader,
2302 struct string_list *options)
2303 {
2304 while (1) {
2305 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
2306 break;
2307
2308 string_list_append(options, reader->line);
2309 }
2310 }
2311
2312 static const char *parse_pack_header(struct pack_header *hdr)
2313 {
2314 switch (read_pack_header(0, hdr)) {
2315 case PH_ERROR_EOF:
2316 return "eof before pack header was fully read";
2317
2318 case PH_ERROR_PACK_SIGNATURE:
2319 return "protocol error (pack signature mismatch detected)";
2320
2321 case PH_ERROR_PROTOCOL:
2322 return "protocol error (pack version unsupported)";
2323
2324 default:
2325 return "unknown error in parse_pack_header";
2326
2327 case 0:
2328 return NULL;
2329 }
2330 }
2331
2332 static struct tempfile *pack_lockfile;
2333
2334 static void push_header_arg(struct strvec *args, struct pack_header *hdr)
2335 {
2336 strvec_pushf(args, "--pack_header=%"PRIu32",%"PRIu32,
2337 ntohl(hdr->hdr_version), ntohl(hdr->hdr_entries));
2338 }
2339
2340 static const char *unpack(int err_fd, struct shallow_info *si,
2341 struct odb_transaction *transaction)
2342 {
2343 struct pack_header hdr;
2344 const char *hdr_err;
2345 int status;
2346 struct child_process child = CHILD_PROCESS_INIT;
2347 int fsck_objects = (receive_fsck_objects >= 0
2348 ? receive_fsck_objects
2349 : transfer_fsck_objects >= 0
2350 ? transfer_fsck_objects
2351 : 0);
2352
2353 hdr_err = parse_pack_header(&hdr);
2354 if (hdr_err) {
2355 if (err_fd > 0)
2356 close(err_fd);
2357 return hdr_err;
2358 }
2359
2360 if (si->nr_ours || si->nr_theirs) {
2361 alt_shallow_file = setup_temporary_shallow(si->shallow);
2362 strvec_push(&child.args, "--shallow-file");
2363 strvec_push(&child.args, alt_shallow_file);
2364 }
2365
2366 odb_transaction_env(transaction, &child.env);
2367
2368 if (ntohl(hdr.hdr_entries) < unpack_limit) {
2369 strvec_push(&child.args, "unpack-objects");
2370 push_header_arg(&child.args, &hdr);
2371 if (quiet)
2372 strvec_push(&child.args, "-q");
2373 if (fsck_objects)
2374 strvec_pushf(&child.args, "--strict%s",
2375 fsck_msg_types.buf);
2376 if (max_input_size)
2377 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2378 (uintmax_t)max_input_size);
2379 child.no_stdout = 1;
2380 child.err = err_fd;
2381 child.git_cmd = 1;
2382 status = run_command(&child);
2383 if (status)
2384 return "unpack-objects abnormal exit";
2385 } else {
2386 char hostname[HOST_NAME_MAX + 1];
2387 char *lockfile;
2388
2389 strvec_pushl(&child.args, "index-pack", "--stdin", NULL);
2390 push_header_arg(&child.args, &hdr);
2391
2392 if (xgethostname(hostname, sizeof(hostname)))
2393 xsnprintf(hostname, sizeof(hostname), "localhost");
2394 strvec_pushf(&child.args,
2395 "--keep=receive-pack %"PRIuMAX" on %s",
2396 (uintmax_t)getpid(),
2397 hostname);
2398
2399 if (!quiet && err_fd)
2400 strvec_push(&child.args, "--show-resolving-progress");
2401 if (use_sideband)
2402 strvec_push(&child.args, "--report-end-of-input");
2403 if (fsck_objects)
2404 strvec_pushf(&child.args, "--strict%s",
2405 fsck_msg_types.buf);
2406 if (!reject_thin)
2407 strvec_push(&child.args, "--fix-thin");
2408 if (max_input_size)
2409 strvec_pushf(&child.args, "--max-input-size=%"PRIuMAX,
2410 (uintmax_t)max_input_size);
2411 child.out = -1;
2412 child.err = err_fd;
2413 child.git_cmd = 1;
2414 status = start_command(&child);
2415 if (status)
2416 return "index-pack fork failed";
2417
2418 lockfile = index_pack_lockfile(the_repository, child.out, NULL);
2419 if (lockfile) {
2420 pack_lockfile = register_tempfile(lockfile);
2421 free(lockfile);
2422 }
2423 close(child.out);
2424
2425 status = finish_command(&child);
2426 if (status)
2427 return "index-pack abnormal exit";
2428 odb_reprepare(the_repository->objects);
2429 }
2430 return NULL;
2431 }
2432
2433 static const char *unpack_with_sideband(struct shallow_info *si,
2434 struct odb_transaction *transaction)
2435 {
2436 struct async muxer;
2437 const char *ret;
2438
2439 if (!use_sideband)
2440 return unpack(0, si, transaction);
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, transaction);
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 struct odb_transaction *transaction = NULL;
2627
2628 struct option options[] = {
2629 OPT__QUIET(&quiet, N_("quiet")),
2630 OPT_HIDDEN_BOOL(0, "skip-connectivity-check", &skip_connectivity_check, NULL),
2631 OPT_HIDDEN_BOOL(0, "stateless-rpc", &stateless_rpc, NULL),
2632 OPT_HIDDEN_BOOL(0, "http-backend-info-refs", &advertise_refs, NULL),
2633 OPT_ALIAS(0, "advertise-refs", "http-backend-info-refs"),
2634 OPT_HIDDEN_BOOL(0, "reject-thin-pack-for-testing", &reject_thin, NULL),
2635 OPT_HIDDEN_BOOL(0, "advertise-no-ref-delta-for-testing",
2636 &advertise_no_ref_delta, NULL),
2637 OPT_END()
2638 };
2639
2640 packet_trace_identity("receive-pack");
2641
2642 argc = parse_options(argc, argv, prefix, options, receive_pack_usage, 0);
2643
2644 if (argc > 1)
2645 usage_msg_opt(_("too many arguments"), receive_pack_usage, options);
2646 if (argc == 0)
2647 usage_msg_opt(_("you must specify a directory"), receive_pack_usage, options);
2648
2649 service_dir = argv[0];
2650
2651 setup_path();
2652
2653 if (!enter_repo(the_repository, service_dir, 0))
2654 die("'%s' does not appear to be a git repository", service_dir);
2655
2656 repo_config(the_repository, receive_pack_config, NULL);
2657 if (cert_nonce_seed)
2658 push_cert_nonce = prepare_push_cert_nonce(service_dir, time(NULL));
2659
2660 if (0 <= receive_unpack_limit)
2661 unpack_limit = receive_unpack_limit;
2662 else if (0 <= transfer_unpack_limit)
2663 unpack_limit = transfer_unpack_limit;
2664
2665 switch (determine_protocol_version_server()) {
2666 case protocol_v2:
2667 /*
2668 * push support for protocol v2 has not been implemented yet,
2669 * so ignore the request to use v2 and fallback to using v0.
2670 */
2671 break;
2672 case protocol_v1:
2673 /*
2674 * v1 is just the original protocol with a version string,
2675 * so just fall through after writing the version string.
2676 */
2677 if (advertise_refs || !stateless_rpc)
2678 packet_write_fmt(1, "version 1\n");
2679
2680 /* fallthrough */
2681 case protocol_v0:
2682 break;
2683 case protocol_unknown_version:
2684 BUG("unknown protocol version");
2685 }
2686
2687 if (advertise_refs || !stateless_rpc) {
2688 write_head_info();
2689 }
2690 if (advertise_refs)
2691 return 0;
2692
2693 packet_reader_init(&reader, 0, NULL, 0,
2694 PACKET_READ_CHOMP_NEWLINE |
2695 PACKET_READ_DIE_ON_ERR_PACKET);
2696
2697 if ((commands = read_head_info(&reader, &shallow))) {
2698 const char *unpack_status = NULL;
2699 struct string_list push_options = STRING_LIST_INIT_DUP;
2700
2701 if (use_push_options)
2702 read_push_options(&reader, &push_options);
2703 if (!check_cert_push_options(&push_options)) {
2704 struct command *cmd;
2705 for (cmd = commands; cmd; cmd = cmd->next)
2706 cmd->error_string = "inconsistent push options";
2707 }
2708
2709 prepare_shallow_info(&si, &shallow);
2710 if (!si.nr_ours && !si.nr_theirs)
2711 shallow_update = 0;
2712 if (!delete_only(commands)) {
2713 if (odb_transaction_begin(the_repository->objects, &transaction, ODB_TRANSACTION_RECEIVE))
2714 unpack_status = "unable to start object transaction";
2715 else
2716 unpack_status = unpack_with_sideband(&si, transaction);
2717 update_shallow_info(commands, &si, &ref);
2718 }
2719 use_keepalive = KEEPALIVE_ALWAYS;
2720 execute_commands(commands, unpack_status, &si, transaction,
2721 &push_options);
2722 delete_tempfile(&pack_lockfile);
2723 sigchain_push(SIGPIPE, SIG_IGN);
2724 if (report_status_v2)
2725 report_v2(commands, unpack_status);
2726 else if (report_status)
2727 report(commands, unpack_status);
2728 sigchain_pop(SIGPIPE);
2729 run_receive_hook(commands, "post-receive", 1, NULL,
2730 &push_options);
2731 run_update_post_hook(commands);
2732 free_commands(commands);
2733 string_list_clear(&push_options, 0);
2734 if (auto_gc) {
2735 struct child_process proc = CHILD_PROCESS_INIT;
2736
2737 if (prepare_auto_maintenance(the_repository, 1, &proc)) {
2738 proc.no_stdin = 1;
2739 proc.stdout_to_stderr = 1;
2740 proc.err = use_sideband ? -1 : 0;
2741
2742 if (!start_command(&proc)) {
2743 if (use_sideband)
2744 copy_to_sideband(proc.err, -1, NULL);
2745 finish_command(&proc);
2746 }
2747 }
2748 }
2749 if (auto_update_server_info)
2750 update_server_info(the_repository, 0);
2751 clear_shallow_info(&si);
2752 }
2753 if (use_sideband)
2754 packet_flush(1);
2755 oid_array_clear(&shallow);
2756 oid_array_clear(&ref);
2757 strvec_clear(&hidden_refs);
2758 free((void *)push_cert_nonce);
2759 return 0;
2760 }