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