-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathutils.c
More file actions
621 lines (543 loc) · 20.7 KB
/
utils.c
File metadata and controls
621 lines (543 loc) · 20.7 KB
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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/******************************************************************************
* Usage of this file and the SDK is subject to the SOFTWARE DEVELOPMENT KIT
* LICENSE included here as README-LICENSE.txt. Additiona
* lly, this C Agent
* Reference Implementation uses the OpenSSL encryption libraries, which are
* not included as a part of this distribution.
* For hardware key storage or TPM support, libraries such as WolfSSL may also
* be used in place of OpenSSL.
******************************************************************************/
/* @file utils.c */
#include "utils.h"
#include "errno.h"
#include "logging.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
/******************************************************************************/
/***************************** LOCAL DEFINES *********************************/
/******************************************************************************/
/******************************************************************************/
/************************ LOCAL GLOBAL STRUCTURES *****************************/
/******************************************************************************/
/******************************************************************************/
/************************* LOCAL GLOBAL VARIABLES *****************************/
/******************************************************************************/
/******************************************************************************/
/************************ LOCAL FUNCTION DEFINITIONS **************************/
/******************************************************************************/
/* */
/* @brief creates a blank file */
/* @param const char *file = path and filename of file to create */
/* @returns 0 if file file creation fails, 1 if file creation succeeds */
/* */
static int create_file(const char *file) {
int retval = 0;
FILE *fd;
if (!file) {
log_error("%s::%s(%d) : Null pointer dereference - file is NULL",
LOG_INF);
return 0;
}
fd = fopen(file, "w");
if (fd) {
fclose(fd);
retval = 1;
}
return retval;
} /* create_file */
static int copy_file(const char *srcPath, const char *destPath) {
int err = 0;
struct stat st;
if (stat(srcPath, &st) == 0) {
FILE *fpRead = fopen(srcPath, "r");
if (!fpRead) {
err = errno;
}
FILE *fpWrite = fopen(destPath, "w");
if (!fpWrite) {
err = errno;
}
if (fpRead && fpWrite) {
char buf[1024];
bool done = false;
while (!done) {
int rcnt = fread(buf, 1, 1024, fpRead);
if (rcnt != 1024) {
done = true;
err = ferror(fpRead);
}
if (!err) {
int wcnt = fwrite(buf, 1, rcnt, fpWrite);
if (wcnt != rcnt) {
done = true;
err = ferror(fpWrite);
}
}
}
}
if (fpRead)
fclose(fpRead);
if (fpWrite)
fclose(fpWrite);
} else {
err = errno;
}
return err;
}
/******************************************************************************/
/*********************** GLOBAL FUNCTION DEFINITIONS **************************/
/******************************************************************************/
/* */
/* checks if a file exists already */
/* @param const char *file = path and filename of file to check */
/* @returns 0 if file does not exist, is a directory, or is a sym link, */
/* 1 if it does exist */
/* */
int file_exists(const char *file) {
int retval = 0;
if (!file) {
log_error("%s::%s(%d) : Null pointer dereference - file is NULL",
LOG_INF);
return 0;
}
if (-1 != access(file, F_OK))
retval = 1;
return retval;
} /* file_exists */
char *hex_encode(unsigned char *inBuf, int len) {
if (!inBuf) {
log_error("%s::%s(%d) : Null pointer dereference - inBuf is NULL",
LOG_INF);
return NULL;
}
char *thumbBuf = malloc(2 * len + 1);
if (!thumbBuf) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
goto exit;
}
char *tempBuf = thumbBuf;
size_t i;
for (i = 0; i < (size_t)len; i++) {
tempBuf += sprintf(tempBuf, "%02x", inBuf[i]);
}
exit:
return thumbBuf;
}
/**
* @brief Appends a line of text to a dynamically allocated string.
*
* This function safely reallocates the buffer pointed to by msg
* to accommodate the new line, followed by a newline character.
* It correctly handles the case where *msg is initially NULL.
*
* @param msg A pointer to a char*. On success, *msg will be updated
* to point to the new, larger buffer. The caller is
*
* responsible for freeing this memory.
* @param line The null-terminated string to append.
* @return 0 on success, or an error code (EINVAL, ENOMEM) on failure.
* If realloc fails, *msg remains unchanged.
*/
int append_line(char **msg, const char *line) {
/* Validate input parameters */
if (!msg || !line) {
return EINVAL;
}
/* Gracefully handle the case where *msg is NULL to get the current length
*/
const size_t current_len = (*msg) ? strlen(*msg) : 0;
const size_t line_len = strlen(line);
/* Calculate the new total size required:
current string + new line + newline char '\n' + null terminator '\0' */
const size_t new_size = current_len + line_len + 2;
/* Reallocate memory. realloc behaves like malloc if *msg is NULL. */
char *new_buffer = realloc(*msg, new_size);
if (!new_buffer) {
/* On failure, realloc leaves the original block untouched. */
return ENOMEM;
}
/* Copy the new line to the end of the old content */
strcpy(new_buffer + current_len, line);
/* Append the newline character */
new_buffer[current_len + line_len] = '\n';
/* Add the new null terminator */
new_buffer[current_len + line_len + 1] = '\0';
/* Update the caller's pointer to the new buffer */
*msg = new_buffer;
return 0;
} /* append_line */
/**
* @brief Appends a formatted string, followed by a newline, to a dynamic
* buffer.
*
* This function operates like `printf` to create a formatted string and appends
* it, along with a newline character, to the buffer pointed to by `msg`. The
* buffer is automatically reallocated to the necessary size. It correctly
* handles the case where `*msg` is initially `NULL`.
*
* @param[in,out] msg A pointer to a char pointer (`char**`). On a successful
* return,
* `*msg` will point to the newly allocated buffer containing
* the appended content. The caller is responsible for freeing
* this memory using `free()`.
* @param[in] fmt The `printf`-style format string.
* @param[in] ... Variable arguments corresponding to the format string.
*
* @return 0 on success.
* @return `EINVAL` if `msg` or `fmt` is `NULL`.
* @return `EIO` if a formatting or encoding error occurs.
* @return `ENOMEM` if a memory allocation fails.
*
* @note The memory pointed to by `*msg` is managed by this function via
* `realloc`. The caller must not free the old pointer after a successful call,
* as `realloc` may have already done so. The caller is always responsible
* for freeing the final buffer.
*/
int append_linef(char **msg, const char *fmt, ...) {
if (!msg || !fmt) {
return EINVAL;
}
/* Determine the length of the string to be appended */
va_list args;
va_start(args, fmt);
int append_len = vsnprintf(NULL, 0, fmt, args);
va_end(args);
if (append_len < 0) {
return EIO; // Encoding error
}
/* Allocate temporary memory for the new line */
char *line_to_append = malloc(append_len + 1);
if (!line_to_append) {
return ENOMEM;
}
/* Create the new line string */
va_start(args, fmt);
vsnprintf(line_to_append, append_len + 1, fmt, args);
va_end(args);
/* Determine current message length (0 if msg is NULL) */
size_t current_len = (*msg) ? strlen(*msg) : 0;
/* New size = current length + appended line length + newline + null
* terminator */
size_t new_size = current_len + append_len + 2;
char *new_msg = realloc(*msg, new_size);
if (!new_msg) {
free(line_to_append); /* Clean up the temporary line */
return ENOMEM;
}
/* If the buffer was new (current_len was 0), ensure it starts as an empty
* string */
if (current_len == 0) {
new_msg[0] = '\0';
}
/* Concatenate the new parts */
strcat(new_msg, line_to_append);
strcat(new_msg, "\n");
/* Clean up and update the caller's pointer */
free(line_to_append);
*msg = new_msg;
return 0; /* Success */
} /* append_linef */
int read_file_bytes(const char *srcPath, unsigned char **pFileBytes,
size_t *fileLen) {
int err = 0;
FILE *fpRead = fopen(srcPath, "r");
if (!fpRead) {
err = errno;
} else if (fseek(fpRead, 0, SEEK_END) != 0) {
err = ferror(fpRead);
} else {
int len = ftell(fpRead);
if (len < 0) {
log_error("%s::%s(%d) : Error reading file", LOG_INF);
goto exit;
} else {
*fileLen = len;
*pFileBytes = (unsigned char *)calloc((*fileLen) + 1, 1);
if (!(*pFileBytes)) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
goto exit;
}
fseek(fpRead, 0, SEEK_SET);
int rcnt = fread(*pFileBytes, 1, *fileLen, fpRead);
if ((size_t)rcnt != *fileLen) {
err = ferror(fpRead);
free(*pFileBytes);
*fileLen = 0;
}
}
}
exit:
if (fpRead)
fclose(fpRead);
return err;
}
int write_file_bytes(const char *srcPath, char *pFileBytes, size_t len) {
int err = 0;
FILE *fpWrite = fopen(srcPath, "w");
if (!fpWrite) {
err = errno;
} else {
if (fwrite(pFileBytes, 1, len, fpWrite) == len) {
log_info("%s::%s(%d) : config file updated successfully", LOG_INF);
} else {
err = errno;
char *errStr = strerror(errno);
log_error("%s::%s(%d) : Unable to write config file %s: %s",
LOG_INF, srcPath, errStr);
}
}
if (fpWrite)
fclose(fpWrite);
return err;
}
/**
* @brief Creates a backup copy of a file by appending a tilde (~) to the
* filename.
*
* If the specified file does not exist, it is created before the backup is
* attempted. The backup file permissions are set to owner read/write only
* (S_IRUSR | S_IWUSR).
*
* @param[in] file Null-terminated path to the file to back up.
*
* @return 0 on success.
* @return ENOENT if @p file is NULL.
* @return ENOMEM if memory allocation for the backup path fails.
* @return errno value if the chmod on the backup file fails.
*/
int backup_file(const char *file) {
int err = 0;
if (file) {
if (!file_exists(file))
create_file(file);
char *backupPath = malloc(strlen(file) + 2);
if (!backupPath) {
return ENOMEM;
}
strcpy(backupPath, file);
strcat(backupPath, "~");
err = copy_file(file, backupPath);
if (!err) {
if (chmod(backupPath, (S_IRUSR | S_IWUSR)) < 0) {
err = errno;
}
}
free(backupPath);
} else {
log_info("%s::%s(%d) : No file found", LOG_INF);
err = ENOENT;
}
return err;
} /* backup_file */
int replace_file(const char *file, const char *contents, long len,
bool backup) {
int err = 0;
if (backup)
err = backup_file(file);
if (!err || err == ENOENT) {
err = 0;
// Inability to backup a file because it doesn 't exist is fine
FILE *fpWrite = fopen(file, "w");
if (!fpWrite) {
err = errno;
char *errStr = strerror(errno);
log_error("%s::%s(%d) : Unable to open store at %s for writing: %s",
LOG_INF, file, errStr);
} else {
log_verbose("%s::%s(%d) : Preparing to write %ld bytes to the "
"modified store",
LOG_INF, len);
if (fwrite(contents, 1, len, fpWrite) == (size_t)len) {
log_verbose("%s::%s(%d) : Store %s written successfully",
LOG_INF, file);
} else {
err = errno;
char *errStr = strerror(errno);
log_error("%s::%s(%d) : Unable to write store at %s: %s",
LOG_INF, file, errStr);
}
}
if (fpWrite)
fclose(fpWrite);
}
return err;
}
/* */
/* @brief strip a string from another string & return the result. */
/* NOTE: This is a CASE SENSITIVE removal. */
/* @param fromString, the full string from which we want to remove */
/* @param stripString, the string we want to strip from fromString */
/* */
char *util_strip_string(const char *fromString, const char *stripString) {
char *beforeString = NULL;
char *stripPointer = NULL;
char *afterString = NULL;
char *returnString = NULL;
size_t fromLen = 0;
size_t stripLen = 0;
size_t beforeLen = 0;
size_t afterLen = 0;
size_t stripPtrLen = 0;
if (!fromString || !stripString) {
log_error("%s::%s(%d) : Error at least one argument is null", LOG_INF);
goto exit;
}
fromLen = strlen(fromString);
stripLen = strlen(stripString);
log_trace("%s::%s(%d) : Attempting to strip %s from %s", LOG_INF,
stripString, fromString);
/* get a pointer into fromString at the staring location */
/* of the strip string */
stripPointer = strstr(fromString, stripString);
if (stripPointer) {
stripPtrLen = strlen(stripPointer);
if (fromLen > stripPtrLen) {
beforeString =
calloc((fromLen - stripPtrLen + 1), sizeof(*beforeString));
if (!beforeString) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
goto exit;
}
memcpy(beforeString, fromString, fromLen - stripPtrLen);
beforeString[fromLen - stripPtrLen] = '\0';
} else {
beforeString = strdup("");
}
if (!beforeString) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
goto exit;
}
beforeLen = strlen(beforeString);
afterString = &stripPointer[stripLen];
afterLen = strlen(afterString);
returnString = strdup(beforeString);
if (!returnString) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
goto exit;
}
returnString = realloc(returnString, (beforeLen + afterLen + 1));
if (!returnString) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
goto exit;
}
strcat(returnString, afterString);
} else {
returnString = strdup(fromString);
if (!returnString) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
goto exit;
}
log_trace("%s::%s(%d) : Didn't find %s inside %s, not modifying %s",
LOG_INF, stripString, fromString, fromString);
}
exit:
/* Clean up */
if (beforeString)
free(beforeString);
return returnString;
} /* util_strip_string */
/* */
/* Take two strings and merge them together. */
/* NOTE: This fuction allocates memory and the CALLING FUNCTION must */
/* de-allocate that memory */
/* */
/* @param [Input] : string1 the first string to add */
/* @param [Input] : string2 the second string to add */
/* @return success : string1 followed by string2 followed by \0 (or just \0) */
/* failure : NULL */
/* */
char *merge_strings(const char *string1, const char *string2) {
size_t string1_size = 0;
size_t string2_size = 0;
size_t result_size = 0;
char *resultString = NULL;
if (!string1 || !string2) {
log_error("%s::%s(%d) : Null pointer dereference - string1 or string2 "
"is NULL",
LOG_INF);
return NULL;
}
do {
string1_size = strlen(string1); /* Note: Doesn't include the \0 char */
string2_size = strlen(string2); /* Note: Doesn't include the \0 char */
result_size = string1_size + string2_size + 1;
resultString = (char *)calloc(result_size, sizeof(*resultString));
if (!resultString) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
break;
}
if (0 < string1_size) {
memcpy(resultString, string1, string1_size);
}
if (0 < string2_size) {
memcpy(&resultString[string1_size], string2, string2_size);
}
resultString[result_size - 1] = '\0';
} while (false);
return resultString;
} /* merge_strings */
/**
* Return a substring that is everything up to the last character to find
*
* NOTE: Memory is allocated by this function & must be deallocated by the
* calling function.
*
* @param - [Input] string = the null terminated string to search
* @param - [Input] find = the character to search within the string
* @return - The substring of the string parameter up to the character to find
* NULL if the character is not found
*/
char *get_prefix_substring(const char *string, const char find) {
char *subString = NULL;
if (!string) {
log_error("%s::%s(%d) : Null pointer dereference - string is NULL",
LOG_INF);
return NULL;
}
log_trace("%s::%s(%d) : Find character %c in string %s", LOG_INF, find,
string);
char *ptr = strrchr(string, find);
if (ptr) {
log_trace("%s::%s(%d) : Character found", LOG_INF);
size_t len = (size_t)(ptr - string);
subString = strdup(string);
subString =
(char *)realloc(subString, (len + 1)); /* parasoft-suppress
* BD-RES-LEAKS "Freed
* by calling function" */
if (NULL == subString) {
log_error("%s::%s(%d) : Out of memory", LOG_INF);
return NULL;
}
subString[len] = '\0';
} else {
log_trace("%s::%s(%d) : Character not found", LOG_INF);
}
return subString;
} /* get_prefix_substring */
/* */
/* @brief checks if a string is really a directory */
/* @param const char *file = path and filename of file to check */
/* @return true if file is actually a directory */
/* false if the file is actually a file */
/* */
bool is_directory(const char *file) {
if ((NULL == file) || 0 == strlen(file))
return false;
bool bResult = false;
struct stat file_stat;
file_stat.st_mode = 0;
stat(file, &file_stat);
bool is_dir = S_ISDIR(file_stat.st_mode);
// log_trace("%s::%s(%d) : %s = %d", LOG_INF, file, is_dir);
if (is_dir)
bResult = true;
return bResult;
} /* is_directory */
/******************************************************************************/
/******************************* END OF FILE **********************************/