267d3204c209bb0816004dac3009589f08f66074
1#include "builtin.h"
2#include "lockfile.h"
3#include "pack.h"
4#include "refs.h"
5#include "pkt-line.h"
6#include "sideband.h"
7#include "run-command.h"
8#include "exec_cmd.h"
9#include "commit.h"
10#include "object.h"
11#include "remote.h"
12#include "connect.h"
13#include "transport.h"
14#include "string-list.h"
15#include "sha1-array.h"
16#include "connected.h"
17#include "argv-array.h"
18#include "version.h"
19#include "tag.h"
20#include "gpg-interface.h"
21#include "sigchain.h"
22#include "fsck.h"
23#include "tmp-objdir.h"
24
25static const char * const receive_pack_usage[] = {
26 N_("git receive-pack <git-dir>"),
27 NULL
28};
29
30enum deny_action {
31 DENY_UNCONFIGURED,
32 DENY_IGNORE,
33 DENY_WARN,
34 DENY_REFUSE,
35 DENY_UPDATE_INSTEAD
36};
37
38static int deny_deletes;
39static int deny_non_fast_forwards;
40static enum deny_action deny_current_branch = DENY_UNCONFIGURED;
41static enum deny_action deny_delete_current = DENY_UNCONFIGURED;
42static int receive_fsck_objects = -1;
43static int transfer_fsck_objects = -1;
44static struct strbuf fsck_msg_types = STRBUF_INIT;
45static int receive_unpack_limit = -1;
46static int transfer_unpack_limit = -1;
47static int advertise_atomic_push = 1;
48static int advertise_push_options;
49static int unpack_limit = 100;
50static off_t max_input_size;
51static int report_status;
52static int use_sideband;
53static int use_atomic;
54static int use_push_options;
55static int quiet;
56static int prefer_ofs_delta = 1;
57static int auto_update_server_info;
58static int auto_gc = 1;
59static int reject_thin;
60static int stateless_rpc;
61static const char *service_dir;
62static const char *head_name;
63static void *head_name_to_free;
64static int sent_capabilities;
65static int shallow_update;
66static const char *alt_shallow_file;
67static struct strbuf push_cert = STRBUF_INIT;
68static unsigned char push_cert_sha1[20];
69static struct signature_check sigcheck;
70static const char *push_cert_nonce;
71static const char *cert_nonce_seed;
72
73static const char *NONCE_UNSOLICITED = "UNSOLICITED";
74static const char *NONCE_BAD = "BAD";
75static const char *NONCE_MISSING = "MISSING";
76static const char *NONCE_OK = "OK";
77static const char *NONCE_SLOP = "SLOP";
78static const char *nonce_status;
79static long nonce_stamp_slop;
80static unsigned long nonce_stamp_slop_limit;
81static struct ref_transaction *transaction;
82
83static enum {
84 KEEPALIVE_NEVER = 0,
85 KEEPALIVE_AFTER_NUL,
86 KEEPALIVE_ALWAYS
87} use_keepalive;
88static int keepalive_in_sec = 5;
89
90static struct tmp_objdir *tmp_objdir;
91
92static enum deny_action parse_deny_action(const char *var, const char *value)
93{
94 if (value) {
95 if (!strcasecmp(value, "ignore"))
96 return DENY_IGNORE;
97 if (!strcasecmp(value, "warn"))
98 return DENY_WARN;
99 if (!strcasecmp(value, "refuse"))
100 return DENY_REFUSE;
101 if (!strcasecmp(value, "updateinstead"))
102 return DENY_UPDATE_INSTEAD;
103 }
104 if (git_config_bool(var, value))
105 return DENY_REFUSE;
106 return DENY_IGNORE;
107}
108
109static int receive_pack_config(const char *var, const char *value, void *cb)
110{
111 int status = parse_hide_refs_config(var, value, "receive");
112
113 if (status)
114 return status;
115
116 if (strcmp(var, "receive.denydeletes") == 0) {
117 deny_deletes = git_config_bool(var, value);
118 return 0;
119 }
120
121 if (strcmp(var, "receive.denynonfastforwards") == 0) {
122 deny_non_fast_forwards = git_config_bool(var, value);
123 return 0;
124 }
125
126 if (strcmp(var, "receive.unpacklimit") == 0) {
127 receive_unpack_limit = git_config_int(var, value);
128 return 0;
129 }
130
131 if (strcmp(var, "transfer.unpacklimit") == 0) {
132 transfer_unpack_limit = git_config_int(var, value);
133 return 0;
134 }
135
136 if (strcmp(var, "receive.fsck.skiplist") == 0) {
137 const char *path;
138
139 if (git_config_pathname(&path, var, value))
140 return 1;
141 strbuf_addf(&fsck_msg_types, "%cskiplist=%s",
142 fsck_msg_types.len ? ',' : '=', path);
143 free((char *)path);
144 return 0;
145 }
146
147 if (skip_prefix(var, "receive.fsck.", &var)) {
148 if (is_valid_msg_type(var, value))
149 strbuf_addf(&fsck_msg_types, "%c%s=%s",
150 fsck_msg_types.len ? ',' : '=', var, value);
151 else
152 warning("Skipping unknown msg id '%s'", var);
153 return 0;
154 }
155
156 if (strcmp(var, "receive.fsckobjects") == 0) {
157 receive_fsck_objects = git_config_bool(var, value);
158 return 0;
159 }
160
161 if (strcmp(var, "transfer.fsckobjects") == 0) {
162 transfer_fsck_objects = git_config_bool(var, value);
163 return 0;
164 }
165
166 if (!strcmp(var, "receive.denycurrentbranch")) {
167 deny_current_branch = parse_deny_action(var, value);
168 return 0;
169 }
170
171 if (strcmp(var, "receive.denydeletecurrent") == 0) {
172 deny_delete_current = parse_deny_action(var, value);
173 return 0;
174 }
175
176 if (strcmp(var, "repack.usedeltabaseoffset") == 0) {
177 prefer_ofs_delta = git_config_bool(var, value);
178 return 0;
179 }
180
181 if (strcmp(var, "receive.updateserverinfo") == 0) {
182 auto_update_server_info = git_config_bool(var, value);
183 return 0;
184 }
185
186 if (strcmp(var, "receive.autogc") == 0) {
187 auto_gc = git_config_bool(var, value);
188 return 0;
189 }
190
191 if (strcmp(var, "receive.shallowupdate") == 0) {
192 shallow_update = git_config_bool(var, value);
193 return 0;
194 }
195
196 if (strcmp(var, "receive.certnonceseed") == 0)
197 return git_config_string(&cert_nonce_seed, var, value);
198
199 if (strcmp(var, "receive.certnonceslop") == 0) {
200 nonce_stamp_slop_limit = git_config_ulong(var, value);
201 return 0;
202 }
203
204 if (strcmp(var, "receive.advertiseatomic") == 0) {
205 advertise_atomic_push = git_config_bool(var, value);
206 return 0;
207 }
208
209 if (strcmp(var, "receive.advertisepushoptions") == 0) {
210 advertise_push_options = git_config_bool(var, value);
211 return 0;
212 }
213
214 if (strcmp(var, "receive.keepalive") == 0) {
215 keepalive_in_sec = git_config_int(var, value);
216 return 0;
217 }
218
219 if (strcmp(var, "receive.maxinputsize") == 0) {
220 max_input_size = git_config_int64(var, value);
221 return 0;
222 }
223
224 return git_default_config(var, value, cb);
225}
226
227static void show_ref(const char *path, const unsigned char *sha1)
228{
229 if (sent_capabilities) {
230 packet_write(1, "%s %s\n", sha1_to_hex(sha1), path);
231 } else {
232 struct strbuf cap = STRBUF_INIT;
233
234 strbuf_addstr(&cap,
235 "report-status delete-refs side-band-64k quiet");
236 if (advertise_atomic_push)
237 strbuf_addstr(&cap, " atomic");
238 if (prefer_ofs_delta)
239 strbuf_addstr(&cap, " ofs-delta");
240 if (push_cert_nonce)
241 strbuf_addf(&cap, " push-cert=%s", push_cert_nonce);
242 if (advertise_push_options)
243 strbuf_addstr(&cap, " push-options");
244 strbuf_addf(&cap, " agent=%s", git_user_agent_sanitized());
245 packet_write(1, "%s %s%c%s\n",
246 sha1_to_hex(sha1), path, 0, cap.buf);
247 strbuf_release(&cap);
248 sent_capabilities = 1;
249 }
250}
251
252static int show_ref_cb(const char *path_full, const struct object_id *oid,
253 int flag, void *unused)
254{
255 const char *path = strip_namespace(path_full);
256
257 if (ref_is_hidden(path, path_full))
258 return 0;
259
260 /*
261 * Advertise refs outside our current namespace as ".have"
262 * refs, so that the client can use them to minimize data
263 * transfer but will otherwise ignore them. This happens to
264 * cover ".have" that are thrown in by add_one_alternate_ref()
265 * to mark histories that are complete in our alternates as
266 * well.
267 */
268 if (!path)
269 path = ".have";
270 show_ref(path, oid->hash);
271 return 0;
272}
273
274static void show_one_alternate_sha1(const unsigned char sha1[20], void *unused)
275{
276 show_ref(".have", sha1);
277}
278
279static void collect_one_alternate_ref(const struct ref *ref, void *data)
280{
281 struct sha1_array *sa = data;
282 sha1_array_append(sa, ref->old_oid.hash);
283}
284
285static void write_head_info(void)
286{
287 struct sha1_array sa = SHA1_ARRAY_INIT;
288
289 for_each_alternate_ref(collect_one_alternate_ref, &sa);
290 sha1_array_for_each_unique(&sa, show_one_alternate_sha1, NULL);
291 sha1_array_clear(&sa);
292 for_each_ref(show_ref_cb, NULL);
293 if (!sent_capabilities)
294 show_ref("capabilities^{}", null_sha1);
295
296 advertise_shallow_grafts(1);
297
298 /* EOF */
299 packet_flush(1);
300}
301
302struct command {
303 struct command *next;
304 const char *error_string;
305 unsigned int skip_update:1,
306 did_not_exist:1;
307 int index;
308 unsigned char old_sha1[20];
309 unsigned char new_sha1[20];
310 char ref_name[FLEX_ARRAY]; /* more */
311};
312
313static void rp_error(const char *err, ...) __attribute__((format (printf, 1, 2)));
314static void rp_warning(const char *err, ...) __attribute__((format (printf, 1, 2)));
315
316static void report_message(const char *prefix, const char *err, va_list params)
317{
318 int sz;
319 char msg[4096];
320
321 sz = xsnprintf(msg, sizeof(msg), "%s", prefix);
322 sz += vsnprintf(msg + sz, sizeof(msg) - sz, err, params);
323 if (sz > (sizeof(msg) - 1))
324 sz = sizeof(msg) - 1;
325 msg[sz++] = '\n';
326
327 if (use_sideband)
328 send_sideband(1, 2, msg, sz, use_sideband);
329 else
330 xwrite(2, msg, sz);
331}
332
333static void rp_warning(const char *err, ...)
334{
335 va_list params;
336 va_start(params, err);
337 report_message("warning: ", err, params);
338 va_end(params);
339}
340
341static void rp_error(const char *err, ...)
342{
343 va_list params;
344 va_start(params, err);
345 report_message("error: ", err, params);
346 va_end(params);
347}
348
349static int copy_to_sideband(int in, int out, void *arg)
350{
351 char data[128];
352 int keepalive_active = 0;
353
354 if (keepalive_in_sec <= 0)
355 use_keepalive = KEEPALIVE_NEVER;
356 if (use_keepalive == KEEPALIVE_ALWAYS)
357 keepalive_active = 1;
358
359 while (1) {
360 ssize_t sz;
361
362 if (keepalive_active) {
363 struct pollfd pfd;
364 int ret;
365
366 pfd.fd = in;
367 pfd.events = POLLIN;
368 ret = poll(&pfd, 1, 1000 * keepalive_in_sec);
369
370 if (ret < 0) {
371 if (errno == EINTR)
372 continue;
373 else
374 break;
375 } else if (ret == 0) {
376 /* no data; send a keepalive packet */
377 static const char buf[] = "0005\1";
378 write_or_die(1, buf, sizeof(buf) - 1);
379 continue;
380 } /* else there is actual data to read */
381 }
382
383 sz = xread(in, data, sizeof(data));
384 if (sz <= 0)
385 break;
386
387 if (use_keepalive == KEEPALIVE_AFTER_NUL && !keepalive_active) {
388 const char *p = memchr(data, '\0', sz);
389 if (p) {
390 /*
391 * The NUL tells us to start sending keepalives. Make
392 * sure we send any other data we read along
393 * with it.
394 */
395 keepalive_active = 1;
396 send_sideband(1, 2, data, p - data, use_sideband);
397 send_sideband(1, 2, p + 1, sz - (p - data + 1), use_sideband);
398 continue;
399 }
400 }
401
402 /*
403 * Either we're not looking for a NUL signal, or we didn't see
404 * it yet; just pass along the data.
405 */
406 send_sideband(1, 2, data, sz, use_sideband);
407 }
408 close(in);
409 return 0;
410}
411
412#define HMAC_BLOCK_SIZE 64
413
414static void hmac_sha1(unsigned char *out,
415 const char *key_in, size_t key_len,
416 const char *text, size_t text_len)
417{
418 unsigned char key[HMAC_BLOCK_SIZE];
419 unsigned char k_ipad[HMAC_BLOCK_SIZE];
420 unsigned char k_opad[HMAC_BLOCK_SIZE];
421 int i;
422 git_SHA_CTX ctx;
423
424 /* RFC 2104 2. (1) */
425 memset(key, '\0', HMAC_BLOCK_SIZE);
426 if (HMAC_BLOCK_SIZE < key_len) {
427 git_SHA1_Init(&ctx);
428 git_SHA1_Update(&ctx, key_in, key_len);
429 git_SHA1_Final(key, &ctx);
430 } else {
431 memcpy(key, key_in, key_len);
432 }
433
434 /* RFC 2104 2. (2) & (5) */
435 for (i = 0; i < sizeof(key); i++) {
436 k_ipad[i] = key[i] ^ 0x36;
437 k_opad[i] = key[i] ^ 0x5c;
438 }
439
440 /* RFC 2104 2. (3) & (4) */
441 git_SHA1_Init(&ctx);
442 git_SHA1_Update(&ctx, k_ipad, sizeof(k_ipad));
443 git_SHA1_Update(&ctx, text, text_len);
444 git_SHA1_Final(out, &ctx);
445
446 /* RFC 2104 2. (6) & (7) */
447 git_SHA1_Init(&ctx);
448 git_SHA1_Update(&ctx, k_opad, sizeof(k_opad));
449 git_SHA1_Update(&ctx, out, 20);
450 git_SHA1_Final(out, &ctx);
451}
452
453static char *prepare_push_cert_nonce(const char *path, unsigned long stamp)
454{
455 struct strbuf buf = STRBUF_INIT;
456 unsigned char sha1[20];
457
458 strbuf_addf(&buf, "%s:%lu", path, stamp);
459 hmac_sha1(sha1, buf.buf, buf.len, cert_nonce_seed, strlen(cert_nonce_seed));;
460 strbuf_release(&buf);
461
462 /* RFC 2104 5. HMAC-SHA1-80 */
463 strbuf_addf(&buf, "%lu-%.*s", stamp, 20, sha1_to_hex(sha1));
464 return strbuf_detach(&buf, NULL);
465}
466
467/*
468 * NEEDSWORK: reuse find_commit_header() from jk/commit-author-parsing
469 * after dropping "_commit" from its name and possibly moving it out
470 * of commit.c
471 */
472static char *find_header(const char *msg, size_t len, const char *key)
473{
474 int key_len = strlen(key);
475 const char *line = msg;
476
477 while (line && line < msg + len) {
478 const char *eol = strchrnul(line, '\n');
479
480 if ((msg + len <= eol) || line == eol)
481 return NULL;
482 if (line + key_len < eol &&
483 !memcmp(line, key, key_len) && line[key_len] == ' ') {
484 int offset = key_len + 1;
485 return xmemdupz(line + offset, (eol - line) - offset);
486 }
487 line = *eol ? eol + 1 : NULL;
488 }
489 return NULL;
490}
491
492static const char *check_nonce(const char *buf, size_t len)
493{
494 char *nonce = find_header(buf, len, "nonce");
495 unsigned long stamp, ostamp;
496 char *bohmac, *expect = NULL;
497 const char *retval = NONCE_BAD;
498
499 if (!nonce) {
500 retval = NONCE_MISSING;
501 goto leave;
502 } else if (!push_cert_nonce) {
503 retval = NONCE_UNSOLICITED;
504 goto leave;
505 } else if (!strcmp(push_cert_nonce, nonce)) {
506 retval = NONCE_OK;
507 goto leave;
508 }
509
510 if (!stateless_rpc) {
511 /* returned nonce MUST match what we gave out earlier */
512 retval = NONCE_BAD;
513 goto leave;
514 }
515
516 /*
517 * In stateless mode, we may be receiving a nonce issued by
518 * another instance of the server that serving the same
519 * repository, and the timestamps may not match, but the
520 * nonce-seed and dir should match, so we can recompute and
521 * report the time slop.
522 *
523 * In addition, when a nonce issued by another instance has
524 * timestamp within receive.certnonceslop seconds, we pretend
525 * as if we issued that nonce when reporting to the hook.
526 */
527
528 /* nonce is concat(<seconds-since-epoch>, "-", <hmac>) */
529 if (*nonce <= '0' || '9' < *nonce) {
530 retval = NONCE_BAD;
531 goto leave;
532 }
533 stamp = strtoul(nonce, &bohmac, 10);
534 if (bohmac == nonce || bohmac[0] != '-') {
535 retval = NONCE_BAD;
536 goto leave;
537 }
538
539 expect = prepare_push_cert_nonce(service_dir, stamp);
540 if (strcmp(expect, nonce)) {
541 /* Not what we would have signed earlier */
542 retval = NONCE_BAD;
543 goto leave;
544 }
545
546 /*
547 * By how many seconds is this nonce stale? Negative value
548 * would mean it was issued by another server with its clock
549 * skewed in the future.
550 */
551 ostamp = strtoul(push_cert_nonce, NULL, 10);
552 nonce_stamp_slop = (long)ostamp - (long)stamp;
553
554 if (nonce_stamp_slop_limit &&
555 labs(nonce_stamp_slop) <= nonce_stamp_slop_limit) {
556 /*
557 * Pretend as if the received nonce (which passes the
558 * HMAC check, so it is not a forged by third-party)
559 * is what we issued.
560 */
561 free((void *)push_cert_nonce);
562 push_cert_nonce = xstrdup(nonce);
563 retval = NONCE_OK;
564 } else {
565 retval = NONCE_SLOP;
566 }
567
568leave:
569 free(nonce);
570 free(expect);
571 return retval;
572}
573
574static void prepare_push_cert_sha1(struct child_process *proc)
575{
576 static int already_done;
577
578 if (!push_cert.len)
579 return;
580
581 if (!already_done) {
582 struct strbuf gpg_output = STRBUF_INIT;
583 struct strbuf gpg_status = STRBUF_INIT;
584 int bogs /* beginning_of_gpg_sig */;
585
586 already_done = 1;
587 if (write_sha1_file(push_cert.buf, push_cert.len, "blob", push_cert_sha1))
588 hashclr(push_cert_sha1);
589
590 memset(&sigcheck, '\0', sizeof(sigcheck));
591 sigcheck.result = 'N';
592
593 bogs = parse_signature(push_cert.buf, push_cert.len);
594 if (verify_signed_buffer(push_cert.buf, bogs,
595 push_cert.buf + bogs, push_cert.len - bogs,
596 &gpg_output, &gpg_status) < 0) {
597 ; /* error running gpg */
598 } else {
599 sigcheck.payload = push_cert.buf;
600 sigcheck.gpg_output = gpg_output.buf;
601 sigcheck.gpg_status = gpg_status.buf;
602 parse_gpg_output(&sigcheck);
603 }
604
605 strbuf_release(&gpg_output);
606 strbuf_release(&gpg_status);
607 nonce_status = check_nonce(push_cert.buf, bogs);
608 }
609 if (!is_null_sha1(push_cert_sha1)) {
610 argv_array_pushf(&proc->env_array, "GIT_PUSH_CERT=%s",
611 sha1_to_hex(push_cert_sha1));
612 argv_array_pushf(&proc->env_array, "GIT_PUSH_CERT_SIGNER=%s",
613 sigcheck.signer ? sigcheck.signer : "");
614 argv_array_pushf(&proc->env_array, "GIT_PUSH_CERT_KEY=%s",
615 sigcheck.key ? sigcheck.key : "");
616 argv_array_pushf(&proc->env_array, "GIT_PUSH_CERT_STATUS=%c",
617 sigcheck.result);
618 if (push_cert_nonce) {
619 argv_array_pushf(&proc->env_array,
620 "GIT_PUSH_CERT_NONCE=%s",
621 push_cert_nonce);
622 argv_array_pushf(&proc->env_array,
623 "GIT_PUSH_CERT_NONCE_STATUS=%s",
624 nonce_status);
625 if (nonce_status == NONCE_SLOP)
626 argv_array_pushf(&proc->env_array,
627 "GIT_PUSH_CERT_NONCE_SLOP=%ld",
628 nonce_stamp_slop);
629 }
630 }
631}
632
633struct receive_hook_feed_state {
634 struct command *cmd;
635 int skip_broken;
636 struct strbuf buf;
637 const struct string_list *push_options;
638};
639
640typedef int (*feed_fn)(void *, const char **, size_t *);
641static int run_and_feed_hook(const char *hook_name, feed_fn feed,
642 struct receive_hook_feed_state *feed_state)
643{
644 struct child_process proc = CHILD_PROCESS_INIT;
645 struct async muxer;
646 const char *argv[2];
647 int code;
648
649 argv[0] = find_hook(hook_name);
650 if (!argv[0])
651 return 0;
652
653 argv[1] = NULL;
654
655 proc.argv = argv;
656 proc.in = -1;
657 proc.stdout_to_stderr = 1;
658 if (feed_state->push_options) {
659 int i;
660 for (i = 0; i < feed_state->push_options->nr; i++)
661 argv_array_pushf(&proc.env_array,
662 "GIT_PUSH_OPTION_%d=%s", i,
663 feed_state->push_options->items[i].string);
664 argv_array_pushf(&proc.env_array, "GIT_PUSH_OPTION_COUNT=%d",
665 feed_state->push_options->nr);
666 } else
667 argv_array_pushf(&proc.env_array, "GIT_PUSH_OPTION_COUNT");
668
669 if (tmp_objdir)
670 argv_array_pushv(&proc.env_array, tmp_objdir_env(tmp_objdir));
671
672 if (use_sideband) {
673 memset(&muxer, 0, sizeof(muxer));
674 muxer.proc = copy_to_sideband;
675 muxer.in = -1;
676 code = start_async(&muxer);
677 if (code)
678 return code;
679 proc.err = muxer.in;
680 }
681
682 prepare_push_cert_sha1(&proc);
683
684 code = start_command(&proc);
685 if (code) {
686 if (use_sideband)
687 finish_async(&muxer);
688 return code;
689 }
690
691 sigchain_push(SIGPIPE, SIG_IGN);
692
693 while (1) {
694 const char *buf;
695 size_t n;
696 if (feed(feed_state, &buf, &n))
697 break;
698 if (write_in_full(proc.in, buf, n) != n)
699 break;
700 }
701 close(proc.in);
702 if (use_sideband)
703 finish_async(&muxer);
704
705 sigchain_pop(SIGPIPE);
706
707 return finish_command(&proc);
708}
709
710static int feed_receive_hook(void *state_, const char **bufp, size_t *sizep)
711{
712 struct receive_hook_feed_state *state = state_;
713 struct command *cmd = state->cmd;
714
715 while (cmd &&
716 state->skip_broken && (cmd->error_string || cmd->did_not_exist))
717 cmd = cmd->next;
718 if (!cmd)
719 return -1; /* EOF */
720 strbuf_reset(&state->buf);
721 strbuf_addf(&state->buf, "%s %s %s\n",
722 sha1_to_hex(cmd->old_sha1), sha1_to_hex(cmd->new_sha1),
723 cmd->ref_name);
724 state->cmd = cmd->next;
725 if (bufp) {
726 *bufp = state->buf.buf;
727 *sizep = state->buf.len;
728 }
729 return 0;
730}
731
732static int run_receive_hook(struct command *commands,
733 const char *hook_name,
734 int skip_broken,
735 const struct string_list *push_options)
736{
737 struct receive_hook_feed_state state;
738 int status;
739
740 strbuf_init(&state.buf, 0);
741 state.cmd = commands;
742 state.skip_broken = skip_broken;
743 if (feed_receive_hook(&state, NULL, NULL))
744 return 0;
745 state.cmd = commands;
746 state.push_options = push_options;
747 status = run_and_feed_hook(hook_name, feed_receive_hook, &state);
748 strbuf_release(&state.buf);
749 return status;
750}
751
752static int run_update_hook(struct command *cmd)
753{
754 const char *argv[5];
755 struct child_process proc = CHILD_PROCESS_INIT;
756 int code;
757
758 argv[0] = find_hook("update");
759 if (!argv[0])
760 return 0;
761
762 argv[1] = cmd->ref_name;
763 argv[2] = sha1_to_hex(cmd->old_sha1);
764 argv[3] = sha1_to_hex(cmd->new_sha1);
765 argv[4] = NULL;
766
767 proc.no_stdin = 1;
768 proc.stdout_to_stderr = 1;
769 proc.err = use_sideband ? -1 : 0;
770 proc.argv = argv;
771 proc.env = tmp_objdir_env(tmp_objdir);
772
773 code = start_command(&proc);
774 if (code)
775 return code;
776 if (use_sideband)
777 copy_to_sideband(proc.err, -1, NULL);
778 return finish_command(&proc);
779}
780
781static int is_ref_checked_out(const char *ref)
782{
783 if (is_bare_repository())
784 return 0;
785
786 if (!head_name)
787 return 0;
788 return !strcmp(head_name, ref);
789}
790
791static char *refuse_unconfigured_deny_msg =
792 N_("By default, updating the current branch in a non-bare repository\n"
793 "is denied, because it will make the index and work tree inconsistent\n"
794 "with what you pushed, and will require 'git reset --hard' to match\n"
795 "the work tree to HEAD.\n"
796 "\n"
797 "You can set 'receive.denyCurrentBranch' configuration variable to\n"
798 "'ignore' or 'warn' in the remote repository to allow pushing into\n"
799 "its current branch; however, this is not recommended unless you\n"
800 "arranged to update its work tree to match what you pushed in some\n"
801 "other way.\n"
802 "\n"
803 "To squelch this message and still keep the default behaviour, set\n"
804 "'receive.denyCurrentBranch' configuration variable to 'refuse'.");
805
806static void refuse_unconfigured_deny(void)
807{
808 rp_error("%s", _(refuse_unconfigured_deny_msg));
809}
810
811static char *refuse_unconfigured_deny_delete_current_msg =
812 N_("By default, deleting the current branch is denied, because the next\n"
813 "'git clone' won't result in any file checked out, causing confusion.\n"
814 "\n"
815 "You can set 'receive.denyDeleteCurrent' configuration variable to\n"
816 "'warn' or 'ignore' in the remote repository to allow deleting the\n"
817 "current branch, with or without a warning message.\n"
818 "\n"
819 "To squelch this message, you can set it to 'refuse'.");
820
821static void refuse_unconfigured_deny_delete_current(void)
822{
823 rp_error("%s", _(refuse_unconfigured_deny_delete_current_msg));
824}
825
826static int command_singleton_iterator(void *cb_data, unsigned char sha1[20]);
827static int update_shallow_ref(struct command *cmd, struct shallow_info *si)
828{
829 static struct lock_file shallow_lock;
830 struct sha1_array extra = SHA1_ARRAY_INIT;
831 struct check_connected_options opt = CHECK_CONNECTED_INIT;
832 uint32_t mask = 1 << (cmd->index % 32);
833 int i;
834
835 trace_printf_key(&trace_shallow,
836 "shallow: update_shallow_ref %s\n", cmd->ref_name);
837 for (i = 0; i < si->shallow->nr; i++)
838 if (si->used_shallow[i] &&
839 (si->used_shallow[i][cmd->index / 32] & mask) &&
840 !delayed_reachability_test(si, i))
841 sha1_array_append(&extra, si->shallow->sha1[i]);
842
843 opt.env = tmp_objdir_env(tmp_objdir);
844 setup_alternate_shallow(&shallow_lock, &opt.shallow_file, &extra);
845 if (check_connected(command_singleton_iterator, cmd, &opt)) {
846 rollback_lock_file(&shallow_lock);
847 sha1_array_clear(&extra);
848 return -1;
849 }
850
851 commit_lock_file(&shallow_lock);
852
853 /*
854 * Make sure setup_alternate_shallow() for the next ref does
855 * not lose these new roots..
856 */
857 for (i = 0; i < extra.nr; i++)
858 register_shallow(extra.sha1[i]);
859
860 si->shallow_ref[cmd->index] = 0;
861 sha1_array_clear(&extra);
862 return 0;
863}
864
865/*
866 * NEEDSWORK: we should consolidate various implementions of "are we
867 * on an unborn branch?" test into one, and make the unified one more
868 * robust. !get_sha1() based check used here and elsewhere would not
869 * allow us to tell an unborn branch from corrupt ref, for example.
870 * For the purpose of fixing "deploy-to-update does not work when
871 * pushing into an empty repository" issue, this should suffice for
872 * now.
873 */
874static int head_has_history(void)
875{
876 unsigned char sha1[20];
877
878 return !get_sha1("HEAD", sha1);
879}
880
881static const char *push_to_deploy(unsigned char *sha1,
882 struct argv_array *env,
883 const char *work_tree)
884{
885 const char *update_refresh[] = {
886 "update-index", "-q", "--ignore-submodules", "--refresh", NULL
887 };
888 const char *diff_files[] = {
889 "diff-files", "--quiet", "--ignore-submodules", "--", NULL
890 };
891 const char *diff_index[] = {
892 "diff-index", "--quiet", "--cached", "--ignore-submodules",
893 NULL, "--", NULL
894 };
895 const char *read_tree[] = {
896 "read-tree", "-u", "-m", NULL, NULL
897 };
898 struct child_process child = CHILD_PROCESS_INIT;
899
900 child.argv = update_refresh;
901 child.env = env->argv;
902 child.dir = work_tree;
903 child.no_stdin = 1;
904 child.stdout_to_stderr = 1;
905 child.git_cmd = 1;
906 if (run_command(&child))
907 return "Up-to-date check failed";
908
909 /* run_command() does not clean up completely; reinitialize */
910 child_process_init(&child);
911 child.argv = diff_files;
912 child.env = env->argv;
913 child.dir = work_tree;
914 child.no_stdin = 1;
915 child.stdout_to_stderr = 1;
916 child.git_cmd = 1;
917 if (run_command(&child))
918 return "Working directory has unstaged changes";
919
920 /* diff-index with either HEAD or an empty tree */
921 diff_index[4] = head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX;
922
923 child_process_init(&child);
924 child.argv = diff_index;
925 child.env = env->argv;
926 child.no_stdin = 1;
927 child.no_stdout = 1;
928 child.stdout_to_stderr = 0;
929 child.git_cmd = 1;
930 if (run_command(&child))
931 return "Working directory has staged changes";
932
933 read_tree[3] = sha1_to_hex(sha1);
934 child_process_init(&child);
935 child.argv = read_tree;
936 child.env = env->argv;
937 child.dir = work_tree;
938 child.no_stdin = 1;
939 child.no_stdout = 1;
940 child.stdout_to_stderr = 0;
941 child.git_cmd = 1;
942 if (run_command(&child))
943 return "Could not update working tree to new HEAD";
944
945 return NULL;
946}
947
948static const char *push_to_checkout_hook = "push-to-checkout";
949
950static const char *push_to_checkout(unsigned char *sha1,
951 struct argv_array *env,
952 const char *work_tree)
953{
954 argv_array_pushf(env, "GIT_WORK_TREE=%s", absolute_path(work_tree));
955 if (run_hook_le(env->argv, push_to_checkout_hook,
956 sha1_to_hex(sha1), NULL))
957 return "push-to-checkout hook declined";
958 else
959 return NULL;
960}
961
962static const char *update_worktree(unsigned char *sha1)
963{
964 const char *retval;
965 const char *work_tree = git_work_tree_cfg ? git_work_tree_cfg : "..";
966 struct argv_array env = ARGV_ARRAY_INIT;
967
968 if (is_bare_repository())
969 return "denyCurrentBranch = updateInstead needs a worktree";
970
971 argv_array_pushf(&env, "GIT_DIR=%s", absolute_path(get_git_dir()));
972
973 if (!find_hook(push_to_checkout_hook))
974 retval = push_to_deploy(sha1, &env, work_tree);
975 else
976 retval = push_to_checkout(sha1, &env, work_tree);
977
978 argv_array_clear(&env);
979 return retval;
980}
981
982static const char *update(struct command *cmd, struct shallow_info *si)
983{
984 const char *name = cmd->ref_name;
985 struct strbuf namespaced_name_buf = STRBUF_INIT;
986 const char *namespaced_name, *ret;
987 unsigned char *old_sha1 = cmd->old_sha1;
988 unsigned char *new_sha1 = cmd->new_sha1;
989
990 /* only refs/... are allowed */
991 if (!starts_with(name, "refs/") || check_refname_format(name + 5, 0)) {
992 rp_error("refusing to create funny ref '%s' remotely", name);
993 return "funny refname";
994 }
995
996 strbuf_addf(&namespaced_name_buf, "%s%s", get_git_namespace(), name);
997 namespaced_name = strbuf_detach(&namespaced_name_buf, NULL);
998
999 if (is_ref_checked_out(namespaced_name)) {
1000 switch (deny_current_branch) {
1001 case DENY_IGNORE:
1002 break;
1003 case DENY_WARN:
1004 rp_warning("updating the current branch");
1005 break;
1006 case DENY_REFUSE:
1007 case DENY_UNCONFIGURED:
1008 rp_error("refusing to update checked out branch: %s", name);
1009 if (deny_current_branch == DENY_UNCONFIGURED)
1010 refuse_unconfigured_deny();
1011 return "branch is currently checked out";
1012 case DENY_UPDATE_INSTEAD:
1013 ret = update_worktree(new_sha1);
1014 if (ret)
1015 return ret;
1016 break;
1017 }
1018 }
1019
1020 if (!is_null_sha1(new_sha1) && !has_sha1_file(new_sha1)) {
1021 error("unpack should have generated %s, "
1022 "but I can't find it!", sha1_to_hex(new_sha1));
1023 return "bad pack";
1024 }
1025
1026 if (!is_null_sha1(old_sha1) && is_null_sha1(new_sha1)) {
1027 if (deny_deletes && starts_with(name, "refs/heads/")) {
1028 rp_error("denying ref deletion for %s", name);
1029 return "deletion prohibited";
1030 }
1031
1032 if (head_name && !strcmp(namespaced_name, head_name)) {
1033 switch (deny_delete_current) {
1034 case DENY_IGNORE:
1035 break;
1036 case DENY_WARN:
1037 rp_warning("deleting the current branch");
1038 break;
1039 case DENY_REFUSE:
1040 case DENY_UNCONFIGURED:
1041 case DENY_UPDATE_INSTEAD:
1042 if (deny_delete_current == DENY_UNCONFIGURED)
1043 refuse_unconfigured_deny_delete_current();
1044 rp_error("refusing to delete the current branch: %s", name);
1045 return "deletion of the current branch prohibited";
1046 default:
1047 return "Invalid denyDeleteCurrent setting";
1048 }
1049 }
1050 }
1051
1052 if (deny_non_fast_forwards && !is_null_sha1(new_sha1) &&
1053 !is_null_sha1(old_sha1) &&
1054 starts_with(name, "refs/heads/")) {
1055 struct object *old_object, *new_object;
1056 struct commit *old_commit, *new_commit;
1057
1058 old_object = parse_object(old_sha1);
1059 new_object = parse_object(new_sha1);
1060
1061 if (!old_object || !new_object ||
1062 old_object->type != OBJ_COMMIT ||
1063 new_object->type != OBJ_COMMIT) {
1064 error("bad sha1 objects for %s", name);
1065 return "bad ref";
1066 }
1067 old_commit = (struct commit *)old_object;
1068 new_commit = (struct commit *)new_object;
1069 if (!in_merge_bases(old_commit, new_commit)) {
1070 rp_error("denying non-fast-forward %s"
1071 " (you should pull first)", name);
1072 return "non-fast-forward";
1073 }
1074 }
1075 if (run_update_hook(cmd)) {
1076 rp_error("hook declined to update %s", name);
1077 return "hook declined";
1078 }
1079
1080 if (is_null_sha1(new_sha1)) {
1081 struct strbuf err = STRBUF_INIT;
1082 if (!parse_object(old_sha1)) {
1083 old_sha1 = NULL;
1084 if (ref_exists(name)) {
1085 rp_warning("Allowing deletion of corrupt ref.");
1086 } else {
1087 rp_warning("Deleting a non-existent ref.");
1088 cmd->did_not_exist = 1;
1089 }
1090 }
1091 if (ref_transaction_delete(transaction,
1092 namespaced_name,
1093 old_sha1,
1094 0, "push", &err)) {
1095 rp_error("%s", err.buf);
1096 strbuf_release(&err);
1097 return "failed to delete";
1098 }
1099 strbuf_release(&err);
1100 return NULL; /* good */
1101 }
1102 else {
1103 struct strbuf err = STRBUF_INIT;
1104 if (shallow_update && si->shallow_ref[cmd->index] &&
1105 update_shallow_ref(cmd, si))
1106 return "shallow error";
1107
1108 if (ref_transaction_update(transaction,
1109 namespaced_name,
1110 new_sha1, old_sha1,
1111 0, "push",
1112 &err)) {
1113 rp_error("%s", err.buf);
1114 strbuf_release(&err);
1115
1116 return "failed to update ref";
1117 }
1118 strbuf_release(&err);
1119
1120 return NULL; /* good */
1121 }
1122}
1123
1124static void run_update_post_hook(struct command *commands)
1125{
1126 struct command *cmd;
1127 int argc;
1128 struct child_process proc = CHILD_PROCESS_INIT;
1129 const char *hook;
1130
1131 hook = find_hook("post-update");
1132 for (argc = 0, cmd = commands; cmd; cmd = cmd->next) {
1133 if (cmd->error_string || cmd->did_not_exist)
1134 continue;
1135 argc++;
1136 }
1137 if (!argc || !hook)
1138 return;
1139
1140 argv_array_push(&proc.args, hook);
1141 for (cmd = commands; cmd; cmd = cmd->next) {
1142 if (cmd->error_string || cmd->did_not_exist)
1143 continue;
1144 argv_array_push(&proc.args, cmd->ref_name);
1145 }
1146
1147 proc.no_stdin = 1;
1148 proc.stdout_to_stderr = 1;
1149 proc.err = use_sideband ? -1 : 0;
1150
1151 if (!start_command(&proc)) {
1152 if (use_sideband)
1153 copy_to_sideband(proc.err, -1, NULL);
1154 finish_command(&proc);
1155 }
1156}
1157
1158static void check_aliased_update(struct command *cmd, struct string_list *list)
1159{
1160 struct strbuf buf = STRBUF_INIT;
1161 const char *dst_name;
1162 struct string_list_item *item;
1163 struct command *dst_cmd;
1164 unsigned char sha1[GIT_SHA1_RAWSZ];
1165 char cmd_oldh[GIT_SHA1_HEXSZ + 1],
1166 cmd_newh[GIT_SHA1_HEXSZ + 1],
1167 dst_oldh[GIT_SHA1_HEXSZ + 1],
1168 dst_newh[GIT_SHA1_HEXSZ + 1];
1169 int flag;
1170
1171 strbuf_addf(&buf, "%s%s", get_git_namespace(), cmd->ref_name);
1172 dst_name = resolve_ref_unsafe(buf.buf, 0, sha1, &flag);
1173 strbuf_release(&buf);
1174
1175 if (!(flag & REF_ISSYMREF))
1176 return;
1177
1178 if (!dst_name) {
1179 rp_error("refusing update to broken symref '%s'", cmd->ref_name);
1180 cmd->skip_update = 1;
1181 cmd->error_string = "broken symref";
1182 return;
1183 }
1184 dst_name = strip_namespace(dst_name);
1185
1186 if ((item = string_list_lookup(list, dst_name)) == NULL)
1187 return;
1188
1189 cmd->skip_update = 1;
1190
1191 dst_cmd = (struct command *) item->util;
1192
1193 if (!hashcmp(cmd->old_sha1, dst_cmd->old_sha1) &&
1194 !hashcmp(cmd->new_sha1, dst_cmd->new_sha1))
1195 return;
1196
1197 dst_cmd->skip_update = 1;
1198
1199 find_unique_abbrev_r(cmd_oldh, cmd->old_sha1, DEFAULT_ABBREV);
1200 find_unique_abbrev_r(cmd_newh, cmd->new_sha1, DEFAULT_ABBREV);
1201 find_unique_abbrev_r(dst_oldh, dst_cmd->old_sha1, DEFAULT_ABBREV);
1202 find_unique_abbrev_r(dst_newh, dst_cmd->new_sha1, DEFAULT_ABBREV);
1203 rp_error("refusing inconsistent update between symref '%s' (%s..%s) and"
1204 " its target '%s' (%s..%s)",
1205 cmd->ref_name, cmd_oldh, cmd_newh,
1206 dst_cmd->ref_name, dst_oldh, dst_newh);
1207
1208 cmd->error_string = dst_cmd->error_string =
1209 "inconsistent aliased update";
1210}
1211
1212static void check_aliased_updates(struct command *commands)
1213{
1214 struct command *cmd;
1215 struct string_list ref_list = STRING_LIST_INIT_NODUP;
1216
1217 for (cmd = commands; cmd; cmd = cmd->next) {
1218 struct string_list_item *item =
1219 string_list_append(&ref_list, cmd->ref_name);
1220 item->util = (void *)cmd;
1221 }
1222 string_list_sort(&ref_list);
1223
1224 for (cmd = commands; cmd; cmd = cmd->next) {
1225 if (!cmd->error_string)
1226 check_aliased_update(cmd, &ref_list);
1227 }
1228
1229 string_list_clear(&ref_list, 0);
1230}
1231
1232static int command_singleton_iterator(void *cb_data, unsigned char sha1[20])
1233{
1234 struct command **cmd_list = cb_data;
1235 struct command *cmd = *cmd_list;
1236
1237 if (!cmd || is_null_sha1(cmd->new_sha1))
1238 return -1; /* end of list */
1239 *cmd_list = NULL; /* this returns only one */
1240 hashcpy(sha1, cmd->new_sha1);
1241 return 0;
1242}
1243
1244static void set_connectivity_errors(struct command *commands,
1245 struct shallow_info *si)
1246{
1247 struct command *cmd;
1248
1249 for (cmd = commands; cmd; cmd = cmd->next) {
1250 struct command *singleton = cmd;
1251 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1252
1253 if (shallow_update && si->shallow_ref[cmd->index])
1254 /* to be checked in update_shallow_ref() */
1255 continue;
1256
1257 opt.env = tmp_objdir_env(tmp_objdir);
1258 if (!check_connected(command_singleton_iterator, &singleton,
1259 &opt))
1260 continue;
1261
1262 cmd->error_string = "missing necessary objects";
1263 }
1264}
1265
1266struct iterate_data {
1267 struct command *cmds;
1268 struct shallow_info *si;
1269};
1270
1271static int iterate_receive_command_list(void *cb_data, unsigned char sha1[20])
1272{
1273 struct iterate_data *data = cb_data;
1274 struct command **cmd_list = &data->cmds;
1275 struct command *cmd = *cmd_list;
1276
1277 for (; cmd; cmd = cmd->next) {
1278 if (shallow_update && data->si->shallow_ref[cmd->index])
1279 /* to be checked in update_shallow_ref() */
1280 continue;
1281 if (!is_null_sha1(cmd->new_sha1) && !cmd->skip_update) {
1282 hashcpy(sha1, cmd->new_sha1);
1283 *cmd_list = cmd->next;
1284 return 0;
1285 }
1286 }
1287 *cmd_list = NULL;
1288 return -1; /* end of list */
1289}
1290
1291static void reject_updates_to_hidden(struct command *commands)
1292{
1293 struct strbuf refname_full = STRBUF_INIT;
1294 size_t prefix_len;
1295 struct command *cmd;
1296
1297 strbuf_addstr(&refname_full, get_git_namespace());
1298 prefix_len = refname_full.len;
1299
1300 for (cmd = commands; cmd; cmd = cmd->next) {
1301 if (cmd->error_string)
1302 continue;
1303
1304 strbuf_setlen(&refname_full, prefix_len);
1305 strbuf_addstr(&refname_full, cmd->ref_name);
1306
1307 if (!ref_is_hidden(cmd->ref_name, refname_full.buf))
1308 continue;
1309 if (is_null_sha1(cmd->new_sha1))
1310 cmd->error_string = "deny deleting a hidden ref";
1311 else
1312 cmd->error_string = "deny updating a hidden ref";
1313 }
1314
1315 strbuf_release(&refname_full);
1316}
1317
1318static int should_process_cmd(struct command *cmd)
1319{
1320 return !cmd->error_string && !cmd->skip_update;
1321}
1322
1323static void warn_if_skipped_connectivity_check(struct command *commands,
1324 struct shallow_info *si)
1325{
1326 struct command *cmd;
1327 int checked_connectivity = 1;
1328
1329 for (cmd = commands; cmd; cmd = cmd->next) {
1330 if (should_process_cmd(cmd) && si->shallow_ref[cmd->index]) {
1331 error("BUG: connectivity check has not been run on ref %s",
1332 cmd->ref_name);
1333 checked_connectivity = 0;
1334 }
1335 }
1336 if (!checked_connectivity)
1337 die("BUG: connectivity check skipped???");
1338}
1339
1340static void execute_commands_non_atomic(struct command *commands,
1341 struct shallow_info *si)
1342{
1343 struct command *cmd;
1344 struct strbuf err = STRBUF_INIT;
1345
1346 for (cmd = commands; cmd; cmd = cmd->next) {
1347 if (!should_process_cmd(cmd))
1348 continue;
1349
1350 transaction = ref_transaction_begin(&err);
1351 if (!transaction) {
1352 rp_error("%s", err.buf);
1353 strbuf_reset(&err);
1354 cmd->error_string = "transaction failed to start";
1355 continue;
1356 }
1357
1358 cmd->error_string = update(cmd, si);
1359
1360 if (!cmd->error_string
1361 && ref_transaction_commit(transaction, &err)) {
1362 rp_error("%s", err.buf);
1363 strbuf_reset(&err);
1364 cmd->error_string = "failed to update ref";
1365 }
1366 ref_transaction_free(transaction);
1367 }
1368 strbuf_release(&err);
1369}
1370
1371static void execute_commands_atomic(struct command *commands,
1372 struct shallow_info *si)
1373{
1374 struct command *cmd;
1375 struct strbuf err = STRBUF_INIT;
1376 const char *reported_error = "atomic push failure";
1377
1378 transaction = ref_transaction_begin(&err);
1379 if (!transaction) {
1380 rp_error("%s", err.buf);
1381 strbuf_reset(&err);
1382 reported_error = "transaction failed to start";
1383 goto failure;
1384 }
1385
1386 for (cmd = commands; cmd; cmd = cmd->next) {
1387 if (!should_process_cmd(cmd))
1388 continue;
1389
1390 cmd->error_string = update(cmd, si);
1391
1392 if (cmd->error_string)
1393 goto failure;
1394 }
1395
1396 if (ref_transaction_commit(transaction, &err)) {
1397 rp_error("%s", err.buf);
1398 reported_error = "atomic transaction failed";
1399 goto failure;
1400 }
1401 goto cleanup;
1402
1403failure:
1404 for (cmd = commands; cmd; cmd = cmd->next)
1405 if (!cmd->error_string)
1406 cmd->error_string = reported_error;
1407
1408cleanup:
1409 ref_transaction_free(transaction);
1410 strbuf_release(&err);
1411}
1412
1413static void execute_commands(struct command *commands,
1414 const char *unpacker_error,
1415 struct shallow_info *si,
1416 const struct string_list *push_options)
1417{
1418 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1419 struct command *cmd;
1420 unsigned char sha1[20];
1421 struct iterate_data data;
1422 struct async muxer;
1423 int err_fd = 0;
1424
1425 if (unpacker_error) {
1426 for (cmd = commands; cmd; cmd = cmd->next)
1427 cmd->error_string = "unpacker error";
1428 return;
1429 }
1430
1431 if (use_sideband) {
1432 memset(&muxer, 0, sizeof(muxer));
1433 muxer.proc = copy_to_sideband;
1434 muxer.in = -1;
1435 if (!start_async(&muxer))
1436 err_fd = muxer.in;
1437 /* ...else, continue without relaying sideband */
1438 }
1439
1440 data.cmds = commands;
1441 data.si = si;
1442 opt.err_fd = err_fd;
1443 opt.progress = err_fd && !quiet;
1444 opt.env = tmp_objdir_env(tmp_objdir);
1445 if (check_connected(iterate_receive_command_list, &data, &opt))
1446 set_connectivity_errors(commands, si);
1447
1448 if (use_sideband)
1449 finish_async(&muxer);
1450
1451 reject_updates_to_hidden(commands);
1452
1453 if (run_receive_hook(commands, "pre-receive", 0, push_options)) {
1454 for (cmd = commands; cmd; cmd = cmd->next) {
1455 if (!cmd->error_string)
1456 cmd->error_string = "pre-receive hook declined";
1457 }
1458 return;
1459 }
1460
1461 /*
1462 * Now we'll start writing out refs, which means the objects need
1463 * to be in their final positions so that other processes can see them.
1464 */
1465 if (tmp_objdir_migrate(tmp_objdir) < 0) {
1466 for (cmd = commands; cmd; cmd = cmd->next) {
1467 if (!cmd->error_string)
1468 cmd->error_string = "unable to migrate objects to permanent storage";
1469 }
1470 return;
1471 }
1472 tmp_objdir = NULL;
1473
1474 check_aliased_updates(commands);
1475
1476 free(head_name_to_free);
1477 head_name = head_name_to_free = resolve_refdup("HEAD", 0, sha1, NULL);
1478
1479 if (use_atomic)
1480 execute_commands_atomic(commands, si);
1481 else
1482 execute_commands_non_atomic(commands, si);
1483
1484 if (shallow_update)
1485 warn_if_skipped_connectivity_check(commands, si);
1486}
1487
1488static struct command **queue_command(struct command **tail,
1489 const char *line,
1490 int linelen)
1491{
1492 unsigned char old_sha1[20], new_sha1[20];
1493 struct command *cmd;
1494 const char *refname;
1495 int reflen;
1496
1497 if (linelen < 83 ||
1498 line[40] != ' ' ||
1499 line[81] != ' ' ||
1500 get_sha1_hex(line, old_sha1) ||
1501 get_sha1_hex(line + 41, new_sha1))
1502 die("protocol error: expected old/new/ref, got '%s'", line);
1503
1504 refname = line + 82;
1505 reflen = linelen - 82;
1506 FLEX_ALLOC_MEM(cmd, ref_name, refname, reflen);
1507 hashcpy(cmd->old_sha1, old_sha1);
1508 hashcpy(cmd->new_sha1, new_sha1);
1509 *tail = cmd;
1510 return &cmd->next;
1511}
1512
1513static void queue_commands_from_cert(struct command **tail,
1514 struct strbuf *push_cert)
1515{
1516 const char *boc, *eoc;
1517
1518 if (*tail)
1519 die("protocol error: got both push certificate and unsigned commands");
1520
1521 boc = strstr(push_cert->buf, "\n\n");
1522 if (!boc)
1523 die("malformed push certificate %.*s", 100, push_cert->buf);
1524 else
1525 boc += 2;
1526 eoc = push_cert->buf + parse_signature(push_cert->buf, push_cert->len);
1527
1528 while (boc < eoc) {
1529 const char *eol = memchr(boc, '\n', eoc - boc);
1530 tail = queue_command(tail, boc, eol ? eol - boc : eoc - eol);
1531 boc = eol ? eol + 1 : eoc;
1532 }
1533}
1534
1535static struct command *read_head_info(struct sha1_array *shallow)
1536{
1537 struct command *commands = NULL;
1538 struct command **p = &commands;
1539 for (;;) {
1540 char *line;
1541 int len, linelen;
1542
1543 line = packet_read_line(0, &len);
1544 if (!line)
1545 break;
1546
1547 if (len == 48 && starts_with(line, "shallow ")) {
1548 unsigned char sha1[20];
1549 if (get_sha1_hex(line + 8, sha1))
1550 die("protocol error: expected shallow sha, got '%s'",
1551 line + 8);
1552 sha1_array_append(shallow, sha1);
1553 continue;
1554 }
1555
1556 linelen = strlen(line);
1557 if (linelen < len) {
1558 const char *feature_list = line + linelen + 1;
1559 if (parse_feature_request(feature_list, "report-status"))
1560 report_status = 1;
1561 if (parse_feature_request(feature_list, "side-band-64k"))
1562 use_sideband = LARGE_PACKET_MAX;
1563 if (parse_feature_request(feature_list, "quiet"))
1564 quiet = 1;
1565 if (advertise_atomic_push
1566 && parse_feature_request(feature_list, "atomic"))
1567 use_atomic = 1;
1568 if (advertise_push_options
1569 && parse_feature_request(feature_list, "push-options"))
1570 use_push_options = 1;
1571 }
1572
1573 if (!strcmp(line, "push-cert")) {
1574 int true_flush = 0;
1575 char certbuf[1024];
1576
1577 for (;;) {
1578 len = packet_read(0, NULL, NULL,
1579 certbuf, sizeof(certbuf), 0);
1580 if (!len) {
1581 true_flush = 1;
1582 break;
1583 }
1584 if (!strcmp(certbuf, "push-cert-end\n"))
1585 break; /* end of cert */
1586 strbuf_addstr(&push_cert, certbuf);
1587 }
1588
1589 if (true_flush)
1590 break;
1591 continue;
1592 }
1593
1594 p = queue_command(p, line, linelen);
1595 }
1596
1597 if (push_cert.len)
1598 queue_commands_from_cert(p, &push_cert);
1599
1600 return commands;
1601}
1602
1603static void read_push_options(struct string_list *options)
1604{
1605 while (1) {
1606 char *line;
1607 int len;
1608
1609 line = packet_read_line(0, &len);
1610
1611 if (!line)
1612 break;
1613
1614 string_list_append(options, line);
1615 }
1616}
1617
1618static const char *parse_pack_header(struct pack_header *hdr)
1619{
1620 switch (read_pack_header(0, hdr)) {
1621 case PH_ERROR_EOF:
1622 return "eof before pack header was fully read";
1623
1624 case PH_ERROR_PACK_SIGNATURE:
1625 return "protocol error (pack signature mismatch detected)";
1626
1627 case PH_ERROR_PROTOCOL:
1628 return "protocol error (pack version unsupported)";
1629
1630 default:
1631 return "unknown error in parse_pack_header";
1632
1633 case 0:
1634 return NULL;
1635 }
1636}
1637
1638static const char *pack_lockfile;
1639
1640static const char *unpack(int err_fd, struct shallow_info *si)
1641{
1642 struct pack_header hdr;
1643 const char *hdr_err;
1644 int status;
1645 char hdr_arg[38];
1646 struct child_process child = CHILD_PROCESS_INIT;
1647 int fsck_objects = (receive_fsck_objects >= 0
1648 ? receive_fsck_objects
1649 : transfer_fsck_objects >= 0
1650 ? transfer_fsck_objects
1651 : 0);
1652
1653 hdr_err = parse_pack_header(&hdr);
1654 if (hdr_err) {
1655 if (err_fd > 0)
1656 close(err_fd);
1657 return hdr_err;
1658 }
1659 snprintf(hdr_arg, sizeof(hdr_arg),
1660 "--pack_header=%"PRIu32",%"PRIu32,
1661 ntohl(hdr.hdr_version), ntohl(hdr.hdr_entries));
1662
1663 if (si->nr_ours || si->nr_theirs) {
1664 alt_shallow_file = setup_temporary_shallow(si->shallow);
1665 argv_array_push(&child.args, "--shallow-file");
1666 argv_array_push(&child.args, alt_shallow_file);
1667 }
1668
1669 tmp_objdir = tmp_objdir_create();
1670 if (!tmp_objdir)
1671 return "unable to create temporary object directory";
1672 child.env = tmp_objdir_env(tmp_objdir);
1673
1674 /*
1675 * Normally we just pass the tmp_objdir environment to the child
1676 * processes that do the heavy lifting, but we may need to see these
1677 * objects ourselves to set up shallow information.
1678 */
1679 tmp_objdir_add_as_alternate(tmp_objdir);
1680
1681 if (ntohl(hdr.hdr_entries) < unpack_limit) {
1682 argv_array_pushl(&child.args, "unpack-objects", hdr_arg, NULL);
1683 if (quiet)
1684 argv_array_push(&child.args, "-q");
1685 if (fsck_objects)
1686 argv_array_pushf(&child.args, "--strict%s",
1687 fsck_msg_types.buf);
1688 if (max_input_size)
1689 argv_array_pushf(&child.args, "--max-input-size=%"PRIuMAX,
1690 (uintmax_t)max_input_size);
1691 child.no_stdout = 1;
1692 child.err = err_fd;
1693 child.git_cmd = 1;
1694 status = run_command(&child);
1695 if (status)
1696 return "unpack-objects abnormal exit";
1697 } else {
1698 char hostname[256];
1699
1700 argv_array_pushl(&child.args, "index-pack",
1701 "--stdin", hdr_arg, NULL);
1702
1703 if (gethostname(hostname, sizeof(hostname)))
1704 xsnprintf(hostname, sizeof(hostname), "localhost");
1705 argv_array_pushf(&child.args,
1706 "--keep=receive-pack %"PRIuMAX" on %s",
1707 (uintmax_t)getpid(),
1708 hostname);
1709
1710 if (!quiet && err_fd)
1711 argv_array_push(&child.args, "--show-resolving-progress");
1712 if (use_sideband)
1713 argv_array_push(&child.args, "--report-end-of-input");
1714 if (fsck_objects)
1715 argv_array_pushf(&child.args, "--strict%s",
1716 fsck_msg_types.buf);
1717 if (!reject_thin)
1718 argv_array_push(&child.args, "--fix-thin");
1719 if (max_input_size)
1720 argv_array_pushf(&child.args, "--max-input-size=%"PRIuMAX,
1721 (uintmax_t)max_input_size);
1722 child.out = -1;
1723 child.err = err_fd;
1724 child.git_cmd = 1;
1725 status = start_command(&child);
1726 if (status)
1727 return "index-pack fork failed";
1728 pack_lockfile = index_pack_lockfile(child.out);
1729 close(child.out);
1730 status = finish_command(&child);
1731 if (status)
1732 return "index-pack abnormal exit";
1733 reprepare_packed_git();
1734 }
1735 return NULL;
1736}
1737
1738static const char *unpack_with_sideband(struct shallow_info *si)
1739{
1740 struct async muxer;
1741 const char *ret;
1742
1743 if (!use_sideband)
1744 return unpack(0, si);
1745
1746 use_keepalive = KEEPALIVE_AFTER_NUL;
1747 memset(&muxer, 0, sizeof(muxer));
1748 muxer.proc = copy_to_sideband;
1749 muxer.in = -1;
1750 if (start_async(&muxer))
1751 return NULL;
1752
1753 ret = unpack(muxer.in, si);
1754
1755 finish_async(&muxer);
1756 return ret;
1757}
1758
1759static void prepare_shallow_update(struct command *commands,
1760 struct shallow_info *si)
1761{
1762 int i, j, k, bitmap_size = (si->ref->nr + 31) / 32;
1763
1764 ALLOC_ARRAY(si->used_shallow, si->shallow->nr);
1765 assign_shallow_commits_to_refs(si, si->used_shallow, NULL);
1766
1767 si->need_reachability_test =
1768 xcalloc(si->shallow->nr, sizeof(*si->need_reachability_test));
1769 si->reachable =
1770 xcalloc(si->shallow->nr, sizeof(*si->reachable));
1771 si->shallow_ref = xcalloc(si->ref->nr, sizeof(*si->shallow_ref));
1772
1773 for (i = 0; i < si->nr_ours; i++)
1774 si->need_reachability_test[si->ours[i]] = 1;
1775
1776 for (i = 0; i < si->shallow->nr; i++) {
1777 if (!si->used_shallow[i])
1778 continue;
1779 for (j = 0; j < bitmap_size; j++) {
1780 if (!si->used_shallow[i][j])
1781 continue;
1782 si->need_reachability_test[i]++;
1783 for (k = 0; k < 32; k++)
1784 if (si->used_shallow[i][j] & (1U << k))
1785 si->shallow_ref[j * 32 + k]++;
1786 }
1787
1788 /*
1789 * true for those associated with some refs and belong
1790 * in "ours" list aka "step 7 not done yet"
1791 */
1792 si->need_reachability_test[i] =
1793 si->need_reachability_test[i] > 1;
1794 }
1795
1796 /*
1797 * keep hooks happy by forcing a temporary shallow file via
1798 * env variable because we can't add --shallow-file to every
1799 * command. check_everything_connected() will be done with
1800 * true .git/shallow though.
1801 */
1802 setenv(GIT_SHALLOW_FILE_ENVIRONMENT, alt_shallow_file, 1);
1803}
1804
1805static void update_shallow_info(struct command *commands,
1806 struct shallow_info *si,
1807 struct sha1_array *ref)
1808{
1809 struct command *cmd;
1810 int *ref_status;
1811 remove_nonexistent_theirs_shallow(si);
1812 if (!si->nr_ours && !si->nr_theirs) {
1813 shallow_update = 0;
1814 return;
1815 }
1816
1817 for (cmd = commands; cmd; cmd = cmd->next) {
1818 if (is_null_sha1(cmd->new_sha1))
1819 continue;
1820 sha1_array_append(ref, cmd->new_sha1);
1821 cmd->index = ref->nr - 1;
1822 }
1823 si->ref = ref;
1824
1825 if (shallow_update) {
1826 prepare_shallow_update(commands, si);
1827 return;
1828 }
1829
1830 ALLOC_ARRAY(ref_status, ref->nr);
1831 assign_shallow_commits_to_refs(si, NULL, ref_status);
1832 for (cmd = commands; cmd; cmd = cmd->next) {
1833 if (is_null_sha1(cmd->new_sha1))
1834 continue;
1835 if (ref_status[cmd->index]) {
1836 cmd->error_string = "shallow update not allowed";
1837 cmd->skip_update = 1;
1838 }
1839 }
1840 free(ref_status);
1841}
1842
1843static void report(struct command *commands, const char *unpack_status)
1844{
1845 struct command *cmd;
1846 struct strbuf buf = STRBUF_INIT;
1847
1848 packet_buf_write(&buf, "unpack %s\n",
1849 unpack_status ? unpack_status : "ok");
1850 for (cmd = commands; cmd; cmd = cmd->next) {
1851 if (!cmd->error_string)
1852 packet_buf_write(&buf, "ok %s\n",
1853 cmd->ref_name);
1854 else
1855 packet_buf_write(&buf, "ng %s %s\n",
1856 cmd->ref_name, cmd->error_string);
1857 }
1858 packet_buf_flush(&buf);
1859
1860 if (use_sideband)
1861 send_sideband(1, 1, buf.buf, buf.len, use_sideband);
1862 else
1863 write_or_die(1, buf.buf, buf.len);
1864 strbuf_release(&buf);
1865}
1866
1867static int delete_only(struct command *commands)
1868{
1869 struct command *cmd;
1870 for (cmd = commands; cmd; cmd = cmd->next) {
1871 if (!is_null_sha1(cmd->new_sha1))
1872 return 0;
1873 }
1874 return 1;
1875}
1876
1877int cmd_receive_pack(int argc, const char **argv, const char *prefix)
1878{
1879 int advertise_refs = 0;
1880 struct command *commands;
1881 struct sha1_array shallow = SHA1_ARRAY_INIT;
1882 struct sha1_array ref = SHA1_ARRAY_INIT;
1883 struct shallow_info si;
1884
1885 struct option options[] = {
1886 OPT__QUIET(&quiet, N_("quiet")),
1887 OPT_HIDDEN_BOOL(0, "stateless-rpc", &stateless_rpc, NULL),
1888 OPT_HIDDEN_BOOL(0, "advertise-refs", &advertise_refs, NULL),
1889 OPT_HIDDEN_BOOL(0, "reject-thin-pack-for-testing", &reject_thin, NULL),
1890 OPT_END()
1891 };
1892
1893 packet_trace_identity("receive-pack");
1894
1895 argc = parse_options(argc, argv, prefix, options, receive_pack_usage, 0);
1896
1897 if (argc > 1)
1898 usage_msg_opt(_("Too many arguments."), receive_pack_usage, options);
1899 if (argc == 0)
1900 usage_msg_opt(_("You must specify a directory."), receive_pack_usage, options);
1901
1902 service_dir = argv[0];
1903
1904 setup_path();
1905
1906 if (!enter_repo(service_dir, 0))
1907 die("'%s' does not appear to be a git repository", service_dir);
1908
1909 git_config(receive_pack_config, NULL);
1910 if (cert_nonce_seed)
1911 push_cert_nonce = prepare_push_cert_nonce(service_dir, time(NULL));
1912
1913 if (0 <= transfer_unpack_limit)
1914 unpack_limit = transfer_unpack_limit;
1915 else if (0 <= receive_unpack_limit)
1916 unpack_limit = receive_unpack_limit;
1917
1918 if (advertise_refs || !stateless_rpc) {
1919 write_head_info();
1920 }
1921 if (advertise_refs)
1922 return 0;
1923
1924 if ((commands = read_head_info(&shallow)) != NULL) {
1925 const char *unpack_status = NULL;
1926 struct string_list push_options = STRING_LIST_INIT_DUP;
1927
1928 if (use_push_options)
1929 read_push_options(&push_options);
1930
1931 prepare_shallow_info(&si, &shallow);
1932 if (!si.nr_ours && !si.nr_theirs)
1933 shallow_update = 0;
1934 if (!delete_only(commands)) {
1935 unpack_status = unpack_with_sideband(&si);
1936 update_shallow_info(commands, &si, &ref);
1937 }
1938 use_keepalive = KEEPALIVE_ALWAYS;
1939 execute_commands(commands, unpack_status, &si,
1940 &push_options);
1941 if (pack_lockfile)
1942 unlink_or_warn(pack_lockfile);
1943 if (report_status)
1944 report(commands, unpack_status);
1945 run_receive_hook(commands, "post-receive", 1,
1946 &push_options);
1947 run_update_post_hook(commands);
1948 if (push_options.nr)
1949 string_list_clear(&push_options, 0);
1950 if (auto_gc) {
1951 const char *argv_gc_auto[] = {
1952 "gc", "--auto", "--quiet", NULL,
1953 };
1954 struct child_process proc = CHILD_PROCESS_INIT;
1955
1956 proc.no_stdin = 1;
1957 proc.stdout_to_stderr = 1;
1958 proc.err = use_sideband ? -1 : 0;
1959 proc.git_cmd = 1;
1960 proc.argv = argv_gc_auto;
1961
1962 close_all_packs();
1963 if (!start_command(&proc)) {
1964 if (use_sideband)
1965 copy_to_sideband(proc.err, -1, NULL);
1966 finish_command(&proc);
1967 }
1968 }
1969 if (auto_update_server_info)
1970 update_server_info(0);
1971 clear_shallow_info(&si);
1972 }
1973 if (use_sideband)
1974 packet_flush(1);
1975 sha1_array_clear(&shallow);
1976 sha1_array_clear(&ref);
1977 free((void *)push_cert_nonce);
1978 return 0;
1979}