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 '%s' write error. Out of diskspace", f->name);
28 if (errno == EAGAIN || errno == EINTR)
30 die("sha1 file '%s' write error (%s)", f->name, strerror(errno));
34 int sha1close(struct sha1file *f, unsigned char *result, int update)
36 unsigned offset = f->offset;
38 SHA1_Update(&f->ctx, f->buffer, offset);
41 SHA1_Final(f->buffer, &f->ctx);
43 memcpy(result, f->buffer, 20);
47 die("%s: sha1 file error on close (%s)", f->name, strerror(errno));
52 int sha1write(struct sha1file *f, void *buf, unsigned int 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);
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));
100 struct sha1file *sha1fd(int fd, const char *name)
105 f = xmalloc(sizeof(*f));
109 die("you wascally wabbit, you");
111 memcpy(f->name, name, len+1);
120 int sha1write_compressed(struct sha1file *f, void *in, unsigned int size)
123 unsigned long maxsize;
126 memset(&stream, 0, sizeof(stream));
127 deflateInit(&stream, Z_DEFAULT_COMPRESSION);
128 maxsize = deflateBound(&stream, size);
129 out = xmalloc(maxsize);
133 stream.avail_in = size;
135 stream.next_out = out;
136 stream.avail_out = maxsize;
138 while (deflate(&stream, Z_FINISH) == Z_OK)
142 size = stream.total_out;
143 sha1write(f, out, size);