1 /*****************************************************************************
2  * Copyright ©2017-2019 Gemalto – a Thales Company. All rights Reserved.
3  *
4  * This copy is licensed under the Apache License, Version 2.0 (the "License");
5  * You may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *     http://www.apache.org/licenses/LICENSE-2.0 or https://www.apache.org/licenses/LICENSE-2.0.html
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10  * See the License for the specific language governing permissions and limitations under the License.
11 
12  ****************************************************************************/
13 
14 /**
15  * @file
16  * $Author$
17  * $Revision$
18  * $Date$
19  *
20  * Logging facilities.
21  *
22  */
23 
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <string.h>
28 
29 #include "libse-gto-private.h"
30 
31 #ifdef ENABLE_LOGGING
32 
33 # define BUFSIZE 1024
34 
35 static const char *levels[] = {
36     "ERROR:", "WARNING:", "NOTICE:", "INFO:", "DEBUG:", "????:"
37 };
38 
39 void
vsay(struct se_gto_ctx * ctx,const char * fmt,va_list args)40 vsay(struct se_gto_ctx *ctx, const char *fmt, va_list args)
41 {
42     static int k = 0;
43     char      *buf;
44 
45     if (!ctx->log_fn)
46         return;
47 
48     if (!ctx->log_buf) {
49         ctx->log_buf = malloc(BUFSIZE);
50         if (!ctx->log_buf)
51             return;
52     }
53 
54     if (fmt[0] == 1) {
55         int n = fmt[1] - '0';
56         n = (n < 0 || n > 4) ? 5 : n;
57         if (n <= ctx->log_level) {
58             if (k == 0)
59                 strcpy(ctx->log_buf, levels[n]);
60             k += strlen(ctx->log_buf + k);
61             k += vsnprintf(ctx->log_buf + k, BUFSIZE - k, fmt + 2, args);
62         }
63     } else
64         k += vsnprintf(ctx->log_buf + k, 1024 - k, fmt, args);
65 
66     if (k >= BUFSIZE)
67         k = BUFSIZE - 1;
68     buf    = ctx->log_buf;
69     buf[k] = '\000';
70     if ((buf[k - 1] == '\n') || (k == (BUFSIZE - 1))) {
71         k = 0;
72         ctx->log_fn(ctx, buf);
73     }
74 }
75 
76 #endif /* ifdef ENABLE_LOGGING */
77 
78 void
log_teardown(struct se_gto_ctx * ctx)79 log_teardown(struct se_gto_ctx *ctx)
80 {
81     if (ctx->log_buf) {
82         free(ctx->log_buf);
83         ctx->log_buf = NULL;
84     }
85 }
86