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