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