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