Merge branch 'jk/tempfile-ferror-fclose-confusion'
[git] / pack-write.c
1 #include "cache.h"
2 #include "pack.h"
3 #include "csum-file.h"
4
5 void reset_pack_idx_option(struct pack_idx_option *opts)
6 {
7         memset(opts, 0, sizeof(*opts));
8         opts->version = 2;
9         opts->off32_limit = 0x7fffffff;
10 }
11
12 static int sha1_compare(const void *_a, const void *_b)
13 {
14         struct pack_idx_entry *a = *(struct pack_idx_entry **)_a;
15         struct pack_idx_entry *b = *(struct pack_idx_entry **)_b;
16         return hashcmp(a->sha1, b->sha1);
17 }
18
19 static int cmp_uint32(const void *a_, const void *b_)
20 {
21         uint32_t a = *((uint32_t *)a_);
22         uint32_t b = *((uint32_t *)b_);
23
24         return (a < b) ? -1 : (a != b);
25 }
26
27 static int need_large_offset(off_t offset, const struct pack_idx_option *opts)
28 {
29         uint32_t ofsval;
30
31         if ((offset >> 31) || (opts->off32_limit < offset))
32                 return 1;
33         if (!opts->anomaly_nr)
34                 return 0;
35         ofsval = offset;
36         return !!bsearch(&ofsval, opts->anomaly, opts->anomaly_nr,
37                          sizeof(ofsval), cmp_uint32);
38 }
39
40 /*
41  * On entry *sha1 contains the pack content SHA1 hash, on exit it is
42  * the SHA1 hash of sorted object names. The objects array passed in
43  * will be sorted by SHA1 on exit.
44  */
45 const char *write_idx_file(const char *index_name, struct pack_idx_entry **objects,
46                            int nr_objects, const struct pack_idx_option *opts,
47                            const unsigned char *sha1)
48 {
49         struct sha1file *f;
50         struct pack_idx_entry **sorted_by_sha, **list, **last;
51         off_t last_obj_offset = 0;
52         uint32_t array[256];
53         int i, fd;
54         uint32_t index_version;
55
56         if (nr_objects) {
57                 sorted_by_sha = objects;
58                 list = sorted_by_sha;
59                 last = sorted_by_sha + nr_objects;
60                 for (i = 0; i < nr_objects; ++i) {
61                         if (objects[i]->offset > last_obj_offset)
62                                 last_obj_offset = objects[i]->offset;
63                 }
64                 QSORT(sorted_by_sha, nr_objects, sha1_compare);
65         }
66         else
67                 sorted_by_sha = list = last = NULL;
68
69         if (opts->flags & WRITE_IDX_VERIFY) {
70                 assert(index_name);
71                 f = sha1fd_check(index_name);
72         } else {
73                 if (!index_name) {
74                         static char tmp_file[PATH_MAX];
75                         fd = odb_mkstemp(tmp_file, sizeof(tmp_file), "pack/tmp_idx_XXXXXX");
76                         index_name = xstrdup(tmp_file);
77                 } else {
78                         unlink(index_name);
79                         fd = open(index_name, O_CREAT|O_EXCL|O_WRONLY, 0600);
80                 }
81                 if (fd < 0)
82                         die_errno("unable to create '%s'", index_name);
83                 f = sha1fd(fd, index_name);
84         }
85
86         /* if last object's offset is >= 2^31 we should use index V2 */
87         index_version = need_large_offset(last_obj_offset, opts) ? 2 : opts->version;
88
89         /* index versions 2 and above need a header */
90         if (index_version >= 2) {
91                 struct pack_idx_header hdr;
92                 hdr.idx_signature = htonl(PACK_IDX_SIGNATURE);
93                 hdr.idx_version = htonl(index_version);
94                 sha1write(f, &hdr, sizeof(hdr));
95         }
96
97         /*
98          * Write the first-level table (the list is sorted,
99          * but we use a 256-entry lookup to be able to avoid
100          * having to do eight extra binary search iterations).
101          */
102         for (i = 0; i < 256; i++) {
103                 struct pack_idx_entry **next = list;
104                 while (next < last) {
105                         struct pack_idx_entry *obj = *next;
106                         if (obj->sha1[0] != i)
107                                 break;
108                         next++;
109                 }
110                 array[i] = htonl(next - sorted_by_sha);
111                 list = next;
112         }
113         sha1write(f, array, 256 * 4);
114
115         /*
116          * Write the actual SHA1 entries..
117          */
118         list = sorted_by_sha;
119         for (i = 0; i < nr_objects; i++) {
120                 struct pack_idx_entry *obj = *list++;
121                 if (index_version < 2) {
122                         uint32_t offset = htonl(obj->offset);
123                         sha1write(f, &offset, 4);
124                 }
125                 sha1write(f, obj->sha1, 20);
126                 if ((opts->flags & WRITE_IDX_STRICT) &&
127                     (i && !hashcmp(list[-2]->sha1, obj->sha1)))
128                         die("The same object %s appears twice in the pack",
129                             sha1_to_hex(obj->sha1));
130         }
131
132         if (index_version >= 2) {
133                 unsigned int nr_large_offset = 0;
134
135                 /* write the crc32 table */
136                 list = sorted_by_sha;
137                 for (i = 0; i < nr_objects; i++) {
138                         struct pack_idx_entry *obj = *list++;
139                         uint32_t crc32_val = htonl(obj->crc32);
140                         sha1write(f, &crc32_val, 4);
141                 }
142
143                 /* write the 32-bit offset table */
144                 list = sorted_by_sha;
145                 for (i = 0; i < nr_objects; i++) {
146                         struct pack_idx_entry *obj = *list++;
147                         uint32_t offset;
148
149                         offset = (need_large_offset(obj->offset, opts)
150                                   ? (0x80000000 | nr_large_offset++)
151                                   : obj->offset);
152                         offset = htonl(offset);
153                         sha1write(f, &offset, 4);
154                 }
155
156                 /* write the large offset table */
157                 list = sorted_by_sha;
158                 while (nr_large_offset) {
159                         struct pack_idx_entry *obj = *list++;
160                         uint64_t offset = obj->offset;
161                         uint32_t split[2];
162
163                         if (!need_large_offset(offset, opts))
164                                 continue;
165                         split[0] = htonl(offset >> 32);
166                         split[1] = htonl(offset & 0xffffffff);
167                         sha1write(f, split, 8);
168                         nr_large_offset--;
169                 }
170         }
171
172         sha1write(f, sha1, 20);
173         sha1close(f, NULL, ((opts->flags & WRITE_IDX_VERIFY)
174                             ? CSUM_CLOSE : CSUM_FSYNC));
175         return index_name;
176 }
177
178 off_t write_pack_header(struct sha1file *f, uint32_t nr_entries)
179 {
180         struct pack_header hdr;
181
182         hdr.hdr_signature = htonl(PACK_SIGNATURE);
183         hdr.hdr_version = htonl(PACK_VERSION);
184         hdr.hdr_entries = htonl(nr_entries);
185         sha1write(f, &hdr, sizeof(hdr));
186         return sizeof(hdr);
187 }
188
189 /*
190  * Update pack header with object_count and compute new SHA1 for pack data
191  * associated to pack_fd, and write that SHA1 at the end.  That new SHA1
192  * is also returned in new_pack_sha1.
193  *
194  * If partial_pack_sha1 is non null, then the SHA1 of the existing pack
195  * (without the header update) is computed and validated against the
196  * one provided in partial_pack_sha1.  The validation is performed at
197  * partial_pack_offset bytes in the pack file.  The SHA1 of the remaining
198  * data (i.e. from partial_pack_offset to the end) is then computed and
199  * returned in partial_pack_sha1.
200  *
201  * Note that new_pack_sha1 is updated last, so both new_pack_sha1 and
202  * partial_pack_sha1 can refer to the same buffer if the caller is not
203  * interested in the resulting SHA1 of pack data above partial_pack_offset.
204  */
205 void fixup_pack_header_footer(int pack_fd,
206                          unsigned char *new_pack_sha1,
207                          const char *pack_name,
208                          uint32_t object_count,
209                          unsigned char *partial_pack_sha1,
210                          off_t partial_pack_offset)
211 {
212         int aligned_sz, buf_sz = 8 * 1024;
213         git_SHA_CTX old_sha1_ctx, new_sha1_ctx;
214         struct pack_header hdr;
215         char *buf;
216
217         git_SHA1_Init(&old_sha1_ctx);
218         git_SHA1_Init(&new_sha1_ctx);
219
220         if (lseek(pack_fd, 0, SEEK_SET) != 0)
221                 die_errno("Failed seeking to start of '%s'", pack_name);
222         if (read_in_full(pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
223                 die_errno("Unable to reread header of '%s'", pack_name);
224         if (lseek(pack_fd, 0, SEEK_SET) != 0)
225                 die_errno("Failed seeking to start of '%s'", pack_name);
226         git_SHA1_Update(&old_sha1_ctx, &hdr, sizeof(hdr));
227         hdr.hdr_entries = htonl(object_count);
228         git_SHA1_Update(&new_sha1_ctx, &hdr, sizeof(hdr));
229         write_or_die(pack_fd, &hdr, sizeof(hdr));
230         partial_pack_offset -= sizeof(hdr);
231
232         buf = xmalloc(buf_sz);
233         aligned_sz = buf_sz - sizeof(hdr);
234         for (;;) {
235                 ssize_t m, n;
236                 m = (partial_pack_sha1 && partial_pack_offset < aligned_sz) ?
237                         partial_pack_offset : aligned_sz;
238                 n = xread(pack_fd, buf, m);
239                 if (!n)
240                         break;
241                 if (n < 0)
242                         die_errno("Failed to checksum '%s'", pack_name);
243                 git_SHA1_Update(&new_sha1_ctx, buf, n);
244
245                 aligned_sz -= n;
246                 if (!aligned_sz)
247                         aligned_sz = buf_sz;
248
249                 if (!partial_pack_sha1)
250                         continue;
251
252                 git_SHA1_Update(&old_sha1_ctx, buf, n);
253                 partial_pack_offset -= n;
254                 if (partial_pack_offset == 0) {
255                         unsigned char sha1[20];
256                         git_SHA1_Final(sha1, &old_sha1_ctx);
257                         if (hashcmp(sha1, partial_pack_sha1) != 0)
258                                 die("Unexpected checksum for %s "
259                                     "(disk corruption?)", pack_name);
260                         /*
261                          * Now let's compute the SHA1 of the remainder of the
262                          * pack, which also means making partial_pack_offset
263                          * big enough not to matter anymore.
264                          */
265                         git_SHA1_Init(&old_sha1_ctx);
266                         partial_pack_offset = ~partial_pack_offset;
267                         partial_pack_offset -= MSB(partial_pack_offset, 1);
268                 }
269         }
270         free(buf);
271
272         if (partial_pack_sha1)
273                 git_SHA1_Final(partial_pack_sha1, &old_sha1_ctx);
274         git_SHA1_Final(new_pack_sha1, &new_sha1_ctx);
275         write_or_die(pack_fd, new_pack_sha1, 20);
276         fsync_or_die(pack_fd, pack_name);
277 }
278
279 char *index_pack_lockfile(int ip_out)
280 {
281         char packname[46];
282
283         /*
284          * The first thing we expect from index-pack's output
285          * is "pack\t%40s\n" or "keep\t%40s\n" (46 bytes) where
286          * %40s is the newly created pack SHA1 name.  In the "keep"
287          * case, we need it to remove the corresponding .keep file
288          * later on.  If we don't get that then tough luck with it.
289          */
290         if (read_in_full(ip_out, packname, 46) == 46 && packname[45] == '\n') {
291                 const char *name;
292                 packname[45] = 0;
293                 if (skip_prefix(packname, "keep\t", &name))
294                         return xstrfmt("%s/pack/pack-%s.keep",
295                                        get_object_directory(), name);
296         }
297         return NULL;
298 }
299
300 /*
301  * The per-object header is a pretty dense thing, which is
302  *  - first byte: low four bits are "size", then three bits of "type",
303  *    and the high bit is "size continues".
304  *  - each byte afterwards: low seven bits are size continuation,
305  *    with the high bit being "size continues"
306  */
307 int encode_in_pack_object_header(enum object_type type, uintmax_t size, unsigned char *hdr)
308 {
309         int n = 1;
310         unsigned char c;
311
312         if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
313                 die("bad type %d", type);
314
315         c = (type << 4) | (size & 15);
316         size >>= 4;
317         while (size) {
318                 *hdr++ = c | 0x80;
319                 c = size & 0x7f;
320                 size >>= 7;
321                 n++;
322         }
323         *hdr = c;
324         return n;
325 }
326
327 struct sha1file *create_tmp_packfile(char **pack_tmp_name)
328 {
329         char tmpname[PATH_MAX];
330         int fd;
331
332         fd = odb_mkstemp(tmpname, sizeof(tmpname), "pack/tmp_pack_XXXXXX");
333         *pack_tmp_name = xstrdup(tmpname);
334         return sha1fd(fd, *pack_tmp_name);
335 }
336
337 void finish_tmp_packfile(struct strbuf *name_buffer,
338                          const char *pack_tmp_name,
339                          struct pack_idx_entry **written_list,
340                          uint32_t nr_written,
341                          struct pack_idx_option *pack_idx_opts,
342                          unsigned char sha1[])
343 {
344         const char *idx_tmp_name;
345         int basename_len = name_buffer->len;
346
347         if (adjust_shared_perm(pack_tmp_name))
348                 die_errno("unable to make temporary pack file readable");
349
350         idx_tmp_name = write_idx_file(NULL, written_list, nr_written,
351                                       pack_idx_opts, sha1);
352         if (adjust_shared_perm(idx_tmp_name))
353                 die_errno("unable to make temporary index file readable");
354
355         strbuf_addf(name_buffer, "%s.pack", sha1_to_hex(sha1));
356
357         if (rename(pack_tmp_name, name_buffer->buf))
358                 die_errno("unable to rename temporary pack file");
359
360         strbuf_setlen(name_buffer, basename_len);
361
362         strbuf_addf(name_buffer, "%s.idx", sha1_to_hex(sha1));
363         if (rename(idx_tmp_name, name_buffer->buf))
364                 die_errno("unable to rename temporary index file");
365
366         strbuf_setlen(name_buffer, basename_len);
367
368         free((void *)idx_tmp_name);
369 }