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