]> granicus.if.org Git - apache/blobdiff - support/rotatelogs.c
* Let mod_proxy_wstunnel and mod_proxy_connect use ap_proxy_transfer_between_connections
[apache] / support / rotatelogs.c
index a295ad0a7bcb8f267407eb4e8c1663c31bbeb35f..87a26a4d08ebdd1ca385f61040c994032d4259dd 100644 (file)
  * limitations under the License.
  */
 
-/*
- * Simple program to rotate Apache logs without having to kill the server.
- *
- * Contributed by Ben Laurie <ben algroup.co.uk>
- *
- * 12 Mar 1996
- *
- * Ported to APR by Mladen Turk <mturk mappingsoft.com>
- *
- * 23 Sep 2001
- *
- * -l option added 2004-06-11
- *
- * -l causes the use of local time rather than GMT as the base for the
- * interval.  NB: Using -l in an environment which changes the GMT offset
- * (such as for BST or DST) can lead to unpredictable results!
- *
- * -f option added Feb, 2008. This causes rotatelog to open/create
- *    the logfile as soon as it's started, not as soon as it sees
- *    data.
- *
- * -v option added Feb, 2008. Verbose output of command line parsing.
- */
-
-
 #include "apr.h"
 #include "apr_lib.h"
 #include "apr_strings.h"
 #include "apr_general.h"
 #include "apr_time.h"
 #include "apr_getopt.h"
+#include "apr_thread_proc.h"
+#include "apr_signal.h"
+#if APR_FILES_AS_SOCKETS
+#include "apr_poll.h"
+#endif
 
 #if APR_HAVE_STDLIB_H
 #include <stdlib.h>
 #include "apr_want.h"
 
 #define BUFSIZE         65536
-#define ERRMSGSZ        256
-
-#ifndef MAX_PATH
-#define MAX_PATH        1024
-#endif
 
 #define ROTATE_NONE     0
 #define ROTATE_NEW      1
@@ -68,7 +43,7 @@
 #define ROTATE_SIZE     3
 #define ROTATE_FORCE    4
 
-static const char *ROTATE_REASONS[] = {
+static const char *const ROTATE_REASONS[] = {
     "None",
     "Open a new file",
     "Time interval expired",
@@ -87,23 +62,41 @@ struct rotate_config {
     int use_strftime;
     int force_open;
     int verbose;
-    const char *szLogRoot;
+    int echo;
+    char *szLogRoot;
     int truncate;
+    const char *linkfile;
+    const char *postrotate_prog;
+#if APR_FILES_AS_SOCKETS
+    int create_empty;
+#endif
+    int num_files;
+    int create_path;
 };
 
 typedef struct rotate_status rotate_status_t;
 
-struct rotate_status {
+/* "adjusted_time_t" is used to store Unix time (seconds since epoch)
+ * which has been adjusted for some timezone fudge factor.  It should
+ * be used for storing the return values from get_now().  A typedef is
+ * used since this type is similar to time_t, but different. */
+typedef long adjusted_time_t;
+
+/* Structure to contain relevant logfile state: fd, pool and
+ * filename. */
+struct logfile {
     apr_pool_t *pool;
-    apr_pool_t *pfile;
-    apr_pool_t *pfile_prev;
-    apr_file_t *nLogFD;
-    apr_file_t *nLogFDprev;
-    char filename[MAX_PATH];
-    char errbuf[ERRMSGSZ];
+    apr_file_t *fd;
+    char name[APR_PATH_MAX];
+};
+
+struct rotate_status {
+    struct logfile current; /* current logfile. */
+    apr_pool_t *pool; /* top-level pool */
     int rotateReason;
-    int tLogEnd;
+    adjusted_time_t tLogEnd;
     int nMessCount;
+    int fileNum;
 };
 
 static rotate_config_t config;
@@ -115,7 +108,11 @@ static void usage(const char *argv0, const char *reason)
         fprintf(stderr, "%s\n", reason);
     }
     fprintf(stderr,
-            "Usage: %s [-v] [-l] [-f] [-t] <logfile> "
+#if APR_FILES_AS_SOCKETS
+            "Usage: %s [-v] [-l] [-L linkname] [-p prog] [-f] [-D] [-t] [-e] [-c] [-n number] <logfile> "
+#else
+            "Usage: %s [-v] [-l] [-L linkname] [-p prog] [-f] [-D] [-t] [-e] [-n number] <logfile> "
+#endif
             "{<rotation time in seconds>|<rotation size>(B|K|M|G)} "
             "[offset minutes from UTC]\n\n",
             argv0);
@@ -131,26 +128,44 @@ static void usage(const char *argv0, const char *reason)
             "or \n\nTransferLog \"|%s /some/where 5M\"\n\n", argv0);
 #endif
     fprintf(stderr,
-            "to httpd.conf. The generated name will be /some/where.nnnn "
-            "where nnnn is the\nsystem time at which the log nominally "
-            "starts (N.B. if using a rotation time,\nthe time will always "
-            "be a multiple of the rotation time, so you can synchronize\n"
-            "cron scripts with it). At the end of each rotation time or "
-            "when the file size\nis reached a new log is started. If the "
-            "-t option is specified, the specified\nfile will be truncated "
-            "instead of rotated, and is useful where tail is used to\n"
-            "process logs in real time.\n");
+            "to httpd.conf. By default, the generated name will be\n"
+            "<logfile>.nnnn where nnnn is the system time at which the log\n"
+            "nominally starts (N.B. if using a rotation time, the time will\n"
+            "always be a multiple of the rotation time, so you can synchronize\n"
+            "cron scripts with it). If <logfile> contains strftime conversion\n"
+            "specifications, those will be used instead. At the end of each\n"
+            "rotation time or when the file size is reached a new log is\n"
+            "started.\n"
+            "\n"
+            "Options:\n"
+            "  -v       Verbose operation. Messages are written to stderr.\n"
+            "  -l       Base rotation on local time instead of UTC.\n"
+            "  -L path  Create hard link from current log to specified path.\n"
+            "  -p prog  Run specified program after opening a new log file. See below.\n"
+            "  -f       Force opening of log on program start.\n"
+            "  -D       Create parent directories of log file.\n" 
+            "  -t       Truncate logfile instead of rotating, tail friendly.\n"
+            "  -e       Echo log to stdout for further processing.\n"
+#if APR_FILES_AS_SOCKETS
+            "  -c       Create log even if it is empty.\n"
+#endif
+            "  -n num   Rotate file by adding suffixes '.0', '.1', ..., '.(num-1)'.\n"
+            "\n"
+            "The program for '-p' is invoked as \"[prog] <curfile> [<prevfile>]\"\n"
+            "where <curfile> is the filename of the newly opened logfile, and\n"
+            "<prevfile>, if given, is the filename of the previously used logfile.\n"
+            "\n");
     exit(1);
 }
 
-/*
- * Get the unix time with timezone corrections
- * given in the config struct.
- */
-static int get_now(rotate_config_t *config)
+/* This function returns the current Unix time (time_t) adjusted for
+ * any configured or derived local time offset.  The offset applied is
+ * returned via *offset. */
+static adjusted_time_t get_now(rotate_config_t *config, apr_int32_t *offset)
 {
     apr_time_t tNow = apr_time_now();
-    int utc_offset = config->utc_offset;
+    apr_int32_t utc_offset;
+
     if (config->use_localtime) {
         /* Check for our UTC offset before using it, since it might
          * change if there's a switch between standard and daylight
@@ -160,27 +175,26 @@ static int get_now(rotate_config_t *config)
         apr_time_exp_lt(&lt, tNow);
         utc_offset = lt.tm_gmtoff;
     }
-    return (int)apr_time_sec(tNow) + utc_offset;
+    else {
+        utc_offset = config->utc_offset;
+    }
+
+    if (offset)
+        *offset = utc_offset;
+
+    return apr_time_sec(tNow) + utc_offset;
 }
 
 /*
  * Close a file and destroy the associated pool.
  */
-static void closeFile(rotate_config_t *config, apr_pool_t *pool, apr_file_t *file)
+static void close_logfile(rotate_config_t *config, struct logfile *logfile)
 {
-    if (file != NULL) {
-        if (config->verbose) {
-            apr_finfo_t finfo;
-            apr_int32_t wanted = APR_FINFO_NAME;
-            if (apr_file_info_get(&finfo, wanted, file) == APR_SUCCESS) {
-                fprintf(stderr, "Closing file %s (%s)\n", finfo.name, finfo.fname);
-            }
-        }
-        apr_file_close(file);
-        if (pool) {
-            apr_pool_destroy(pool);
-        }
+    if (config->verbose) {
+        fprintf(stderr, "Closing file %s\n", logfile->name);
     }
+    apr_file_close(logfile->fd);
+    apr_pool_destroy(logfile->pool);
 }
 
 /*
@@ -194,8 +208,13 @@ static void dumpConfig (rotate_config_t *config)
     fprintf(stderr, "Rotation based on localtime: %12s\n", config->use_localtime ? "yes" : "no");
     fprintf(stderr, "Rotation file date pattern:  %12s\n", config->use_strftime ? "yes" : "no");
     fprintf(stderr, "Rotation file forced open:   %12s\n", config->force_open ? "yes" : "no");
+    fprintf(stderr, "Create parent directories:   %12s\n", config->create_path ? "yes" : "no");
     fprintf(stderr, "Rotation verbose:            %12s\n", config->verbose ? "yes" : "no");
+#if APR_FILES_AS_SOCKETS
+    fprintf(stderr, "Rotation create empty logs:  %12s\n", config->create_empty ? "yes" : "no");
+#endif
     fprintf(stderr, "Rotation file name: %21s\n", config->szLogRoot);
+    fprintf(stderr, "Post-rotation prog: %21s\n", config->postrotate_prog ? config->postrotate_prog : "not used");
 }
 
 /*
@@ -212,15 +231,14 @@ static void dumpConfig (rotate_config_t *config)
  */
 static void checkRotate(rotate_config_t *config, rotate_status_t *status)
 {
-
-    if (status->nLogFD == NULL) {
+    if (status->current.fd == NULL) {
         status->rotateReason = ROTATE_NEW;
     }
     else if (config->sRotation) {
         apr_finfo_t finfo;
         apr_off_t current_size = -1;
 
-        if (apr_file_info_get(&finfo, APR_FINFO_SIZE, status->nLogFD) == APR_SUCCESS) {
+        if (apr_file_info_get(&finfo, APR_FINFO_SIZE, status->current.fd) == APR_SUCCESS) {
             current_size = finfo.size;
         }
 
@@ -228,13 +246,13 @@ static void checkRotate(rotate_config_t *config, rotate_status_t *status)
             status->rotateReason = ROTATE_SIZE;
         }
         else if (config->tRotation) {
-            if (get_now(config) >= status->tLogEnd) {
+            if (get_now(config, NULL) >= status->tLogEnd) {
                 status->rotateReason = ROTATE_TIME;
             }
         }
     }
     else if (config->tRotation) {
-        if (get_now(config) >= status->tLogEnd) {
+        if (get_now(config, NULL) >= status->tLogEnd) {
             status->rotateReason = ROTATE_TIME;
         }
     }
@@ -246,8 +264,100 @@ static void checkRotate(rotate_config_t *config, rotate_status_t *status)
     if (status->rotateReason != ROTATE_NONE && config->verbose) {
         fprintf(stderr, "File rotation needed, reason: %s\n", ROTATE_REASONS[status->rotateReason]);
     }
+}
+
+/*
+ * Handle post-rotate processing.
+ */
+static void post_rotate(apr_pool_t *pool, struct logfile *newlog,
+                        rotate_config_t *config, rotate_status_t *status)
+{
+    apr_status_t rv;
+    apr_procattr_t *pattr;
+    const char *argv[4];
+    apr_proc_t proc;
+
+    /* Handle link file, if configured. */
+    if (config->linkfile) {
+        apr_file_remove(config->linkfile, newlog->pool);
+        if (config->verbose) {
+            fprintf(stderr, "Linking %s to %s\n", newlog->name, config->linkfile);
+        }
+        rv = apr_file_link(newlog->name, config->linkfile);
+        if (rv != APR_SUCCESS) {
+            char *error = apr_psprintf(pool, "Error linking file %s to %s (%pm)\n",
+                                       newlog->name, config->linkfile, &rv);
+            fputs(error, stderr);
+            exit(2);
+        }
+    }
+
+    if (!config->postrotate_prog) {
+        /* Nothing more to do. */
+        return;
+    }
+
+    /* Collect any zombies from a previous run, but don't wait. */
+    while (apr_proc_wait_all_procs(&proc, NULL, NULL, APR_NOWAIT, pool) == APR_CHILD_DONE)
+        /* noop */;
+
+    if ((rv = apr_procattr_create(&pattr, pool)) != APR_SUCCESS) {
+        char *error = apr_psprintf(pool, "post_rotate: apr_procattr_create failed " \
+                                         "for '%s': %pm\n", config->postrotate_prog, &rv);
+        fputs(error, stderr);
+        return;
+    }
+
+    rv = apr_procattr_error_check_set(pattr, 1);
+    if (rv == APR_SUCCESS)
+        rv = apr_procattr_cmdtype_set(pattr, APR_PROGRAM_ENV);
+
+    if (rv != APR_SUCCESS) {
+        char *error = apr_psprintf(pool, "post_rotate: could not set up process " \
+                                   "attributes for '%s': %pm\n", config->postrotate_prog,
+                                   &rv);
+        fputs(error, stderr);
+        return;
+    }
+
+    argv[0] = config->postrotate_prog;
+    argv[1] = newlog->name;
+    if (status->current.fd) {
+        argv[2] = status->current.name;
+        argv[3] = NULL;
+    }
+    else {
+        argv[2] = NULL;
+    }
+
+    if (config->verbose)
+        fprintf(stderr, "Calling post-rotate program: %s\n", argv[0]);
 
-    return;
+    rv = apr_proc_create(&proc, argv[0], argv, NULL, pattr, pool);
+    if (rv != APR_SUCCESS) {
+        char *error = apr_psprintf(pool, "Could not spawn post-rotate process " \
+                                   "'%s': %pm\n", config->postrotate_prog, &rv);
+        fputs(error, stderr);
+        return;
+    }
+}
+
+/* After a error, truncate the current file and write out an error
+ * message, which must be contained in message.  The process is
+ * terminated on failure.  */
+static void truncate_and_write_error(rotate_status_t *status, const char *message)
+{
+    apr_size_t buflen = strlen(message);
+
+    if (apr_file_trunc(status->current.fd, 0) != APR_SUCCESS) {
+        fprintf(stderr, "Error truncating the file %s\n", status->current.name);
+        exit(2);
+    }
+    if (apr_file_write_full(status->current.fd, message, buflen, NULL) != APR_SUCCESS) {
+        fprintf(stderr, "Error writing error (%s) to the file %s\n", 
+                message, status->current.name);
+        exit(2);
+    }
 }
 
 /*
@@ -263,18 +373,20 @@ static void checkRotate(rotate_config_t *config, rotate_status_t *status)
  */
 static void doRotate(rotate_config_t *config, rotate_status_t *status)
 {
-
-    int now = get_now(config);
-    int tLogStart;
+    apr_int32_t offset;
+    adjusted_time_t now, tLogStart;
     apr_status_t rv;
+    struct logfile newlog;
+    int thisLogNum = -1;
+
+    /* Retrieve local-time-adjusted-Unix-time. */
+    now = get_now(config, &offset);
 
     status->rotateReason = ROTATE_NONE;
-    status->nLogFDprev = status->nLogFD;
-    status->nLogFD = NULL;
-    status->pfile_prev = status->pfile;
 
     if (config->tRotation) {
-        int tLogEnd;
+        adjusted_time_t tLogEnd;
+
         tLogStart = (now / config->tRotation) * config->tRotation;
         tLogEnd = tLogStart + config->tRotation;
         /*
@@ -296,60 +408,96 @@ static void doRotate(rotate_config_t *config, rotate_status_t *status)
         apr_time_exp_t e;
         apr_size_t rs;
 
-        apr_time_exp_gmt(&e, tNow);
-        apr_strftime(status->filename, &rs, sizeof(status->filename), config->szLogRoot, &e);
+        /* Explode the local-time-adjusted-Unix-time into a struct tm,
+         * first *reversing* local-time-adjustment applied by
+         * get_now() if we are using localtime. */
+        if (config->use_localtime)
+            apr_time_exp_lt(&e, tNow - apr_time_from_sec(offset));
+        else
+            apr_time_exp_gmt(&e, tNow);
+        apr_strftime(newlog.name, &rs, sizeof(newlog.name), config->szLogRoot, &e);
     }
     else {
         if (config->truncate) {
-            snprintf(status->filename, sizeof(status->filename), "%s", config->szLogRoot);
+            apr_snprintf(newlog.name, sizeof(newlog.name), "%s", config->szLogRoot);
+        }
+        else if (config->num_files > 0) { 
+            if (status->fileNum == -1 || status->fileNum == (config->num_files - 1)) {
+                thisLogNum = 0;
+                apr_snprintf(newlog.name, sizeof(newlog.name), "%s", config->szLogRoot);
+            }
+            else { 
+                thisLogNum = status->fileNum + 1;
+                apr_snprintf(newlog.name, sizeof(newlog.name), "%s.%d", config->szLogRoot, thisLogNum);
+            }
         }
         else {
-            snprintf(status->filename, sizeof(status->filename), "%s.%010d", config->szLogRoot,
-                    tLogStart);
+            apr_snprintf(newlog.name, sizeof(newlog.name), "%s.%010ld", config->szLogRoot,
+                         tLogStart);
+        }
+    }
+    apr_pool_create(&newlog.pool, status->pool);
+    if (config->create_path) {
+        char *ptr = strrchr(newlog.name, '/');
+        if (ptr && ptr > newlog.name) {
+            char *path = apr_pstrmemdup(newlog.pool, newlog.name, ptr - newlog.name);
+            if (config->verbose) {
+                fprintf(stderr, "Creating directory tree %s\n", path);
+            }
+            rv = apr_dir_make_recursive(path, APR_FPROT_OS_DEFAULT, newlog.pool);
+            if (rv != APR_SUCCESS) {
+                char *error = apr_psprintf(newlog.pool,
+                                           "Could not create directory '%s' (%pm)\n",
+                                           path, &rv);
+                fputs(error, stderr);
+                exit(2);
+            }
         }
     }
-    apr_pool_create(&status->pfile, status->pool);
     if (config->verbose) {
-        fprintf(stderr, "Opening file %s\n", status->filename);
+        fprintf(stderr, "Opening file %s\n", newlog.name);
     }
-    rv = apr_file_open(&status->nLogFD, status->filename, APR_WRITE | APR_CREATE | APR_APPEND
-                       | (config->truncate ? APR_TRUNCATE : 0), APR_OS_DEFAULT, status->pfile);
-    if (rv != APR_SUCCESS) {
-        char error[120];
+    rv = apr_file_open(&newlog.fd, newlog.name, APR_WRITE | APR_CREATE | APR_APPEND
+                       | (config->truncate || (config->num_files > 0 && status->current.fd) ? APR_TRUNCATE : 0), 
+                       APR_OS_DEFAULT, newlog.pool);
+    if (rv == APR_SUCCESS) {
+        /* Handle post-rotate processing. */
+        post_rotate(newlog.pool, &newlog, config, status);
+
+        status->fileNum = thisLogNum;
+        /* Close out old (previously 'current') logfile, if any. */
+        if (status->current.fd) {
+            close_logfile(config, &status->current);
+        }
 
-        apr_strerror(rv, error, sizeof error);
+        /* New log file is now 'current'. */
+        status->current = newlog;
+    }
+    else {
+        char *error = apr_psprintf(newlog.pool, "%pm", &rv);
+        char *message;
 
         /* Uh-oh. Failed to open the new log file. Try to clear
          * the previous log file, note the lost log entries,
          * and keep on truckin'. */
-        if (status->nLogFDprev == NULL) {
-            fprintf(stderr, "Could not open log file '%s' (%s)\n", status->filename, error);
+        if (status->current.fd == NULL) {
+            fprintf(stderr, "Could not open log file '%s' (%s)\n", newlog.name, error);
             exit(2);
         }
-        else {
-            apr_size_t nWrite;
-            status->nLogFD = status->nLogFDprev;
-            apr_pool_destroy(status->pfile);
-            status->pfile = status->pfile_prev;
-            /* Try to keep this error message constant length
-             * in case it occurs several times. */
-            apr_snprintf(status->errbuf, sizeof status->errbuf,
-                         "Resetting log file due to error opening "
-                         "new log file, %10d messages lost: %-25.25s\n",
-                         status->nMessCount, error);
-            nWrite = strlen(status->errbuf);
-            apr_file_trunc(status->nLogFD, 0);
-            if (apr_file_write(status->nLogFD, status->errbuf, &nWrite) != APR_SUCCESS) {
-                fprintf(stderr, "Error writing to the file %s\n", status->filename);
-                exit(2);
-            }
-        }
-    }
-    else {
-        closeFile(config, status->pfile_prev, status->nLogFDprev);
-        status->nLogFDprev = NULL;
-        status->pfile_prev = NULL;
+
+        /* Try to keep this error message constant length
+         * in case it occurs several times. */
+        message = apr_psprintf(newlog.pool,
+                               "Resetting log file due to error opening "
+                               "new log file, %10d messages lost: %-25.25s\n",
+                               status->nMessCount, error);
+
+        truncate_and_write_error(status, message);
+
+        /* Throw away new state; it isn't going to be used. */
+        apr_pool_destroy(newlog.pool);
     }
+
     status->nMessCount = 0;
 }
 
@@ -413,47 +561,70 @@ int main (int argc, const char * const argv[])
     char buf[BUFSIZE];
     apr_size_t nRead, nWrite;
     apr_file_t *f_stdin;
+    apr_file_t *f_stdout;
     apr_getopt_t *opt;
     apr_status_t rv;
     char c;
-    const char *optarg;
+    const char *opt_arg;
     const char *err = NULL;
+#if APR_FILES_AS_SOCKETS
+    apr_pollfd_t pollfd = { 0 };
+    apr_status_t pollret = APR_SUCCESS;
+    long polltimeout;
+#endif
 
     apr_app_initialize(&argc, &argv, NULL);
     atexit(apr_terminate);
 
-    config.sRotation = 0;
-    config.tRotation = 0;
-    config.utc_offset = 0;
-    config.use_localtime = 0;
-    config.use_strftime = 0;
-    config.force_open = 0;
-    config.verbose = 0;
-    status.pool = NULL;
-    status.pfile = NULL;
-    status.pfile_prev = NULL;
-    status.nLogFD = NULL;
-    status.nLogFDprev = NULL;
-    status.tLogEnd = 0;
+    memset(&config, 0, sizeof config);
+    memset(&status, 0, sizeof status);
     status.rotateReason = ROTATE_NONE;
-    status.nMessCount = 0;
 
     apr_pool_create(&status.pool, NULL);
     apr_getopt_init(&opt, status.pool, argc, argv);
-    while ((rv = apr_getopt(opt, "lftv", &c, &optarg)) == APR_SUCCESS) {
+#if APR_FILES_AS_SOCKETS
+    while ((rv = apr_getopt(opt, "lL:p:fDtvecn:", &c, &opt_arg)) == APR_SUCCESS) {
+#else
+    while ((rv = apr_getopt(opt, "lL:p:fDtven:", &c, &opt_arg)) == APR_SUCCESS) {
+#endif
         switch (c) {
         case 'l':
             config.use_localtime = 1;
             break;
+        case 'L':
+            config.linkfile = opt_arg;
+            break;
+        case 'p':
+            config.postrotate_prog = opt_arg;
+#ifdef SIGCHLD
+            /* Prevent creation of zombies (on modern Unix systems). */
+            apr_signal(SIGCHLD, SIG_IGN);
+#endif
+            break;
         case 'f':
             config.force_open = 1;
             break;
+        case 'D':
+            config.create_path = 1;
+            break;
         case 't':
             config.truncate = 1;
             break;
         case 'v':
             config.verbose = 1;
             break;
+        case 'e':
+            config.echo = 1;
+            break;
+#if APR_FILES_AS_SOCKETS
+        case 'c':
+            config.create_empty = 1;
+            break;
+#endif
+        case 'n':
+            config.num_files = atoi(opt_arg);
+            status.fileNum = -1;
+            break;
         }
     }
 
@@ -470,7 +641,11 @@ int main (int argc, const char * const argv[])
         usage(argv[0], "Incorrect number of arguments");
     }
 
-    config.szLogRoot = argv[opt->ind++];
+    rv = apr_filepath_merge(&config.szLogRoot, "", argv[opt->ind++],
+                            APR_FILEPATH_TRUENAME, status.pool);
+    if (rv != APR_SUCCESS && rv != APR_EPATHWILD) {
+        usage(argv[0], "Invalid filename given");
+    }
 
     /* Read in the remaining flags, namely time, size and UTC offset. */
     for(; opt->ind < argc; opt->ind++) {
@@ -482,11 +657,26 @@ int main (int argc, const char * const argv[])
 
     config.use_strftime = (strchr(config.szLogRoot, '%') != NULL);
 
+    if (config.use_strftime && config.num_files > 0) { 
+        fprintf(stderr, "Cannot use -n with %% in filename\n");
+        exit(1);
+    }
+
+    if (status.fileNum == -1 && config.num_files < 1) { 
+        fprintf(stderr, "Invalid -n argument\n");
+        exit(1);
+    }
+
     if (apr_file_open_stdin(&f_stdin, status.pool) != APR_SUCCESS) {
         fprintf(stderr, "Unable to open stdin\n");
         exit(1);
     }
 
+    if (apr_file_open_stdout(&f_stdout, status.pool) != APR_SUCCESS) {
+        fprintf(stderr, "Unable to open stdout\n");
+        exit(1);
+    }
+
     /*
      * Write out result of config parsing if verbose is set.
      */
@@ -494,6 +684,15 @@ int main (int argc, const char * const argv[])
         dumpConfig(&config);
     }
 
+#if APR_FILES_AS_SOCKETS
+    if (config.create_empty && config.tRotation) {
+        pollfd.p = status.pool;
+        pollfd.desc_type = APR_POLL_FILE;
+        pollfd.reqevents = APR_POLLIN;
+        pollfd.desc.f = f_stdin;
+    }
+#endif
+
     /*
      * Immediately open the logfile as we start, if we were forced
      * to do so via '-f'.
@@ -504,53 +703,77 @@ int main (int argc, const char * const argv[])
 
     for (;;) {
         nRead = sizeof(buf);
+#if APR_FILES_AS_SOCKETS
+        if (config.create_empty && config.tRotation) {
+            polltimeout = status.tLogEnd ? status.tLogEnd - get_now(&config, NULL) : config.tRotation;
+            if (polltimeout <= 0) {
+                pollret = APR_TIMEUP;
+            }
+            else {
+                pollret = apr_poll(&pollfd, 1, &pollret, apr_time_from_sec(polltimeout));
+            }
+        }
+        if (pollret == APR_SUCCESS) {
+            rv = apr_file_read(f_stdin, buf, &nRead);
+            if (APR_STATUS_IS_EOF(rv)) {
+                break;
+            }
+            else if (rv != APR_SUCCESS) {
+                exit(3);
+            }
+        }
+        else if (pollret == APR_TIMEUP) {
+            *buf = 0;
+            nRead = 0;
+        }
+        else {
+            fprintf(stderr, "Unable to poll stdin\n");
+            exit(5);
+        }
+#else /* APR_FILES_AS_SOCKETS */
         rv = apr_file_read(f_stdin, buf, &nRead);
-        if (rv != APR_SUCCESS) {
+        if (APR_STATUS_IS_EOF(rv)) {
+            break;
+        }
+        else if (rv != APR_SUCCESS) {
             exit(3);
         }
+#endif /* APR_FILES_AS_SOCKETS */
         checkRotate(&config, &status);
         if (status.rotateReason != ROTATE_NONE) {
             doRotate(&config, &status);
         }
 
         nWrite = nRead;
-        rv = apr_file_write(status.nLogFD, buf, &nWrite);
-        if (rv == APR_SUCCESS && nWrite != nRead) {
-            /* buffer partially written, which for rotatelogs means we encountered
-             * an error such as out of space or quota or some other limit reached;
-             * try to write the rest so we get the real error code
-             */
-            apr_size_t nWritten = nWrite;
-
-            nRead  = nRead - nWritten;
-            nWrite = nRead;
-            rv = apr_file_write(status.nLogFD, buf + nWritten, &nWrite);
-        }
+        rv = apr_file_write_full(status.current.fd, buf, nWrite, &nWrite);
         if (nWrite != nRead) {
-            char strerrbuf[120];
             apr_off_t cur_offset;
+            apr_pool_t *pool;
+            char *error;
 
             cur_offset = 0;
-            if (apr_file_seek(status.nLogFD, APR_CUR, &cur_offset) != APR_SUCCESS) {
+            if (apr_file_seek(status.current.fd, APR_CUR, &cur_offset) != APR_SUCCESS) {
                 cur_offset = -1;
             }
-            apr_strerror(rv, strerrbuf, sizeof strerrbuf);
             status.nMessCount++;
-            apr_snprintf(status.errbuf, sizeof status.errbuf,
-                         "Error %d writing to log file at offset %" APR_OFF_T_FMT ". "
-                         "%10d messages lost (%s)\n",
-                         rv, cur_offset, status.nMessCount, strerrbuf);
-            nWrite = strlen(status.errbuf);
-            apr_file_trunc(status.nLogFD, 0);
-            if (apr_file_write(status.nLogFD, status.errbuf, &nWrite) != APR_SUCCESS) {
-                fprintf(stderr, "Error writing to the file %s\n", status.filename);
-                exit(2);
-            }
+            apr_pool_create(&pool, status.pool);
+            error = apr_psprintf(pool, "Error %d writing to log file at offset %"
+                                 APR_OFF_T_FMT ". %10d messages lost (%pm)\n",
+                                 rv, cur_offset, status.nMessCount, &rv);
+
+            truncate_and_write_error(&status, error);
+            apr_pool_destroy(pool);
         }
         else {
             status.nMessCount++;
         }
+        if (config.echo) {
+            if (apr_file_write_full(f_stdout, buf, nRead, NULL)) {
+                fprintf(stderr, "Unable to write to stdout\n");
+                exit(4);
+            }
+        }
     }
-    /* Of course we never, but prevent compiler warnings */
-    return 0;
+
+    return 0; /* reached only at stdin EOF. */
 }