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 unsigned offset
= f
->offset
;
54 unsigned left
= sizeof(f
->buffer
) - offset
;
55 unsigned nr
= count
> left
? left
: count
;
57 memcpy(f
->buffer
+ offset
, buf
, nr
);
60 buf
= (char *) buf
+ nr
;
63 SHA1_Update(&f
->ctx
, f
->buffer
, offset
);
72 struct sha1file
*sha1create(const char *fmt
, ...)
79 f
= xmalloc(sizeof(*f
));
82 len
= vsnprintf(f
->name
, sizeof(f
->name
), fmt
, arg
);
85 die("you wascally wabbit, you");
88 fd
= open(f
->name
, O_CREAT
| O_EXCL
| O_WRONLY
, 0666);
90 die("unable to open %s (%s)", f
->name
, strerror(errno
));
98 struct sha1file
*sha1fd(int fd
, const char *name
)
103 f
= xmalloc(sizeof(*f
));
107 die("you wascally wabbit, you");
109 memcpy(f
->name
, name
, len
+1);
118 int sha1write_compressed(struct sha1file
*f
, void *in
, unsigned int size
)
121 unsigned long maxsize
;
124 memset(&stream
, 0, sizeof(stream
));
125 deflateInit(&stream
, zlib_compression_level
);
126 maxsize
= deflateBound(&stream
, size
);
127 out
= xmalloc(maxsize
);
131 stream
.avail_in
= size
;
133 stream
.next_out
= out
;
134 stream
.avail_out
= maxsize
;
136 while (deflate(&stream
, Z_FINISH
) == Z_OK
)
140 size
= stream
.total_out
;
141 sha1write(f
, out
, size
);