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