1275793eaSopenharmony_ci/*
2275793eaSopenharmony_ci * gzlog.c
3275793eaSopenharmony_ci * Copyright (C) 2004, 2008, 2012, 2016, 2019 Mark Adler, all rights reserved
4275793eaSopenharmony_ci * For conditions of distribution and use, see copyright notice in gzlog.h
5275793eaSopenharmony_ci * version 2.3, 25 May 2019
6275793eaSopenharmony_ci */
7275793eaSopenharmony_ci
8275793eaSopenharmony_ci/*
9275793eaSopenharmony_ci   gzlog provides a mechanism for frequently appending short strings to a gzip
10275793eaSopenharmony_ci   file that is efficient both in execution time and compression ratio.  The
11275793eaSopenharmony_ci   strategy is to write the short strings in an uncompressed form to the end of
12275793eaSopenharmony_ci   the gzip file, only compressing when the amount of uncompressed data has
13275793eaSopenharmony_ci   reached a given threshold.
14275793eaSopenharmony_ci
15275793eaSopenharmony_ci   gzlog also provides protection against interruptions in the process due to
16275793eaSopenharmony_ci   system crashes.  The status of the operation is recorded in an extra field
17275793eaSopenharmony_ci   in the gzip file, and is only updated once the gzip file is brought to a
18275793eaSopenharmony_ci   valid state.  The last data to be appended or compressed is saved in an
19275793eaSopenharmony_ci   auxiliary file, so that if the operation is interrupted, it can be completed
20275793eaSopenharmony_ci   the next time an append operation is attempted.
21275793eaSopenharmony_ci
22275793eaSopenharmony_ci   gzlog maintains another auxiliary file with the last 32K of data from the
23275793eaSopenharmony_ci   compressed portion, which is preloaded for the compression of the subsequent
24275793eaSopenharmony_ci   data.  This minimizes the impact to the compression ratio of appending.
25275793eaSopenharmony_ci */
26275793eaSopenharmony_ci
27275793eaSopenharmony_ci/*
28275793eaSopenharmony_ci   Operations Concept:
29275793eaSopenharmony_ci
30275793eaSopenharmony_ci   Files (log name "foo"):
31275793eaSopenharmony_ci   foo.gz -- gzip file with the complete log
32275793eaSopenharmony_ci   foo.add -- last message to append or last data to compress
33275793eaSopenharmony_ci   foo.dict -- dictionary of the last 32K of data for next compression
34275793eaSopenharmony_ci   foo.temp -- temporary dictionary file for compression after this one
35275793eaSopenharmony_ci   foo.lock -- lock file for reading and writing the other files
36275793eaSopenharmony_ci   foo.repairs -- log file for log file recovery operations (not compressed)
37275793eaSopenharmony_ci
38275793eaSopenharmony_ci   gzip file structure:
39275793eaSopenharmony_ci   - fixed-length (no file name) header with extra field (see below)
40275793eaSopenharmony_ci   - compressed data ending initially with empty stored block
41275793eaSopenharmony_ci   - uncompressed data filling out originally empty stored block and
42275793eaSopenharmony_ci     subsequent stored blocks as needed (16K max each)
43275793eaSopenharmony_ci   - gzip trailer
44275793eaSopenharmony_ci   - no junk at end (no other gzip streams)
45275793eaSopenharmony_ci
46275793eaSopenharmony_ci   When appending data, the information in the first three items above plus the
47275793eaSopenharmony_ci   foo.add file are sufficient to recover an interrupted append operation.  The
48275793eaSopenharmony_ci   extra field has the necessary information to restore the start of the last
49275793eaSopenharmony_ci   stored block and determine where to append the data in the foo.add file, as
50275793eaSopenharmony_ci   well as the crc and length of the gzip data before the append operation.
51275793eaSopenharmony_ci
52275793eaSopenharmony_ci   The foo.add file is created before the gzip file is marked for append, and
53275793eaSopenharmony_ci   deleted after the gzip file is marked as complete.  So if the append
54275793eaSopenharmony_ci   operation is interrupted, the data to add will still be there.  If due to
55275793eaSopenharmony_ci   some external force, the foo.add file gets deleted between when the append
56275793eaSopenharmony_ci   operation was interrupted and when recovery is attempted, the gzip file will
57275793eaSopenharmony_ci   still be restored, but without the appended data.
58275793eaSopenharmony_ci
59275793eaSopenharmony_ci   When compressing data, the information in the first two items above plus the
60275793eaSopenharmony_ci   foo.add file are sufficient to recover an interrupted compress operation.
61275793eaSopenharmony_ci   The extra field has the necessary information to find the end of the
62275793eaSopenharmony_ci   compressed data, and contains both the crc and length of just the compressed
63275793eaSopenharmony_ci   data and of the complete set of data including the contents of the foo.add
64275793eaSopenharmony_ci   file.
65275793eaSopenharmony_ci
66275793eaSopenharmony_ci   Again, the foo.add file is maintained during the compress operation in case
67275793eaSopenharmony_ci   of an interruption.  If in the unlikely event the foo.add file with the data
68275793eaSopenharmony_ci   to be compressed is missing due to some external force, a gzip file with
69275793eaSopenharmony_ci   just the previous compressed data will be reconstructed.  In this case, all
70275793eaSopenharmony_ci   of the data that was to be compressed is lost (approximately one megabyte).
71275793eaSopenharmony_ci   This will not occur if all that happened was an interruption of the compress
72275793eaSopenharmony_ci   operation.
73275793eaSopenharmony_ci
74275793eaSopenharmony_ci   The third state that is marked is the replacement of the old dictionary with
75275793eaSopenharmony_ci   the new dictionary after a compress operation.  Once compression is
76275793eaSopenharmony_ci   complete, the gzip file is marked as being in the replace state.  This
77275793eaSopenharmony_ci   completes the gzip file, so an interrupt after being so marked does not
78275793eaSopenharmony_ci   result in recompression.  Then the dictionary file is replaced, and the gzip
79275793eaSopenharmony_ci   file is marked as completed.  This state prevents the possibility of
80275793eaSopenharmony_ci   restarting compression with the wrong dictionary file.
81275793eaSopenharmony_ci
82275793eaSopenharmony_ci   All three operations are wrapped by a lock/unlock procedure.  In order to
83275793eaSopenharmony_ci   gain exclusive access to the log files, first a foo.lock file must be
84275793eaSopenharmony_ci   exclusively created.  When all operations are complete, the lock is
85275793eaSopenharmony_ci   released by deleting the foo.lock file.  If when attempting to create the
86275793eaSopenharmony_ci   lock file, it already exists and the modify time of the lock file is more
87275793eaSopenharmony_ci   than five minutes old (set by the PATIENCE define below), then the old
88275793eaSopenharmony_ci   lock file is considered stale and deleted, and the exclusive creation of
89275793eaSopenharmony_ci   the lock file is retried.  To assure that there are no false assessments
90275793eaSopenharmony_ci   of the staleness of the lock file, the operations periodically touch the
91275793eaSopenharmony_ci   lock file to update the modified date.
92275793eaSopenharmony_ci
93275793eaSopenharmony_ci   Following is the definition of the extra field with all of the information
94275793eaSopenharmony_ci   required to enable the above append and compress operations and their
95275793eaSopenharmony_ci   recovery if interrupted.  Multi-byte values are stored little endian
96275793eaSopenharmony_ci   (consistent with the gzip format).  File pointers are eight bytes long.
97275793eaSopenharmony_ci   The crc's and lengths for the gzip trailer are four bytes long.  (Note that
98275793eaSopenharmony_ci   the length at the end of a gzip file is used for error checking only, and
99275793eaSopenharmony_ci   for large files is actually the length modulo 2^32.)  The stored block
100275793eaSopenharmony_ci   length is two bytes long.  The gzip extra field two-byte identification is
101275793eaSopenharmony_ci   "ap" for append.  It is assumed that writing the extra field to the file is
102275793eaSopenharmony_ci   an "atomic" operation.  That is, either all of the extra field is written
103275793eaSopenharmony_ci   to the file, or none of it is, if the operation is interrupted right at the
104275793eaSopenharmony_ci   point of updating the extra field.  This is a reasonable assumption, since
105275793eaSopenharmony_ci   the extra field is within the first 52 bytes of the file, which is smaller
106275793eaSopenharmony_ci   than any expected block size for a mass storage device (usually 512 bytes or
107275793eaSopenharmony_ci   larger).
108275793eaSopenharmony_ci
109275793eaSopenharmony_ci   Extra field (35 bytes):
110275793eaSopenharmony_ci   - Pointer to first stored block length -- this points to the two-byte length
111275793eaSopenharmony_ci     of the first stored block, which is followed by the two-byte, one's
112275793eaSopenharmony_ci     complement of that length.  The stored block length is preceded by the
113275793eaSopenharmony_ci     three-bit header of the stored block, which is the actual start of the
114275793eaSopenharmony_ci     stored block in the deflate format.  See the bit offset field below.
115275793eaSopenharmony_ci   - Pointer to the last stored block length.  This is the same as above, but
116275793eaSopenharmony_ci     for the last stored block of the uncompressed data in the gzip file.
117275793eaSopenharmony_ci     Initially this is the same as the first stored block length pointer.
118275793eaSopenharmony_ci     When the stored block gets to 16K (see the MAX_STORE define), then a new
119275793eaSopenharmony_ci     stored block as added, at which point the last stored block length pointer
120275793eaSopenharmony_ci     is different from the first stored block length pointer.  When they are
121275793eaSopenharmony_ci     different, the first bit of the last stored block header is eight bits, or
122275793eaSopenharmony_ci     one byte back from the block length.
123275793eaSopenharmony_ci   - Compressed data crc and length.  This is the crc and length of the data
124275793eaSopenharmony_ci     that is in the compressed portion of the deflate stream.  These are used
125275793eaSopenharmony_ci     only in the event that the foo.add file containing the data to compress is
126275793eaSopenharmony_ci     lost after a compress operation is interrupted.
127275793eaSopenharmony_ci   - Total data crc and length.  This is the crc and length of all of the data
128275793eaSopenharmony_ci     stored in the gzip file, compressed and uncompressed.  It is used to
129275793eaSopenharmony_ci     reconstruct the gzip trailer when compressing, as well as when recovering
130275793eaSopenharmony_ci     interrupted operations.
131275793eaSopenharmony_ci   - Final stored block length.  This is used to quickly find where to append,
132275793eaSopenharmony_ci     and allows the restoration of the original final stored block state when
133275793eaSopenharmony_ci     an append operation is interrupted.
134275793eaSopenharmony_ci   - First stored block start as the number of bits back from the final stored
135275793eaSopenharmony_ci     block first length byte.  This value is in the range of 3..10, and is
136275793eaSopenharmony_ci     stored as the low three bits of the final byte of the extra field after
137275793eaSopenharmony_ci     subtracting three (0..7).  This allows the last-block bit of the stored
138275793eaSopenharmony_ci     block header to be updated when a new stored block is added, for the case
139275793eaSopenharmony_ci     when the first stored block and the last stored block are the same.  (When
140275793eaSopenharmony_ci     they are different, the numbers of bits back is known to be eight.)  This
141275793eaSopenharmony_ci     also allows for new compressed data to be appended to the old compressed
142275793eaSopenharmony_ci     data in the compress operation, overwriting the previous first stored
143275793eaSopenharmony_ci     block, or for the compressed data to be terminated and a valid gzip file
144275793eaSopenharmony_ci     reconstructed on the off chance that a compression operation was
145275793eaSopenharmony_ci     interrupted and the data to compress in the foo.add file was deleted.
146275793eaSopenharmony_ci   - The operation in process.  This is the next two bits in the last byte (the
147275793eaSopenharmony_ci     bits under the mask 0x18).  The are interpreted as 0: nothing in process,
148275793eaSopenharmony_ci     1: append in process, 2: compress in process, 3: replace in process.
149275793eaSopenharmony_ci   - The top three bits of the last byte in the extra field are reserved and
150275793eaSopenharmony_ci     are currently set to zero.
151275793eaSopenharmony_ci
152275793eaSopenharmony_ci   Main procedure:
153275793eaSopenharmony_ci   - Exclusively create the foo.lock file using the O_CREAT and O_EXCL modes of
154275793eaSopenharmony_ci     the system open() call.  If the modify time of an existing lock file is
155275793eaSopenharmony_ci     more than PATIENCE seconds old, then the lock file is deleted and the
156275793eaSopenharmony_ci     exclusive create is retried.
157275793eaSopenharmony_ci   - Load the extra field from the foo.gz file, and see if an operation was in
158275793eaSopenharmony_ci     progress but not completed.  If so, apply the recovery procedure below.
159275793eaSopenharmony_ci   - Perform the append procedure with the provided data.
160275793eaSopenharmony_ci   - If the uncompressed data in the foo.gz file is 1MB or more, apply the
161275793eaSopenharmony_ci     compress procedure.
162275793eaSopenharmony_ci   - Delete the foo.lock file.
163275793eaSopenharmony_ci
164275793eaSopenharmony_ci   Append procedure:
165275793eaSopenharmony_ci   - Put what to append in the foo.add file so that the operation can be
166275793eaSopenharmony_ci     restarted if this procedure is interrupted.
167275793eaSopenharmony_ci   - Mark the foo.gz extra field with the append operation in progress.
168275793eaSopenharmony_ci   + Restore the original last-block bit and stored block length of the last
169275793eaSopenharmony_ci     stored block from the information in the extra field, in case a previous
170275793eaSopenharmony_ci     append operation was interrupted.
171275793eaSopenharmony_ci   - Append the provided data to the last stored block, creating new stored
172275793eaSopenharmony_ci     blocks as needed and updating the stored blocks last-block bits and
173275793eaSopenharmony_ci     lengths.
174275793eaSopenharmony_ci   - Update the crc and length with the new data, and write the gzip trailer.
175275793eaSopenharmony_ci   - Write over the extra field (with a single write operation) with the new
176275793eaSopenharmony_ci     pointers, lengths, and crc's, and mark the gzip file as not in process.
177275793eaSopenharmony_ci     Though there is still a foo.add file, it will be ignored since nothing
178275793eaSopenharmony_ci     is in process.  If a foo.add file is leftover from a previously
179275793eaSopenharmony_ci     completed operation, it is truncated when writing new data to it.
180275793eaSopenharmony_ci   - Delete the foo.add file.
181275793eaSopenharmony_ci
182275793eaSopenharmony_ci   Compress and replace procedures:
183275793eaSopenharmony_ci   - Read all of the uncompressed data in the stored blocks in foo.gz and write
184275793eaSopenharmony_ci     it to foo.add.  Also write foo.temp with the last 32K of that data to
185275793eaSopenharmony_ci     provide a dictionary for the next invocation of this procedure.
186275793eaSopenharmony_ci   - Rewrite the extra field marking foo.gz with a compression in process.
187275793eaSopenharmony_ci   * If there is no data provided to compress (due to a missing foo.add file
188275793eaSopenharmony_ci     when recovering), reconstruct and truncate the foo.gz file to contain
189275793eaSopenharmony_ci     only the previous compressed data and proceed to the step after the next
190275793eaSopenharmony_ci     one.  Otherwise ...
191275793eaSopenharmony_ci   - Compress the data with the dictionary in foo.dict, and write to the
192275793eaSopenharmony_ci     foo.gz file starting at the bit immediately following the last previously
193275793eaSopenharmony_ci     compressed block.  If there is no foo.dict, proceed anyway with the
194275793eaSopenharmony_ci     compression at slightly reduced efficiency.  (For the foo.dict file to be
195275793eaSopenharmony_ci     missing requires some external failure beyond simply the interruption of
196275793eaSopenharmony_ci     a compress operation.)  During this process, the foo.lock file is
197275793eaSopenharmony_ci     periodically touched to assure that that file is not considered stale by
198275793eaSopenharmony_ci     another process before we're done.  The deflation is terminated with a
199275793eaSopenharmony_ci     non-last empty static block (10 bits long), that is then located and
200275793eaSopenharmony_ci     written over by a last-bit-set empty stored block.
201275793eaSopenharmony_ci   - Append the crc and length of the data in the gzip file (previously
202275793eaSopenharmony_ci     calculated during the append operations).
203275793eaSopenharmony_ci   - Write over the extra field with the updated stored block offsets, bits
204275793eaSopenharmony_ci     back, crc's, and lengths, and mark foo.gz as in process for a replacement
205275793eaSopenharmony_ci     of the dictionary.
206275793eaSopenharmony_ci   @ Delete the foo.add file.
207275793eaSopenharmony_ci   - Replace foo.dict with foo.temp.
208275793eaSopenharmony_ci   - Write over the extra field, marking foo.gz as complete.
209275793eaSopenharmony_ci
210275793eaSopenharmony_ci   Recovery procedure:
211275793eaSopenharmony_ci   - If not a replace recovery, read in the foo.add file, and provide that data
212275793eaSopenharmony_ci     to the appropriate recovery below.  If there is no foo.add file, provide
213275793eaSopenharmony_ci     a zero data length to the recovery.  In that case, the append recovery
214275793eaSopenharmony_ci     restores the foo.gz to the previous compressed + uncompressed data state.
215275793eaSopenharmony_ci     For the compress recovery, a missing foo.add file results in foo.gz being
216275793eaSopenharmony_ci     restored to the previous compressed-only data state.
217275793eaSopenharmony_ci   - Append recovery:
218275793eaSopenharmony_ci     - Pick up append at + step above
219275793eaSopenharmony_ci   - Compress recovery:
220275793eaSopenharmony_ci     - Pick up compress at * step above
221275793eaSopenharmony_ci   - Replace recovery:
222275793eaSopenharmony_ci     - Pick up compress at @ step above
223275793eaSopenharmony_ci   - Log the repair with a date stamp in foo.repairs
224275793eaSopenharmony_ci */
225275793eaSopenharmony_ci
226275793eaSopenharmony_ci#include <sys/types.h>
227275793eaSopenharmony_ci#include <stdio.h>      /* rename, fopen, fprintf, fclose */
228275793eaSopenharmony_ci#include <stdlib.h>     /* malloc, free */
229275793eaSopenharmony_ci#include <string.h>     /* strlen, strrchr, strcpy, strncpy, strcmp */
230275793eaSopenharmony_ci#include <fcntl.h>      /* open */
231275793eaSopenharmony_ci#include <unistd.h>     /* lseek, read, write, close, unlink, sleep, */
232275793eaSopenharmony_ci                        /* ftruncate, fsync */
233275793eaSopenharmony_ci#include <errno.h>      /* errno */
234275793eaSopenharmony_ci#include <time.h>       /* time, ctime */
235275793eaSopenharmony_ci#include <sys/stat.h>   /* stat */
236275793eaSopenharmony_ci#include <sys/time.h>   /* utimes */
237275793eaSopenharmony_ci#include "zlib.h"       /* crc32 */
238275793eaSopenharmony_ci
239275793eaSopenharmony_ci#include "gzlog.h"      /* header for external access */
240275793eaSopenharmony_ci
241275793eaSopenharmony_ci#define local static
242275793eaSopenharmony_citypedef unsigned int uint;
243275793eaSopenharmony_citypedef unsigned long ulong;
244275793eaSopenharmony_ci
245275793eaSopenharmony_ci/* Macro for debugging to deterministically force recovery operations */
246275793eaSopenharmony_ci#ifdef GZLOG_DEBUG
247275793eaSopenharmony_ci    #include <setjmp.h>         /* longjmp */
248275793eaSopenharmony_ci    jmp_buf gzlog_jump;         /* where to go back to */
249275793eaSopenharmony_ci    int gzlog_bail = 0;         /* which point to bail at (1..8) */
250275793eaSopenharmony_ci    int gzlog_count = -1;       /* number of times through to wait */
251275793eaSopenharmony_ci#   define BAIL(n) do { if (n == gzlog_bail && gzlog_count-- == 0) \
252275793eaSopenharmony_ci                            longjmp(gzlog_jump, gzlog_bail); } while (0)
253275793eaSopenharmony_ci#else
254275793eaSopenharmony_ci#   define BAIL(n)
255275793eaSopenharmony_ci#endif
256275793eaSopenharmony_ci
257275793eaSopenharmony_ci/* how old the lock file can be in seconds before considering it stale */
258275793eaSopenharmony_ci#define PATIENCE 300
259275793eaSopenharmony_ci
260275793eaSopenharmony_ci/* maximum stored block size in Kbytes -- must be in 1..63 */
261275793eaSopenharmony_ci#define MAX_STORE 16
262275793eaSopenharmony_ci
263275793eaSopenharmony_ci/* number of stored Kbytes to trigger compression (must be >= 32 to allow
264275793eaSopenharmony_ci   dictionary construction, and <= 204 * MAX_STORE, in order for >> 10 to
265275793eaSopenharmony_ci   discard the stored block headers contribution of five bytes each) */
266275793eaSopenharmony_ci#define TRIGGER 1024
267275793eaSopenharmony_ci
268275793eaSopenharmony_ci/* size of a deflate dictionary (this cannot be changed) */
269275793eaSopenharmony_ci#define DICT 32768U
270275793eaSopenharmony_ci
271275793eaSopenharmony_ci/* values for the operation (2 bits) */
272275793eaSopenharmony_ci#define NO_OP 0
273275793eaSopenharmony_ci#define APPEND_OP 1
274275793eaSopenharmony_ci#define COMPRESS_OP 2
275275793eaSopenharmony_ci#define REPLACE_OP 3
276275793eaSopenharmony_ci
277275793eaSopenharmony_ci/* macros to extract little-endian integers from an unsigned byte buffer */
278275793eaSopenharmony_ci#define PULL2(p) ((p)[0]+((uint)((p)[1])<<8))
279275793eaSopenharmony_ci#define PULL4(p) (PULL2(p)+((ulong)PULL2(p+2)<<16))
280275793eaSopenharmony_ci#define PULL8(p) (PULL4(p)+((off_t)PULL4(p+4)<<32))
281275793eaSopenharmony_ci
282275793eaSopenharmony_ci/* macros to store integers into a byte buffer in little-endian order */
283275793eaSopenharmony_ci#define PUT2(p,a) do {(p)[0]=a;(p)[1]=(a)>>8;} while(0)
284275793eaSopenharmony_ci#define PUT4(p,a) do {PUT2(p,a);PUT2(p+2,a>>16);} while(0)
285275793eaSopenharmony_ci#define PUT8(p,a) do {PUT4(p,a);PUT4(p+4,a>>32);} while(0)
286275793eaSopenharmony_ci
287275793eaSopenharmony_ci/* internal structure for log information */
288275793eaSopenharmony_ci#define LOGID "\106\035\172"    /* should be three non-zero characters */
289275793eaSopenharmony_cistruct log {
290275793eaSopenharmony_ci    char id[4];     /* contains LOGID to detect inadvertent overwrites */
291275793eaSopenharmony_ci    int fd;         /* file descriptor for .gz file, opened read/write */
292275793eaSopenharmony_ci    char *path;     /* allocated path, e.g. "/var/log/foo" or "foo" */
293275793eaSopenharmony_ci    char *end;      /* end of path, for appending suffices such as ".gz" */
294275793eaSopenharmony_ci    off_t first;    /* offset of first stored block first length byte */
295275793eaSopenharmony_ci    int back;       /* location of first block id in bits back from first */
296275793eaSopenharmony_ci    uint stored;    /* bytes currently in last stored block */
297275793eaSopenharmony_ci    off_t last;     /* offset of last stored block first length byte */
298275793eaSopenharmony_ci    ulong ccrc;     /* crc of compressed data */
299275793eaSopenharmony_ci    ulong clen;     /* length (modulo 2^32) of compressed data */
300275793eaSopenharmony_ci    ulong tcrc;     /* crc of total data */
301275793eaSopenharmony_ci    ulong tlen;     /* length (modulo 2^32) of total data */
302275793eaSopenharmony_ci    time_t lock;    /* last modify time of our lock file */
303275793eaSopenharmony_ci};
304275793eaSopenharmony_ci
305275793eaSopenharmony_ci/* gzip header for gzlog */
306275793eaSopenharmony_cilocal unsigned char log_gzhead[] = {
307275793eaSopenharmony_ci    0x1f, 0x8b,                 /* magic gzip id */
308275793eaSopenharmony_ci    8,                          /* compression method is deflate */
309275793eaSopenharmony_ci    4,                          /* there is an extra field (no file name) */
310275793eaSopenharmony_ci    0, 0, 0, 0,                 /* no modification time provided */
311275793eaSopenharmony_ci    0, 0xff,                    /* no extra flags, no OS specified */
312275793eaSopenharmony_ci    39, 0, 'a', 'p', 35, 0      /* extra field with "ap" subfield */
313275793eaSopenharmony_ci                                /* 35 is EXTRA, 39 is EXTRA + 4 */
314275793eaSopenharmony_ci};
315275793eaSopenharmony_ci
316275793eaSopenharmony_ci#define HEAD sizeof(log_gzhead)     /* should be 16 */
317275793eaSopenharmony_ci
318275793eaSopenharmony_ci/* initial gzip extra field content (52 == HEAD + EXTRA + 1) */
319275793eaSopenharmony_cilocal unsigned char log_gzext[] = {
320275793eaSopenharmony_ci    52, 0, 0, 0, 0, 0, 0, 0,    /* offset of first stored block length */
321275793eaSopenharmony_ci    52, 0, 0, 0, 0, 0, 0, 0,    /* offset of last stored block length */
322275793eaSopenharmony_ci    0, 0, 0, 0, 0, 0, 0, 0,     /* compressed data crc and length */
323275793eaSopenharmony_ci    0, 0, 0, 0, 0, 0, 0, 0,     /* total data crc and length */
324275793eaSopenharmony_ci    0, 0,                       /* final stored block data length */
325275793eaSopenharmony_ci    5                           /* op is NO_OP, last bit 8 bits back */
326275793eaSopenharmony_ci};
327275793eaSopenharmony_ci
328275793eaSopenharmony_ci#define EXTRA sizeof(log_gzext)     /* should be 35 */
329275793eaSopenharmony_ci
330275793eaSopenharmony_ci/* initial gzip data and trailer */
331275793eaSopenharmony_cilocal unsigned char log_gzbody[] = {
332275793eaSopenharmony_ci    1, 0, 0, 0xff, 0xff,        /* empty stored block (last) */
333275793eaSopenharmony_ci    0, 0, 0, 0,                 /* crc */
334275793eaSopenharmony_ci    0, 0, 0, 0                  /* uncompressed length */
335275793eaSopenharmony_ci};
336275793eaSopenharmony_ci
337275793eaSopenharmony_ci#define BODY sizeof(log_gzbody)
338275793eaSopenharmony_ci
339275793eaSopenharmony_ci/* Exclusively create foo.lock in order to negotiate exclusive access to the
340275793eaSopenharmony_ci   foo.* files.  If the modify time of an existing lock file is greater than
341275793eaSopenharmony_ci   PATIENCE seconds in the past, then consider the lock file to have been
342275793eaSopenharmony_ci   abandoned, delete it, and try the exclusive create again.  Save the lock
343275793eaSopenharmony_ci   file modify time for verification of ownership.  Return 0 on success, or -1
344275793eaSopenharmony_ci   on failure, usually due to an access restriction or invalid path.  Note that
345275793eaSopenharmony_ci   if stat() or unlink() fails, it may be due to another process noticing the
346275793eaSopenharmony_ci   abandoned lock file a smidge sooner and deleting it, so those are not
347275793eaSopenharmony_ci   flagged as an error. */
348275793eaSopenharmony_cilocal int log_lock(struct log *log)
349275793eaSopenharmony_ci{
350275793eaSopenharmony_ci    int fd;
351275793eaSopenharmony_ci    struct stat st;
352275793eaSopenharmony_ci
353275793eaSopenharmony_ci    strcpy(log->end, ".lock");
354275793eaSopenharmony_ci    while ((fd = open(log->path, O_CREAT | O_EXCL, 0644)) < 0) {
355275793eaSopenharmony_ci        if (errno != EEXIST)
356275793eaSopenharmony_ci            return -1;
357275793eaSopenharmony_ci        if (stat(log->path, &st) == 0 && time(NULL) - st.st_mtime > PATIENCE) {
358275793eaSopenharmony_ci            unlink(log->path);
359275793eaSopenharmony_ci            continue;
360275793eaSopenharmony_ci        }
361275793eaSopenharmony_ci        sleep(2);       /* relinquish the CPU for two seconds while waiting */
362275793eaSopenharmony_ci    }
363275793eaSopenharmony_ci    close(fd);
364275793eaSopenharmony_ci    if (stat(log->path, &st) == 0)
365275793eaSopenharmony_ci        log->lock = st.st_mtime;
366275793eaSopenharmony_ci    return 0;
367275793eaSopenharmony_ci}
368275793eaSopenharmony_ci
369275793eaSopenharmony_ci/* Update the modify time of the lock file to now, in order to prevent another
370275793eaSopenharmony_ci   task from thinking that the lock is stale.  Save the lock file modify time
371275793eaSopenharmony_ci   for verification of ownership. */
372275793eaSopenharmony_cilocal void log_touch(struct log *log)
373275793eaSopenharmony_ci{
374275793eaSopenharmony_ci    struct stat st;
375275793eaSopenharmony_ci
376275793eaSopenharmony_ci    strcpy(log->end, ".lock");
377275793eaSopenharmony_ci    utimes(log->path, NULL);
378275793eaSopenharmony_ci    if (stat(log->path, &st) == 0)
379275793eaSopenharmony_ci        log->lock = st.st_mtime;
380275793eaSopenharmony_ci}
381275793eaSopenharmony_ci
382275793eaSopenharmony_ci/* Check the log file modify time against what is expected.  Return true if
383275793eaSopenharmony_ci   this is not our lock.  If it is our lock, touch it to keep it. */
384275793eaSopenharmony_cilocal int log_check(struct log *log)
385275793eaSopenharmony_ci{
386275793eaSopenharmony_ci    struct stat st;
387275793eaSopenharmony_ci
388275793eaSopenharmony_ci    strcpy(log->end, ".lock");
389275793eaSopenharmony_ci    if (stat(log->path, &st) || st.st_mtime != log->lock)
390275793eaSopenharmony_ci        return 1;
391275793eaSopenharmony_ci    log_touch(log);
392275793eaSopenharmony_ci    return 0;
393275793eaSopenharmony_ci}
394275793eaSopenharmony_ci
395275793eaSopenharmony_ci/* Unlock a previously acquired lock, but only if it's ours. */
396275793eaSopenharmony_cilocal void log_unlock(struct log *log)
397275793eaSopenharmony_ci{
398275793eaSopenharmony_ci    if (log_check(log))
399275793eaSopenharmony_ci        return;
400275793eaSopenharmony_ci    strcpy(log->end, ".lock");
401275793eaSopenharmony_ci    unlink(log->path);
402275793eaSopenharmony_ci    log->lock = 0;
403275793eaSopenharmony_ci}
404275793eaSopenharmony_ci
405275793eaSopenharmony_ci/* Check the gzip header and read in the extra field, filling in the values in
406275793eaSopenharmony_ci   the log structure.  Return op on success or -1 if the gzip header was not as
407275793eaSopenharmony_ci   expected.  op is the current operation in progress last written to the extra
408275793eaSopenharmony_ci   field.  This assumes that the gzip file has already been opened, with the
409275793eaSopenharmony_ci   file descriptor log->fd. */
410275793eaSopenharmony_cilocal int log_head(struct log *log)
411275793eaSopenharmony_ci{
412275793eaSopenharmony_ci    int op;
413275793eaSopenharmony_ci    unsigned char buf[HEAD + EXTRA];
414275793eaSopenharmony_ci
415275793eaSopenharmony_ci    if (lseek(log->fd, 0, SEEK_SET) < 0 ||
416275793eaSopenharmony_ci        read(log->fd, buf, HEAD + EXTRA) != HEAD + EXTRA ||
417275793eaSopenharmony_ci        memcmp(buf, log_gzhead, HEAD)) {
418275793eaSopenharmony_ci        return -1;
419275793eaSopenharmony_ci    }
420275793eaSopenharmony_ci    log->first = PULL8(buf + HEAD);
421275793eaSopenharmony_ci    log->last = PULL8(buf + HEAD + 8);
422275793eaSopenharmony_ci    log->ccrc = PULL4(buf + HEAD + 16);
423275793eaSopenharmony_ci    log->clen = PULL4(buf + HEAD + 20);
424275793eaSopenharmony_ci    log->tcrc = PULL4(buf + HEAD + 24);
425275793eaSopenharmony_ci    log->tlen = PULL4(buf + HEAD + 28);
426275793eaSopenharmony_ci    log->stored = PULL2(buf + HEAD + 32);
427275793eaSopenharmony_ci    log->back = 3 + (buf[HEAD + 34] & 7);
428275793eaSopenharmony_ci    op = (buf[HEAD + 34] >> 3) & 3;
429275793eaSopenharmony_ci    return op;
430275793eaSopenharmony_ci}
431275793eaSopenharmony_ci
432275793eaSopenharmony_ci/* Write over the extra field contents, marking the operation as op.  Use fsync
433275793eaSopenharmony_ci   to assure that the device is written to, and in the requested order.  This
434275793eaSopenharmony_ci   operation, and only this operation, is assumed to be atomic in order to
435275793eaSopenharmony_ci   assure that the log is recoverable in the event of an interruption at any
436275793eaSopenharmony_ci   point in the process.  Return -1 if the write to foo.gz failed. */
437275793eaSopenharmony_cilocal int log_mark(struct log *log, int op)
438275793eaSopenharmony_ci{
439275793eaSopenharmony_ci    int ret;
440275793eaSopenharmony_ci    unsigned char ext[EXTRA];
441275793eaSopenharmony_ci
442275793eaSopenharmony_ci    PUT8(ext, log->first);
443275793eaSopenharmony_ci    PUT8(ext + 8, log->last);
444275793eaSopenharmony_ci    PUT4(ext + 16, log->ccrc);
445275793eaSopenharmony_ci    PUT4(ext + 20, log->clen);
446275793eaSopenharmony_ci    PUT4(ext + 24, log->tcrc);
447275793eaSopenharmony_ci    PUT4(ext + 28, log->tlen);
448275793eaSopenharmony_ci    PUT2(ext + 32, log->stored);
449275793eaSopenharmony_ci    ext[34] = log->back - 3 + (op << 3);
450275793eaSopenharmony_ci    fsync(log->fd);
451275793eaSopenharmony_ci    ret = lseek(log->fd, HEAD, SEEK_SET) < 0 ||
452275793eaSopenharmony_ci          write(log->fd, ext, EXTRA) != EXTRA ? -1 : 0;
453275793eaSopenharmony_ci    fsync(log->fd);
454275793eaSopenharmony_ci    return ret;
455275793eaSopenharmony_ci}
456275793eaSopenharmony_ci
457275793eaSopenharmony_ci/* Rewrite the last block header bits and subsequent zero bits to get to a byte
458275793eaSopenharmony_ci   boundary, setting the last block bit if last is true, and then write the
459275793eaSopenharmony_ci   remainder of the stored block header (length and one's complement).  Leave
460275793eaSopenharmony_ci   the file pointer after the end of the last stored block data.  Return -1 if
461275793eaSopenharmony_ci   there is a read or write failure on the foo.gz file */
462275793eaSopenharmony_cilocal int log_last(struct log *log, int last)
463275793eaSopenharmony_ci{
464275793eaSopenharmony_ci    int back, len, mask;
465275793eaSopenharmony_ci    unsigned char buf[6];
466275793eaSopenharmony_ci
467275793eaSopenharmony_ci    /* determine the locations of the bytes and bits to modify */
468275793eaSopenharmony_ci    back = log->last == log->first ? log->back : 8;
469275793eaSopenharmony_ci    len = back > 8 ? 2 : 1;                 /* bytes back from log->last */
470275793eaSopenharmony_ci    mask = 0x80 >> ((back - 1) & 7);        /* mask for block last-bit */
471275793eaSopenharmony_ci
472275793eaSopenharmony_ci    /* get the byte to modify (one or two back) into buf[0] -- don't need to
473275793eaSopenharmony_ci       read the byte if the last-bit is eight bits back, since in that case
474275793eaSopenharmony_ci       the entire byte will be modified */
475275793eaSopenharmony_ci    buf[0] = 0;
476275793eaSopenharmony_ci    if (back != 8 && (lseek(log->fd, log->last - len, SEEK_SET) < 0 ||
477275793eaSopenharmony_ci                      read(log->fd, buf, 1) != 1))
478275793eaSopenharmony_ci        return -1;
479275793eaSopenharmony_ci
480275793eaSopenharmony_ci    /* change the last-bit of the last stored block as requested -- note
481275793eaSopenharmony_ci       that all bits above the last-bit are set to zero, per the type bits
482275793eaSopenharmony_ci       of a stored block being 00 and per the convention that the bits to
483275793eaSopenharmony_ci       bring the stream to a byte boundary are also zeros */
484275793eaSopenharmony_ci    buf[1] = 0;
485275793eaSopenharmony_ci    buf[2 - len] = (*buf & (mask - 1)) + (last ? mask : 0);
486275793eaSopenharmony_ci
487275793eaSopenharmony_ci    /* write the modified stored block header and lengths, move the file
488275793eaSopenharmony_ci       pointer to after the last stored block data */
489275793eaSopenharmony_ci    PUT2(buf + 2, log->stored);
490275793eaSopenharmony_ci    PUT2(buf + 4, log->stored ^ 0xffff);
491275793eaSopenharmony_ci    return lseek(log->fd, log->last - len, SEEK_SET) < 0 ||
492275793eaSopenharmony_ci           write(log->fd, buf + 2 - len, len + 4) != len + 4 ||
493275793eaSopenharmony_ci           lseek(log->fd, log->stored, SEEK_CUR) < 0 ? -1 : 0;
494275793eaSopenharmony_ci}
495275793eaSopenharmony_ci
496275793eaSopenharmony_ci/* Append len bytes from data to the locked and open log file.  len may be zero
497275793eaSopenharmony_ci   if recovering and no .add file was found.  In that case, the previous state
498275793eaSopenharmony_ci   of the foo.gz file is restored.  The data is appended uncompressed in
499275793eaSopenharmony_ci   deflate stored blocks.  Return -1 if there was an error reading or writing
500275793eaSopenharmony_ci   the foo.gz file. */
501275793eaSopenharmony_cilocal int log_append(struct log *log, unsigned char *data, size_t len)
502275793eaSopenharmony_ci{
503275793eaSopenharmony_ci    uint put;
504275793eaSopenharmony_ci    off_t end;
505275793eaSopenharmony_ci    unsigned char buf[8];
506275793eaSopenharmony_ci
507275793eaSopenharmony_ci    /* set the last block last-bit and length, in case recovering an
508275793eaSopenharmony_ci       interrupted append, then position the file pointer to append to the
509275793eaSopenharmony_ci       block */
510275793eaSopenharmony_ci    if (log_last(log, 1))
511275793eaSopenharmony_ci        return -1;
512275793eaSopenharmony_ci
513275793eaSopenharmony_ci    /* append, adding stored blocks and updating the offset of the last stored
514275793eaSopenharmony_ci       block as needed, and update the total crc and length */
515275793eaSopenharmony_ci    while (len) {
516275793eaSopenharmony_ci        /* append as much as we can to the last block */
517275793eaSopenharmony_ci        put = (MAX_STORE << 10) - log->stored;
518275793eaSopenharmony_ci        if (put > len)
519275793eaSopenharmony_ci            put = (uint)len;
520275793eaSopenharmony_ci        if (put) {
521275793eaSopenharmony_ci            if (write(log->fd, data, put) != put)
522275793eaSopenharmony_ci                return -1;
523275793eaSopenharmony_ci            BAIL(1);
524275793eaSopenharmony_ci            log->tcrc = crc32(log->tcrc, data, put);
525275793eaSopenharmony_ci            log->tlen += put;
526275793eaSopenharmony_ci            log->stored += put;
527275793eaSopenharmony_ci            data += put;
528275793eaSopenharmony_ci            len -= put;
529275793eaSopenharmony_ci        }
530275793eaSopenharmony_ci
531275793eaSopenharmony_ci        /* if we need to, add a new empty stored block */
532275793eaSopenharmony_ci        if (len) {
533275793eaSopenharmony_ci            /* mark current block as not last */
534275793eaSopenharmony_ci            if (log_last(log, 0))
535275793eaSopenharmony_ci                return -1;
536275793eaSopenharmony_ci
537275793eaSopenharmony_ci            /* point to new, empty stored block */
538275793eaSopenharmony_ci            log->last += 4 + log->stored + 1;
539275793eaSopenharmony_ci            log->stored = 0;
540275793eaSopenharmony_ci        }
541275793eaSopenharmony_ci
542275793eaSopenharmony_ci        /* mark last block as last, update its length */
543275793eaSopenharmony_ci        if (log_last(log, 1))
544275793eaSopenharmony_ci            return -1;
545275793eaSopenharmony_ci        BAIL(2);
546275793eaSopenharmony_ci    }
547275793eaSopenharmony_ci
548275793eaSopenharmony_ci    /* write the new crc and length trailer, and truncate just in case (could
549275793eaSopenharmony_ci       be recovering from partial append with a missing foo.add file) */
550275793eaSopenharmony_ci    PUT4(buf, log->tcrc);
551275793eaSopenharmony_ci    PUT4(buf + 4, log->tlen);
552275793eaSopenharmony_ci    if (write(log->fd, buf, 8) != 8 ||
553275793eaSopenharmony_ci        (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end))
554275793eaSopenharmony_ci        return -1;
555275793eaSopenharmony_ci
556275793eaSopenharmony_ci    /* write the extra field, marking the log file as done, delete .add file */
557275793eaSopenharmony_ci    if (log_mark(log, NO_OP))
558275793eaSopenharmony_ci        return -1;
559275793eaSopenharmony_ci    strcpy(log->end, ".add");
560275793eaSopenharmony_ci    unlink(log->path);          /* ignore error, since may not exist */
561275793eaSopenharmony_ci    return 0;
562275793eaSopenharmony_ci}
563275793eaSopenharmony_ci
564275793eaSopenharmony_ci/* Replace the foo.dict file with the foo.temp file.  Also delete the foo.add
565275793eaSopenharmony_ci   file, since the compress operation may have been interrupted before that was
566275793eaSopenharmony_ci   done.  Returns 1 if memory could not be allocated, or -1 if reading or
567275793eaSopenharmony_ci   writing foo.gz fails, or if the rename fails for some reason other than
568275793eaSopenharmony_ci   foo.temp not existing.  foo.temp not existing is a permitted error, since
569275793eaSopenharmony_ci   the replace operation may have been interrupted after the rename is done,
570275793eaSopenharmony_ci   but before foo.gz is marked as complete. */
571275793eaSopenharmony_cilocal int log_replace(struct log *log)
572275793eaSopenharmony_ci{
573275793eaSopenharmony_ci    int ret;
574275793eaSopenharmony_ci    char *dest;
575275793eaSopenharmony_ci
576275793eaSopenharmony_ci    /* delete foo.add file */
577275793eaSopenharmony_ci    strcpy(log->end, ".add");
578275793eaSopenharmony_ci    unlink(log->path);         /* ignore error, since may not exist */
579275793eaSopenharmony_ci    BAIL(3);
580275793eaSopenharmony_ci
581275793eaSopenharmony_ci    /* rename foo.name to foo.dict, replacing foo.dict if it exists */
582275793eaSopenharmony_ci    strcpy(log->end, ".dict");
583275793eaSopenharmony_ci    dest = malloc(strlen(log->path) + 1);
584275793eaSopenharmony_ci    if (dest == NULL)
585275793eaSopenharmony_ci        return -2;
586275793eaSopenharmony_ci    strcpy(dest, log->path);
587275793eaSopenharmony_ci    strcpy(log->end, ".temp");
588275793eaSopenharmony_ci    ret = rename(log->path, dest);
589275793eaSopenharmony_ci    free(dest);
590275793eaSopenharmony_ci    if (ret && errno != ENOENT)
591275793eaSopenharmony_ci        return -1;
592275793eaSopenharmony_ci    BAIL(4);
593275793eaSopenharmony_ci
594275793eaSopenharmony_ci    /* mark the foo.gz file as done */
595275793eaSopenharmony_ci    return log_mark(log, NO_OP);
596275793eaSopenharmony_ci}
597275793eaSopenharmony_ci
598275793eaSopenharmony_ci/* Compress the len bytes at data and append the compressed data to the
599275793eaSopenharmony_ci   foo.gz deflate data immediately after the previous compressed data.  This
600275793eaSopenharmony_ci   overwrites the previous uncompressed data, which was stored in foo.add
601275793eaSopenharmony_ci   and is the data provided in data[0..len-1].  If this operation is
602275793eaSopenharmony_ci   interrupted, it picks up at the start of this routine, with the foo.add
603275793eaSopenharmony_ci   file read in again.  If there is no data to compress (len == 0), then we
604275793eaSopenharmony_ci   simply terminate the foo.gz file after the previously compressed data,
605275793eaSopenharmony_ci   appending a final empty stored block and the gzip trailer.  Return -1 if
606275793eaSopenharmony_ci   reading or writing the log.gz file failed, or -2 if there was a memory
607275793eaSopenharmony_ci   allocation failure. */
608275793eaSopenharmony_cilocal int log_compress(struct log *log, unsigned char *data, size_t len)
609275793eaSopenharmony_ci{
610275793eaSopenharmony_ci    int fd;
611275793eaSopenharmony_ci    uint got, max;
612275793eaSopenharmony_ci    ssize_t dict;
613275793eaSopenharmony_ci    off_t end;
614275793eaSopenharmony_ci    z_stream strm;
615275793eaSopenharmony_ci    unsigned char buf[DICT];
616275793eaSopenharmony_ci
617275793eaSopenharmony_ci    /* compress and append compressed data */
618275793eaSopenharmony_ci    if (len) {
619275793eaSopenharmony_ci        /* set up for deflate, allocating memory */
620275793eaSopenharmony_ci        strm.zalloc = Z_NULL;
621275793eaSopenharmony_ci        strm.zfree = Z_NULL;
622275793eaSopenharmony_ci        strm.opaque = Z_NULL;
623275793eaSopenharmony_ci        if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8,
624275793eaSopenharmony_ci                         Z_DEFAULT_STRATEGY) != Z_OK)
625275793eaSopenharmony_ci            return -2;
626275793eaSopenharmony_ci
627275793eaSopenharmony_ci        /* read in dictionary (last 32K of data that was compressed) */
628275793eaSopenharmony_ci        strcpy(log->end, ".dict");
629275793eaSopenharmony_ci        fd = open(log->path, O_RDONLY, 0);
630275793eaSopenharmony_ci        if (fd >= 0) {
631275793eaSopenharmony_ci            dict = read(fd, buf, DICT);
632275793eaSopenharmony_ci            close(fd);
633275793eaSopenharmony_ci            if (dict < 0) {
634275793eaSopenharmony_ci                deflateEnd(&strm);
635275793eaSopenharmony_ci                return -1;
636275793eaSopenharmony_ci            }
637275793eaSopenharmony_ci            if (dict)
638275793eaSopenharmony_ci                deflateSetDictionary(&strm, buf, (uint)dict);
639275793eaSopenharmony_ci        }
640275793eaSopenharmony_ci        log_touch(log);
641275793eaSopenharmony_ci
642275793eaSopenharmony_ci        /* prime deflate with last bits of previous block, position write
643275793eaSopenharmony_ci           pointer to write those bits and overwrite what follows */
644275793eaSopenharmony_ci        if (lseek(log->fd, log->first - (log->back > 8 ? 2 : 1),
645275793eaSopenharmony_ci                SEEK_SET) < 0 ||
646275793eaSopenharmony_ci            read(log->fd, buf, 1) != 1 || lseek(log->fd, -1, SEEK_CUR) < 0) {
647275793eaSopenharmony_ci            deflateEnd(&strm);
648275793eaSopenharmony_ci            return -1;
649275793eaSopenharmony_ci        }
650275793eaSopenharmony_ci        deflatePrime(&strm, (8 - log->back) & 7, *buf);
651275793eaSopenharmony_ci
652275793eaSopenharmony_ci        /* compress, finishing with a partial non-last empty static block */
653275793eaSopenharmony_ci        strm.next_in = data;
654275793eaSopenharmony_ci        max = (((uint)0 - 1) >> 1) + 1; /* in case int smaller than size_t */
655275793eaSopenharmony_ci        do {
656275793eaSopenharmony_ci            strm.avail_in = len > max ? max : (uint)len;
657275793eaSopenharmony_ci            len -= strm.avail_in;
658275793eaSopenharmony_ci            do {
659275793eaSopenharmony_ci                strm.avail_out = DICT;
660275793eaSopenharmony_ci                strm.next_out = buf;
661275793eaSopenharmony_ci                deflate(&strm, len ? Z_NO_FLUSH : Z_PARTIAL_FLUSH);
662275793eaSopenharmony_ci                got = DICT - strm.avail_out;
663275793eaSopenharmony_ci                if (got && write(log->fd, buf, got) != got) {
664275793eaSopenharmony_ci                    deflateEnd(&strm);
665275793eaSopenharmony_ci                    return -1;
666275793eaSopenharmony_ci                }
667275793eaSopenharmony_ci                log_touch(log);
668275793eaSopenharmony_ci            } while (strm.avail_out == 0);
669275793eaSopenharmony_ci        } while (len);
670275793eaSopenharmony_ci        deflateEnd(&strm);
671275793eaSopenharmony_ci        BAIL(5);
672275793eaSopenharmony_ci
673275793eaSopenharmony_ci        /* find start of empty static block -- scanning backwards the first one
674275793eaSopenharmony_ci           bit is the second bit of the block, if the last byte is zero, then
675275793eaSopenharmony_ci           we know the byte before that has a one in the top bit, since an
676275793eaSopenharmony_ci           empty static block is ten bits long */
677275793eaSopenharmony_ci        if ((log->first = lseek(log->fd, -1, SEEK_CUR)) < 0 ||
678275793eaSopenharmony_ci            read(log->fd, buf, 1) != 1)
679275793eaSopenharmony_ci            return -1;
680275793eaSopenharmony_ci        log->first++;
681275793eaSopenharmony_ci        if (*buf) {
682275793eaSopenharmony_ci            log->back = 1;
683275793eaSopenharmony_ci            while ((*buf & ((uint)1 << (8 - log->back++))) == 0)
684275793eaSopenharmony_ci                ;       /* guaranteed to terminate, since *buf != 0 */
685275793eaSopenharmony_ci        }
686275793eaSopenharmony_ci        else
687275793eaSopenharmony_ci            log->back = 10;
688275793eaSopenharmony_ci
689275793eaSopenharmony_ci        /* update compressed crc and length */
690275793eaSopenharmony_ci        log->ccrc = log->tcrc;
691275793eaSopenharmony_ci        log->clen = log->tlen;
692275793eaSopenharmony_ci    }
693275793eaSopenharmony_ci    else {
694275793eaSopenharmony_ci        /* no data to compress -- fix up existing gzip stream */
695275793eaSopenharmony_ci        log->tcrc = log->ccrc;
696275793eaSopenharmony_ci        log->tlen = log->clen;
697275793eaSopenharmony_ci    }
698275793eaSopenharmony_ci
699275793eaSopenharmony_ci    /* complete and truncate gzip stream */
700275793eaSopenharmony_ci    log->last = log->first;
701275793eaSopenharmony_ci    log->stored = 0;
702275793eaSopenharmony_ci    PUT4(buf, log->tcrc);
703275793eaSopenharmony_ci    PUT4(buf + 4, log->tlen);
704275793eaSopenharmony_ci    if (log_last(log, 1) || write(log->fd, buf, 8) != 8 ||
705275793eaSopenharmony_ci        (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end))
706275793eaSopenharmony_ci        return -1;
707275793eaSopenharmony_ci    BAIL(6);
708275793eaSopenharmony_ci
709275793eaSopenharmony_ci    /* mark as being in the replace operation */
710275793eaSopenharmony_ci    if (log_mark(log, REPLACE_OP))
711275793eaSopenharmony_ci        return -1;
712275793eaSopenharmony_ci
713275793eaSopenharmony_ci    /* execute the replace operation and mark the file as done */
714275793eaSopenharmony_ci    return log_replace(log);
715275793eaSopenharmony_ci}
716275793eaSopenharmony_ci
717275793eaSopenharmony_ci/* log a repair record to the .repairs file */
718275793eaSopenharmony_cilocal void log_log(struct log *log, int op, char *record)
719275793eaSopenharmony_ci{
720275793eaSopenharmony_ci    time_t now;
721275793eaSopenharmony_ci    FILE *rec;
722275793eaSopenharmony_ci
723275793eaSopenharmony_ci    now = time(NULL);
724275793eaSopenharmony_ci    strcpy(log->end, ".repairs");
725275793eaSopenharmony_ci    rec = fopen(log->path, "a");
726275793eaSopenharmony_ci    if (rec == NULL)
727275793eaSopenharmony_ci        return;
728275793eaSopenharmony_ci    fprintf(rec, "%.24s %s recovery: %s\n", ctime(&now), op == APPEND_OP ?
729275793eaSopenharmony_ci            "append" : (op == COMPRESS_OP ? "compress" : "replace"), record);
730275793eaSopenharmony_ci    fclose(rec);
731275793eaSopenharmony_ci    return;
732275793eaSopenharmony_ci}
733275793eaSopenharmony_ci
734275793eaSopenharmony_ci/* Recover the interrupted operation op.  First read foo.add for recovering an
735275793eaSopenharmony_ci   append or compress operation.  Return -1 if there was an error reading or
736275793eaSopenharmony_ci   writing foo.gz or reading an existing foo.add, or -2 if there was a memory
737275793eaSopenharmony_ci   allocation failure. */
738275793eaSopenharmony_cilocal int log_recover(struct log *log, int op)
739275793eaSopenharmony_ci{
740275793eaSopenharmony_ci    int fd, ret = 0;
741275793eaSopenharmony_ci    unsigned char *data = NULL;
742275793eaSopenharmony_ci    size_t len = 0;
743275793eaSopenharmony_ci    struct stat st;
744275793eaSopenharmony_ci
745275793eaSopenharmony_ci    /* log recovery */
746275793eaSopenharmony_ci    log_log(log, op, "start");
747275793eaSopenharmony_ci
748275793eaSopenharmony_ci    /* load foo.add file if expected and present */
749275793eaSopenharmony_ci    if (op == APPEND_OP || op == COMPRESS_OP) {
750275793eaSopenharmony_ci        strcpy(log->end, ".add");
751275793eaSopenharmony_ci        if (stat(log->path, &st) == 0 && st.st_size) {
752275793eaSopenharmony_ci            len = (size_t)(st.st_size);
753275793eaSopenharmony_ci            if ((off_t)len != st.st_size ||
754275793eaSopenharmony_ci                    (data = malloc(st.st_size)) == NULL) {
755275793eaSopenharmony_ci                log_log(log, op, "allocation failure");
756275793eaSopenharmony_ci                return -2;
757275793eaSopenharmony_ci            }
758275793eaSopenharmony_ci            if ((fd = open(log->path, O_RDONLY, 0)) < 0) {
759275793eaSopenharmony_ci                free(data);
760275793eaSopenharmony_ci                log_log(log, op, ".add file read failure");
761275793eaSopenharmony_ci                return -1;
762275793eaSopenharmony_ci            }
763275793eaSopenharmony_ci            ret = (size_t)read(fd, data, len) != len;
764275793eaSopenharmony_ci            close(fd);
765275793eaSopenharmony_ci            if (ret) {
766275793eaSopenharmony_ci                free(data);
767275793eaSopenharmony_ci                log_log(log, op, ".add file read failure");
768275793eaSopenharmony_ci                return -1;
769275793eaSopenharmony_ci            }
770275793eaSopenharmony_ci            log_log(log, op, "loaded .add file");
771275793eaSopenharmony_ci        }
772275793eaSopenharmony_ci        else
773275793eaSopenharmony_ci            log_log(log, op, "missing .add file!");
774275793eaSopenharmony_ci    }
775275793eaSopenharmony_ci
776275793eaSopenharmony_ci    /* recover the interrupted operation */
777275793eaSopenharmony_ci    switch (op) {
778275793eaSopenharmony_ci    case APPEND_OP:
779275793eaSopenharmony_ci        ret = log_append(log, data, len);
780275793eaSopenharmony_ci        break;
781275793eaSopenharmony_ci    case COMPRESS_OP:
782275793eaSopenharmony_ci        ret = log_compress(log, data, len);
783275793eaSopenharmony_ci        break;
784275793eaSopenharmony_ci    case REPLACE_OP:
785275793eaSopenharmony_ci        ret = log_replace(log);
786275793eaSopenharmony_ci    }
787275793eaSopenharmony_ci
788275793eaSopenharmony_ci    /* log status */
789275793eaSopenharmony_ci    log_log(log, op, ret ? "failure" : "complete");
790275793eaSopenharmony_ci
791275793eaSopenharmony_ci    /* clean up */
792275793eaSopenharmony_ci    if (data != NULL)
793275793eaSopenharmony_ci        free(data);
794275793eaSopenharmony_ci    return ret;
795275793eaSopenharmony_ci}
796275793eaSopenharmony_ci
797275793eaSopenharmony_ci/* Close the foo.gz file (if open) and release the lock. */
798275793eaSopenharmony_cilocal void log_close(struct log *log)
799275793eaSopenharmony_ci{
800275793eaSopenharmony_ci    if (log->fd >= 0)
801275793eaSopenharmony_ci        close(log->fd);
802275793eaSopenharmony_ci    log->fd = -1;
803275793eaSopenharmony_ci    log_unlock(log);
804275793eaSopenharmony_ci}
805275793eaSopenharmony_ci
806275793eaSopenharmony_ci/* Open foo.gz, verify the header, and load the extra field contents, after
807275793eaSopenharmony_ci   first creating the foo.lock file to gain exclusive access to the foo.*
808275793eaSopenharmony_ci   files.  If foo.gz does not exist or is empty, then write the initial header,
809275793eaSopenharmony_ci   extra, and body content of an empty foo.gz log file.  If there is an error
810275793eaSopenharmony_ci   creating the lock file due to access restrictions, or an error reading or
811275793eaSopenharmony_ci   writing the foo.gz file, or if the foo.gz file is not a proper log file for
812275793eaSopenharmony_ci   this object (e.g. not a gzip file or does not contain the expected extra
813275793eaSopenharmony_ci   field), then return true.  If there is an error, the lock is released.
814275793eaSopenharmony_ci   Otherwise, the lock is left in place. */
815275793eaSopenharmony_cilocal int log_open(struct log *log)
816275793eaSopenharmony_ci{
817275793eaSopenharmony_ci    int op;
818275793eaSopenharmony_ci
819275793eaSopenharmony_ci    /* release open file resource if left over -- can occur if lock lost
820275793eaSopenharmony_ci       between gzlog_open() and gzlog_write() */
821275793eaSopenharmony_ci    if (log->fd >= 0)
822275793eaSopenharmony_ci        close(log->fd);
823275793eaSopenharmony_ci    log->fd = -1;
824275793eaSopenharmony_ci
825275793eaSopenharmony_ci    /* negotiate exclusive access */
826275793eaSopenharmony_ci    if (log_lock(log) < 0)
827275793eaSopenharmony_ci        return -1;
828275793eaSopenharmony_ci
829275793eaSopenharmony_ci    /* open the log file, foo.gz */
830275793eaSopenharmony_ci    strcpy(log->end, ".gz");
831275793eaSopenharmony_ci    log->fd = open(log->path, O_RDWR | O_CREAT, 0644);
832275793eaSopenharmony_ci    if (log->fd < 0) {
833275793eaSopenharmony_ci        log_close(log);
834275793eaSopenharmony_ci        return -1;
835275793eaSopenharmony_ci    }
836275793eaSopenharmony_ci
837275793eaSopenharmony_ci    /* if new, initialize foo.gz with an empty log, delete old dictionary */
838275793eaSopenharmony_ci    if (lseek(log->fd, 0, SEEK_END) == 0) {
839275793eaSopenharmony_ci        if (write(log->fd, log_gzhead, HEAD) != HEAD ||
840275793eaSopenharmony_ci            write(log->fd, log_gzext, EXTRA) != EXTRA ||
841275793eaSopenharmony_ci            write(log->fd, log_gzbody, BODY) != BODY) {
842275793eaSopenharmony_ci            log_close(log);
843275793eaSopenharmony_ci            return -1;
844275793eaSopenharmony_ci        }
845275793eaSopenharmony_ci        strcpy(log->end, ".dict");
846275793eaSopenharmony_ci        unlink(log->path);
847275793eaSopenharmony_ci    }
848275793eaSopenharmony_ci
849275793eaSopenharmony_ci    /* verify log file and load extra field information */
850275793eaSopenharmony_ci    if ((op = log_head(log)) < 0) {
851275793eaSopenharmony_ci        log_close(log);
852275793eaSopenharmony_ci        return -1;
853275793eaSopenharmony_ci    }
854275793eaSopenharmony_ci
855275793eaSopenharmony_ci    /* check for interrupted process and if so, recover */
856275793eaSopenharmony_ci    if (op != NO_OP && log_recover(log, op)) {
857275793eaSopenharmony_ci        log_close(log);
858275793eaSopenharmony_ci        return -1;
859275793eaSopenharmony_ci    }
860275793eaSopenharmony_ci
861275793eaSopenharmony_ci    /* touch the lock file to prevent another process from grabbing it */
862275793eaSopenharmony_ci    log_touch(log);
863275793eaSopenharmony_ci    return 0;
864275793eaSopenharmony_ci}
865275793eaSopenharmony_ci
866275793eaSopenharmony_ci/* See gzlog.h for the description of the external methods below */
867275793eaSopenharmony_cigzlog *gzlog_open(char *path)
868275793eaSopenharmony_ci{
869275793eaSopenharmony_ci    size_t n;
870275793eaSopenharmony_ci    struct log *log;
871275793eaSopenharmony_ci
872275793eaSopenharmony_ci    /* check arguments */
873275793eaSopenharmony_ci    if (path == NULL || *path == 0)
874275793eaSopenharmony_ci        return NULL;
875275793eaSopenharmony_ci
876275793eaSopenharmony_ci    /* allocate and initialize log structure */
877275793eaSopenharmony_ci    log = malloc(sizeof(struct log));
878275793eaSopenharmony_ci    if (log == NULL)
879275793eaSopenharmony_ci        return NULL;
880275793eaSopenharmony_ci    strcpy(log->id, LOGID);
881275793eaSopenharmony_ci    log->fd = -1;
882275793eaSopenharmony_ci
883275793eaSopenharmony_ci    /* save path and end of path for name construction */
884275793eaSopenharmony_ci    n = strlen(path);
885275793eaSopenharmony_ci    log->path = malloc(n + 9);              /* allow for ".repairs" */
886275793eaSopenharmony_ci    if (log->path == NULL) {
887275793eaSopenharmony_ci        free(log);
888275793eaSopenharmony_ci        return NULL;
889275793eaSopenharmony_ci    }
890275793eaSopenharmony_ci    strcpy(log->path, path);
891275793eaSopenharmony_ci    log->end = log->path + n;
892275793eaSopenharmony_ci
893275793eaSopenharmony_ci    /* gain exclusive access and verify log file -- may perform a
894275793eaSopenharmony_ci       recovery operation if needed */
895275793eaSopenharmony_ci    if (log_open(log)) {
896275793eaSopenharmony_ci        free(log->path);
897275793eaSopenharmony_ci        free(log);
898275793eaSopenharmony_ci        return NULL;
899275793eaSopenharmony_ci    }
900275793eaSopenharmony_ci
901275793eaSopenharmony_ci    /* return pointer to log structure */
902275793eaSopenharmony_ci    return log;
903275793eaSopenharmony_ci}
904275793eaSopenharmony_ci
905275793eaSopenharmony_ci/* gzlog_compress() return values:
906275793eaSopenharmony_ci    0: all good
907275793eaSopenharmony_ci   -1: file i/o error (usually access issue)
908275793eaSopenharmony_ci   -2: memory allocation failure
909275793eaSopenharmony_ci   -3: invalid log pointer argument */
910275793eaSopenharmony_ciint gzlog_compress(gzlog *logd)
911275793eaSopenharmony_ci{
912275793eaSopenharmony_ci    int fd, ret;
913275793eaSopenharmony_ci    uint block;
914275793eaSopenharmony_ci    size_t len, next;
915275793eaSopenharmony_ci    unsigned char *data, buf[5];
916275793eaSopenharmony_ci    struct log *log = logd;
917275793eaSopenharmony_ci
918275793eaSopenharmony_ci    /* check arguments */
919275793eaSopenharmony_ci    if (log == NULL || strcmp(log->id, LOGID))
920275793eaSopenharmony_ci        return -3;
921275793eaSopenharmony_ci
922275793eaSopenharmony_ci    /* see if we lost the lock -- if so get it again and reload the extra
923275793eaSopenharmony_ci       field information (it probably changed), recover last operation if
924275793eaSopenharmony_ci       necessary */
925275793eaSopenharmony_ci    if (log_check(log) && log_open(log))
926275793eaSopenharmony_ci        return -1;
927275793eaSopenharmony_ci
928275793eaSopenharmony_ci    /* create space for uncompressed data */
929275793eaSopenharmony_ci    len = ((size_t)(log->last - log->first) & ~(((size_t)1 << 10) - 1)) +
930275793eaSopenharmony_ci          log->stored;
931275793eaSopenharmony_ci    if ((data = malloc(len)) == NULL)
932275793eaSopenharmony_ci        return -2;
933275793eaSopenharmony_ci
934275793eaSopenharmony_ci    /* do statement here is just a cheap trick for error handling */
935275793eaSopenharmony_ci    do {
936275793eaSopenharmony_ci        /* read in the uncompressed data */
937275793eaSopenharmony_ci        if (lseek(log->fd, log->first - 1, SEEK_SET) < 0)
938275793eaSopenharmony_ci            break;
939275793eaSopenharmony_ci        next = 0;
940275793eaSopenharmony_ci        while (next < len) {
941275793eaSopenharmony_ci            if (read(log->fd, buf, 5) != 5)
942275793eaSopenharmony_ci                break;
943275793eaSopenharmony_ci            block = PULL2(buf + 1);
944275793eaSopenharmony_ci            if (next + block > len ||
945275793eaSopenharmony_ci                read(log->fd, (char *)data + next, block) != block)
946275793eaSopenharmony_ci                break;
947275793eaSopenharmony_ci            next += block;
948275793eaSopenharmony_ci        }
949275793eaSopenharmony_ci        if (lseek(log->fd, 0, SEEK_CUR) != log->last + 4 + log->stored)
950275793eaSopenharmony_ci            break;
951275793eaSopenharmony_ci        log_touch(log);
952275793eaSopenharmony_ci
953275793eaSopenharmony_ci        /* write the uncompressed data to the .add file */
954275793eaSopenharmony_ci        strcpy(log->end, ".add");
955275793eaSopenharmony_ci        fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
956275793eaSopenharmony_ci        if (fd < 0)
957275793eaSopenharmony_ci            break;
958275793eaSopenharmony_ci        ret = (size_t)write(fd, data, len) != len;
959275793eaSopenharmony_ci        if (ret | close(fd))
960275793eaSopenharmony_ci            break;
961275793eaSopenharmony_ci        log_touch(log);
962275793eaSopenharmony_ci
963275793eaSopenharmony_ci        /* write the dictionary for the next compress to the .temp file */
964275793eaSopenharmony_ci        strcpy(log->end, ".temp");
965275793eaSopenharmony_ci        fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
966275793eaSopenharmony_ci        if (fd < 0)
967275793eaSopenharmony_ci            break;
968275793eaSopenharmony_ci        next = DICT > len ? len : DICT;
969275793eaSopenharmony_ci        ret = (size_t)write(fd, (char *)data + len - next, next) != next;
970275793eaSopenharmony_ci        if (ret | close(fd))
971275793eaSopenharmony_ci            break;
972275793eaSopenharmony_ci        log_touch(log);
973275793eaSopenharmony_ci
974275793eaSopenharmony_ci        /* roll back to compressed data, mark the compress in progress */
975275793eaSopenharmony_ci        log->last = log->first;
976275793eaSopenharmony_ci        log->stored = 0;
977275793eaSopenharmony_ci        if (log_mark(log, COMPRESS_OP))
978275793eaSopenharmony_ci            break;
979275793eaSopenharmony_ci        BAIL(7);
980275793eaSopenharmony_ci
981275793eaSopenharmony_ci        /* compress and append the data (clears mark) */
982275793eaSopenharmony_ci        ret = log_compress(log, data, len);
983275793eaSopenharmony_ci        free(data);
984275793eaSopenharmony_ci        return ret;
985275793eaSopenharmony_ci    } while (0);
986275793eaSopenharmony_ci
987275793eaSopenharmony_ci    /* broke out of do above on i/o error */
988275793eaSopenharmony_ci    free(data);
989275793eaSopenharmony_ci    return -1;
990275793eaSopenharmony_ci}
991275793eaSopenharmony_ci
992275793eaSopenharmony_ci/* gzlog_write() return values:
993275793eaSopenharmony_ci    0: all good
994275793eaSopenharmony_ci   -1: file i/o error (usually access issue)
995275793eaSopenharmony_ci   -2: memory allocation failure
996275793eaSopenharmony_ci   -3: invalid log pointer argument */
997275793eaSopenharmony_ciint gzlog_write(gzlog *logd, void *data, size_t len)
998275793eaSopenharmony_ci{
999275793eaSopenharmony_ci    int fd, ret;
1000275793eaSopenharmony_ci    struct log *log = logd;
1001275793eaSopenharmony_ci
1002275793eaSopenharmony_ci    /* check arguments */
1003275793eaSopenharmony_ci    if (log == NULL || strcmp(log->id, LOGID))
1004275793eaSopenharmony_ci        return -3;
1005275793eaSopenharmony_ci    if (data == NULL || len <= 0)
1006275793eaSopenharmony_ci        return 0;
1007275793eaSopenharmony_ci
1008275793eaSopenharmony_ci    /* see if we lost the lock -- if so get it again and reload the extra
1009275793eaSopenharmony_ci       field information (it probably changed), recover last operation if
1010275793eaSopenharmony_ci       necessary */
1011275793eaSopenharmony_ci    if (log_check(log) && log_open(log))
1012275793eaSopenharmony_ci        return -1;
1013275793eaSopenharmony_ci
1014275793eaSopenharmony_ci    /* create and write .add file */
1015275793eaSopenharmony_ci    strcpy(log->end, ".add");
1016275793eaSopenharmony_ci    fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1017275793eaSopenharmony_ci    if (fd < 0)
1018275793eaSopenharmony_ci        return -1;
1019275793eaSopenharmony_ci    ret = (size_t)write(fd, data, len) != len;
1020275793eaSopenharmony_ci    if (ret | close(fd))
1021275793eaSopenharmony_ci        return -1;
1022275793eaSopenharmony_ci    log_touch(log);
1023275793eaSopenharmony_ci
1024275793eaSopenharmony_ci    /* mark log file with append in progress */
1025275793eaSopenharmony_ci    if (log_mark(log, APPEND_OP))
1026275793eaSopenharmony_ci        return -1;
1027275793eaSopenharmony_ci    BAIL(8);
1028275793eaSopenharmony_ci
1029275793eaSopenharmony_ci    /* append data (clears mark) */
1030275793eaSopenharmony_ci    if (log_append(log, data, len))
1031275793eaSopenharmony_ci        return -1;
1032275793eaSopenharmony_ci
1033275793eaSopenharmony_ci    /* check to see if it's time to compress -- if not, then done */
1034275793eaSopenharmony_ci    if (((log->last - log->first) >> 10) + (log->stored >> 10) < TRIGGER)
1035275793eaSopenharmony_ci        return 0;
1036275793eaSopenharmony_ci
1037275793eaSopenharmony_ci    /* time to compress */
1038275793eaSopenharmony_ci    return gzlog_compress(log);
1039275793eaSopenharmony_ci}
1040275793eaSopenharmony_ci
1041275793eaSopenharmony_ci/* gzlog_close() return values:
1042275793eaSopenharmony_ci    0: ok
1043275793eaSopenharmony_ci   -3: invalid log pointer argument */
1044275793eaSopenharmony_ciint gzlog_close(gzlog *logd)
1045275793eaSopenharmony_ci{
1046275793eaSopenharmony_ci    struct log *log = logd;
1047275793eaSopenharmony_ci
1048275793eaSopenharmony_ci    /* check arguments */
1049275793eaSopenharmony_ci    if (log == NULL || strcmp(log->id, LOGID))
1050275793eaSopenharmony_ci        return -3;
1051275793eaSopenharmony_ci
1052275793eaSopenharmony_ci    /* close the log file and release the lock */
1053275793eaSopenharmony_ci    log_close(log);
1054275793eaSopenharmony_ci
1055275793eaSopenharmony_ci    /* free structure and return */
1056275793eaSopenharmony_ci    if (log->path != NULL)
1057275793eaSopenharmony_ci        free(log->path);
1058275793eaSopenharmony_ci    strcpy(log->id, "bad");
1059275793eaSopenharmony_ci    free(log);
1060275793eaSopenharmony_ci    return 0;
1061275793eaSopenharmony_ci}
1062