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 int sha1flush(struct sha1file *f, unsigned int count)
15 void *buf = f->buffer;
18 int ret = write(f->fd, buf, count);
27 die("sha1 file write error. Out of diskspace");
28 if (errno == EAGAIN || errno == EINTR)
30 die("sha1 file write error (%s)", strerror(errno));
34 int sha1close(struct sha1file *f)
36 unsigned offset = f->offset;
38 SHA1_Update(&f->ctx, f->buffer, offset);
41 SHA1_Final(f->buffer, &f->ctx);
46 int sha1write(struct sha1file *f, void *buf, unsigned int count)
49 unsigned offset = f->offset;
50 unsigned left = sizeof(f->buffer) - offset;
51 unsigned nr = count > left ? left : count;
53 memcpy(f->buffer + offset, buf, nr);
58 SHA1_Update(&f->ctx, f->buffer, offset);
67 struct sha1file *sha1create(const char *fmt, ...)
69 static char filename[PATH_MAX];
76 len = vsnprintf(filename, PATH_MAX, fmt, arg);
80 die("you wascally wabbit, you");
81 fd = open(filename, O_CREAT | O_EXCL | O_WRONLY, 0644);
83 die("unable to open %s (%s)", filename, strerror(errno));
84 f = xmalloc(sizeof(*f));
92 int sha1write_compressed(struct sha1file *f, void *in, unsigned int size)
95 unsigned long maxsize;
98 memset(&stream, 0, sizeof(stream));
99 deflateInit(&stream, Z_DEFAULT_COMPRESSION);
100 maxsize = deflateBound(&stream, size);
101 out = xmalloc(maxsize);
105 stream.avail_in = size;
107 stream.next_out = out;
108 stream.avail_out = maxsize;
110 while (deflate(&stream, Z_FINISH) == Z_OK)
114 size = stream.total_out;
115 sha1write(f, out, size);