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