upload-pack: move allow_ref_in_want to upload_pack_data
[git] / upload-pack.c
1 #include "cache.h"
2 #include "config.h"
3 #include "refs.h"
4 #include "pkt-line.h"
5 #include "sideband.h"
6 #include "repository.h"
7 #include "object-store.h"
8 #include "tag.h"
9 #include "object.h"
10 #include "commit.h"
11 #include "diff.h"
12 #include "revision.h"
13 #include "list-objects.h"
14 #include "list-objects-filter.h"
15 #include "list-objects-filter-options.h"
16 #include "run-command.h"
17 #include "connect.h"
18 #include "sigchain.h"
19 #include "version.h"
20 #include "string-list.h"
21 #include "argv-array.h"
22 #include "prio-queue.h"
23 #include "protocol.h"
24 #include "quote.h"
25 #include "upload-pack.h"
26 #include "serve.h"
27 #include "commit-graph.h"
28 #include "commit-reach.h"
29 #include "shallow.h"
30
31 /* Remember to update object flag allocation in object.h */
32 #define THEY_HAVE       (1u << 11)
33 #define OUR_REF         (1u << 12)
34 #define WANTED          (1u << 13)
35 #define COMMON_KNOWN    (1u << 14)
36
37 #define SHALLOW         (1u << 16)
38 #define NOT_SHALLOW     (1u << 17)
39 #define CLIENT_SHALLOW  (1u << 18)
40 #define HIDDEN_REF      (1u << 19)
41
42 #define ALL_FLAGS (THEY_HAVE | OUR_REF | WANTED | COMMON_KNOWN | SHALLOW | \
43                 NOT_SHALLOW | CLIENT_SHALLOW | HIDDEN_REF)
44
45 static timestamp_t oldest_have;
46
47 /* Allow specifying sha1 if it is a ref tip. */
48 #define ALLOW_TIP_SHA1  01
49 /* Allow request of a sha1 if it is reachable from a ref (possibly hidden ref). */
50 #define ALLOW_REACHABLE_SHA1    02
51 /* Allow request of any sha1. Implies ALLOW_TIP_SHA1 and ALLOW_REACHABLE_SHA1. */
52 #define ALLOW_ANY_SHA1  07
53 static unsigned int allow_unadvertised_object_request;
54 static int shallow_nr;
55 static struct object_array extra_edge_obj;
56 static const char *pack_objects_hook;
57
58 static int allow_sideband_all;
59
60 /*
61  * Please annotate, and if possible group together, fields used only
62  * for protocol v0 or only for protocol v2.
63  */
64 struct upload_pack_data {
65         struct string_list symref;                              /* v0 only */
66         struct object_array want_obj;
67         struct object_array have_obj;
68         struct oid_array haves;                                 /* v2 only */
69         struct string_list wanted_refs;                         /* v2 only */
70
71         struct object_array shallows;
72         struct string_list deepen_not;
73         int depth;
74         timestamp_t deepen_since;
75         int deepen_rev_list;
76         int deepen_relative;
77         int keepalive;
78
79         unsigned int timeout;                                   /* v0 only */
80         enum {
81                 NO_MULTI_ACK = 0,
82                 MULTI_ACK = 1,
83                 MULTI_ACK_DETAILED = 2
84         } multi_ack;                                            /* v0 only */
85
86         /* 0 for no sideband, otherwise DEFAULT_PACKET_MAX or LARGE_PACKET_MAX */
87         int use_sideband;
88
89         struct list_objects_filter_options filter_options;
90
91         struct packet_writer writer;
92
93         unsigned stateless_rpc : 1;                             /* v0 only */
94         unsigned no_done : 1;                                   /* v0 only */
95         unsigned daemon_mode : 1;                               /* v0 only */
96         unsigned filter_capability_requested : 1;               /* v0 only */
97
98         unsigned use_thin_pack : 1;
99         unsigned use_ofs_delta : 1;
100         unsigned no_progress : 1;
101         unsigned use_include_tag : 1;
102         unsigned allow_filter : 1;
103
104         unsigned done : 1;                                      /* v2 only */
105         unsigned allow_ref_in_want : 1;                         /* v2 only */
106 };
107
108 static void upload_pack_data_init(struct upload_pack_data *data)
109 {
110         struct string_list symref = STRING_LIST_INIT_DUP;
111         struct string_list wanted_refs = STRING_LIST_INIT_DUP;
112         struct object_array want_obj = OBJECT_ARRAY_INIT;
113         struct object_array have_obj = OBJECT_ARRAY_INIT;
114         struct oid_array haves = OID_ARRAY_INIT;
115         struct object_array shallows = OBJECT_ARRAY_INIT;
116         struct string_list deepen_not = STRING_LIST_INIT_DUP;
117
118         memset(data, 0, sizeof(*data));
119         data->symref = symref;
120         data->wanted_refs = wanted_refs;
121         data->want_obj = want_obj;
122         data->have_obj = have_obj;
123         data->haves = haves;
124         data->shallows = shallows;
125         data->deepen_not = deepen_not;
126         packet_writer_init(&data->writer, 1);
127
128         data->keepalive = 5;
129 }
130
131 static void upload_pack_data_clear(struct upload_pack_data *data)
132 {
133         string_list_clear(&data->symref, 1);
134         string_list_clear(&data->wanted_refs, 1);
135         object_array_clear(&data->want_obj);
136         object_array_clear(&data->have_obj);
137         oid_array_clear(&data->haves);
138         object_array_clear(&data->shallows);
139         string_list_clear(&data->deepen_not, 0);
140         list_objects_filter_release(&data->filter_options);
141 }
142
143 static void reset_timeout(unsigned int timeout)
144 {
145         alarm(timeout);
146 }
147
148 static void send_client_data(int fd, const char *data, ssize_t sz,
149                              int use_sideband)
150 {
151         if (use_sideband) {
152                 send_sideband(1, fd, data, sz, use_sideband);
153                 return;
154         }
155         if (fd == 3)
156                 /* emergency quit */
157                 fd = 2;
158         if (fd == 2) {
159                 /* XXX: are we happy to lose stuff here? */
160                 xwrite(fd, data, sz);
161                 return;
162         }
163         write_or_die(fd, data, sz);
164 }
165
166 static int write_one_shallow(const struct commit_graft *graft, void *cb_data)
167 {
168         FILE *fp = cb_data;
169         if (graft->nr_parent == -1)
170                 fprintf(fp, "--shallow %s\n", oid_to_hex(&graft->oid));
171         return 0;
172 }
173
174 static void create_pack_file(struct upload_pack_data *pack_data)
175 {
176         struct child_process pack_objects = CHILD_PROCESS_INIT;
177         char data[8193], progress[128];
178         char abort_msg[] = "aborting due to possible repository "
179                 "corruption on the remote side.";
180         int buffered = -1;
181         ssize_t sz;
182         int i;
183         FILE *pipe_fd;
184
185         if (!pack_objects_hook)
186                 pack_objects.git_cmd = 1;
187         else {
188                 argv_array_push(&pack_objects.args, pack_objects_hook);
189                 argv_array_push(&pack_objects.args, "git");
190                 pack_objects.use_shell = 1;
191         }
192
193         if (shallow_nr) {
194                 argv_array_push(&pack_objects.args, "--shallow-file");
195                 argv_array_push(&pack_objects.args, "");
196         }
197         argv_array_push(&pack_objects.args, "pack-objects");
198         argv_array_push(&pack_objects.args, "--revs");
199         if (pack_data->use_thin_pack)
200                 argv_array_push(&pack_objects.args, "--thin");
201
202         argv_array_push(&pack_objects.args, "--stdout");
203         if (shallow_nr)
204                 argv_array_push(&pack_objects.args, "--shallow");
205         if (!pack_data->no_progress)
206                 argv_array_push(&pack_objects.args, "--progress");
207         if (pack_data->use_ofs_delta)
208                 argv_array_push(&pack_objects.args, "--delta-base-offset");
209         if (pack_data->use_include_tag)
210                 argv_array_push(&pack_objects.args, "--include-tag");
211         if (pack_data->filter_options.choice) {
212                 const char *spec =
213                         expand_list_objects_filter_spec(&pack_data->filter_options);
214                 if (pack_objects.use_shell) {
215                         struct strbuf buf = STRBUF_INIT;
216                         sq_quote_buf(&buf, spec);
217                         argv_array_pushf(&pack_objects.args, "--filter=%s", buf.buf);
218                         strbuf_release(&buf);
219                 } else {
220                         argv_array_pushf(&pack_objects.args, "--filter=%s",
221                                          spec);
222                 }
223         }
224
225         pack_objects.in = -1;
226         pack_objects.out = -1;
227         pack_objects.err = -1;
228
229         if (start_command(&pack_objects))
230                 die("git upload-pack: unable to fork git-pack-objects");
231
232         pipe_fd = xfdopen(pack_objects.in, "w");
233
234         if (shallow_nr)
235                 for_each_commit_graft(write_one_shallow, pipe_fd);
236
237         for (i = 0; i < pack_data->want_obj.nr; i++)
238                 fprintf(pipe_fd, "%s\n",
239                         oid_to_hex(&pack_data->want_obj.objects[i].item->oid));
240         fprintf(pipe_fd, "--not\n");
241         for (i = 0; i < pack_data->have_obj.nr; i++)
242                 fprintf(pipe_fd, "%s\n",
243                         oid_to_hex(&pack_data->have_obj.objects[i].item->oid));
244         for (i = 0; i < extra_edge_obj.nr; i++)
245                 fprintf(pipe_fd, "%s\n",
246                         oid_to_hex(&extra_edge_obj.objects[i].item->oid));
247         fprintf(pipe_fd, "\n");
248         fflush(pipe_fd);
249         fclose(pipe_fd);
250
251         /* We read from pack_objects.err to capture stderr output for
252          * progress bar, and pack_objects.out to capture the pack data.
253          */
254
255         while (1) {
256                 struct pollfd pfd[2];
257                 int pe, pu, pollsize, polltimeout;
258                 int ret;
259
260                 reset_timeout(pack_data->timeout);
261
262                 pollsize = 0;
263                 pe = pu = -1;
264
265                 if (0 <= pack_objects.out) {
266                         pfd[pollsize].fd = pack_objects.out;
267                         pfd[pollsize].events = POLLIN;
268                         pu = pollsize;
269                         pollsize++;
270                 }
271                 if (0 <= pack_objects.err) {
272                         pfd[pollsize].fd = pack_objects.err;
273                         pfd[pollsize].events = POLLIN;
274                         pe = pollsize;
275                         pollsize++;
276                 }
277
278                 if (!pollsize)
279                         break;
280
281                 polltimeout = pack_data->keepalive < 0
282                         ? -1
283                         : 1000 * pack_data->keepalive;
284
285                 ret = poll(pfd, pollsize, polltimeout);
286
287                 if (ret < 0) {
288                         if (errno != EINTR) {
289                                 error_errno("poll failed, resuming");
290                                 sleep(1);
291                         }
292                         continue;
293                 }
294                 if (0 <= pe && (pfd[pe].revents & (POLLIN|POLLHUP))) {
295                         /* Status ready; we ship that in the side-band
296                          * or dump to the standard error.
297                          */
298                         sz = xread(pack_objects.err, progress,
299                                   sizeof(progress));
300                         if (0 < sz)
301                                 send_client_data(2, progress, sz,
302                                                  pack_data->use_sideband);
303                         else if (sz == 0) {
304                                 close(pack_objects.err);
305                                 pack_objects.err = -1;
306                         }
307                         else
308                                 goto fail;
309                         /* give priority to status messages */
310                         continue;
311                 }
312                 if (0 <= pu && (pfd[pu].revents & (POLLIN|POLLHUP))) {
313                         /* Data ready; we keep the last byte to ourselves
314                          * in case we detect broken rev-list, so that we
315                          * can leave the stream corrupted.  This is
316                          * unfortunate -- unpack-objects would happily
317                          * accept a valid packdata with trailing garbage,
318                          * so appending garbage after we pass all the
319                          * pack data is not good enough to signal
320                          * breakage to downstream.
321                          */
322                         char *cp = data;
323                         ssize_t outsz = 0;
324                         if (0 <= buffered) {
325                                 *cp++ = buffered;
326                                 outsz++;
327                         }
328                         sz = xread(pack_objects.out, cp,
329                                   sizeof(data) - outsz);
330                         if (0 < sz)
331                                 ;
332                         else if (sz == 0) {
333                                 close(pack_objects.out);
334                                 pack_objects.out = -1;
335                         }
336                         else
337                                 goto fail;
338                         sz += outsz;
339                         if (1 < sz) {
340                                 buffered = data[sz-1] & 0xFF;
341                                 sz--;
342                         }
343                         else
344                                 buffered = -1;
345                         send_client_data(1, data, sz,
346                                          pack_data->use_sideband);
347                 }
348
349                 /*
350                  * We hit the keepalive timeout without saying anything; send
351                  * an empty message on the data sideband just to let the other
352                  * side know we're still working on it, but don't have any data
353                  * yet.
354                  *
355                  * If we don't have a sideband channel, there's no room in the
356                  * protocol to say anything, so those clients are just out of
357                  * luck.
358                  */
359                 if (!ret && pack_data->use_sideband) {
360                         static const char buf[] = "0005\1";
361                         write_or_die(1, buf, 5);
362                 }
363         }
364
365         if (finish_command(&pack_objects)) {
366                 error("git upload-pack: git-pack-objects died with error.");
367                 goto fail;
368         }
369
370         /* flush the data */
371         if (0 <= buffered) {
372                 data[0] = buffered;
373                 send_client_data(1, data, 1,
374                                  pack_data->use_sideband);
375                 fprintf(stderr, "flushed.\n");
376         }
377         if (pack_data->use_sideband)
378                 packet_flush(1);
379         return;
380
381  fail:
382         send_client_data(3, abort_msg, sizeof(abort_msg),
383                          pack_data->use_sideband);
384         die("git upload-pack: %s", abort_msg);
385 }
386
387 static int got_oid(const char *hex, struct object_id *oid,
388                    struct object_array *have_obj)
389 {
390         struct object *o;
391         int we_knew_they_have = 0;
392
393         if (get_oid_hex(hex, oid))
394                 die("git upload-pack: expected SHA1 object, got '%s'", hex);
395         if (!has_object_file(oid))
396                 return -1;
397
398         o = parse_object(the_repository, oid);
399         if (!o)
400                 die("oops (%s)", oid_to_hex(oid));
401         if (o->type == OBJ_COMMIT) {
402                 struct commit_list *parents;
403                 struct commit *commit = (struct commit *)o;
404                 if (o->flags & THEY_HAVE)
405                         we_knew_they_have = 1;
406                 else
407                         o->flags |= THEY_HAVE;
408                 if (!oldest_have || (commit->date < oldest_have))
409                         oldest_have = commit->date;
410                 for (parents = commit->parents;
411                      parents;
412                      parents = parents->next)
413                         parents->item->object.flags |= THEY_HAVE;
414         }
415         if (!we_knew_they_have) {
416                 add_object_array(o, NULL, have_obj);
417                 return 1;
418         }
419         return 0;
420 }
421
422 static int ok_to_give_up(const struct object_array *have_obj,
423                          struct object_array *want_obj)
424 {
425         uint32_t min_generation = GENERATION_NUMBER_ZERO;
426
427         if (!have_obj->nr)
428                 return 0;
429
430         return can_all_from_reach_with_flag(want_obj, THEY_HAVE,
431                                             COMMON_KNOWN, oldest_have,
432                                             min_generation);
433 }
434
435 static int get_common_commits(struct upload_pack_data *data,
436                               struct packet_reader *reader)
437 {
438         struct object_id oid;
439         char last_hex[GIT_MAX_HEXSZ + 1];
440         int got_common = 0;
441         int got_other = 0;
442         int sent_ready = 0;
443
444         save_commit_buffer = 0;
445
446         for (;;) {
447                 const char *arg;
448
449                 reset_timeout(data->timeout);
450
451                 if (packet_reader_read(reader) != PACKET_READ_NORMAL) {
452                         if (data->multi_ack == MULTI_ACK_DETAILED
453                             && got_common
454                             && !got_other
455                             && ok_to_give_up(&data->have_obj, &data->want_obj)) {
456                                 sent_ready = 1;
457                                 packet_write_fmt(1, "ACK %s ready\n", last_hex);
458                         }
459                         if (data->have_obj.nr == 0 || data->multi_ack)
460                                 packet_write_fmt(1, "NAK\n");
461
462                         if (data->no_done && sent_ready) {
463                                 packet_write_fmt(1, "ACK %s\n", last_hex);
464                                 return 0;
465                         }
466                         if (data->stateless_rpc)
467                                 exit(0);
468                         got_common = 0;
469                         got_other = 0;
470                         continue;
471                 }
472                 if (skip_prefix(reader->line, "have ", &arg)) {
473                         switch (got_oid(arg, &oid, &data->have_obj)) {
474                         case -1: /* they have what we do not */
475                                 got_other = 1;
476                                 if (data->multi_ack
477                                     && ok_to_give_up(&data->have_obj, &data->want_obj)) {
478                                         const char *hex = oid_to_hex(&oid);
479                                         if (data->multi_ack == MULTI_ACK_DETAILED) {
480                                                 sent_ready = 1;
481                                                 packet_write_fmt(1, "ACK %s ready\n", hex);
482                                         } else
483                                                 packet_write_fmt(1, "ACK %s continue\n", hex);
484                                 }
485                                 break;
486                         default:
487                                 got_common = 1;
488                                 oid_to_hex_r(last_hex, &oid);
489                                 if (data->multi_ack == MULTI_ACK_DETAILED)
490                                         packet_write_fmt(1, "ACK %s common\n", last_hex);
491                                 else if (data->multi_ack)
492                                         packet_write_fmt(1, "ACK %s continue\n", last_hex);
493                                 else if (data->have_obj.nr == 1)
494                                         packet_write_fmt(1, "ACK %s\n", last_hex);
495                                 break;
496                         }
497                         continue;
498                 }
499                 if (!strcmp(reader->line, "done")) {
500                         if (data->have_obj.nr > 0) {
501                                 if (data->multi_ack)
502                                         packet_write_fmt(1, "ACK %s\n", last_hex);
503                                 return 0;
504                         }
505                         packet_write_fmt(1, "NAK\n");
506                         return -1;
507                 }
508                 die("git upload-pack: expected SHA1 list, got '%s'", reader->line);
509         }
510 }
511
512 static int is_our_ref(struct object *o)
513 {
514         int allow_hidden_ref = (allow_unadvertised_object_request &
515                         (ALLOW_TIP_SHA1 | ALLOW_REACHABLE_SHA1));
516         return o->flags & ((allow_hidden_ref ? HIDDEN_REF : 0) | OUR_REF);
517 }
518
519 /*
520  * on successful case, it's up to the caller to close cmd->out
521  */
522 static int do_reachable_revlist(struct child_process *cmd,
523                                 struct object_array *src,
524                                 struct object_array *reachable)
525 {
526         static const char *argv[] = {
527                 "rev-list", "--stdin", NULL,
528         };
529         struct object *o;
530         char namebuf[GIT_MAX_HEXSZ + 2]; /* ^ + hash + LF */
531         int i;
532         const unsigned hexsz = the_hash_algo->hexsz;
533
534         cmd->argv = argv;
535         cmd->git_cmd = 1;
536         cmd->no_stderr = 1;
537         cmd->in = -1;
538         cmd->out = -1;
539
540         /*
541          * If the next rev-list --stdin encounters an unknown commit,
542          * it terminates, which will cause SIGPIPE in the write loop
543          * below.
544          */
545         sigchain_push(SIGPIPE, SIG_IGN);
546
547         if (start_command(cmd))
548                 goto error;
549
550         namebuf[0] = '^';
551         namebuf[hexsz + 1] = '\n';
552         for (i = get_max_object_index(); 0 < i; ) {
553                 o = get_indexed_object(--i);
554                 if (!o)
555                         continue;
556                 if (reachable && o->type == OBJ_COMMIT)
557                         o->flags &= ~TMP_MARK;
558                 if (!is_our_ref(o))
559                         continue;
560                 memcpy(namebuf + 1, oid_to_hex(&o->oid), hexsz);
561                 if (write_in_full(cmd->in, namebuf, hexsz + 2) < 0)
562                         goto error;
563         }
564         namebuf[hexsz] = '\n';
565         for (i = 0; i < src->nr; i++) {
566                 o = src->objects[i].item;
567                 if (is_our_ref(o)) {
568                         if (reachable)
569                                 add_object_array(o, NULL, reachable);
570                         continue;
571                 }
572                 if (reachable && o->type == OBJ_COMMIT)
573                         o->flags |= TMP_MARK;
574                 memcpy(namebuf, oid_to_hex(&o->oid), hexsz);
575                 if (write_in_full(cmd->in, namebuf, hexsz + 1) < 0)
576                         goto error;
577         }
578         close(cmd->in);
579         cmd->in = -1;
580         sigchain_pop(SIGPIPE);
581
582         return 0;
583
584 error:
585         sigchain_pop(SIGPIPE);
586
587         if (cmd->in >= 0)
588                 close(cmd->in);
589         if (cmd->out >= 0)
590                 close(cmd->out);
591         return -1;
592 }
593
594 static int get_reachable_list(struct object_array *src,
595                               struct object_array *reachable)
596 {
597         struct child_process cmd = CHILD_PROCESS_INIT;
598         int i;
599         struct object *o;
600         char namebuf[GIT_MAX_HEXSZ + 2]; /* ^ + hash + LF */
601         const unsigned hexsz = the_hash_algo->hexsz;
602
603         if (do_reachable_revlist(&cmd, src, reachable) < 0)
604                 return -1;
605
606         while ((i = read_in_full(cmd.out, namebuf, hexsz + 1)) == hexsz + 1) {
607                 struct object_id oid;
608                 const char *p;
609
610                 if (parse_oid_hex(namebuf, &oid, &p) || *p != '\n')
611                         break;
612
613                 o = lookup_object(the_repository, &oid);
614                 if (o && o->type == OBJ_COMMIT) {
615                         o->flags &= ~TMP_MARK;
616                 }
617         }
618         for (i = get_max_object_index(); 0 < i; i--) {
619                 o = get_indexed_object(i - 1);
620                 if (o && o->type == OBJ_COMMIT &&
621                     (o->flags & TMP_MARK)) {
622                         add_object_array(o, NULL, reachable);
623                                 o->flags &= ~TMP_MARK;
624                 }
625         }
626         close(cmd.out);
627
628         if (finish_command(&cmd))
629                 return -1;
630
631         return 0;
632 }
633
634 static int has_unreachable(struct object_array *src)
635 {
636         struct child_process cmd = CHILD_PROCESS_INIT;
637         char buf[1];
638         int i;
639
640         if (do_reachable_revlist(&cmd, src, NULL) < 0)
641                 return 1;
642
643         /*
644          * The commits out of the rev-list are not ancestors of
645          * our ref.
646          */
647         i = read_in_full(cmd.out, buf, 1);
648         if (i)
649                 goto error;
650         close(cmd.out);
651         cmd.out = -1;
652
653         /*
654          * rev-list may have died by encountering a bad commit
655          * in the history, in which case we do want to bail out
656          * even when it showed no commit.
657          */
658         if (finish_command(&cmd))
659                 goto error;
660
661         /* All the non-tip ones are ancestors of what we advertised */
662         return 0;
663
664 error:
665         sigchain_pop(SIGPIPE);
666         if (cmd.out >= 0)
667                 close(cmd.out);
668         return 1;
669 }
670
671 static void check_non_tip(struct upload_pack_data *data)
672 {
673         int i;
674
675         /*
676          * In the normal in-process case without
677          * uploadpack.allowReachableSHA1InWant,
678          * non-tip requests can never happen.
679          */
680         if (!data->stateless_rpc
681             && !(allow_unadvertised_object_request & ALLOW_REACHABLE_SHA1))
682                 goto error;
683         if (!has_unreachable(&data->want_obj))
684                 /* All the non-tip ones are ancestors of what we advertised */
685                 return;
686
687 error:
688         /* Pick one of them (we know there at least is one) */
689         for (i = 0; i < data->want_obj.nr; i++) {
690                 struct object *o = data->want_obj.objects[i].item;
691                 if (!is_our_ref(o)) {
692                         packet_writer_error(&data->writer,
693                                             "upload-pack: not our ref %s",
694                                             oid_to_hex(&o->oid));
695                         die("git upload-pack: not our ref %s",
696                             oid_to_hex(&o->oid));
697                 }
698         }
699 }
700
701 static void send_shallow(struct packet_writer *writer,
702                          struct commit_list *result)
703 {
704         while (result) {
705                 struct object *object = &result->item->object;
706                 if (!(object->flags & (CLIENT_SHALLOW|NOT_SHALLOW))) {
707                         packet_writer_write(writer, "shallow %s",
708                                             oid_to_hex(&object->oid));
709                         register_shallow(the_repository, &object->oid);
710                         shallow_nr++;
711                 }
712                 result = result->next;
713         }
714 }
715
716 static void send_unshallow(struct packet_writer *writer,
717                            const struct object_array *shallows,
718                            struct object_array *want_obj)
719 {
720         int i;
721
722         for (i = 0; i < shallows->nr; i++) {
723                 struct object *object = shallows->objects[i].item;
724                 if (object->flags & NOT_SHALLOW) {
725                         struct commit_list *parents;
726                         packet_writer_write(writer, "unshallow %s",
727                                             oid_to_hex(&object->oid));
728                         object->flags &= ~CLIENT_SHALLOW;
729                         /*
730                          * We want to _register_ "object" as shallow, but we
731                          * also need to traverse object's parents to deepen a
732                          * shallow clone. Unregister it for now so we can
733                          * parse and add the parents to the want list, then
734                          * re-register it.
735                          */
736                         unregister_shallow(&object->oid);
737                         object->parsed = 0;
738                         parse_commit_or_die((struct commit *)object);
739                         parents = ((struct commit *)object)->parents;
740                         while (parents) {
741                                 add_object_array(&parents->item->object,
742                                                  NULL, want_obj);
743                                 parents = parents->next;
744                         }
745                         add_object_array(object, NULL, &extra_edge_obj);
746                 }
747                 /* make sure commit traversal conforms to client */
748                 register_shallow(the_repository, &object->oid);
749         }
750 }
751
752 static int check_ref(const char *refname_full, const struct object_id *oid,
753                      int flag, void *cb_data);
754 static void deepen(struct packet_writer *writer, int depth, int deepen_relative,
755                    struct object_array *shallows, struct object_array *want_obj)
756 {
757         if (depth == INFINITE_DEPTH && !is_repository_shallow(the_repository)) {
758                 int i;
759
760                 for (i = 0; i < shallows->nr; i++) {
761                         struct object *object = shallows->objects[i].item;
762                         object->flags |= NOT_SHALLOW;
763                 }
764         } else if (deepen_relative) {
765                 struct object_array reachable_shallows = OBJECT_ARRAY_INIT;
766                 struct commit_list *result;
767
768                 /*
769                  * Checking for reachable shallows requires that our refs be
770                  * marked with OUR_REF.
771                  */
772                 head_ref_namespaced(check_ref, NULL);
773                 for_each_namespaced_ref(check_ref, NULL);
774
775                 get_reachable_list(shallows, &reachable_shallows);
776                 result = get_shallow_commits(&reachable_shallows,
777                                              depth + 1,
778                                              SHALLOW, NOT_SHALLOW);
779                 send_shallow(writer, result);
780                 free_commit_list(result);
781                 object_array_clear(&reachable_shallows);
782         } else {
783                 struct commit_list *result;
784
785                 result = get_shallow_commits(want_obj, depth,
786                                              SHALLOW, NOT_SHALLOW);
787                 send_shallow(writer, result);
788                 free_commit_list(result);
789         }
790
791         send_unshallow(writer, shallows, want_obj);
792 }
793
794 static void deepen_by_rev_list(struct packet_writer *writer, int ac,
795                                const char **av,
796                                struct object_array *shallows,
797                                struct object_array *want_obj)
798 {
799         struct commit_list *result;
800
801         disable_commit_graph(the_repository);
802         result = get_shallow_commits_by_rev_list(ac, av, SHALLOW, NOT_SHALLOW);
803         send_shallow(writer, result);
804         free_commit_list(result);
805         send_unshallow(writer, shallows, want_obj);
806 }
807
808 /* Returns 1 if a shallow list is sent or 0 otherwise */
809 static int send_shallow_list(struct packet_writer *writer,
810                              int depth, int deepen_rev_list,
811                              timestamp_t deepen_since,
812                              struct string_list *deepen_not,
813                              int deepen_relative,
814                              struct object_array *shallows,
815                              struct object_array *want_obj)
816 {
817         int ret = 0;
818
819         if (depth > 0 && deepen_rev_list)
820                 die("git upload-pack: deepen and deepen-since (or deepen-not) cannot be used together");
821         if (depth > 0) {
822                 deepen(writer, depth, deepen_relative, shallows, want_obj);
823                 ret = 1;
824         } else if (deepen_rev_list) {
825                 struct argv_array av = ARGV_ARRAY_INIT;
826                 int i;
827
828                 argv_array_push(&av, "rev-list");
829                 if (deepen_since)
830                         argv_array_pushf(&av, "--max-age=%"PRItime, deepen_since);
831                 if (deepen_not->nr) {
832                         argv_array_push(&av, "--not");
833                         for (i = 0; i < deepen_not->nr; i++) {
834                                 struct string_list_item *s = deepen_not->items + i;
835                                 argv_array_push(&av, s->string);
836                         }
837                         argv_array_push(&av, "--not");
838                 }
839                 for (i = 0; i < want_obj->nr; i++) {
840                         struct object *o = want_obj->objects[i].item;
841                         argv_array_push(&av, oid_to_hex(&o->oid));
842                 }
843                 deepen_by_rev_list(writer, av.argc, av.argv, shallows, want_obj);
844                 argv_array_clear(&av);
845                 ret = 1;
846         } else {
847                 if (shallows->nr > 0) {
848                         int i;
849                         for (i = 0; i < shallows->nr; i++)
850                                 register_shallow(the_repository,
851                                                  &shallows->objects[i].item->oid);
852                 }
853         }
854
855         shallow_nr += shallows->nr;
856         return ret;
857 }
858
859 static int process_shallow(const char *line, struct object_array *shallows)
860 {
861         const char *arg;
862         if (skip_prefix(line, "shallow ", &arg)) {
863                 struct object_id oid;
864                 struct object *object;
865                 if (get_oid_hex(arg, &oid))
866                         die("invalid shallow line: %s", line);
867                 object = parse_object(the_repository, &oid);
868                 if (!object)
869                         return 1;
870                 if (object->type != OBJ_COMMIT)
871                         die("invalid shallow object %s", oid_to_hex(&oid));
872                 if (!(object->flags & CLIENT_SHALLOW)) {
873                         object->flags |= CLIENT_SHALLOW;
874                         add_object_array(object, NULL, shallows);
875                 }
876                 return 1;
877         }
878
879         return 0;
880 }
881
882 static int process_deepen(const char *line, int *depth)
883 {
884         const char *arg;
885         if (skip_prefix(line, "deepen ", &arg)) {
886                 char *end = NULL;
887                 *depth = (int)strtol(arg, &end, 0);
888                 if (!end || *end || *depth <= 0)
889                         die("Invalid deepen: %s", line);
890                 return 1;
891         }
892
893         return 0;
894 }
895
896 static int process_deepen_since(const char *line, timestamp_t *deepen_since, int *deepen_rev_list)
897 {
898         const char *arg;
899         if (skip_prefix(line, "deepen-since ", &arg)) {
900                 char *end = NULL;
901                 *deepen_since = parse_timestamp(arg, &end, 0);
902                 if (!end || *end || !deepen_since ||
903                     /* revisions.c's max_age -1 is special */
904                     *deepen_since == -1)
905                         die("Invalid deepen-since: %s", line);
906                 *deepen_rev_list = 1;
907                 return 1;
908         }
909         return 0;
910 }
911
912 static int process_deepen_not(const char *line, struct string_list *deepen_not, int *deepen_rev_list)
913 {
914         const char *arg;
915         if (skip_prefix(line, "deepen-not ", &arg)) {
916                 char *ref = NULL;
917                 struct object_id oid;
918                 if (expand_ref(the_repository, arg, strlen(arg), &oid, &ref) != 1)
919                         die("git upload-pack: ambiguous deepen-not: %s", line);
920                 string_list_append(deepen_not, ref);
921                 free(ref);
922                 *deepen_rev_list = 1;
923                 return 1;
924         }
925         return 0;
926 }
927
928 static void receive_needs(struct upload_pack_data *data,
929                           struct packet_reader *reader)
930 {
931         int has_non_tip = 0;
932
933         shallow_nr = 0;
934         for (;;) {
935                 struct object *o;
936                 const char *features;
937                 struct object_id oid_buf;
938                 const char *arg;
939
940                 reset_timeout(data->timeout);
941                 if (packet_reader_read(reader) != PACKET_READ_NORMAL)
942                         break;
943
944                 if (process_shallow(reader->line, &data->shallows))
945                         continue;
946                 if (process_deepen(reader->line, &data->depth))
947                         continue;
948                 if (process_deepen_since(reader->line, &data->deepen_since, &data->deepen_rev_list))
949                         continue;
950                 if (process_deepen_not(reader->line, &data->deepen_not, &data->deepen_rev_list))
951                         continue;
952
953                 if (skip_prefix(reader->line, "filter ", &arg)) {
954                         if (!data->filter_capability_requested)
955                                 die("git upload-pack: filtering capability not negotiated");
956                         list_objects_filter_die_if_populated(&data->filter_options);
957                         parse_list_objects_filter(&data->filter_options, arg);
958                         continue;
959                 }
960
961                 if (!skip_prefix(reader->line, "want ", &arg) ||
962                     parse_oid_hex(arg, &oid_buf, &features))
963                         die("git upload-pack: protocol error, "
964                             "expected to get object ID, not '%s'", reader->line);
965
966                 if (parse_feature_request(features, "deepen-relative"))
967                         data->deepen_relative = 1;
968                 if (parse_feature_request(features, "multi_ack_detailed"))
969                         data->multi_ack = MULTI_ACK_DETAILED;
970                 else if (parse_feature_request(features, "multi_ack"))
971                         data->multi_ack = MULTI_ACK;
972                 if (parse_feature_request(features, "no-done"))
973                         data->no_done = 1;
974                 if (parse_feature_request(features, "thin-pack"))
975                         data->use_thin_pack = 1;
976                 if (parse_feature_request(features, "ofs-delta"))
977                         data->use_ofs_delta = 1;
978                 if (parse_feature_request(features, "side-band-64k"))
979                         data->use_sideband = LARGE_PACKET_MAX;
980                 else if (parse_feature_request(features, "side-band"))
981                         data->use_sideband = DEFAULT_PACKET_MAX;
982                 if (parse_feature_request(features, "no-progress"))
983                         data->no_progress = 1;
984                 if (parse_feature_request(features, "include-tag"))
985                         data->use_include_tag = 1;
986                 if (data->allow_filter &&
987                     parse_feature_request(features, "filter"))
988                         data->filter_capability_requested = 1;
989
990                 o = parse_object(the_repository, &oid_buf);
991                 if (!o) {
992                         packet_writer_error(&data->writer,
993                                             "upload-pack: not our ref %s",
994                                             oid_to_hex(&oid_buf));
995                         die("git upload-pack: not our ref %s",
996                             oid_to_hex(&oid_buf));
997                 }
998                 if (!(o->flags & WANTED)) {
999                         o->flags |= WANTED;
1000                         if (!((allow_unadvertised_object_request & ALLOW_ANY_SHA1) == ALLOW_ANY_SHA1
1001                               || is_our_ref(o)))
1002                                 has_non_tip = 1;
1003                         add_object_array(o, NULL, &data->want_obj);
1004                 }
1005         }
1006
1007         /*
1008          * We have sent all our refs already, and the other end
1009          * should have chosen out of them. When we are operating
1010          * in the stateless RPC mode, however, their choice may
1011          * have been based on the set of older refs advertised
1012          * by another process that handled the initial request.
1013          */
1014         if (has_non_tip)
1015                 check_non_tip(data);
1016
1017         if (!data->use_sideband && data->daemon_mode)
1018                 data->no_progress = 1;
1019
1020         if (data->depth == 0 && !data->deepen_rev_list && data->shallows.nr == 0)
1021                 return;
1022
1023         if (send_shallow_list(&data->writer,
1024                               data->depth,
1025                               data->deepen_rev_list,
1026                               data->deepen_since,
1027                               &data->deepen_not,
1028                               data->deepen_relative,
1029                               &data->shallows,
1030                               &data->want_obj))
1031                 packet_flush(1);
1032 }
1033
1034 /* return non-zero if the ref is hidden, otherwise 0 */
1035 static int mark_our_ref(const char *refname, const char *refname_full,
1036                         const struct object_id *oid)
1037 {
1038         struct object *o = lookup_unknown_object(oid);
1039
1040         if (ref_is_hidden(refname, refname_full)) {
1041                 o->flags |= HIDDEN_REF;
1042                 return 1;
1043         }
1044         o->flags |= OUR_REF;
1045         return 0;
1046 }
1047
1048 static int check_ref(const char *refname_full, const struct object_id *oid,
1049                      int flag, void *cb_data)
1050 {
1051         const char *refname = strip_namespace(refname_full);
1052
1053         mark_our_ref(refname, refname_full, oid);
1054         return 0;
1055 }
1056
1057 static void format_symref_info(struct strbuf *buf, struct string_list *symref)
1058 {
1059         struct string_list_item *item;
1060
1061         if (!symref->nr)
1062                 return;
1063         for_each_string_list_item(item, symref)
1064                 strbuf_addf(buf, " symref=%s:%s", item->string, (char *)item->util);
1065 }
1066
1067 static int send_ref(const char *refname, const struct object_id *oid,
1068                     int flag, void *cb_data)
1069 {
1070         static const char *capabilities = "multi_ack thin-pack side-band"
1071                 " side-band-64k ofs-delta shallow deepen-since deepen-not"
1072                 " deepen-relative no-progress include-tag multi_ack_detailed";
1073         const char *refname_nons = strip_namespace(refname);
1074         struct object_id peeled;
1075         struct upload_pack_data *data = cb_data;
1076
1077         if (mark_our_ref(refname_nons, refname, oid))
1078                 return 0;
1079
1080         if (capabilities) {
1081                 struct strbuf symref_info = STRBUF_INIT;
1082
1083                 format_symref_info(&symref_info, &data->symref);
1084                 packet_write_fmt(1, "%s %s%c%s%s%s%s%s%s agent=%s\n",
1085                              oid_to_hex(oid), refname_nons,
1086                              0, capabilities,
1087                              (allow_unadvertised_object_request & ALLOW_TIP_SHA1) ?
1088                                      " allow-tip-sha1-in-want" : "",
1089                              (allow_unadvertised_object_request & ALLOW_REACHABLE_SHA1) ?
1090                                      " allow-reachable-sha1-in-want" : "",
1091                              data->stateless_rpc ? " no-done" : "",
1092                              symref_info.buf,
1093                              data->allow_filter ? " filter" : "",
1094                              git_user_agent_sanitized());
1095                 strbuf_release(&symref_info);
1096         } else {
1097                 packet_write_fmt(1, "%s %s\n", oid_to_hex(oid), refname_nons);
1098         }
1099         capabilities = NULL;
1100         if (!peel_ref(refname, &peeled))
1101                 packet_write_fmt(1, "%s %s^{}\n", oid_to_hex(&peeled), refname_nons);
1102         return 0;
1103 }
1104
1105 static int find_symref(const char *refname, const struct object_id *oid,
1106                        int flag, void *cb_data)
1107 {
1108         const char *symref_target;
1109         struct string_list_item *item;
1110
1111         if ((flag & REF_ISSYMREF) == 0)
1112                 return 0;
1113         symref_target = resolve_ref_unsafe(refname, 0, NULL, &flag);
1114         if (!symref_target || (flag & REF_ISSYMREF) == 0)
1115                 die("'%s' is a symref but it is not?", refname);
1116         item = string_list_append(cb_data, strip_namespace(refname));
1117         item->util = xstrdup(strip_namespace(symref_target));
1118         return 0;
1119 }
1120
1121 static int upload_pack_config(const char *var, const char *value, void *cb_data)
1122 {
1123         struct upload_pack_data *data = cb_data;
1124
1125         if (!strcmp("uploadpack.allowtipsha1inwant", var)) {
1126                 if (git_config_bool(var, value))
1127                         allow_unadvertised_object_request |= ALLOW_TIP_SHA1;
1128                 else
1129                         allow_unadvertised_object_request &= ~ALLOW_TIP_SHA1;
1130         } else if (!strcmp("uploadpack.allowreachablesha1inwant", var)) {
1131                 if (git_config_bool(var, value))
1132                         allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
1133                 else
1134                         allow_unadvertised_object_request &= ~ALLOW_REACHABLE_SHA1;
1135         } else if (!strcmp("uploadpack.allowanysha1inwant", var)) {
1136                 if (git_config_bool(var, value))
1137                         allow_unadvertised_object_request |= ALLOW_ANY_SHA1;
1138                 else
1139                         allow_unadvertised_object_request &= ~ALLOW_ANY_SHA1;
1140         } else if (!strcmp("uploadpack.keepalive", var)) {
1141                 data->keepalive = git_config_int(var, value);
1142                 if (!data->keepalive)
1143                         data->keepalive = -1;
1144         } else if (!strcmp("uploadpack.allowfilter", var)) {
1145                 data->allow_filter = git_config_bool(var, value);
1146         } else if (!strcmp("uploadpack.allowrefinwant", var)) {
1147                 data->allow_ref_in_want = git_config_bool(var, value);
1148         } else if (!strcmp("uploadpack.allowsidebandall", var)) {
1149                 allow_sideband_all = git_config_bool(var, value);
1150         } else if (!strcmp("core.precomposeunicode", var)) {
1151                 precomposed_unicode = git_config_bool(var, value);
1152         }
1153
1154         if (current_config_scope() != CONFIG_SCOPE_LOCAL &&
1155         current_config_scope() != CONFIG_SCOPE_WORKTREE) {
1156                 if (!strcmp("uploadpack.packobjectshook", var))
1157                         return git_config_string(&pack_objects_hook, var, value);
1158         }
1159
1160         return parse_hide_refs_config(var, value, "uploadpack");
1161 }
1162
1163 void upload_pack(struct upload_pack_options *options)
1164 {
1165         struct packet_reader reader;
1166         struct upload_pack_data data;
1167
1168         upload_pack_data_init(&data);
1169
1170         git_config(upload_pack_config, &data);
1171
1172         data.stateless_rpc = options->stateless_rpc;
1173         data.daemon_mode = options->daemon_mode;
1174         data.timeout = options->timeout;
1175
1176         head_ref_namespaced(find_symref, &data.symref);
1177
1178         if (options->advertise_refs || !data.stateless_rpc) {
1179                 reset_timeout(data.timeout);
1180                 head_ref_namespaced(send_ref, &data);
1181                 for_each_namespaced_ref(send_ref, &data);
1182                 advertise_shallow_grafts(1);
1183                 packet_flush(1);
1184         } else {
1185                 head_ref_namespaced(check_ref, NULL);
1186                 for_each_namespaced_ref(check_ref, NULL);
1187         }
1188
1189         if (!options->advertise_refs) {
1190                 packet_reader_init(&reader, 0, NULL, 0,
1191                                    PACKET_READ_CHOMP_NEWLINE |
1192                                    PACKET_READ_DIE_ON_ERR_PACKET);
1193
1194                 receive_needs(&data, &reader);
1195                 if (data.want_obj.nr) {
1196                         get_common_commits(&data, &reader);
1197                         create_pack_file(&data);
1198                 }
1199         }
1200
1201         upload_pack_data_clear(&data);
1202 }
1203
1204 static int parse_want(struct packet_writer *writer, const char *line,
1205                       struct object_array *want_obj)
1206 {
1207         const char *arg;
1208         if (skip_prefix(line, "want ", &arg)) {
1209                 struct object_id oid;
1210                 struct object *o;
1211
1212                 if (get_oid_hex(arg, &oid))
1213                         die("git upload-pack: protocol error, "
1214                             "expected to get oid, not '%s'", line);
1215
1216                 o = parse_object(the_repository, &oid);
1217                 if (!o) {
1218                         packet_writer_error(writer,
1219                                             "upload-pack: not our ref %s",
1220                                             oid_to_hex(&oid));
1221                         die("git upload-pack: not our ref %s",
1222                             oid_to_hex(&oid));
1223                 }
1224
1225                 if (!(o->flags & WANTED)) {
1226                         o->flags |= WANTED;
1227                         add_object_array(o, NULL, want_obj);
1228                 }
1229
1230                 return 1;
1231         }
1232
1233         return 0;
1234 }
1235
1236 static int parse_want_ref(struct packet_writer *writer, const char *line,
1237                           struct string_list *wanted_refs,
1238                           struct object_array *want_obj)
1239 {
1240         const char *arg;
1241         if (skip_prefix(line, "want-ref ", &arg)) {
1242                 struct object_id oid;
1243                 struct string_list_item *item;
1244                 struct object *o;
1245
1246                 if (read_ref(arg, &oid)) {
1247                         packet_writer_error(writer, "unknown ref %s", arg);
1248                         die("unknown ref %s", arg);
1249                 }
1250
1251                 item = string_list_append(wanted_refs, arg);
1252                 item->util = oiddup(&oid);
1253
1254                 o = parse_object_or_die(&oid, arg);
1255                 if (!(o->flags & WANTED)) {
1256                         o->flags |= WANTED;
1257                         add_object_array(o, NULL, want_obj);
1258                 }
1259
1260                 return 1;
1261         }
1262
1263         return 0;
1264 }
1265
1266 static int parse_have(const char *line, struct oid_array *haves)
1267 {
1268         const char *arg;
1269         if (skip_prefix(line, "have ", &arg)) {
1270                 struct object_id oid;
1271
1272                 if (get_oid_hex(arg, &oid))
1273                         die("git upload-pack: expected SHA1 object, got '%s'", arg);
1274                 oid_array_append(haves, &oid);
1275                 return 1;
1276         }
1277
1278         return 0;
1279 }
1280
1281 static void process_args(struct packet_reader *request,
1282                          struct upload_pack_data *data)
1283 {
1284         while (packet_reader_read(request) == PACKET_READ_NORMAL) {
1285                 const char *arg = request->line;
1286                 const char *p;
1287
1288                 /* process want */
1289                 if (parse_want(&data->writer, arg, &data->want_obj))
1290                         continue;
1291                 if (data->allow_ref_in_want &&
1292                     parse_want_ref(&data->writer, arg, &data->wanted_refs,
1293                                    &data->want_obj))
1294                         continue;
1295                 /* process have line */
1296                 if (parse_have(arg, &data->haves))
1297                         continue;
1298
1299                 /* process args like thin-pack */
1300                 if (!strcmp(arg, "thin-pack")) {
1301                         data->use_thin_pack = 1;
1302                         continue;
1303                 }
1304                 if (!strcmp(arg, "ofs-delta")) {
1305                         data->use_ofs_delta = 1;
1306                         continue;
1307                 }
1308                 if (!strcmp(arg, "no-progress")) {
1309                         data->no_progress = 1;
1310                         continue;
1311                 }
1312                 if (!strcmp(arg, "include-tag")) {
1313                         data->use_include_tag = 1;
1314                         continue;
1315                 }
1316                 if (!strcmp(arg, "done")) {
1317                         data->done = 1;
1318                         continue;
1319                 }
1320
1321                 /* Shallow related arguments */
1322                 if (process_shallow(arg, &data->shallows))
1323                         continue;
1324                 if (process_deepen(arg, &data->depth))
1325                         continue;
1326                 if (process_deepen_since(arg, &data->deepen_since,
1327                                          &data->deepen_rev_list))
1328                         continue;
1329                 if (process_deepen_not(arg, &data->deepen_not,
1330                                        &data->deepen_rev_list))
1331                         continue;
1332                 if (!strcmp(arg, "deepen-relative")) {
1333                         data->deepen_relative = 1;
1334                         continue;
1335                 }
1336
1337                 if (data->allow_filter && skip_prefix(arg, "filter ", &p)) {
1338                         list_objects_filter_die_if_populated(&data->filter_options);
1339                         parse_list_objects_filter(&data->filter_options, p);
1340                         continue;
1341                 }
1342
1343                 if ((git_env_bool("GIT_TEST_SIDEBAND_ALL", 0) ||
1344                      allow_sideband_all) &&
1345                     !strcmp(arg, "sideband-all")) {
1346                         data->writer.use_sideband = 1;
1347                         continue;
1348                 }
1349
1350                 /* ignore unknown lines maybe? */
1351                 die("unexpected line: '%s'", arg);
1352         }
1353
1354         if (request->status != PACKET_READ_FLUSH)
1355                 die(_("expected flush after fetch arguments"));
1356 }
1357
1358 static int process_haves(struct oid_array *haves, struct oid_array *common,
1359                          struct object_array *have_obj)
1360 {
1361         int i;
1362
1363         /* Process haves */
1364         for (i = 0; i < haves->nr; i++) {
1365                 const struct object_id *oid = &haves->oid[i];
1366                 struct object *o;
1367                 int we_knew_they_have = 0;
1368
1369                 if (!has_object_file(oid))
1370                         continue;
1371
1372                 oid_array_append(common, oid);
1373
1374                 o = parse_object(the_repository, oid);
1375                 if (!o)
1376                         die("oops (%s)", oid_to_hex(oid));
1377                 if (o->type == OBJ_COMMIT) {
1378                         struct commit_list *parents;
1379                         struct commit *commit = (struct commit *)o;
1380                         if (o->flags & THEY_HAVE)
1381                                 we_knew_they_have = 1;
1382                         else
1383                                 o->flags |= THEY_HAVE;
1384                         if (!oldest_have || (commit->date < oldest_have))
1385                                 oldest_have = commit->date;
1386                         for (parents = commit->parents;
1387                              parents;
1388                              parents = parents->next)
1389                                 parents->item->object.flags |= THEY_HAVE;
1390                 }
1391                 if (!we_knew_they_have)
1392                         add_object_array(o, NULL, have_obj);
1393         }
1394
1395         return 0;
1396 }
1397
1398 static int send_acks(struct packet_writer *writer, struct oid_array *acks,
1399                      const struct object_array *have_obj,
1400                      struct object_array *want_obj)
1401 {
1402         int i;
1403
1404         packet_writer_write(writer, "acknowledgments\n");
1405
1406         /* Send Acks */
1407         if (!acks->nr)
1408                 packet_writer_write(writer, "NAK\n");
1409
1410         for (i = 0; i < acks->nr; i++) {
1411                 packet_writer_write(writer, "ACK %s\n",
1412                                     oid_to_hex(&acks->oid[i]));
1413         }
1414
1415         if (ok_to_give_up(have_obj, want_obj)) {
1416                 /* Send Ready */
1417                 packet_writer_write(writer, "ready\n");
1418                 return 1;
1419         }
1420
1421         return 0;
1422 }
1423
1424 static int process_haves_and_send_acks(struct upload_pack_data *data)
1425 {
1426         struct oid_array common = OID_ARRAY_INIT;
1427         int ret = 0;
1428
1429         process_haves(&data->haves, &common, &data->have_obj);
1430         if (data->done) {
1431                 ret = 1;
1432         } else if (send_acks(&data->writer, &common,
1433                              &data->have_obj, &data->want_obj)) {
1434                 packet_writer_delim(&data->writer);
1435                 ret = 1;
1436         } else {
1437                 /* Add Flush */
1438                 packet_writer_flush(&data->writer);
1439                 ret = 0;
1440         }
1441
1442         oid_array_clear(&data->haves);
1443         oid_array_clear(&common);
1444         return ret;
1445 }
1446
1447 static void send_wanted_ref_info(struct upload_pack_data *data)
1448 {
1449         const struct string_list_item *item;
1450
1451         if (!data->wanted_refs.nr)
1452                 return;
1453
1454         packet_writer_write(&data->writer, "wanted-refs\n");
1455
1456         for_each_string_list_item(item, &data->wanted_refs) {
1457                 packet_writer_write(&data->writer, "%s %s\n",
1458                                     oid_to_hex(item->util),
1459                                     item->string);
1460         }
1461
1462         packet_writer_delim(&data->writer);
1463 }
1464
1465 static void send_shallow_info(struct upload_pack_data *data)
1466 {
1467         /* No shallow info needs to be sent */
1468         if (!data->depth && !data->deepen_rev_list && !data->shallows.nr &&
1469             !is_repository_shallow(the_repository))
1470                 return;
1471
1472         packet_writer_write(&data->writer, "shallow-info\n");
1473
1474         if (!send_shallow_list(&data->writer, data->depth,
1475                                data->deepen_rev_list,
1476                                data->deepen_since, &data->deepen_not,
1477                                data->deepen_relative,
1478                                &data->shallows, &data->want_obj) &&
1479             is_repository_shallow(the_repository))
1480                 deepen(&data->writer, INFINITE_DEPTH, data->deepen_relative,
1481                        &data->shallows, &data->want_obj);
1482
1483         packet_delim(1);
1484 }
1485
1486 enum fetch_state {
1487         FETCH_PROCESS_ARGS = 0,
1488         FETCH_SEND_ACKS,
1489         FETCH_SEND_PACK,
1490         FETCH_DONE,
1491 };
1492
1493 int upload_pack_v2(struct repository *r, struct argv_array *keys,
1494                    struct packet_reader *request)
1495 {
1496         enum fetch_state state = FETCH_PROCESS_ARGS;
1497         struct upload_pack_data data;
1498
1499         clear_object_flags(ALL_FLAGS);
1500
1501         upload_pack_data_init(&data);
1502         data.use_sideband = LARGE_PACKET_MAX;
1503
1504         git_config(upload_pack_config, &data);
1505
1506         while (state != FETCH_DONE) {
1507                 switch (state) {
1508                 case FETCH_PROCESS_ARGS:
1509                         process_args(request, &data);
1510
1511                         if (!data.want_obj.nr) {
1512                                 /*
1513                                  * Request didn't contain any 'want' lines,
1514                                  * guess they didn't want anything.
1515                                  */
1516                                 state = FETCH_DONE;
1517                         } else if (data.haves.nr) {
1518                                 /*
1519                                  * Request had 'have' lines, so lets ACK them.
1520                                  */
1521                                 state = FETCH_SEND_ACKS;
1522                         } else {
1523                                 /*
1524                                  * Request had 'want's but no 'have's so we can
1525                                  * immedietly go to construct and send a pack.
1526                                  */
1527                                 state = FETCH_SEND_PACK;
1528                         }
1529                         break;
1530                 case FETCH_SEND_ACKS:
1531                         if (process_haves_and_send_acks(&data))
1532                                 state = FETCH_SEND_PACK;
1533                         else
1534                                 state = FETCH_DONE;
1535                         break;
1536                 case FETCH_SEND_PACK:
1537                         send_wanted_ref_info(&data);
1538                         send_shallow_info(&data);
1539
1540                         packet_writer_write(&data.writer, "packfile\n");
1541                         create_pack_file(&data);
1542                         state = FETCH_DONE;
1543                         break;
1544                 case FETCH_DONE:
1545                         continue;
1546                 }
1547         }
1548
1549         upload_pack_data_clear(&data);
1550         return 0;
1551 }
1552
1553 int upload_pack_advertise(struct repository *r,
1554                           struct strbuf *value)
1555 {
1556         if (value) {
1557                 int allow_filter_value;
1558                 int allow_ref_in_want;
1559                 int allow_sideband_all_value;
1560
1561                 strbuf_addstr(value, "shallow");
1562
1563                 if (!repo_config_get_bool(the_repository,
1564                                          "uploadpack.allowfilter",
1565                                          &allow_filter_value) &&
1566                     allow_filter_value)
1567                         strbuf_addstr(value, " filter");
1568
1569                 if (!repo_config_get_bool(the_repository,
1570                                          "uploadpack.allowrefinwant",
1571                                          &allow_ref_in_want) &&
1572                     allow_ref_in_want)
1573                         strbuf_addstr(value, " ref-in-want");
1574
1575                 if (git_env_bool("GIT_TEST_SIDEBAND_ALL", 0) ||
1576                     (!repo_config_get_bool(the_repository,
1577                                            "uploadpack.allowsidebandall",
1578                                            &allow_sideband_all_value) &&
1579                      allow_sideband_all_value))
1580                         strbuf_addstr(value, " sideband-all");
1581         }
1582
1583         return 1;
1584 }