new upstream release (3.3.0); modify package compatibility for Stretch
[ossec-hids.git] / src / monitord / compress_log.c
1 /* Copyright (C) 2009 Trend Micro Inc.
2  * All right reserved.
3  *
4  * This program is a free software; you can redistribute it
5  * and/or modify it under the terms of the GNU General Public
6  * License (version 2) as published by the FSF - Free Software
7  * Foundation
8  */
9
10 #include "shared.h"
11 #include "monitord.h"
12
13 #ifdef ZLIB_SYSTEM
14 #include <zlib.h>
15 #else
16 #include "../external/zlib-1.2.11/zlib.h"
17 #endif
18
19 /* gzip a log file */
20 void OS_CompressLog(const char *logfile)
21 {
22     FILE *log;
23     gzFile zlog;
24
25     char logfileGZ[OS_FLSIZE + 1];
26     int len, err;
27
28     char buf[OS_MAXSTR + 1];
29
30     /* Do not compress */
31     if (mond.compress == 0) {
32         return;
33     }
34
35     /* Clear memory */
36     memset(logfileGZ, '\0', OS_FLSIZE + 1);
37     memset(buf, '\0', OS_MAXSTR + 1);
38
39     /* Set umask */
40     umask(0027);
41
42     /* Create the gzip file name */
43     snprintf(logfileGZ, OS_FLSIZE, "%s.gz", logfile);
44
45     /* Read log file */
46     log = fopen(logfile, "r");
47     if (!log) {
48         /* Do not warn in here, since the alert file may not exist */
49         return;
50     }
51
52     /* Open compressed file */
53     zlog = gzopen(logfileGZ, "w");
54     if (!zlog) {
55         fclose(log);
56         merror(FOPEN_ERROR, ARGV0, logfileGZ, errno, strerror(errno));
57         return;
58     }
59
60     for (;;) {
61         len = (int) fread(buf, 1, OS_MAXSTR, log);
62         if (len <= 0) {
63             break;
64         }
65         if (gzwrite(zlog, buf, (unsigned)len) != len) {
66             merror("%s: Compression error: %s", ARGV0, gzerror(zlog, &err));
67         }
68     }
69
70     fclose(log);
71     gzclose(zlog);
72
73     /* Remove uncompressed file */
74     unlink(logfile);
75
76     return;
77 }
78