summaryrefslogtreecommitdiffstats
path: root/src/log.c
blob: 990dcaffd6db4f9ae99e31e204bdf4843703309c (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
/*
 * log.c
 *
 * Copyright (c) 2024 Nikias Bassen. All Rights Reserved.
 *
 * This library 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; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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 GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#include <errno.h>

#include <libimobiledevice-glue/thread.h>
#include <plist/plist.h>

#include "log.h"

static int stderr_enabled = 1;

enum loglevel log_level = LL_VERBOSE;
enum loglevel print_level = LL_INFO;

static logger_print_func print_func = NULL;

const char *_level_label[6] = {
	"  <Error>",
	"<Warning>",
	" <Notice>",
	"   <Info>",
	"<Verbose>",
	"  <Debug>"	
};

// Reference: https://stackoverflow.com/a/2390626/1806760
// Initializer/finalizer sample for MSVC and GCC/Clang.
// 2010-2016 Joe Lowe. Released into the public domain.

#ifdef __cplusplus
    #define INITIALIZER(f) \
        static void f(void); \
        struct f##_t_ { f##_t_(void) { f(); } }; static f##_t_ f##_; \
        static void f(void)
#elif defined(_MSC_VER)
    #pragma section(".CRT$XCU",read)
    #define INITIALIZER2_(f,p) \
        static void f(void); \
        __declspec(allocate(".CRT$XCU")) void (*f##_)(void) = f; \
        __pragma(comment(linker,"/include:" p #f "_")) \
        static void f(void)
    #ifdef _WIN64
        #define INITIALIZER(f) INITIALIZER2_(f,"")
    #else
        #define INITIALIZER(f) INITIALIZER2_(f,"_")
    #endif
#else
    #define INITIALIZER(f) \
        static void f(void) __attribute__((__constructor__)); \
        static void f(void)
#endif

static mutex_t log_mutex;

static void logger_deinit(void)
{
	mutex_destroy(&log_mutex);
}

INITIALIZER(logger_init)
{
	mutex_init(&log_mutex);
	atexit(logger_deinit);
}

void logger(enum loglevel level, const char *fmt, ...)
{
	va_list ap;
	va_list ap2;
	char *fs;

	if (level > log_level)
		return;

	mutex_lock(&log_mutex);

	size_t fslen = 24 + strlen(fmt);
	fs = malloc(fslen);

#ifdef _WIN32
	SYSTEMTIME lt;
	GetLocalTime(&lt);
	snprintf(fs, 24, "%02d:%02d:%02d.%03d", lt.wHour, lt.wMinute, lt.wSecond, lt.wMilliseconds);
#else
	struct timeval ts;
	struct tm *tp;

	gettimeofday(&ts, NULL);
#ifdef HAVE_LOCALTIME_R
	struct tm tp_;
	tp = localtime_r(&ts.tv_sec, &tp_);
#else
	tp = localtime(&ts.tv_sec);
#endif

	strftime(fs, 9, "%H:%M:%S", tp);
	snprintf(fs+8, fslen-8, ".%03d %s %s", (int)(ts.tv_usec / 1000), _level_label[level], fmt);
#endif

	va_start(ap, fmt);
	va_copy(ap2, ap);
	if (print_func) {
		if (stderr_enabled) {
			vfprintf(stderr, fs, ap);
			fflush(stderr);
		}
		if (level <= print_level) {
			// skip the timestamp and log level string
			print_func(level, fs+23, ap2);
		}
	} else {
		vprintf(fs, ap);
	}

	va_end(ap);
	va_end(ap2);

	free(fs);

	mutex_unlock(&log_mutex);
}

#if defined(__GNUC__) || defined(__clang__)
static void print_funcf(enum loglevel level, const char* fmt, ...) __attribute__ ((format (printf, 2, 3)));
#else
static void print_funcf(enum loglevel level, const char* fmt, ...);
#endif

static void print_funcf(enum loglevel level, const char* fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	print_func(level, fmt, ap);
	va_end(ap);
}

void logger_dump_hex(enum loglevel level, const void* buf, size_t len)
{
	char *fs;

	if (level > log_level)
		return;

	mutex_lock(&log_mutex);

	fs = (char*)malloc(len * 3 + 1);
	for (unsigned int i = 0; i < len; i++) {
		snprintf(fs + i*3, 4, "%02x%c", ((unsigned char*)buf)[i], (i < len-1) ? ' ' : '\n');
	}
	if (print_func) {
		if (stderr_enabled) {
			fprintf(stderr, "%s", fs);
			fflush(stderr);
		}
		if (level <= print_level) {
			print_funcf(level, "%s", fs);
		}
	} else {
		printf("%s", fs);
	}
	free(fs);
	
	mutex_unlock(&log_mutex);
}

void logger_dump_plist(enum loglevel level, plist_t plist, int human_readable)
{
	if (level > log_level)
		return;
	mutex_lock(&log_mutex);
	plist_write_to_stream(plist, stderr_enabled ? stderr : stdout, (human_readable) ? PLIST_FORMAT_PRINT : PLIST_FORMAT_XML, PLIST_OPT_NONE);
	mutex_unlock(&log_mutex);
}

int logger_set_logfile(const char* path)
{
	if (!path || !strcasecmp(path, "NULL") || !strcasecmp(path, "NONE")) {
		stderr_enabled = 0;
		return 0;
	}
	stderr_enabled = 1;
	if (strcmp(path, "-")) {
		FILE* newf = freopen(path, "w", stderr);
		if (!newf) {
			logger(LL_ERROR, "Could not open logfile '%s': %s\n", path, strerror(errno));
			return -1;
		}
	}
	return 0;
}

void logger_set_print_func(logger_print_func func)
{
	print_func = func;
}