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