blc_tools.cpp 13.2 KB
Newer Older
Arnaud Blanchard's avatar
Arnaud Blanchard committed
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
/* Basic Library for C/C++ (blclib)
 Copyright  ETIS — ENSEA, Université de Cergy-Pontoise, CNRS (2011 - 2014)
 
 Author: Arnaud Blanchard
 
 This software is governed by the CeCILL v2.1 license under French law and abiding by the rules of distribution of free software.
 You can use, modify and/ or redistribute the software under the terms of the CeCILL v2.1 license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info".
 As a counterpart to the access to the source code and  rights to copy, modify and redistribute granted by the license,
  users are provided only with a limited warranty and the software's author, the holder of the economic rights,  and the successive licensors have only limited liability.
  In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software,
  that may mean  that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge.
 Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured
  and, more generally, to use and operate it in the same conditions as regards security.
  The fact that you are presently reading this means that you have had knowledge of the CeCILL v2.1 license and that you accept its terms. */

//
//  Created by Arnaud Blanchard on 17/06/2014.
//
//

#include "blc_tools.h"

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>  //time val localtime
#include <arpa/inet.h> //htonl, ...
#include <sys/time.h> //gettimeofday
#include <sys/uio.h> //iovec
#include "blc_text.h"
FILE *blc_log_file = NULL;

35
char *blc_program_name=NULL;
Arnaud Blanchard's avatar
Arnaud Blanchard committed
36
37
38
39
40
41
42
43
44
45
46
47
48

size_t blc_get_type_size(uint32_t type)
{
    uint32_t type_str;
    switch (type) {
        case 'UIN8':case 'INT8':return 1;
            break;
        case 'UI16':case 'IN16': return 2;
            break;
        case 'UI32':case 'IN32':case 'FL32': return 4;
            break;
        case 'UI64':case 'IN64':case 'FL64': return 8;
            break;
49
        case 'CHAR': case 'TEXT': EXIT_ON_ERROR("The type '%.4s' is unknown. You probably mean 'INT8'", UINT32_TO_STRING(type_str, type));
Arnaud Blanchard's avatar
Arnaud Blanchard committed
50
51
52
53
54
55
56
57
58
59
60
        default:EXIT_ON_ERROR("Unknonw type '%.4s'.", UINT32_TO_STRING(type_str, type));
            break;
    }
    return 0;
}

//Envoie un message de warning avec name_of_file, name_of_function, number_of_line et affiche le message formate avec les parametres variables. To be used with PRINT_WARNING.
void print_warning(const char *name_of_file, const char* name_of_function, int numero_of_line, const char *message, ...)
{
    va_list arguments;
    va_start(arguments, message);
61
62
    color_eprintf(BLC_YELLOW, "\n%s: %s \t %s \t %i :\nWarning: ", blc_program_name, name_of_file, name_of_function, numero_of_line);
    color_veprintf(BLC_YELLOW, message, arguments);
63
    fprintf(stderr, "\n");
Arnaud Blanchard's avatar
Arnaud Blanchard committed
64
65
66
67
68
69
70
71
72
    fflush(stderr);
    va_end(arguments);
}

//Envoie un message de warning avec name_of_file, name_of_function, number_of_line et affiche le message formate avec les parametres variables. To be used with PRINT_WARNING.
void print_system_error(const char *name_of_file, const char* name_of_function, int numero_of_line, const char *message, ...)
{
    va_list arguments;
    va_start(arguments, message);
73
74
    color_eprintf(BLC_BRIGHT_RED, "\n%s: %s \t %s \t %i :\nSystem error: %s\n", blc_program_name, name_of_file, name_of_function, numero_of_line, strerror(errno));
    color_veprintf(BLC_BRIGHT_RED, message, arguments);
75
    fprintf(stderr, "\n");
Arnaud Blanchard's avatar
Arnaud Blanchard committed
76
77
78
79
80
81
82
83
84
    fflush(stderr);
    va_end(arguments);
}

// Envoie un message d'erreur avec name_of_file, name_of_function, number_of_line et affiche le message formate avec les parametres variables. Puis exit le programme avec le parametre EXIT_FAILURE. To be used with EXIT_ON_ERROR.
void fatal_error(const char *name_of_file, const char* name_of_function, int numero_of_line, const char *message, ...)
{
    va_list arguments;
    va_start(arguments, message);
85
    color_eprintf(BLC_BRIGHT_RED, "%s: %s \t %s \t %i :\nError: ", blc_program_name, name_of_file, name_of_function, numero_of_line);
86
    color_veprintf(BLC_BRIGHT_RED, message, arguments);
Arnaud Blanchard's avatar
Arnaud Blanchard committed
87
    va_end(arguments);
88
    fprintf(stderr, "\n");
Arnaud Blanchard's avatar
Arnaud Blanchard committed
89
90
91
92
93
94
95
96
97
98
    fflush(stderr);
    raise(SIGABRT);
    exit(EXIT_FAILURE);
}

//Envoie un message d'erreur avec name_of_file, name_of_function, number_of_line et affiche le message formate avec les parametres variables. Puis exit le programme avec le parametre EXIT_FAILURE. To be used with @ref EXIT_ON_SYSTEM_ERROR .
void fatal_system_error(const char *name_of_file, const char* name_of_function, int numero_of_line, const char *message, ...)
{
    va_list arguments;
    va_start(arguments, message);
99
100
101
    color_eprintf(BLC_BRIGHT_RED, "\n%s: %s \t %i:%s\n", blc_program_name, name_of_file, numero_of_line, name_of_function);
    color_eprintf(BLC_BRIGHT_RED, "System error: %s\n", strerror(errno));
    color_veprintf(BLC_BRIGHT_RED, message, arguments);
Arnaud Blanchard's avatar
Arnaud Blanchard committed
102
103
104
105
106
107
108
109
110
111
112
    va_end(arguments);
    fprintf(stderr, "\n");
    fflush(stderr);
    raise(SIGABRT);
    exit(EXIT_FAILURE);
}

void fatal_command_system_error(const char *name_of_file, const char* name_of_function, int numero_of_line, char const *command,const char *message, ...)
{
    va_list arguments;
    va_start(arguments, message);
113
    color_eprintf(BLC_BRIGHT_RED, "\n%s: %s \t %i:%s\n", blc_program_name, name_of_file, numero_of_line, name_of_function);
Arnaud Blanchard's avatar
Arnaud Blanchard committed
114
    fprintf(stderr, "Executing: %s\n", command);
115
116
    color_eprintf(BLC_BRIGHT_RED, "System error: %s\n", strerror(errno));
    color_veprintf(BLC_BRIGHT_RED, message, arguments);
Arnaud Blanchard's avatar
Arnaud Blanchard committed
117
    va_end(arguments);
118
    fprintf(stderr, "\n");
Arnaud Blanchard's avatar
Arnaud Blanchard committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    fflush(stderr);
    raise(SIGABRT);
    exit(EXIT_FAILURE);
}

// Fait un malloc de taille 'size' verifie qu'il n'a pas renvoye NULL et renvoie ce pointeur. Si le malloc a renvoye NULL alors une erreur fatal est generee avec le filename, name_of_function, et line comme parametres.
void *secure_malloc(const char *file, const char *function, int line, size_t size)
{
    void *pointer;
    
    if (size){
        pointer = malloc(size);
        if (pointer == NULL) fatal_error(file, function, line, "malloc of size %d has failed (return NULL)", size);
        else return pointer;
    }
    return NULL;
}

//Fait un realloc de taille 'size' sur le pointeur verifie qu'il n'a pas renvoye NULL et renvoie la nouvelle addresse du pointeur. Si le pointeur d'origine est NULL alors la fonction a le meme effet que secure_malloc. Si le realloc a renvoiye NULL alors une erreur fatal est generee avec le filename, name_of_function, et line comme parametres.
void secure_realloc(const char *file, const char *function, int line, void** pointer, size_t size)
{
140
141
    if (size==0) FREE(*pointer);
    else SYSTEM_ERROR_CHECK(*pointer = realloc(*pointer, size), NULL, "size: '%lu'", size);
Arnaud Blanchard's avatar
Arnaud Blanchard committed
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
}

void *append_allocation(const char *file, const char *function, int line, void** pointer, size_t pointer_content_size, int *items_nb, size_t item_size)
{
    void *new_address;
    
    if (pointer_content_size != item_size) fatal_error(file, function, line, "The size '%ld' of the content of the array must be equal to the size '%ld' of the item to contain.\nYou may mix content and pointer.", pointer_content_size, item_size);
    
    secure_realloc(file, function, line, (void**) pointer, item_size * (*items_nb + 1));
    new_address=((char*)*pointer)+(*items_nb) * item_size;
    *items_nb += 1;
    return new_address;
}

void *append_item(const char *file, const char *function, int line, void** pointer, size_t pointer_content_size, int *items_nb, size_t item_size, void* new_item)
{
    void *new_address;
    
    new_address=append_allocation(file, function, line, pointer, pointer_content_size, items_nb, item_size);
    memcpy(new_address, new_item, item_size);
    return new_address;
}

void *insert_item(const char *file, const char *function, int line, void** pointer, size_t pointer_content_size, int *items_nb, size_t item_size, void* new_item, int position)
{
    char *tmp_pointer;
    
    if (pointer_content_size != item_size) fatal_error(file, function, line, "The size '%ld' of the content of the array must be equal to the size '%ld' of the item to contain.", pointer_content_size, item_size);
    
    secure_realloc(file, function, line, (void**) pointer, item_size * (*items_nb + 1));
    tmp_pointer = (char*)*pointer;
    memmove(tmp_pointer + (position+1) * item_size, tmp_pointer+position*item_size, (*items_nb - position)*item_size);
    memcpy(tmp_pointer+position * item_size, new_item, item_size);
    *items_nb += 1;
    return tmp_pointer+position * item_size;
}

void remove_item_position(const char *file, const char *function, int line, void** pointer, size_t pointer_content_size, int *items_nb, int position)
{
    char *tmp_pointer;
    
    (*items_nb)--;
    tmp_pointer = (char*)*pointer;
    
    memcpy(tmp_pointer+pointer_content_size*position, tmp_pointer + pointer_content_size*(*items_nb), pointer_content_size);
    secure_realloc(file, function, line, (void**) pointer, pointer_content_size * (*items_nb));
}


int get_item_position(const char *file, const char *function, int line, void const *const* array, size_t pointer_content_size, int items_nb, size_t item_size, void* researched_item)
{
    int i;
    
    if (pointer_content_size != item_size) fatal_error(file, function, line, "The size '%d' of the content of array must be equal to the size of the researched item '%d'", pointer_content_size, item_size);
    
    FOR_INV(i, items_nb) if (memcmp(researched_item, &array[i], item_size) == 0) return i;
    return -1;
}

201
/* May be changed */
Arnaud Blanchard's avatar
Arnaud Blanchard committed
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
char rand_char()
{
    return rand() / (((unsigned int) (RAND_MAX) + 1) / 256);
}

/* We use an intermediate buffer line in order to avoid thread mix */
void printf_log(const char *log_name, char const *source_filename, char const *function,  int line_id, ...)
{
    const char*format;
    va_list arguments;
    struct timeval tv;
    struct tm *tm;
    time_t nowtime;
    char line[LINE_MAX]; //The buffer in order to avoid concurency problem
    char filename[FILENAME_MAX];
    size_t line_size;
    
    if (blc_log_file == NULL)
    {
        snprintf(filename, FILENAME_MAX, "/tmp/%s%d.log", log_name, getpid());
        blc_log_file = fopen(filename, "w+");
        if (blc_log_file== NULL) EXIT_ON_SYSTEM_ERROR("Creating log file %s", filename);
    }
    
    gettimeofday(&tv, NULL);
    nowtime = tv.tv_sec;
    tm = localtime(&nowtime);
    line_size = strftime(line, LINE_MAX, "[%Hh%Mm%S", tm);
    line_size+=sprintf(line+line_size, ".%.6lds %s %s:%d]", (long)tv.tv_usec,source_filename, function ,line_id);
    va_start(arguments, line_id);
    format = va_arg(arguments, const char *);
    line_size+=vsnprintf(line+line_size, LINE_MAX,  format, arguments);
    va_end(arguments);
    line[line_size]='\n';
    if (fwrite(line, line_size+1, 1, blc_log_file) != 1) EXIT_ON_SYSTEM_ERROR("Writing log: %s", line);
    if (fflush(blc_log_file) != 0) EXIT_ON_SYSTEM_ERROR("Flushing log file.");
}

void blc_close_pipe(int *pipe)
{
    SYSTEM_ERROR_CHECK(close(pipe[0]), -1, "Closing pipe 0");
    SYSTEM_ERROR_CHECK(close(pipe[1]), -1, "Closing pipe 1");
}

/*copy file to buffer
 
 SYSTEM_ERROR_CHECK(blc_channels_file = fopen("/tmp/blc_channels.list", "r"), NULL, "");
 SYSTEM_ERROR_CHECK(fseek(blc_channels_file, 0 , SEEK_END), -1, "");
 SYSTEM_ERROR_CHECK(file_size = ftell(blc_channels_file), -1, "");
 SYSTEM_ERROR_CHECK(buf = mmap(NULL, file_size, PROT_READ, MAP_PRIVATE, fileno(blc_channels_file), 0 ), MAP_FAILED, "");
 SYSTEM_SUCCESS_CHECK(fwrite(buf,  file_size, 1, stdout),1 , "");
 munmap(buf, file_size);
 fclose(blc_channels_file);
 
 */

258
259
260
261
262
263
char const *blc_get_filename_extension(char const *filename){
    char const *ext=NULL, *next_ext;
    
    
    next_ext=strchr(filename, '.');
    if (next_ext==NULL) return NULL;
264
    
265
266
267
268
269
270
271
    do{
        ext=next_ext;
        next_ext=strchr(ext+1, '.');
    }while(next_ext);
    
    return ext+1;
}
Arnaud Blanchard's avatar
Arnaud Blanchard committed
272

273
START_EXTERN_C
274
275
276
277
char* blc_uint32_to_string(uint32_t *string, uint32_t x){
    *string=htonl(x);
    return (char*)string;
}
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

void blc_add_arg( int *argc, char ***argv, char const *arg, char const *value){
    APPEND_ITEM(argv, argc, &arg);
    if (value!=NULL) APPEND_ITEM(argv, argc, &value);
}

char *blc_create_command_line_from_argv(char const *const *argv){
    int command_line_size, i;
    char *command_line, *pos;
    
    command_line_size=0;
    for(i=0; argv[i] != NULL; i++) command_line_size+=strlen(argv[i])+1; // + 1 for the space
    
    command_line=MANY_ALLOCATIONS(command_line_size+1, char);
    pos=command_line;
    for(i=0; argv[i] != NULL; i++)
        pos+=sprintf(pos, "%s ", argv[i]);
    return command_line;
}

char * const*blc_create_argv_from_command_line(char const *command_line)
{
    char * const*argv=NULL;
    char *arg_pt;
    char const *pos;
    char tmp_arg[NAME_MAX+1];
    int length, argc=0;
    
    pos=command_line;
    while(sscanf(pos, SCAN_CONV(NAME_MAX, "s")"%n", tmp_arg, &length)==1)
    {
        arg_pt = strdup(tmp_arg);
        APPEND_ITEM(&argv, &argc, &arg_pt);
        pos+=length;
    }
    arg_pt=NULL;
    APPEND_ITEM(&argv, &argc, &arg_pt);
    return argv;
316
}
317
END_EXTERN_C
Arnaud Blanchard's avatar
Arnaud Blanchard committed
318
319