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