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