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