2 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "stc-iptables-log.h"
27 #define LOG_FILE_PATH "/opt/usr/data/network/stc-iptables.log"
28 #define MAX_LOG_SIZE 1 * 1024 * 1024
29 #define MAX_LOG_COUNT 1
31 static FILE *log_file = NULL;
33 static void __stc_iptables_log_update_file_revision(int rev)
36 char *log_file = NULL;
37 char *next_log_file = NULL;
39 next_log_rev = rev + 1;
41 log_file = g_strdup_printf("%s.%d", LOG_FILE_PATH, rev);
42 next_log_file = g_strdup_printf("%s.%d", LOG_FILE_PATH, next_log_rev);
44 if (next_log_rev >= MAX_LOG_COUNT)
45 remove(next_log_file);
47 if (access(next_log_file, F_OK) == 0)
48 __stc_iptables_log_update_file_revision(next_log_rev);
50 if (rename(log_file, next_log_file) != 0)
54 g_free(next_log_file);
57 static void __stc_iptables_log_make_backup(void)
62 backup = g_strdup_printf("%s.%d", LOG_FILE_PATH, rev);
64 if (access(backup, F_OK) == 0)
65 __stc_iptables_log_update_file_revision(rev);
67 if (rename(LOG_FILE_PATH, backup) != 0)
68 remove(LOG_FILE_PATH);
73 static void __stc_iptables_log_get_local_time(char *strtime, const int size)
77 struct tm result = {0, };
81 local_ptm = localtime_r(&buf, &result);
84 strftime(strtime, size, "%m/%d %H:%M:%S", local_ptm);
87 void stc_iptables_log(const char *format, ...)
96 log_file = (FILE *)fopen(LOG_FILE_PATH, "a+");
101 va_start(ap, format);
103 if (fstat(fileno(log_file), &buf) == 0)
104 log_size = buf.st_size;
106 if (log_size >= MAX_LOG_SIZE) {
110 __stc_iptables_log_make_backup();
112 log_file = (FILE *)fopen(LOG_FILE_PATH, "a+");
114 if (log_file == NULL) {
120 __stc_iptables_log_get_local_time(strtime, sizeof(strtime));
122 if (vsnprintf(str, sizeof(str), format, ap) > 0)
123 fprintf(log_file, "%s %s", strtime, str);
128 gboolean stc_iptables_log_sync(gpointer data)
132 fsync(log_file->_fileno);
138 void stc_iptables_log_cleanup(void)
140 if (log_file == NULL)