4 * Copyright (C) 2005 Linus Torvalds
6 * Simple file write infrastructure for writing SHA1-summed
7 * files. Useful when you write a file that you want to be
8 * able to verify hasn't been messed with afterwards.
11 #include "csum-file.h"
13 static void sha1flush(struct sha1file *f, unsigned int count)
15 void *buf = f->buffer;
18 int ret = xwrite(f->fd, buf, count);
20 buf = (char *) buf + ret;
27 die("sha1 file '%s' write error. Out of diskspace", f->name);
28 die("sha1 file '%s' write error (%s)", f->name, strerror(errno));
32 int sha1close(struct sha1file *f, unsigned char *result, int update)
34 unsigned offset = f->offset;
36 SHA1_Update(&f->ctx, f->buffer, offset);
39 SHA1_Final(f->buffer, &f->ctx);
41 hashcpy(result, f->buffer);
45 die("%s: sha1 file error on close (%s)", f->name, strerror(errno));
50 int sha1write(struct sha1file *f, void *buf, unsigned int count)
53 f->crc32 = crc32(f->crc32, buf, count);
55 unsigned offset = f->offset;
56 unsigned left = sizeof(f->buffer) - offset;
57 unsigned nr = count > left ? left : count;
59 memcpy(f->buffer + offset, buf, nr);
62 buf = (char *) buf + nr;
65 SHA1_Update(&f->ctx, f->buffer, offset);
74 struct sha1file *sha1create(const char *fmt, ...)
81 f = xmalloc(sizeof(*f));
84 len = vsnprintf(f->name, sizeof(f->name), fmt, arg);
87 die("you wascally wabbit, you");
90 fd = open(f->name, O_CREAT | O_EXCL | O_WRONLY, 0666);
92 die("unable to open %s (%s)", f->name, strerror(errno));
101 struct sha1file *sha1fd(int fd, const char *name)
106 f = xmalloc(sizeof(*f));
110 die("you wascally wabbit, you");
112 memcpy(f->name, name, len+1);
122 int sha1write_compressed(struct sha1file *f, void *in, unsigned int size)
125 unsigned long maxsize;
128 memset(&stream, 0, sizeof(stream));
129 deflateInit(&stream, zlib_compression_level);
130 maxsize = deflateBound(&stream, size);
131 out = xmalloc(maxsize);
135 stream.avail_in = size;
137 stream.next_out = out;
138 stream.avail_out = maxsize;
140 while (deflate(&stream, Z_FINISH) == Z_OK)
144 size = stream.total_out;
145 sha1write(f, out, size);
150 void crc32_begin(struct sha1file *f)
152 f->crc32 = crc32(0, Z_NULL, 0);
156 uint32_t crc32_end(struct sha1file *f)