Chris@4: /* Chris@4: * gzlog.c Chris@4: * Copyright (C) 2004, 2008 Mark Adler, all rights reserved Chris@4: * For conditions of distribution and use, see copyright notice in gzlog.h Chris@4: * version 2.0, 25 Apr 2008 Chris@4: */ Chris@4: Chris@4: /* Chris@4: gzlog provides a mechanism for frequently appending short strings to a gzip Chris@4: file that is efficient both in execution time and compression ratio. The Chris@4: strategy is to write the short strings in an uncompressed form to the end of Chris@4: the gzip file, only compressing when the amount of uncompressed data has Chris@4: reached a given threshold. Chris@4: Chris@4: gzlog also provides protection against interruptions in the process due to Chris@4: system crashes. The status of the operation is recorded in an extra field Chris@4: in the gzip file, and is only updated once the gzip file is brought to a Chris@4: valid state. The last data to be appended or compressed is saved in an Chris@4: auxiliary file, so that if the operation is interrupted, it can be completed Chris@4: the next time an append operation is attempted. Chris@4: Chris@4: gzlog maintains another auxiliary file with the last 32K of data from the Chris@4: compressed portion, which is preloaded for the compression of the subsequent Chris@4: data. This minimizes the impact to the compression ratio of appending. Chris@4: */ Chris@4: Chris@4: /* Chris@4: Operations Concept: Chris@4: Chris@4: Files (log name "foo"): Chris@4: foo.gz -- gzip file with the complete log Chris@4: foo.add -- last message to append or last data to compress Chris@4: foo.dict -- dictionary of the last 32K of data for next compression Chris@4: foo.temp -- temporary dictionary file for compression after this one Chris@4: foo.lock -- lock file for reading and writing the other files Chris@4: foo.repairs -- log file for log file recovery operations (not compressed) Chris@4: Chris@4: gzip file structure: Chris@4: - fixed-length (no file name) header with extra field (see below) Chris@4: - compressed data ending initially with empty stored block Chris@4: - uncompressed data filling out originally empty stored block and Chris@4: subsequent stored blocks as needed (16K max each) Chris@4: - gzip trailer Chris@4: - no junk at end (no other gzip streams) Chris@4: Chris@4: When appending data, the information in the first three items above plus the Chris@4: foo.add file are sufficient to recover an interrupted append operation. The Chris@4: extra field has the necessary information to restore the start of the last Chris@4: stored block and determine where to append the data in the foo.add file, as Chris@4: well as the crc and length of the gzip data before the append operation. Chris@4: Chris@4: The foo.add file is created before the gzip file is marked for append, and Chris@4: deleted after the gzip file is marked as complete. So if the append Chris@4: operation is interrupted, the data to add will still be there. If due to Chris@4: some external force, the foo.add file gets deleted between when the append Chris@4: operation was interrupted and when recovery is attempted, the gzip file will Chris@4: still be restored, but without the appended data. Chris@4: Chris@4: When compressing data, the information in the first two items above plus the Chris@4: foo.add file are sufficient to recover an interrupted compress operation. Chris@4: The extra field has the necessary information to find the end of the Chris@4: compressed data, and contains both the crc and length of just the compressed Chris@4: data and of the complete set of data including the contents of the foo.add Chris@4: file. Chris@4: Chris@4: Again, the foo.add file is maintained during the compress operation in case Chris@4: of an interruption. If in the unlikely event the foo.add file with the data Chris@4: to be compressed is missing due to some external force, a gzip file with Chris@4: just the previous compressed data will be reconstructed. In this case, all Chris@4: of the data that was to be compressed is lost (approximately one megabyte). Chris@4: This will not occur if all that happened was an interruption of the compress Chris@4: operation. Chris@4: Chris@4: The third state that is marked is the replacement of the old dictionary with Chris@4: the new dictionary after a compress operation. Once compression is Chris@4: complete, the gzip file is marked as being in the replace state. This Chris@4: completes the gzip file, so an interrupt after being so marked does not Chris@4: result in recompression. Then the dictionary file is replaced, and the gzip Chris@4: file is marked as completed. This state prevents the possibility of Chris@4: restarting compression with the wrong dictionary file. Chris@4: Chris@4: All three operations are wrapped by a lock/unlock procedure. In order to Chris@4: gain exclusive access to the log files, first a foo.lock file must be Chris@4: exclusively created. When all operations are complete, the lock is Chris@4: released by deleting the foo.lock file. If when attempting to create the Chris@4: lock file, it already exists and the modify time of the lock file is more Chris@4: than five minutes old (set by the PATIENCE define below), then the old Chris@4: lock file is considered stale and deleted, and the exclusive creation of Chris@4: the lock file is retried. To assure that there are no false assessments Chris@4: of the staleness of the lock file, the operations periodically touch the Chris@4: lock file to update the modified date. Chris@4: Chris@4: Following is the definition of the extra field with all of the information Chris@4: required to enable the above append and compress operations and their Chris@4: recovery if interrupted. Multi-byte values are stored little endian Chris@4: (consistent with the gzip format). File pointers are eight bytes long. Chris@4: The crc's and lengths for the gzip trailer are four bytes long. (Note that Chris@4: the length at the end of a gzip file is used for error checking only, and Chris@4: for large files is actually the length modulo 2^32.) The stored block Chris@4: length is two bytes long. The gzip extra field two-byte identification is Chris@4: "ap" for append. It is assumed that writing the extra field to the file is Chris@4: an "atomic" operation. That is, either all of the extra field is written Chris@4: to the file, or none of it is, if the operation is interrupted right at the Chris@4: point of updating the extra field. This is a reasonable assumption, since Chris@4: the extra field is within the first 52 bytes of the file, which is smaller Chris@4: than any expected block size for a mass storage device (usually 512 bytes or Chris@4: larger). Chris@4: Chris@4: Extra field (35 bytes): Chris@4: - Pointer to first stored block length -- this points to the two-byte length Chris@4: of the first stored block, which is followed by the two-byte, one's Chris@4: complement of that length. The stored block length is preceded by the Chris@4: three-bit header of the stored block, which is the actual start of the Chris@4: stored block in the deflate format. See the bit offset field below. Chris@4: - Pointer to the last stored block length. This is the same as above, but Chris@4: for the last stored block of the uncompressed data in the gzip file. Chris@4: Initially this is the same as the first stored block length pointer. Chris@4: When the stored block gets to 16K (see the MAX_STORE define), then a new Chris@4: stored block as added, at which point the last stored block length pointer Chris@4: is different from the first stored block length pointer. When they are Chris@4: different, the first bit of the last stored block header is eight bits, or Chris@4: one byte back from the block length. Chris@4: - Compressed data crc and length. This is the crc and length of the data Chris@4: that is in the compressed portion of the deflate stream. These are used Chris@4: only in the event that the foo.add file containing the data to compress is Chris@4: lost after a compress operation is interrupted. Chris@4: - Total data crc and length. This is the crc and length of all of the data Chris@4: stored in the gzip file, compressed and uncompressed. It is used to Chris@4: reconstruct the gzip trailer when compressing, as well as when recovering Chris@4: interrupted operations. Chris@4: - Final stored block length. This is used to quickly find where to append, Chris@4: and allows the restoration of the original final stored block state when Chris@4: an append operation is interrupted. Chris@4: - First stored block start as the number of bits back from the final stored Chris@4: block first length byte. This value is in the range of 3..10, and is Chris@4: stored as the low three bits of the final byte of the extra field after Chris@4: subtracting three (0..7). This allows the last-block bit of the stored Chris@4: block header to be updated when a new stored block is added, for the case Chris@4: when the first stored block and the last stored block are the same. (When Chris@4: they are different, the numbers of bits back is known to be eight.) This Chris@4: also allows for new compressed data to be appended to the old compressed Chris@4: data in the compress operation, overwriting the previous first stored Chris@4: block, or for the compressed data to be terminated and a valid gzip file Chris@4: reconstructed on the off chance that a compression operation was Chris@4: interrupted and the data to compress in the foo.add file was deleted. Chris@4: - The operation in process. This is the next two bits in the last byte (the Chris@4: bits under the mask 0x18). The are interpreted as 0: nothing in process, Chris@4: 1: append in process, 2: compress in process, 3: replace in process. Chris@4: - The top three bits of the last byte in the extra field are reserved and Chris@4: are currently set to zero. Chris@4: Chris@4: Main procedure: Chris@4: - Exclusively create the foo.lock file using the O_CREAT and O_EXCL modes of Chris@4: the system open() call. If the modify time of an existing lock file is Chris@4: more than PATIENCE seconds old, then the lock file is deleted and the Chris@4: exclusive create is retried. Chris@4: - Load the extra field from the foo.gz file, and see if an operation was in Chris@4: progress but not completed. If so, apply the recovery procedure below. Chris@4: - Perform the append procedure with the provided data. Chris@4: - If the uncompressed data in the foo.gz file is 1MB or more, apply the Chris@4: compress procedure. Chris@4: - Delete the foo.lock file. Chris@4: Chris@4: Append procedure: Chris@4: - Put what to append in the foo.add file so that the operation can be Chris@4: restarted if this procedure is interrupted. Chris@4: - Mark the foo.gz extra field with the append operation in progress. Chris@4: + Restore the original last-block bit and stored block length of the last Chris@4: stored block from the information in the extra field, in case a previous Chris@4: append operation was interrupted. Chris@4: - Append the provided data to the last stored block, creating new stored Chris@4: blocks as needed and updating the stored blocks last-block bits and Chris@4: lengths. Chris@4: - Update the crc and length with the new data, and write the gzip trailer. Chris@4: - Write over the extra field (with a single write operation) with the new Chris@4: pointers, lengths, and crc's, and mark the gzip file as not in process. Chris@4: Though there is still a foo.add file, it will be ignored since nothing Chris@4: is in process. If a foo.add file is leftover from a previously Chris@4: completed operation, it is truncated when writing new data to it. Chris@4: - Delete the foo.add file. Chris@4: Chris@4: Compress and replace procedures: Chris@4: - Read all of the uncompressed data in the stored blocks in foo.gz and write Chris@4: it to foo.add. Also write foo.temp with the last 32K of that data to Chris@4: provide a dictionary for the next invocation of this procedure. Chris@4: - Rewrite the extra field marking foo.gz with a compression in process. Chris@4: * If there is no data provided to compress (due to a missing foo.add file Chris@4: when recovering), reconstruct and truncate the foo.gz file to contain Chris@4: only the previous compressed data and proceed to the step after the next Chris@4: one. Otherwise ... Chris@4: - Compress the data with the dictionary in foo.dict, and write to the Chris@4: foo.gz file starting at the bit immediately following the last previously Chris@4: compressed block. If there is no foo.dict, proceed anyway with the Chris@4: compression at slightly reduced efficiency. (For the foo.dict file to be Chris@4: missing requires some external failure beyond simply the interruption of Chris@4: a compress operation.) During this process, the foo.lock file is Chris@4: periodically touched to assure that that file is not considered stale by Chris@4: another process before we're done. The deflation is terminated with a Chris@4: non-last empty static block (10 bits long), that is then located and Chris@4: written over by a last-bit-set empty stored block. Chris@4: - Append the crc and length of the data in the gzip file (previously Chris@4: calculated during the append operations). Chris@4: - Write over the extra field with the updated stored block offsets, bits Chris@4: back, crc's, and lengths, and mark foo.gz as in process for a replacement Chris@4: of the dictionary. Chris@4: @ Delete the foo.add file. Chris@4: - Replace foo.dict with foo.temp. Chris@4: - Write over the extra field, marking foo.gz as complete. Chris@4: Chris@4: Recovery procedure: Chris@4: - If not a replace recovery, read in the foo.add file, and provide that data Chris@4: to the appropriate recovery below. If there is no foo.add file, provide Chris@4: a zero data length to the recovery. In that case, the append recovery Chris@4: restores the foo.gz to the previous compressed + uncompressed data state. Chris@4: For the the compress recovery, a missing foo.add file results in foo.gz Chris@4: being restored to the previous compressed-only data state. Chris@4: - Append recovery: Chris@4: - Pick up append at + step above Chris@4: - Compress recovery: Chris@4: - Pick up compress at * step above Chris@4: - Replace recovery: Chris@4: - Pick up compress at @ step above Chris@4: - Log the repair with a date stamp in foo.repairs Chris@4: */ Chris@4: Chris@4: #include Chris@4: #include /* rename, fopen, fprintf, fclose */ Chris@4: #include /* malloc, free */ Chris@4: #include /* strlen, strrchr, strcpy, strncpy, strcmp */ Chris@4: #include /* open */ Chris@4: #include /* lseek, read, write, close, unlink, sleep, */ Chris@4: /* ftruncate, fsync */ Chris@4: #include /* errno */ Chris@4: #include /* time, ctime */ Chris@4: #include /* stat */ Chris@4: #include /* utimes */ Chris@4: #include "zlib.h" /* crc32 */ Chris@4: Chris@4: #include "gzlog.h" /* header for external access */ Chris@4: Chris@4: #define local static Chris@4: typedef unsigned int uint; Chris@4: typedef unsigned long ulong; Chris@4: Chris@4: /* Macro for debugging to deterministically force recovery operations */ Chris@4: #ifdef DEBUG Chris@4: #include /* longjmp */ Chris@4: jmp_buf gzlog_jump; /* where to go back to */ Chris@4: int gzlog_bail = 0; /* which point to bail at (1..8) */ Chris@4: int gzlog_count = -1; /* number of times through to wait */ Chris@4: # define BAIL(n) do { if (n == gzlog_bail && gzlog_count-- == 0) \ Chris@4: longjmp(gzlog_jump, gzlog_bail); } while (0) Chris@4: #else Chris@4: # define BAIL(n) Chris@4: #endif Chris@4: Chris@4: /* how old the lock file can be in seconds before considering it stale */ Chris@4: #define PATIENCE 300 Chris@4: Chris@4: /* maximum stored block size in Kbytes -- must be in 1..63 */ Chris@4: #define MAX_STORE 16 Chris@4: Chris@4: /* number of stored Kbytes to trigger compression (must be >= 32 to allow Chris@4: dictionary construction, and <= 204 * MAX_STORE, in order for >> 10 to Chris@4: discard the stored block headers contribution of five bytes each) */ Chris@4: #define TRIGGER 1024 Chris@4: Chris@4: /* size of a deflate dictionary (this cannot be changed) */ Chris@4: #define DICT 32768U Chris@4: Chris@4: /* values for the operation (2 bits) */ Chris@4: #define NO_OP 0 Chris@4: #define APPEND_OP 1 Chris@4: #define COMPRESS_OP 2 Chris@4: #define REPLACE_OP 3 Chris@4: Chris@4: /* macros to extract little-endian integers from an unsigned byte buffer */ Chris@4: #define PULL2(p) ((p)[0]+((uint)((p)[1])<<8)) Chris@4: #define PULL4(p) (PULL2(p)+((ulong)PULL2(p+2)<<16)) Chris@4: #define PULL8(p) (PULL4(p)+((off_t)PULL4(p+4)<<32)) Chris@4: Chris@4: /* macros to store integers into a byte buffer in little-endian order */ Chris@4: #define PUT2(p,a) do {(p)[0]=a;(p)[1]=(a)>>8;} while(0) Chris@4: #define PUT4(p,a) do {PUT2(p,a);PUT2(p+2,a>>16);} while(0) Chris@4: #define PUT8(p,a) do {PUT4(p,a);PUT4(p+4,a>>32);} while(0) Chris@4: Chris@4: /* internal structure for log information */ Chris@4: #define LOGID "\106\035\172" /* should be three non-zero characters */ Chris@4: struct log { Chris@4: char id[4]; /* contains LOGID to detect inadvertent overwrites */ Chris@4: int fd; /* file descriptor for .gz file, opened read/write */ Chris@4: char *path; /* allocated path, e.g. "/var/log/foo" or "foo" */ Chris@4: char *end; /* end of path, for appending suffices such as ".gz" */ Chris@4: off_t first; /* offset of first stored block first length byte */ Chris@4: int back; /* location of first block id in bits back from first */ Chris@4: uint stored; /* bytes currently in last stored block */ Chris@4: off_t last; /* offset of last stored block first length byte */ Chris@4: ulong ccrc; /* crc of compressed data */ Chris@4: ulong clen; /* length (modulo 2^32) of compressed data */ Chris@4: ulong tcrc; /* crc of total data */ Chris@4: ulong tlen; /* length (modulo 2^32) of total data */ Chris@4: time_t lock; /* last modify time of our lock file */ Chris@4: }; Chris@4: Chris@4: /* gzip header for gzlog */ Chris@4: local unsigned char log_gzhead[] = { Chris@4: 0x1f, 0x8b, /* magic gzip id */ Chris@4: 8, /* compression method is deflate */ Chris@4: 4, /* there is an extra field (no file name) */ Chris@4: 0, 0, 0, 0, /* no modification time provided */ Chris@4: 0, 0xff, /* no extra flags, no OS specified */ Chris@4: 39, 0, 'a', 'p', 35, 0 /* extra field with "ap" subfield */ Chris@4: /* 35 is EXTRA, 39 is EXTRA + 4 */ Chris@4: }; Chris@4: Chris@4: #define HEAD sizeof(log_gzhead) /* should be 16 */ Chris@4: Chris@4: /* initial gzip extra field content (52 == HEAD + EXTRA + 1) */ Chris@4: local unsigned char log_gzext[] = { Chris@4: 52, 0, 0, 0, 0, 0, 0, 0, /* offset of first stored block length */ Chris@4: 52, 0, 0, 0, 0, 0, 0, 0, /* offset of last stored block length */ Chris@4: 0, 0, 0, 0, 0, 0, 0, 0, /* compressed data crc and length */ Chris@4: 0, 0, 0, 0, 0, 0, 0, 0, /* total data crc and length */ Chris@4: 0, 0, /* final stored block data length */ Chris@4: 5 /* op is NO_OP, last bit 8 bits back */ Chris@4: }; Chris@4: Chris@4: #define EXTRA sizeof(log_gzext) /* should be 35 */ Chris@4: Chris@4: /* initial gzip data and trailer */ Chris@4: local unsigned char log_gzbody[] = { Chris@4: 1, 0, 0, 0xff, 0xff, /* empty stored block (last) */ Chris@4: 0, 0, 0, 0, /* crc */ Chris@4: 0, 0, 0, 0 /* uncompressed length */ Chris@4: }; Chris@4: Chris@4: #define BODY sizeof(log_gzbody) Chris@4: Chris@4: /* Exclusively create foo.lock in order to negotiate exclusive access to the Chris@4: foo.* files. If the modify time of an existing lock file is greater than Chris@4: PATIENCE seconds in the past, then consider the lock file to have been Chris@4: abandoned, delete it, and try the exclusive create again. Save the lock Chris@4: file modify time for verification of ownership. Return 0 on success, or -1 Chris@4: on failure, usually due to an access restriction or invalid path. Note that Chris@4: if stat() or unlink() fails, it may be due to another process noticing the Chris@4: abandoned lock file a smidge sooner and deleting it, so those are not Chris@4: flagged as an error. */ Chris@4: local int log_lock(struct log *log) Chris@4: { Chris@4: int fd; Chris@4: struct stat st; Chris@4: Chris@4: strcpy(log->end, ".lock"); Chris@4: while ((fd = open(log->path, O_CREAT | O_EXCL, 0644)) < 0) { Chris@4: if (errno != EEXIST) Chris@4: return -1; Chris@4: if (stat(log->path, &st) == 0 && time(NULL) - st.st_mtime > PATIENCE) { Chris@4: unlink(log->path); Chris@4: continue; Chris@4: } Chris@4: sleep(2); /* relinquish the CPU for two seconds while waiting */ Chris@4: } Chris@4: close(fd); Chris@4: if (stat(log->path, &st) == 0) Chris@4: log->lock = st.st_mtime; Chris@4: return 0; Chris@4: } Chris@4: Chris@4: /* Update the modify time of the lock file to now, in order to prevent another Chris@4: task from thinking that the lock is stale. Save the lock file modify time Chris@4: for verification of ownership. */ Chris@4: local void log_touch(struct log *log) Chris@4: { Chris@4: struct stat st; Chris@4: Chris@4: strcpy(log->end, ".lock"); Chris@4: utimes(log->path, NULL); Chris@4: if (stat(log->path, &st) == 0) Chris@4: log->lock = st.st_mtime; Chris@4: } Chris@4: Chris@4: /* Check the log file modify time against what is expected. Return true if Chris@4: this is not our lock. If it is our lock, touch it to keep it. */ Chris@4: local int log_check(struct log *log) Chris@4: { Chris@4: struct stat st; Chris@4: Chris@4: strcpy(log->end, ".lock"); Chris@4: if (stat(log->path, &st) || st.st_mtime != log->lock) Chris@4: return 1; Chris@4: log_touch(log); Chris@4: return 0; Chris@4: } Chris@4: Chris@4: /* Unlock a previously acquired lock, but only if it's ours. */ Chris@4: local void log_unlock(struct log *log) Chris@4: { Chris@4: if (log_check(log)) Chris@4: return; Chris@4: strcpy(log->end, ".lock"); Chris@4: unlink(log->path); Chris@4: log->lock = 0; Chris@4: } Chris@4: Chris@4: /* Check the gzip header and read in the extra field, filling in the values in Chris@4: the log structure. Return op on success or -1 if the gzip header was not as Chris@4: expected. op is the current operation in progress last written to the extra Chris@4: field. This assumes that the gzip file has already been opened, with the Chris@4: file descriptor log->fd. */ Chris@4: local int log_head(struct log *log) Chris@4: { Chris@4: int op; Chris@4: unsigned char buf[HEAD + EXTRA]; Chris@4: Chris@4: if (lseek(log->fd, 0, SEEK_SET) < 0 || Chris@4: read(log->fd, buf, HEAD + EXTRA) != HEAD + EXTRA || Chris@4: memcmp(buf, log_gzhead, HEAD)) { Chris@4: return -1; Chris@4: } Chris@4: log->first = PULL8(buf + HEAD); Chris@4: log->last = PULL8(buf + HEAD + 8); Chris@4: log->ccrc = PULL4(buf + HEAD + 16); Chris@4: log->clen = PULL4(buf + HEAD + 20); Chris@4: log->tcrc = PULL4(buf + HEAD + 24); Chris@4: log->tlen = PULL4(buf + HEAD + 28); Chris@4: log->stored = PULL2(buf + HEAD + 32); Chris@4: log->back = 3 + (buf[HEAD + 34] & 7); Chris@4: op = (buf[HEAD + 34] >> 3) & 3; Chris@4: return op; Chris@4: } Chris@4: Chris@4: /* Write over the extra field contents, marking the operation as op. Use fsync Chris@4: to assure that the device is written to, and in the requested order. This Chris@4: operation, and only this operation, is assumed to be atomic in order to Chris@4: assure that the log is recoverable in the event of an interruption at any Chris@4: point in the process. Return -1 if the write to foo.gz failed. */ Chris@4: local int log_mark(struct log *log, int op) Chris@4: { Chris@4: int ret; Chris@4: unsigned char ext[EXTRA]; Chris@4: Chris@4: PUT8(ext, log->first); Chris@4: PUT8(ext + 8, log->last); Chris@4: PUT4(ext + 16, log->ccrc); Chris@4: PUT4(ext + 20, log->clen); Chris@4: PUT4(ext + 24, log->tcrc); Chris@4: PUT4(ext + 28, log->tlen); Chris@4: PUT2(ext + 32, log->stored); Chris@4: ext[34] = log->back - 3 + (op << 3); Chris@4: fsync(log->fd); Chris@4: ret = lseek(log->fd, HEAD, SEEK_SET) < 0 || Chris@4: write(log->fd, ext, EXTRA) != EXTRA ? -1 : 0; Chris@4: fsync(log->fd); Chris@4: return ret; Chris@4: } Chris@4: Chris@4: /* Rewrite the last block header bits and subsequent zero bits to get to a byte Chris@4: boundary, setting the last block bit if last is true, and then write the Chris@4: remainder of the stored block header (length and one's complement). Leave Chris@4: the file pointer after the end of the last stored block data. Return -1 if Chris@4: there is a read or write failure on the foo.gz file */ Chris@4: local int log_last(struct log *log, int last) Chris@4: { Chris@4: int back, len, mask; Chris@4: unsigned char buf[6]; Chris@4: Chris@4: /* determine the locations of the bytes and bits to modify */ Chris@4: back = log->last == log->first ? log->back : 8; Chris@4: len = back > 8 ? 2 : 1; /* bytes back from log->last */ Chris@4: mask = 0x80 >> ((back - 1) & 7); /* mask for block last-bit */ Chris@4: Chris@4: /* get the byte to modify (one or two back) into buf[0] -- don't need to Chris@4: read the byte if the last-bit is eight bits back, since in that case Chris@4: the entire byte will be modified */ Chris@4: buf[0] = 0; Chris@4: if (back != 8 && (lseek(log->fd, log->last - len, SEEK_SET) < 0 || Chris@4: read(log->fd, buf, 1) != 1)) Chris@4: return -1; Chris@4: Chris@4: /* change the last-bit of the last stored block as requested -- note Chris@4: that all bits above the last-bit are set to zero, per the type bits Chris@4: of a stored block being 00 and per the convention that the bits to Chris@4: bring the stream to a byte boundary are also zeros */ Chris@4: buf[1] = 0; Chris@4: buf[2 - len] = (*buf & (mask - 1)) + (last ? mask : 0); Chris@4: Chris@4: /* write the modified stored block header and lengths, move the file Chris@4: pointer to after the last stored block data */ Chris@4: PUT2(buf + 2, log->stored); Chris@4: PUT2(buf + 4, log->stored ^ 0xffff); Chris@4: return lseek(log->fd, log->last - len, SEEK_SET) < 0 || Chris@4: write(log->fd, buf + 2 - len, len + 4) != len + 4 || Chris@4: lseek(log->fd, log->stored, SEEK_CUR) < 0 ? -1 : 0; Chris@4: } Chris@4: Chris@4: /* Append len bytes from data to the locked and open log file. len may be zero Chris@4: if recovering and no .add file was found. In that case, the previous state Chris@4: of the foo.gz file is restored. The data is appended uncompressed in Chris@4: deflate stored blocks. Return -1 if there was an error reading or writing Chris@4: the foo.gz file. */ Chris@4: local int log_append(struct log *log, unsigned char *data, size_t len) Chris@4: { Chris@4: uint put; Chris@4: off_t end; Chris@4: unsigned char buf[8]; Chris@4: Chris@4: /* set the last block last-bit and length, in case recovering an Chris@4: interrupted append, then position the file pointer to append to the Chris@4: block */ Chris@4: if (log_last(log, 1)) Chris@4: return -1; Chris@4: Chris@4: /* append, adding stored blocks and updating the offset of the last stored Chris@4: block as needed, and update the total crc and length */ Chris@4: while (len) { Chris@4: /* append as much as we can to the last block */ Chris@4: put = (MAX_STORE << 10) - log->stored; Chris@4: if (put > len) Chris@4: put = (uint)len; Chris@4: if (put) { Chris@4: if (write(log->fd, data, put) != put) Chris@4: return -1; Chris@4: BAIL(1); Chris@4: log->tcrc = crc32(log->tcrc, data, put); Chris@4: log->tlen += put; Chris@4: log->stored += put; Chris@4: data += put; Chris@4: len -= put; Chris@4: } Chris@4: Chris@4: /* if we need to, add a new empty stored block */ Chris@4: if (len) { Chris@4: /* mark current block as not last */ Chris@4: if (log_last(log, 0)) Chris@4: return -1; Chris@4: Chris@4: /* point to new, empty stored block */ Chris@4: log->last += 4 + log->stored + 1; Chris@4: log->stored = 0; Chris@4: } Chris@4: Chris@4: /* mark last block as last, update its length */ Chris@4: if (log_last(log, 1)) Chris@4: return -1; Chris@4: BAIL(2); Chris@4: } Chris@4: Chris@4: /* write the new crc and length trailer, and truncate just in case (could Chris@4: be recovering from partial append with a missing foo.add file) */ Chris@4: PUT4(buf, log->tcrc); Chris@4: PUT4(buf + 4, log->tlen); Chris@4: if (write(log->fd, buf, 8) != 8 || Chris@4: (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end)) Chris@4: return -1; Chris@4: Chris@4: /* write the extra field, marking the log file as done, delete .add file */ Chris@4: if (log_mark(log, NO_OP)) Chris@4: return -1; Chris@4: strcpy(log->end, ".add"); Chris@4: unlink(log->path); /* ignore error, since may not exist */ Chris@4: return 0; Chris@4: } Chris@4: Chris@4: /* Replace the foo.dict file with the foo.temp file. Also delete the foo.add Chris@4: file, since the compress operation may have been interrupted before that was Chris@4: done. Returns 1 if memory could not be allocated, or -1 if reading or Chris@4: writing foo.gz fails, or if the rename fails for some reason other than Chris@4: foo.temp not existing. foo.temp not existing is a permitted error, since Chris@4: the replace operation may have been interrupted after the rename is done, Chris@4: but before foo.gz is marked as complete. */ Chris@4: local int log_replace(struct log *log) Chris@4: { Chris@4: int ret; Chris@4: char *dest; Chris@4: Chris@4: /* delete foo.add file */ Chris@4: strcpy(log->end, ".add"); Chris@4: unlink(log->path); /* ignore error, since may not exist */ Chris@4: BAIL(3); Chris@4: Chris@4: /* rename foo.name to foo.dict, replacing foo.dict if it exists */ Chris@4: strcpy(log->end, ".dict"); Chris@4: dest = malloc(strlen(log->path) + 1); Chris@4: if (dest == NULL) Chris@4: return -2; Chris@4: strcpy(dest, log->path); Chris@4: strcpy(log->end, ".temp"); Chris@4: ret = rename(log->path, dest); Chris@4: free(dest); Chris@4: if (ret && errno != ENOENT) Chris@4: return -1; Chris@4: BAIL(4); Chris@4: Chris@4: /* mark the foo.gz file as done */ Chris@4: return log_mark(log, NO_OP); Chris@4: } Chris@4: Chris@4: /* Compress the len bytes at data and append the compressed data to the Chris@4: foo.gz deflate data immediately after the previous compressed data. This Chris@4: overwrites the previous uncompressed data, which was stored in foo.add Chris@4: and is the data provided in data[0..len-1]. If this operation is Chris@4: interrupted, it picks up at the start of this routine, with the foo.add Chris@4: file read in again. If there is no data to compress (len == 0), then we Chris@4: simply terminate the foo.gz file after the previously compressed data, Chris@4: appending a final empty stored block and the gzip trailer. Return -1 if Chris@4: reading or writing the log.gz file failed, or -2 if there was a memory Chris@4: allocation failure. */ Chris@4: local int log_compress(struct log *log, unsigned char *data, size_t len) Chris@4: { Chris@4: int fd; Chris@4: uint got, max; Chris@4: ssize_t dict; Chris@4: off_t end; Chris@4: z_stream strm; Chris@4: unsigned char buf[DICT]; Chris@4: Chris@4: /* compress and append compressed data */ Chris@4: if (len) { Chris@4: /* set up for deflate, allocating memory */ Chris@4: strm.zalloc = Z_NULL; Chris@4: strm.zfree = Z_NULL; Chris@4: strm.opaque = Z_NULL; Chris@4: if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 8, Chris@4: Z_DEFAULT_STRATEGY) != Z_OK) Chris@4: return -2; Chris@4: Chris@4: /* read in dictionary (last 32K of data that was compressed) */ Chris@4: strcpy(log->end, ".dict"); Chris@4: fd = open(log->path, O_RDONLY, 0); Chris@4: if (fd >= 0) { Chris@4: dict = read(fd, buf, DICT); Chris@4: close(fd); Chris@4: if (dict < 0) { Chris@4: deflateEnd(&strm); Chris@4: return -1; Chris@4: } Chris@4: if (dict) Chris@4: deflateSetDictionary(&strm, buf, (uint)dict); Chris@4: } Chris@4: log_touch(log); Chris@4: Chris@4: /* prime deflate with last bits of previous block, position write Chris@4: pointer to write those bits and overwrite what follows */ Chris@4: if (lseek(log->fd, log->first - (log->back > 8 ? 2 : 1), Chris@4: SEEK_SET) < 0 || Chris@4: read(log->fd, buf, 1) != 1 || lseek(log->fd, -1, SEEK_CUR) < 0) { Chris@4: deflateEnd(&strm); Chris@4: return -1; Chris@4: } Chris@4: deflatePrime(&strm, (8 - log->back) & 7, *buf); Chris@4: Chris@4: /* compress, finishing with a partial non-last empty static block */ Chris@4: strm.next_in = data; Chris@4: max = (((uint)0 - 1) >> 1) + 1; /* in case int smaller than size_t */ Chris@4: do { Chris@4: strm.avail_in = len > max ? max : (uint)len; Chris@4: len -= strm.avail_in; Chris@4: do { Chris@4: strm.avail_out = DICT; Chris@4: strm.next_out = buf; Chris@4: deflate(&strm, len ? Z_NO_FLUSH : Z_PARTIAL_FLUSH); Chris@4: got = DICT - strm.avail_out; Chris@4: if (got && write(log->fd, buf, got) != got) { Chris@4: deflateEnd(&strm); Chris@4: return -1; Chris@4: } Chris@4: log_touch(log); Chris@4: } while (strm.avail_out == 0); Chris@4: } while (len); Chris@4: deflateEnd(&strm); Chris@4: BAIL(5); Chris@4: Chris@4: /* find start of empty static block -- scanning backwards the first one Chris@4: bit is the second bit of the block, if the last byte is zero, then Chris@4: we know the byte before that has a one in the top bit, since an Chris@4: empty static block is ten bits long */ Chris@4: if ((log->first = lseek(log->fd, -1, SEEK_CUR)) < 0 || Chris@4: read(log->fd, buf, 1) != 1) Chris@4: return -1; Chris@4: log->first++; Chris@4: if (*buf) { Chris@4: log->back = 1; Chris@4: while ((*buf & ((uint)1 << (8 - log->back++))) == 0) Chris@4: ; /* guaranteed to terminate, since *buf != 0 */ Chris@4: } Chris@4: else Chris@4: log->back = 10; Chris@4: Chris@4: /* update compressed crc and length */ Chris@4: log->ccrc = log->tcrc; Chris@4: log->clen = log->tlen; Chris@4: } Chris@4: else { Chris@4: /* no data to compress -- fix up existing gzip stream */ Chris@4: log->tcrc = log->ccrc; Chris@4: log->tlen = log->clen; Chris@4: } Chris@4: Chris@4: /* complete and truncate gzip stream */ Chris@4: log->last = log->first; Chris@4: log->stored = 0; Chris@4: PUT4(buf, log->tcrc); Chris@4: PUT4(buf + 4, log->tlen); Chris@4: if (log_last(log, 1) || write(log->fd, buf, 8) != 8 || Chris@4: (end = lseek(log->fd, 0, SEEK_CUR)) < 0 || ftruncate(log->fd, end)) Chris@4: return -1; Chris@4: BAIL(6); Chris@4: Chris@4: /* mark as being in the replace operation */ Chris@4: if (log_mark(log, REPLACE_OP)) Chris@4: return -1; Chris@4: Chris@4: /* execute the replace operation and mark the file as done */ Chris@4: return log_replace(log); Chris@4: } Chris@4: Chris@4: /* log a repair record to the .repairs file */ Chris@4: local void log_log(struct log *log, int op, char *record) Chris@4: { Chris@4: time_t now; Chris@4: FILE *rec; Chris@4: Chris@4: now = time(NULL); Chris@4: strcpy(log->end, ".repairs"); Chris@4: rec = fopen(log->path, "a"); Chris@4: if (rec == NULL) Chris@4: return; Chris@4: fprintf(rec, "%.24s %s recovery: %s\n", ctime(&now), op == APPEND_OP ? Chris@4: "append" : (op == COMPRESS_OP ? "compress" : "replace"), record); Chris@4: fclose(rec); Chris@4: return; Chris@4: } Chris@4: Chris@4: /* Recover the interrupted operation op. First read foo.add for recovering an Chris@4: append or compress operation. Return -1 if there was an error reading or Chris@4: writing foo.gz or reading an existing foo.add, or -2 if there was a memory Chris@4: allocation failure. */ Chris@4: local int log_recover(struct log *log, int op) Chris@4: { Chris@4: int fd, ret = 0; Chris@4: unsigned char *data = NULL; Chris@4: size_t len = 0; Chris@4: struct stat st; Chris@4: Chris@4: /* log recovery */ Chris@4: log_log(log, op, "start"); Chris@4: Chris@4: /* load foo.add file if expected and present */ Chris@4: if (op == APPEND_OP || op == COMPRESS_OP) { Chris@4: strcpy(log->end, ".add"); Chris@4: if (stat(log->path, &st) == 0 && st.st_size) { Chris@4: len = (size_t)(st.st_size); Chris@4: if (len != st.st_size || (data = malloc(st.st_size)) == NULL) { Chris@4: log_log(log, op, "allocation failure"); Chris@4: return -2; Chris@4: } Chris@4: if ((fd = open(log->path, O_RDONLY, 0)) < 0) { Chris@4: log_log(log, op, ".add file read failure"); Chris@4: return -1; Chris@4: } Chris@4: ret = read(fd, data, len) != len; Chris@4: close(fd); Chris@4: if (ret) { Chris@4: log_log(log, op, ".add file read failure"); Chris@4: return -1; Chris@4: } Chris@4: log_log(log, op, "loaded .add file"); Chris@4: } Chris@4: else Chris@4: log_log(log, op, "missing .add file!"); Chris@4: } Chris@4: Chris@4: /* recover the interrupted operation */ Chris@4: switch (op) { Chris@4: case APPEND_OP: Chris@4: ret = log_append(log, data, len); Chris@4: break; Chris@4: case COMPRESS_OP: Chris@4: ret = log_compress(log, data, len); Chris@4: break; Chris@4: case REPLACE_OP: Chris@4: ret = log_replace(log); Chris@4: } Chris@4: Chris@4: /* log status */ Chris@4: log_log(log, op, ret ? "failure" : "complete"); Chris@4: Chris@4: /* clean up */ Chris@4: if (data != NULL) Chris@4: free(data); Chris@4: return ret; Chris@4: } Chris@4: Chris@4: /* Close the foo.gz file (if open) and release the lock. */ Chris@4: local void log_close(struct log *log) Chris@4: { Chris@4: if (log->fd >= 0) Chris@4: close(log->fd); Chris@4: log->fd = -1; Chris@4: log_unlock(log); Chris@4: } Chris@4: Chris@4: /* Open foo.gz, verify the header, and load the extra field contents, after Chris@4: first creating the foo.lock file to gain exclusive access to the foo.* Chris@4: files. If foo.gz does not exist or is empty, then write the initial header, Chris@4: extra, and body content of an empty foo.gz log file. If there is an error Chris@4: creating the lock file due to access restrictions, or an error reading or Chris@4: writing the foo.gz file, or if the foo.gz file is not a proper log file for Chris@4: this object (e.g. not a gzip file or does not contain the expected extra Chris@4: field), then return true. If there is an error, the lock is released. Chris@4: Otherwise, the lock is left in place. */ Chris@4: local int log_open(struct log *log) Chris@4: { Chris@4: int op; Chris@4: Chris@4: /* release open file resource if left over -- can occur if lock lost Chris@4: between gzlog_open() and gzlog_write() */ Chris@4: if (log->fd >= 0) Chris@4: close(log->fd); Chris@4: log->fd = -1; Chris@4: Chris@4: /* negotiate exclusive access */ Chris@4: if (log_lock(log) < 0) Chris@4: return -1; Chris@4: Chris@4: /* open the log file, foo.gz */ Chris@4: strcpy(log->end, ".gz"); Chris@4: log->fd = open(log->path, O_RDWR | O_CREAT, 0644); Chris@4: if (log->fd < 0) { Chris@4: log_close(log); Chris@4: return -1; Chris@4: } Chris@4: Chris@4: /* if new, initialize foo.gz with an empty log, delete old dictionary */ Chris@4: if (lseek(log->fd, 0, SEEK_END) == 0) { Chris@4: if (write(log->fd, log_gzhead, HEAD) != HEAD || Chris@4: write(log->fd, log_gzext, EXTRA) != EXTRA || Chris@4: write(log->fd, log_gzbody, BODY) != BODY) { Chris@4: log_close(log); Chris@4: return -1; Chris@4: } Chris@4: strcpy(log->end, ".dict"); Chris@4: unlink(log->path); Chris@4: } Chris@4: Chris@4: /* verify log file and load extra field information */ Chris@4: if ((op = log_head(log)) < 0) { Chris@4: log_close(log); Chris@4: return -1; Chris@4: } Chris@4: Chris@4: /* check for interrupted process and if so, recover */ Chris@4: if (op != NO_OP && log_recover(log, op)) { Chris@4: log_close(log); Chris@4: return -1; Chris@4: } Chris@4: Chris@4: /* touch the lock file to prevent another process from grabbing it */ Chris@4: log_touch(log); Chris@4: return 0; Chris@4: } Chris@4: Chris@4: /* See gzlog.h for the description of the external methods below */ Chris@4: gzlog *gzlog_open(char *path) Chris@4: { Chris@4: size_t n; Chris@4: struct log *log; Chris@4: Chris@4: /* check arguments */ Chris@4: if (path == NULL || *path == 0) Chris@4: return NULL; Chris@4: Chris@4: /* allocate and initialize log structure */ Chris@4: log = malloc(sizeof(struct log)); Chris@4: if (log == NULL) Chris@4: return NULL; Chris@4: strcpy(log->id, LOGID); Chris@4: log->fd = -1; Chris@4: Chris@4: /* save path and end of path for name construction */ Chris@4: n = strlen(path); Chris@4: log->path = malloc(n + 9); /* allow for ".repairs" */ Chris@4: if (log->path == NULL) { Chris@4: free(log); Chris@4: return NULL; Chris@4: } Chris@4: strcpy(log->path, path); Chris@4: log->end = log->path + n; Chris@4: Chris@4: /* gain exclusive access and verify log file -- may perform a Chris@4: recovery operation if needed */ Chris@4: if (log_open(log)) { Chris@4: free(log->path); Chris@4: free(log); Chris@4: return NULL; Chris@4: } Chris@4: Chris@4: /* return pointer to log structure */ Chris@4: return log; Chris@4: } Chris@4: Chris@4: /* gzlog_compress() return values: Chris@4: 0: all good Chris@4: -1: file i/o error (usually access issue) Chris@4: -2: memory allocation failure Chris@4: -3: invalid log pointer argument */ Chris@4: int gzlog_compress(gzlog *logd) Chris@4: { Chris@4: int fd, ret; Chris@4: uint block; Chris@4: size_t len, next; Chris@4: unsigned char *data, buf[5]; Chris@4: struct log *log = logd; Chris@4: Chris@4: /* check arguments */ Chris@4: if (log == NULL || strcmp(log->id, LOGID) || len < 0) Chris@4: return -3; Chris@4: Chris@4: /* see if we lost the lock -- if so get it again and reload the extra Chris@4: field information (it probably changed), recover last operation if Chris@4: necessary */ Chris@4: if (log_check(log) && log_open(log)) Chris@4: return -1; Chris@4: Chris@4: /* create space for uncompressed data */ Chris@4: len = ((size_t)(log->last - log->first) & ~(((size_t)1 << 10) - 1)) + Chris@4: log->stored; Chris@4: if ((data = malloc(len)) == NULL) Chris@4: return -2; Chris@4: Chris@4: /* do statement here is just a cheap trick for error handling */ Chris@4: do { Chris@4: /* read in the uncompressed data */ Chris@4: if (lseek(log->fd, log->first - 1, SEEK_SET) < 0) Chris@4: break; Chris@4: next = 0; Chris@4: while (next < len) { Chris@4: if (read(log->fd, buf, 5) != 5) Chris@4: break; Chris@4: block = PULL2(buf + 1); Chris@4: if (next + block > len || Chris@4: read(log->fd, (char *)data + next, block) != block) Chris@4: break; Chris@4: next += block; Chris@4: } Chris@4: if (lseek(log->fd, 0, SEEK_CUR) != log->last + 4 + log->stored) Chris@4: break; Chris@4: log_touch(log); Chris@4: Chris@4: /* write the uncompressed data to the .add file */ Chris@4: strcpy(log->end, ".add"); Chris@4: fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); Chris@4: if (fd < 0) Chris@4: break; Chris@4: ret = write(fd, data, len) != len; Chris@4: if (ret | close(fd)) Chris@4: break; Chris@4: log_touch(log); Chris@4: Chris@4: /* write the dictionary for the next compress to the .temp file */ Chris@4: strcpy(log->end, ".temp"); Chris@4: fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); Chris@4: if (fd < 0) Chris@4: break; Chris@4: next = DICT > len ? len : DICT; Chris@4: ret = write(fd, (char *)data + len - next, next) != next; Chris@4: if (ret | close(fd)) Chris@4: break; Chris@4: log_touch(log); Chris@4: Chris@4: /* roll back to compressed data, mark the compress in progress */ Chris@4: log->last = log->first; Chris@4: log->stored = 0; Chris@4: if (log_mark(log, COMPRESS_OP)) Chris@4: break; Chris@4: BAIL(7); Chris@4: Chris@4: /* compress and append the data (clears mark) */ Chris@4: ret = log_compress(log, data, len); Chris@4: free(data); Chris@4: return ret; Chris@4: } while (0); Chris@4: Chris@4: /* broke out of do above on i/o error */ Chris@4: free(data); Chris@4: return -1; Chris@4: } Chris@4: Chris@4: /* gzlog_write() return values: Chris@4: 0: all good Chris@4: -1: file i/o error (usually access issue) Chris@4: -2: memory allocation failure Chris@4: -3: invalid log pointer argument */ Chris@4: int gzlog_write(gzlog *logd, void *data, size_t len) Chris@4: { Chris@4: int fd, ret; Chris@4: struct log *log = logd; Chris@4: Chris@4: /* check arguments */ Chris@4: if (log == NULL || strcmp(log->id, LOGID) || len < 0) Chris@4: return -3; Chris@4: if (data == NULL || len == 0) Chris@4: return 0; Chris@4: Chris@4: /* see if we lost the lock -- if so get it again and reload the extra Chris@4: field information (it probably changed), recover last operation if Chris@4: necessary */ Chris@4: if (log_check(log) && log_open(log)) Chris@4: return -1; Chris@4: Chris@4: /* create and write .add file */ Chris@4: strcpy(log->end, ".add"); Chris@4: fd = open(log->path, O_WRONLY | O_CREAT | O_TRUNC, 0644); Chris@4: if (fd < 0) Chris@4: return -1; Chris@4: ret = write(fd, data, len) != len; Chris@4: if (ret | close(fd)) Chris@4: return -1; Chris@4: log_touch(log); Chris@4: Chris@4: /* mark log file with append in progress */ Chris@4: if (log_mark(log, APPEND_OP)) Chris@4: return -1; Chris@4: BAIL(8); Chris@4: Chris@4: /* append data (clears mark) */ Chris@4: if (log_append(log, data, len)) Chris@4: return -1; Chris@4: Chris@4: /* check to see if it's time to compress -- if not, then done */ Chris@4: if (((log->last - log->first) >> 10) + (log->stored >> 10) < TRIGGER) Chris@4: return 0; Chris@4: Chris@4: /* time to compress */ Chris@4: return gzlog_compress(log); Chris@4: } Chris@4: Chris@4: /* gzlog_close() return values: Chris@4: 0: ok Chris@4: -3: invalid log pointer argument */ Chris@4: int gzlog_close(gzlog *logd) Chris@4: { Chris@4: struct log *log = logd; Chris@4: Chris@4: /* check arguments */ Chris@4: if (log == NULL || strcmp(log->id, LOGID)) Chris@4: return -3; Chris@4: Chris@4: /* close the log file and release the lock */ Chris@4: log_close(log); Chris@4: Chris@4: /* free structure and return */ Chris@4: if (log->path != NULL) Chris@4: free(log->path); Chris@4: strcpy(log->id, "bad"); Chris@4: free(log); Chris@4: return 0; Chris@4: }