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