Coverage Report

Created: 2023-09-25 06:56

/src/FreeRDP/winpr/libwinpr/utils/wlog/Layout.c
Line
Count
Source (jump to first uncovered line)
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * WinPR Logger
4
 *
5
 * Copyright 2013 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
20
#include <winpr/config.h>
21
22
#include <stdio.h>
23
#include <string.h>
24
#include <stdarg.h>
25
26
#include <winpr/crt.h>
27
#include <winpr/assert.h>
28
#include <winpr/print.h>
29
#include <winpr/sysinfo.h>
30
#include <winpr/environment.h>
31
32
#include "wlog.h"
33
34
#include "Layout.h"
35
36
#if defined __linux__ && !defined ANDROID
37
#include <unistd.h>
38
#include <sys/syscall.h>
39
#endif
40
41
#ifndef MIN
42
0
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
43
#endif
44
45
struct format_option_recurse;
46
47
struct format_option
48
{
49
  const char* fmt;
50
  size_t fmtlen;
51
  const char* replace;
52
  size_t replacelen;
53
  const char* (*fkt)(void*);
54
  void* arg;
55
  const char* (*ext)(const struct format_option* opt, const char* str, size_t* preplacelen,
56
                     size_t* pskiplen);
57
  struct format_option_recurse* recurse;
58
};
59
60
struct format_option_recurse
61
{
62
  struct format_option* options;
63
  size_t nroptions;
64
  wLog* log;
65
  wLogLayout* layout;
66
  wLogMessage* message;
67
  char buffer[WLOG_MAX_PREFIX_SIZE];
68
};
69
70
/**
71
 * Log Layout
72
 */
73
74
static void WLog_PrintMessagePrefixVA(wLog* log, wLogMessage* message, const char* format,
75
                                      va_list args)
76
0
{
77
0
  WINPR_ASSERT(message);
78
0
  vsnprintf(message->PrefixString, WLOG_MAX_PREFIX_SIZE - 1, format, args);
79
0
}
80
81
static void WLog_PrintMessagePrefix(wLog* log, wLogMessage* message, const char* format, ...)
82
0
{
83
0
  va_list args;
84
0
  va_start(args, format);
85
0
  WLog_PrintMessagePrefixVA(log, message, format, args);
86
0
  va_end(args);
87
0
}
88
89
static const char* get_tid(void* arg)
90
0
{
91
0
  char* str = arg;
92
0
  size_t tid;
93
0
#if defined __linux__ && !defined ANDROID
94
  /* On Linux we prefer to see the LWP id */
95
0
  tid = (size_t)syscall(SYS_gettid);
96
#else
97
  tid = (size_t)GetCurrentThreadId();
98
#endif
99
0
  sprintf(str, "%08" PRIxz, tid);
100
0
  return str;
101
0
}
102
103
static BOOL log_invalid_fmt(const char* what)
104
0
{
105
0
  fprintf(stderr, "Invalid format string '%s'\n", what);
106
0
  return FALSE;
107
0
}
108
109
static BOOL check_and_log_format_size(char* format, size_t size, size_t index, size_t add)
110
0
{
111
  /* format string must be '\0' terminated, so abort at size - 1 */
112
0
  if (index + add + 1 >= size)
113
0
  {
114
0
    fprintf(stderr,
115
0
            "Format string too long ['%s', max %" PRIuz ", used %" PRIuz ", adding %" PRIuz
116
0
            "]\n",
117
0
            format, size, index, add);
118
0
    return FALSE;
119
0
  }
120
0
  return TRUE;
121
0
}
122
123
static int opt_compare_fn(const void* a, const void* b)
124
0
{
125
0
  const char* what = a;
126
0
  const struct format_option* opt = b;
127
0
  if (!opt)
128
0
    return -1;
129
0
  return strncmp(what, opt->fmt, opt->fmtlen);
130
0
}
131
132
static BOOL has_format_arg(const char* str, size_t len)
133
0
{
134
0
  if (!str || (len == 0))
135
0
    return FALSE;
136
0
137
0
  for (size_t x = 0; x < len; x++)
138
0
  {
139
0
    char c = str[x];
140
0
    if (c == '%')
141
0
      return TRUE;
142
0
  }
143
0
144
0
  return FALSE;
145
0
}
146
147
static BOOL replace_format_string(const char* FormatString, struct format_option_recurse* recurse,
148
                                  char* format, size_t formatlen);
149
150
static const char* skip_if_null(const struct format_option* opt, const char* fmt,
151
                                size_t* preplacelen, size_t* pskiplen)
152
0
{
153
0
  WINPR_ASSERT(opt);
154
0
  WINPR_ASSERT(fmt);
155
0
  WINPR_ASSERT(preplacelen);
156
0
  WINPR_ASSERT(pskiplen);
157
158
0
  *preplacelen = 0;
159
0
  *pskiplen = 0;
160
161
0
  const char* str = &fmt[opt->fmtlen]; /* Skip first %{ from string */
162
0
  const char* end = strstr(str, opt->replace);
163
0
  if (!end)
164
0
    return NULL;
165
0
  *pskiplen = end - fmt + opt->replacelen;
166
167
0
  if (!opt->arg)
168
0
    return NULL;
169
170
0
  const size_t replacelen = end - str;
171
172
0
  char buffer[WLOG_MAX_PREFIX_SIZE] = { 0 };
173
0
  memcpy(buffer, str, MIN(replacelen, ARRAYSIZE(buffer) - 1));
174
175
0
  if (!replace_format_string(buffer, opt->recurse, opt->recurse->buffer,
176
0
                             ARRAYSIZE(opt->recurse->buffer)))
177
0
    return NULL;
178
179
0
  *preplacelen = strnlen(opt->recurse->buffer, ARRAYSIZE(opt->recurse->buffer));
180
0
  return opt->recurse->buffer;
181
0
}
182
183
static BOOL replace_format_string(const char* FormatString, struct format_option_recurse* recurse,
184
                                  char* format, size_t formatlen)
185
0
{
186
0
  WINPR_ASSERT(FormatString);
187
0
  WINPR_ASSERT(recurse);
188
189
0
  size_t index = 0;
190
191
0
  while (*FormatString)
192
0
  {
193
0
    const struct format_option* opt =
194
0
        bsearch(FormatString, recurse->options, recurse->nroptions,
195
0
                sizeof(struct format_option), opt_compare_fn);
196
0
    if (opt)
197
0
    {
198
0
      size_t replacelen = opt->replacelen;
199
0
      size_t fmtlen = opt->fmtlen;
200
0
      const char* replace = opt->replace;
201
0
      const void* arg = opt->arg;
202
203
0
      if (opt->ext)
204
0
        replace = opt->ext(opt, FormatString, &replacelen, &fmtlen);
205
0
      if (opt->fkt)
206
0
        arg = opt->fkt(opt->arg);
207
208
0
      if (replace && (replacelen > 0))
209
0
      {
210
0
        const int rc = _snprintf(&format[index], formatlen - index, replace, arg);
211
0
        if (rc < 0)
212
0
          return FALSE;
213
0
        if (!check_and_log_format_size(format, formatlen, index, rc))
214
0
          return FALSE;
215
0
        index += rc;
216
0
      }
217
0
      FormatString += fmtlen;
218
0
    }
219
0
    else
220
0
    {
221
      /* Unknown format string */
222
0
      if (*FormatString == '%')
223
0
        return log_invalid_fmt(FormatString);
224
225
0
      if (!check_and_log_format_size(format, formatlen, index, 1))
226
0
        return FALSE;
227
0
      format[index++] = *FormatString++;
228
0
    }
229
0
  }
230
231
0
  if (!check_and_log_format_size(format, formatlen, index, 0))
232
0
    return FALSE;
233
0
  return TRUE;
234
0
}
235
236
BOOL WLog_Layout_GetMessagePrefix(wLog* log, wLogLayout* layout, wLogMessage* message)
237
0
{
238
0
  char format[WLOG_MAX_PREFIX_SIZE] = { 0 };
239
240
0
  WINPR_ASSERT(layout);
241
0
  WINPR_ASSERT(message);
242
243
0
  char tid[32] = { 0 };
244
0
  SYSTEMTIME localTime = { 0 };
245
0
  GetLocalTime(&localTime);
246
247
0
  struct format_option_recurse recurse = {
248
0
    .options = NULL, .nroptions = 0, .log = log, .layout = layout, .message = message
249
0
  };
250
251
0
#define ENTRY(x) x, sizeof(x) - 1
252
0
  struct format_option options[] = {
253
0
    { ENTRY("%ctx"), ENTRY("%s"), log->custom, log->context, NULL, &recurse }, /* log context */
254
0
    { ENTRY("%dw"), ENTRY("%u"), NULL, (void*)(size_t)localTime.wDayOfWeek, NULL,
255
0
      &recurse }, /* day of week */
256
0
    { ENTRY("%dy"), ENTRY("%u"), NULL, (void*)(size_t)localTime.wDay, NULL,
257
0
      &recurse }, /* day of year */
258
0
    { ENTRY("%fl"), ENTRY("%s"), NULL, (void*)message->FileName, NULL, &recurse }, /* file */
259
0
    { ENTRY("%fn"), ENTRY("%s"), NULL, (void*)message->FunctionName, NULL,
260
0
      &recurse }, /* function */
261
0
    { ENTRY("%hr"), ENTRY("%02u"), NULL, (void*)(size_t)localTime.wHour, NULL,
262
0
      &recurse }, /* hours */
263
0
    { ENTRY("%ln"), ENTRY("%" PRIuz), NULL, (void*)(size_t)message->LineNumber, NULL,
264
0
      &recurse }, /* line number */
265
0
    { ENTRY("%lv"), ENTRY("%s"), NULL, (void*)WLOG_LEVELS[message->Level], NULL,
266
0
      &recurse }, /* log level */
267
0
    { ENTRY("%mi"), ENTRY("%02u"), NULL, (void*)(size_t)localTime.wMinute, NULL,
268
0
      &recurse }, /* minutes */
269
0
    { ENTRY("%ml"), ENTRY("%02u"), NULL, (void*)(size_t)localTime.wMilliseconds, NULL,
270
0
      &recurse },                                                   /* milliseconds */
271
0
    { ENTRY("%mn"), ENTRY("%s"), NULL, log->Name, NULL, &recurse }, /* module name */
272
0
    { ENTRY("%mo"), ENTRY("%u"), NULL, (void*)(size_t)localTime.wMonth, NULL,
273
0
      &recurse }, /* month */
274
0
    { ENTRY("%pid"), ENTRY("%u"), NULL, (void*)(size_t)GetCurrentProcessId(), NULL,
275
0
      &recurse }, /* process id */
276
0
    { ENTRY("%se"), ENTRY("%02u"), NULL, (void*)(size_t)localTime.wSecond, NULL,
277
0
      &recurse },                                                 /* seconds */
278
0
    { ENTRY("%tid"), ENTRY("%s"), get_tid, tid, NULL, &recurse }, /* thread id */
279
0
    { ENTRY("%yr"), ENTRY("%u"), NULL, (void*)(size_t)localTime.wYear, NULL,
280
0
      &recurse }, /* year */
281
0
    { ENTRY("%{"), ENTRY("%}"), NULL, log->context, skip_if_null,
282
0
      &recurse }, /* skip if no context */
283
0
  };
284
285
0
  recurse.options = options;
286
0
  recurse.nroptions = ARRAYSIZE(options);
287
288
0
  if (!replace_format_string(layout->FormatString, &recurse, format, ARRAYSIZE(format)))
289
0
    return FALSE;
290
0
  WLog_PrintMessagePrefix(log, message, format);
291
292
0
  return TRUE;
293
0
}
294
295
wLogLayout* WLog_GetLogLayout(wLog* log)
296
0
{
297
0
  wLogAppender* appender;
298
0
  appender = WLog_GetLogAppender(log);
299
0
  return appender->Layout;
300
0
}
301
302
BOOL WLog_Layout_SetPrefixFormat(wLog* log, wLogLayout* layout, const char* format)
303
0
{
304
0
  free(layout->FormatString);
305
0
  layout->FormatString = NULL;
306
307
0
  if (format)
308
0
  {
309
0
    layout->FormatString = _strdup(format);
310
311
0
    if (!layout->FormatString)
312
0
      return FALSE;
313
0
  }
314
315
0
  return TRUE;
316
0
}
317
318
wLogLayout* WLog_Layout_New(wLog* log)
319
0
{
320
0
  LPCSTR prefix = "WLOG_PREFIX";
321
0
  DWORD nSize;
322
0
  char* env = NULL;
323
0
  wLogLayout* layout;
324
0
  layout = (wLogLayout*)calloc(1, sizeof(wLogLayout));
325
326
0
  if (!layout)
327
0
    return NULL;
328
329
0
  nSize = GetEnvironmentVariableA(prefix, NULL, 0);
330
331
0
  if (nSize)
332
0
  {
333
0
    env = (LPSTR)malloc(nSize);
334
335
0
    if (!env)
336
0
    {
337
0
      free(layout);
338
0
      return NULL;
339
0
    }
340
341
0
    if (GetEnvironmentVariableA(prefix, env, nSize) != nSize - 1)
342
0
    {
343
0
      free(env);
344
0
      free(layout);
345
0
      return NULL;
346
0
    }
347
0
  }
348
349
0
  if (env)
350
0
    layout->FormatString = env;
351
0
  else
352
0
  {
353
#ifdef ANDROID
354
    layout->FormatString = _strdup("[pid=%pid:tid=%tid] - [%fn]%{[%ctx]%}: ");
355
#else
356
0
    layout->FormatString =
357
0
        _strdup("[%hr:%mi:%se:%ml] [%pid:%tid] [%lv][%mn] - [%fn]%{[%ctx]%}: ");
358
0
#endif
359
360
0
    if (!layout->FormatString)
361
0
    {
362
0
      free(layout);
363
0
      return NULL;
364
0
    }
365
0
  }
366
367
0
  return layout;
368
0
}
369
370
void WLog_Layout_Free(wLog* log, wLogLayout* layout)
371
0
{
372
0
  if (layout)
373
0
  {
374
0
    if (layout->FormatString)
375
0
    {
376
0
      free(layout->FormatString);
377
0
      layout->FormatString = NULL;
378
0
    }
379
380
0
    free(layout);
381
0
  }
382
0
}