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