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