]> granicus.if.org Git - apache/blob - support/rotatelogs.c
* Don't leak memory when reopening the logfile.
[apache] / support / rotatelogs.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * Simple program to rotate Apache logs without having to kill the server.
19  *
20  * Contributed by Ben Laurie <ben algroup.co.uk>
21  *
22  * 12 Mar 1996
23  *
24  * Ported to APR by Mladen Turk <mturk mappingsoft.com>
25  *
26  * 23 Sep 2001
27  *
28  * -l option added 2004-06-11
29  *
30  * -l causes the use of local time rather than GMT as the base for the
31  * interval.  NB: Using -l in an environment which changes the GMT offset
32  * (such as for BST or DST) can lead to unpredictable results!
33  *
34  */
35
36
37 #include "apr.h"
38 #include "apr_lib.h"
39 #include "apr_strings.h"
40 #include "apr_errno.h"
41 #include "apr_file_io.h"
42 #include "apr_file_info.h"
43 #include "apr_general.h"
44 #include "apr_time.h"
45 #include "apr_getopt.h"
46
47 #if APR_HAVE_STDLIB_H
48 #include <stdlib.h>
49 #endif
50 #if APR_HAVE_STRING_H
51 #include <string.h>
52 #endif
53 #if APR_HAVE_STRINGS_H
54 #include <strings.h>
55 #endif
56
57 #define BUFSIZE         65536
58 #define ERRMSGSZ        128
59
60 #ifndef MAX_PATH
61 #define MAX_PATH        1024
62 #endif
63
64 static void usage(const char *argv0, const char *reason)
65 {
66     if (reason) {
67         fprintf(stderr, "%s\n", reason);
68     }
69     fprintf(stderr,
70             "Usage: %s [-l] <logfile> "
71             "{<rotation time in seconds>|<rotation size in megabytes>} "
72             "[offset minutes from UTC]\n\n",
73             argv0);
74 #ifdef OS2
75     fprintf(stderr,
76             "Add this:\n\nTransferLog \"|%s.exe /some/where 86400\"\n\n",
77             argv0);
78 #else
79     fprintf(stderr,
80             "Add this:\n\nTransferLog \"|%s /some/where 86400\"\n\n",
81             argv0);
82     fprintf(stderr,
83             "or \n\nTransferLog \"|%s /some/where 5M\"\n\n", argv0);
84 #endif
85     fprintf(stderr,
86             "to httpd.conf. The generated name will be /some/where.nnnn "
87             "where nnnn is the\nsystem time at which the log nominally "
88             "starts (N.B. if using a rotation time,\nthe time will always "
89             "be a multiple of the rotation time, so you can synchronize\n"
90             "cron scripts with it). At the end of each rotation time or "
91             "when the file size\nis reached a new log is started.\n");
92     exit(1);
93 }
94
95 static int get_now(int use_localtime, int utc_offset)
96 {
97     apr_time_t tNow = apr_time_now();
98     if (use_localtime) {
99         /* Check for our UTC offset before using it, since it might
100          * change if there's a switch between standard and daylight
101          * savings time.
102          */
103         apr_time_exp_t lt;
104         apr_time_exp_lt(&lt, tNow);
105         utc_offset = lt.tm_gmtoff;
106     }
107     return (int)apr_time_sec(tNow) + utc_offset;
108 }
109
110 int main (int argc, const char * const argv[])
111 {
112     char buf[BUFSIZE], buf2[MAX_PATH], errbuf[ERRMSGSZ];
113     int tLogEnd = 0, tRotation = 0, utc_offset = 0;
114     unsigned int sRotation = 0;
115     int nMessCount = 0;
116     apr_size_t nRead, nWrite;
117     int use_strftime = 0;
118     int use_localtime = 0;
119     int now = 0;
120     const char *szLogRoot;
121     apr_file_t *f_stdin, *nLogFD = NULL, *nLogFDprev = NULL;
122     apr_pool_t *pool;
123     apr_pool_t *pfile = NULL;
124     apr_pool_t *pfile_prev = NULL;
125     apr_getopt_t *opt;
126     apr_status_t rv;
127     char c;
128     const char *optarg;
129     char *ptr = NULL;
130
131     apr_app_initialize(&argc, &argv, NULL);
132     atexit(apr_terminate);
133
134     apr_pool_create(&pool, NULL);
135     apr_getopt_init(&opt, pool, argc, argv);
136     while ((rv = apr_getopt(opt, "l", &c, &optarg)) == APR_SUCCESS) {
137         switch (c) {
138         case 'l':
139             use_localtime = 1;
140             break;
141         }
142     }
143
144     if (rv != APR_EOF) {
145         usage(argv[0], NULL /* specific error message already issued */ );
146     }
147
148     if (opt->ind + 2 != argc && opt->ind + 3 != argc) {
149         usage(argv[0], "Incorrect number of arguments");
150     }
151
152     szLogRoot = argv[opt->ind++];
153
154     ptr = strchr(argv[opt->ind], 'M');
155     if (ptr) { /* rotation based on file size */
156         if (*(ptr+1) == '\0') {
157             sRotation = atoi(argv[opt->ind]) * 1048576;
158         }
159         if (sRotation == 0) {
160             usage(argv[0], "Invalid rotation size parameter");
161         }
162     }
163     else { /* rotation based on elapsed time */
164         tRotation = atoi(argv[opt->ind]);
165         if (tRotation <= 0) {
166             usage(argv[0], "Invalid rotation time parameter");
167         }
168     }
169     opt->ind++;
170
171     if (opt->ind < argc) { /* have UTC offset */
172         if (use_localtime) {
173             usage(argv[0], "UTC offset parameter is not valid with -l");
174         }
175         utc_offset = atoi(argv[opt->ind]) * 60;
176     }
177
178     use_strftime = (strchr(szLogRoot, '%') != NULL);
179     if (apr_file_open_stdin(&f_stdin, pool) != APR_SUCCESS) {
180         fprintf(stderr, "Unable to open stdin\n");
181         exit(1);
182     }
183
184     for (;;) {
185         nRead = sizeof(buf);
186         if (apr_file_read(f_stdin, buf, &nRead) != APR_SUCCESS) {
187             exit(3);
188         }
189         if (tRotation) {
190             now = get_now(use_localtime, utc_offset);
191             if (nLogFD != NULL && now >= tLogEnd) {
192                 nLogFDprev = nLogFD;
193                 nLogFD = NULL;
194             }
195         }
196         else if (sRotation) {
197             apr_finfo_t finfo;
198             apr_off_t current_size = -1;
199
200             if ((nLogFD != NULL) &&
201                 (apr_file_info_get(&finfo, APR_FINFO_SIZE, nLogFD) == APR_SUCCESS)) {
202                 current_size = finfo.size;
203             }
204
205             if (current_size > sRotation) {
206                 nLogFDprev = nLogFD;
207                 nLogFD = NULL;
208             }
209         }
210         else {
211             fprintf(stderr, "No rotation time or size specified\n");
212             exit(2);
213         }
214
215         if (nLogFD == NULL) {
216             int tLogStart;
217             apr_status_t rv;
218
219             if (tRotation) {
220                 tLogStart = (now / tRotation) * tRotation;
221             }
222             else {
223                 tLogStart = get_now(use_localtime, utc_offset);
224             }
225
226             if (use_strftime) {
227                 apr_time_t tNow = apr_time_from_sec(tLogStart);
228                 apr_time_exp_t e;
229                 apr_size_t rs;
230
231                 apr_time_exp_gmt(&e, tNow);
232                 apr_strftime(buf2, &rs, sizeof(buf2), szLogRoot, &e);
233             }
234             else {
235                 sprintf(buf2, "%s.%010d", szLogRoot, tLogStart);
236             }
237             tLogEnd = tLogStart + tRotation;
238             pfile_prev = pfile;
239             apr_pool_create(&pfile, pool);
240             rv = apr_file_open(&nLogFD, buf2, APR_WRITE | APR_CREATE | APR_APPEND,
241                                APR_OS_DEFAULT, pfile);
242             if (rv != APR_SUCCESS) {
243                 char error[120];
244
245                 apr_strerror(rv, error, sizeof error);
246
247                 /* Uh-oh. Failed to open the new log file. Try to clear
248                  * the previous log file, note the lost log entries,
249                  * and keep on truckin'. */
250                 if (nLogFDprev == NULL) {
251                     fprintf(stderr, "Could not open log file '%s' (%s)\n", buf2, error);
252                     exit(2);
253                 }
254                 else {
255                     nLogFD = nLogFDprev;
256                     apr_pool_destroy(pfile);
257                     pfile = pfile_prev;
258                     /* Try to keep this error message constant length
259                      * in case it occurs several times. */
260                     apr_snprintf(errbuf, sizeof errbuf,
261                                  "Resetting log file due to error opening "
262                                  "new log file, %10d messages lost: %-25.25s\n",
263                                  nMessCount, error);
264                     nWrite = strlen(errbuf);
265                     apr_file_trunc(nLogFD, 0);
266                     if (apr_file_write(nLogFD, errbuf, &nWrite) != APR_SUCCESS) {
267                         fprintf(stderr, "Error writing to the file %s\n", buf2);
268                         exit(2);
269                     }
270                 }
271             }
272             else if (nLogFDprev) {
273                 apr_file_close(nLogFDprev);
274                 if (pfile_prev) {
275                     apr_pool_destroy(pfile_prev);
276                 }
277             }
278             nMessCount = 0;
279         }
280         nWrite = nRead;
281         apr_file_write(nLogFD, buf, &nWrite);
282         if (nWrite != nRead) {
283             nMessCount++;
284             sprintf(errbuf,
285                     "Error writing to log file. "
286                     "%10d messages lost.\n",
287                     nMessCount);
288             nWrite = strlen(errbuf);
289             apr_file_trunc(nLogFD, 0);
290             if (apr_file_write(nLogFD, errbuf, &nWrite) != APR_SUCCESS) {
291                 fprintf(stderr, "Error writing to the file %s\n", buf2);
292                 exit(2);
293             }
294         }
295         else {
296             nMessCount++;
297         }
298     }
299     /* Of course we never, but prevent compiler warnings */
300     return 0;
301 }