summaryrefslogtreecommitdiff
path: root/open-vm-tools/vgauth/service/fileLogger.c
blob: bcbc49f4045c876b2286783d700386aff145f710 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/*********************************************************
 * Copyright (C) 2011-2015 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

/**
 * @file fileLogger.c
 *
 * Logger that uses file streams and provides optional log rotation.
 * Heavily 'borrows' from bora-lib/apps/vmtoolslib/fileLogger.c
 */

#include <stdio.h>
#include <string.h>
#include <glib/gstdio.h>
#ifdef _WIN32
#  include <process.h>
#  include <windows.h>
#  include <io.h>
#else
#  include <unistd.h>
#endif
#include "service.h"

typedef struct FileLoggerData {
   FILE             *file;
   gchar            *path;
   gint              logSize;
   gint64            maxSize;
   guint             maxFiles;
   gboolean          append;
   gboolean          error;
   GStaticRWLock     lock;
} FileLoggerData;


/*
 ******************************************************************************
 * ServiceFileLoggerOpen --                                              */ /**
 *
 * Opens a log file for writing, backing up the existing log file if one is
 * present. Only one old log file is preserved.
 *
 * @note Make sure this function is called with the write lock held.
 *
 * @param[in] data   Log handler data.
 *
 * @return Log file pointer (NULL on error).
 *
 ******************************************************************************
 */

static FILE *
ServiceFileLoggerOpen(FileLoggerData *data)
{
   FILE *logfile = NULL;
   gchar *path;

   ASSERT(data != NULL);
   path = g_strdup_printf("%s.%d", data->path, 0);

   if (g_file_test(path, G_FILE_TEST_EXISTS)) {
      struct stat fstats;

      if (g_stat(path, &fstats) > -1) {
         g_atomic_int_set(&data->logSize, (gint) fstats.st_size);
      }

      if (!data->append || g_atomic_int_get(&data->logSize) >= data->maxSize) {
         /*
          * Find the last log file and iterate back, changing the indices as we go,
          * so that the oldest log file has the highest index (the new log file
          * will always be index "0"). When not rotating, "maxFiles" is 1, so we
          * always keep one backup.
          */
         gchar *fname;
         guint id;
         GPtrArray *logfiles = g_ptr_array_new();

         /*
          * Find the id of the last log file. The pointer array will hold
          * the names of all existing log files + the name of the last log
          * file, which may or may not exist.
          */
         for (id = 0; id < data->maxFiles; id++) {
            fname = g_strdup_printf("%s.%d", data->path, id);
            g_ptr_array_add(logfiles, fname);
            if (!g_file_test(fname, G_FILE_TEST_IS_REGULAR)) {
               break;
            }
         }

         /* Rename the existing log files, increasing their index by 1. */
         for (id = logfiles->len - 1; id > 0; id--) {
            gchar *dest = g_ptr_array_index(logfiles, id);
            gchar *src = g_ptr_array_index(logfiles, id - 1);

            if (!g_file_test(dest, G_FILE_TEST_IS_DIR) &&
                (!g_file_test(dest, G_FILE_TEST_EXISTS) ||
                 g_unlink(dest) == 0)) {
               g_rename(src, dest);
            } else {
               g_unlink(src);
            }
         }

         /* Cleanup. */
         for (id = 0; id < logfiles->len; id++) {
            g_free(g_ptr_array_index(logfiles, id));
         }
         g_ptr_array_free(logfiles, TRUE);
         g_atomic_int_set(&data->logSize, 0);
         data->append = FALSE;
      }
   }

   logfile = g_fopen(path, data->append ? "a" : "w");
   g_free(path);

#ifndef VMX86_DEBUG
   /*
    * Redirect anything unexpected that uses stderr.
    */
   if (NULL != logfile) {
      if (dup2(fileno(logfile), 2) == -1) {
         fprintf(logfile, "%s: failed to dup stderr to logfile\n", __FUNCTION__);
      }
   }
#endif

   return logfile;
}


/*
 ******************************************************************************
 * ServiceFileLogger_Log --                                              */ /**
 *
 * Logs a message to the configured destination file. Also opens the file for
 * writing if it hasn't been done yet.
 *
 * @param[in] domain    Log domain.
 * @param[in] level     Log level.
 * @param[in] message   Message to log.
 * @param[in] _data     FileLoggerData pointer.
 *
 * @return Whether the message was successfully written.
 *
 ******************************************************************************
 */

gboolean
ServiceFileLogger_Log(const gchar *domain,
                      GLogLevelFlags level,
                      const gchar *message,
                      void *_data)
{
   gboolean ret = FALSE;
   FileLoggerData *data = (FileLoggerData *) _data;

   g_static_rw_lock_reader_lock(&data->lock);

   if (data->error) {
      goto exit;
   }

   if (data->file == NULL) {
      if (data->path == NULL) {
         /* We should only get in this situation if the domain's log level is "none". */
         ret = TRUE;
         goto exit;
      } else {
         /*
          * We need to drop the read lock and acquire a write lock to open
          * the log file.
          */
         g_static_rw_lock_reader_unlock(&data->lock);
         g_static_rw_lock_writer_lock(&data->lock);
         if (data->file == NULL) {
            data->file = ServiceFileLoggerOpen(data);
         }
         g_static_rw_lock_writer_unlock(&data->lock);
         g_static_rw_lock_reader_lock(&data->lock);
         if (data->file == NULL) {
            data->error = TRUE;
            fprintf(stderr, "Unable to open log file %s\n", data->path);
            goto exit;
         }
      }
   }

   /* Write the log file and do log rotation accounting. */
   if (fputs(message, data->file) >= 0) {
      if (data->maxSize > 0) {
         g_atomic_int_add(&data->logSize, (int) strlen(message));
#if defined(_WIN32)
         /* Account for \r. */
         g_atomic_int_add(&data->logSize, 1);
#endif
         if (g_atomic_int_get(&data->logSize) >= data->maxSize) {
            /* Drop the reader lock, grab the writer lock and re-check. */
            g_static_rw_lock_reader_unlock(&data->lock);
            g_static_rw_lock_writer_lock(&data->lock);
            if (g_atomic_int_get(&data->logSize) >= data->maxSize) {
               fclose(data->file);
               data->append = FALSE;
               data->file = ServiceFileLoggerOpen(data);
            }
            g_static_rw_lock_writer_unlock(&data->lock);
            g_static_rw_lock_reader_lock(&data->lock);
         } else {
            fflush(data->file);
         }
      } else {
         fflush(data->file);
      }
      ret = TRUE;
   }

exit:
   g_static_rw_lock_reader_unlock(&data->lock);
   return ret;
}


/*
 ******************************************************************************
 * ServiceFileLogger_Init --                                             */ /**
 *
 * Initializes the file logger.
 *
 * @return The file logger data, or NULL on failure.
 *
 ******************************************************************************
 */

void *
ServiceFileLogger_Init(void)
{
   gchar *logFileName;
   FileLoggerData *data;
   gchar *defaultFilename;

#ifdef _WIN32
   {
      WCHAR pathW[MAX_PATH];

      if (GetTempPathW(MAX_PATH, pathW) != 0) {
         char *pathA = Convert_Utf16ToUtf8(__FUNCTION__,
                                           __FILE__, __LINE__,
                                           pathW);
         if (NULL == pathA) {
            Warning("%s: out of memory converting filePath\n", __FUNCTION__);
            return NULL;
         }
         defaultFilename = g_strdup_printf("%s%s", pathA, LOGFILENAME_DEFAULT);
         g_free(pathA);
      } else {
         defaultFilename = g_strdup(LOGFILENAME_PATH_DEFAULT);
      }
   }
#else
   defaultFilename = g_strdup(LOGFILENAME_PATH_DEFAULT);
#endif

   logFileName = Pref_GetString(gPrefs,
                                VGAUTH_PREF_NAME_LOGFILE,
                                VGAUTH_PREF_GROUP_NAME_SERVICE,
                                defaultFilename);

   Debug("%s: Using '%s' as logfile\n", __FUNCTION__, logFileName);

   g_free(defaultFilename);
   data = g_malloc0(sizeof(FileLoggerData));

   /*
    * XXX
    *
    * Not sure we want this -- it means we'll append to any existing
    * file, which preserves some data, but it may also cause confusion
    * when the service start isn't at the top of the file.
    */
   data->append = TRUE;

   g_static_rw_lock_init(&data->lock);

   if (logFileName != NULL) {
      data->path = g_filename_from_utf8(logFileName, -1, NULL, NULL, NULL);
      ASSERT(data->path != NULL);
      g_free(logFileName);

      /*
       * Read the rolling file configuration. By default, log rotation is enabled
       * with a max file size of 10MB and a maximum of 10 log files kept around.
       */
      data->maxFiles = Pref_GetInt(gPrefs,
                                   VGAUTH_PREF_NAME_MAX_OLD_LOGFILES,
                                   VGAUTH_PREF_GROUP_NAME_SERVICE, 10);
      if (data->maxFiles < 1) {
         data->maxFiles = 1;
      }

      /* Add 1 to account for the active log file. */
      data->maxFiles += 1;

      data->maxSize = Pref_GetInt(gPrefs,
                                  VGAUTH_PREF_NAME_MAX_LOGSIZE,
                                  VGAUTH_PREF_GROUP_NAME_SERVICE, 10);
      data->maxSize = data->maxSize * 1024 * 1024;
   }

   return data;
}