-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathutility.c
More file actions
559 lines (500 loc) · 16.3 KB
/
utility.c
File metadata and controls
559 lines (500 loc) · 16.3 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
/* Shifter, Copyright (c) 2015, The Regents of the University of California,
## through Lawrence Berkeley National Laboratory (subject to receipt of any
## required approvals from the U.S. Dept. of Energy). All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are met:
## 1. Redistributions of source code must retain the above copyright notice,
## this list of conditions and the following disclaimer.
## 2. Redistributions in binary form must reproduce the above copyright notice,
## this list of conditions and the following disclaimer in the documentation
## and/or other materials provided with the distribution.
## 3. Neither the name of the University of California, Lawrence Berkeley
## National Laboratory, U.S. Dept. of Energy nor the names of its
## contributors may be used to endorse or promote products derived from this
## software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
## POSSIBILITY OF SUCH DAMAGE.
##
## You are under no obligation whatsoever to provide any bug fixes, patches, or
## upgrades to the features, functionality or performance of the source code
## ("Enhancements") to anyone; however, if you choose to make your Enhancements
## available either publicly, or directly to Lawrence Berkeley National
## Laboratory, without imposing a separate written license agreement for such
## Enhancements, then you hereby grant the following license: a non-exclusive,
## royalty-free perpetual license to install, use, modify, prepare derivative
## works, incorporate into other computer software, distribute, and sublicense
## such enhancements or derivative works thereof, in binary and source code
## form.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdint.h>
#include <linux/limits.h>
#include <dirent.h>
#include "utility.h"
int shifter_parseConfig(const char *filename, char delim, void *obj, int (*assign_fp)(const char *, const char *, void *)) {
FILE *fp = NULL;
char *linePtr = NULL;
char *ptr = NULL;
size_t lineSize = 0;
size_t nRead = 0;
int multiline = 0;
char *key = NULL;
char *key_alloc = NULL;
char *value = NULL;
char *tValue = NULL;
int ret = 0;
if (filename == NULL || obj == NULL || assign_fp == NULL) {
return 1;
}
fp = fopen(filename, "r");
if (fp == NULL) {
return 1;
}
while (!feof(fp) && !ferror(fp)) {
char *tmp_value = NULL;
nRead = getline(&linePtr, &lineSize, fp);
if (nRead <= 0) break;
if (linePtr[0] == '#') continue;
/* get key/value pair */
if (!multiline) {
ptr = strchr(linePtr, delim);
if (ptr == NULL) continue;
*ptr++ = 0;
key_alloc = strdup(linePtr);
key = shifter_trim(key_alloc);
if (key == NULL) {
goto _parseConfig_errCleanup;
}
tValue = shifter_trim(ptr);
} else {
tValue = shifter_trim(linePtr);
multiline = 0;
}
if (tValue == NULL) {
goto _parseConfig_errCleanup;
}
/* check to see if value extends over multiple lines */
if (tValue[strlen(tValue) - 1] == '\\') {
multiline = 1;
tValue[strlen(tValue) - 1] = 0;
tValue = shifter_trim(tValue);
}
/* merge value and tValue */
if (value == NULL) {
value = strdup(tValue);
} else {
if (asprintf(&tmp_value, "%s %s", value, tValue) < 0) {
goto _parseConfig_errCleanup;
}
if (tmp_value == NULL) {
goto _parseConfig_errCleanup;
}
free(value);
value = tmp_value;
tmp_value = NULL;
}
tValue = NULL;
/* if value is complete, assign */
if (multiline == 0) {
ptr = shifter_trim(value);
ret = assign_fp(key, ptr, obj);
if (ret != 0) goto _parseConfig_errCleanup;
if (value != NULL) {
free(value);
}
if (key_alloc != NULL) {
free(key_alloc);
}
key = NULL;
key_alloc = NULL;
value = NULL;
}
}
if (linePtr != NULL) {
free(linePtr);
linePtr = NULL;
}
_parseConfig_errCleanup:
if (fp != NULL) {
fclose(fp);
}
if (linePtr != NULL) {
free(linePtr);
}
if (value != NULL) {
free(value);
}
if (key_alloc != NULL) {
free(key_alloc);
}
return ret;
}
char *shifter_trim(char *str) {
char *ptr = str;
ssize_t len = 0;
if (str == NULL) return NULL;
for ( ; isspace(*ptr) && *ptr != 0; ptr++) {
/* that's it */
}
if (*ptr == 0) return ptr;
len = strlen(ptr) - 1;
for ( ; isspace(*(ptr + len)) && len > 0; len--) {
*(ptr + len) = 0;
}
return ptr;
}
/**
* strncpy_StringArray
* Append a string to the specified string array. Assumes a relatively small
* number of items. Uses a block allocation scheem to expand array. String
* is destructively appended at the wptr position. Pointers are naivly
* verified to at least make sense.
*
* Affect: Space is allocated in array if necessary; then n bytes of string
* str are appended to end of array. A NULL terminator is appended to the
* end of array. wptr is left pointing to the NULL terminator for the next
* append.
*
* Parameters:
* str: input string
* n : bytes to copy
* wptr: pointer to write position; value may be changed upon array
* reallocation, or successful append. Left pointing to NULL terminator.
* array: pointer to base of String Array. value may be updated upon
* reallocation
* capacity: pointer to array capacity; updated upon reallocation
* allocationBlock: number of elements to add per reallocation event, must be
* greater than 0.
*
* Returns: 0 upon success, 1 upon failure
*/
int strncpy_StringArray(const char *str, size_t n, char ***wptr,
char ***array, size_t *capacity, size_t allocationBlock) {
size_t count = 0;
if (str == NULL || wptr == NULL || array == NULL
|| capacity == NULL || allocationBlock == 0 ||
*wptr < *array || *wptr - *capacity > *array) {
fprintf(stderr, "ERROR: invalid input to strncpy_StringArray\n");
return 1;
}
if (n == SIZE_MAX) {
fprintf(stderr, "ERROR: input string is too big, would not be able to "
"append terminator\n");
return 1;
}
/* allocate more space at a time */
count = *wptr - *array;
if (*capacity - count < 2) {
size_t new_capacity = *capacity + allocationBlock;
char **tmp = (char **) realloc(*array, sizeof(char *) * new_capacity);
if (tmp == NULL) {
fprintf(stderr, "ERROR: failed to allocate memory, append failed\n");
return 1;
}
*array = tmp;
*wptr = *array + count;
*capacity += allocationBlock;
}
/* append string to array, add ternminated NULL */
**wptr = (char *) malloc(sizeof(char) * (n + 1));
memcpy(**wptr, str, n);
(**wptr)[n] = 0;
(*wptr)++;
**wptr = NULL;
return 0;
}
/**
* alloc_strcatf appends to an existing string (or creates a new one) based on
* user-supplied format in printf style. The current capacity and length of
* the string are used to determine where to write in the string and when to
* allocate. An eager-allocation strategy is used where the string capacity is
* doubled at each reallocation. This is done to improve performance of
* repeated calls
* Parameters:
* string - pointer to string to be extended, can be NULL
* currLen - pointer to integer representing current limit of used portion
* of string
* capacity - pointer to integer representing current capacity of string
* format - printf style formatting string
* ... - variadic arguments for printf
*
* The dereferenced value of currLen is modified upon successful concatenation
* of string.
* The dereferenced value of capacity is modified upon successful reallocation
* of string.
*
* Returns pointer to string, possibly realloc'd. Caller should treat this
* function like realloc (test output for NULL before assigning).
* Returns NULL upon vsnprintf error or failure to realloc.
*/
char *alloc_strcatf(char *string, size_t *currLen, size_t *capacity, const char *format, ...) {
int status = 0;
int n = 0;
if (currLen == 0 || capacity == 0 || format == NULL) {
return NULL;
}
if (*currLen > *capacity) {
return NULL;
}
if (string == NULL || *capacity == 0) {
string = (char *) malloc(sizeof(char) * 128);
*capacity = 128;
}
while (1) {
char *wptr = string + *currLen;
va_list ap;
va_start(ap, format);
n = vsnprintf(wptr, *capacity - (*currLen), format, ap);
va_end(ap);
if (n < 0) {
/* error, break */
status = 1;
break;
} else if ((size_t) n >= (*capacity - *currLen)) {
/* if vsnprintf returns larger than allowed buffer, need more space
* allocating eagerly to reduce cost for successive strcatf
* operations */
size_t newCapacity = *capacity * 2 + 1;
char *tmp = NULL;
if (newCapacity < (size_t) (n + 1)) {
newCapacity = (size_t) (n + 1);
}
tmp = (char *) realloc(string, sizeof(char) * newCapacity);
if (tmp == NULL) {
status = 2;
break;
}
string = tmp;
*capacity = newCapacity;
} else {
/* success */
status = 0;
*currLen += n;
break;
}
}
if (status == 0) {
return string;
}
return NULL;
}
/**
* alloc_strgenf allocates and appopriately-sized buffer and populates it with
* user-supplied format in printf style.
* Parameters:
* format - printf style formatting string
* ... - variadic arguments for printf
*
*
* Returns pointer to string.
* Returns NULL upon vsnprintf error or failure to realloc.
*/
char *alloc_strgenf(const char *format, ...) {
char *string = NULL;
int capacity = 0;
int status = 0;
int n = 0;
if (format == NULL) {
return NULL;
}
string = (char *) malloc(sizeof(char) * 128);
capacity = 128;
while (1) {
va_list ap;
va_start(ap, format);
n = vsnprintf(string, capacity, format, ap);
va_end(ap);
if (n < 0) {
/* error, break */
status = 1;
break;
} else if (n >= capacity) {
/* if vsnprintf returns larger than allowed buffer, need more space
* allocating eagerly to reduce cost for successive strcatf
* operations */
size_t newCapacity = n + 1;
char *tmp = (char *) realloc(string, sizeof(char) * newCapacity);
if (tmp == NULL) {
status = 2;
break;
}
string = tmp;
capacity = newCapacity;
} else {
/* success */
status = 0;
break;
}
}
if (status == 0) {
return string;
}
if (string != NULL) {
free(string);
string = NULL;
}
return NULL;
}
/**
* userInputPathFilter screens out certain characters from user-provided strings
* Parameters:
* input - the user provided string
* allowSlash - flag to allow a '/' in the string (1 for yes, 0 for no)
*
*
* Returns pointer to newly allocated string.
* Returns NULL if input is NULL or there is a memory allocation error
*/
char *userInputPathFilter(const char *input, int allowSlash) {
ssize_t len = 0;
char *ret = NULL;
const char *rptr = NULL;
char *wptr = NULL;
if (input == NULL) return NULL;
len = strlen(input) + 1;
ret = (char *) malloc(sizeof(char) * len);
if (ret == NULL) return NULL;
rptr = input;
wptr = ret;
while (wptr - ret < len && *rptr != 0) {
if (isalnum(*rptr) || *rptr == '_' || *rptr == ':' || *rptr == '.' || *rptr == '+' || *rptr == '-') {
*wptr++ = *rptr;
}
if (allowSlash && *rptr == '/') {
*wptr++ = *rptr;
}
rptr++;
}
*wptr = 0;
return ret;
}
char *cleanPath(const char *path) {
if (!path) return NULL;
ssize_t len = strlen(path) + 1;
char *ret = (char *) malloc(sizeof(char) * len);
memset(ret, 0, sizeof(char) * len);
char *wPtr = ret;
const char *rPtr = path;
char lastWrite = 0;
while (rPtr && *rPtr && (wPtr - ret) < len) {
/* prevent repeated '/' */
if (*rPtr == '/' && lastWrite == '/') {
rPtr++;
continue;
}
*wPtr = *rPtr;
lastWrite = *wPtr;
wPtr++;
rPtr++;
}
/* remove trailing '/' if path is longer than '/' */
if (wPtr - ret > 1 && *(wPtr - 1) == '/') {
*(wPtr - 1) = 0;
}
/* terminate string */
*wPtr = 0;
return ret;
}
int pathcmp(const char *a, const char *b) {
if (a && !b) return 1;
if (!a && b) return -1;
if (!a && !b) return 0;
char *myA = cleanPath(a);
char *myB = cleanPath(b);
int ret = strcmp(myA, myB);
free(myA);
free(myB);
return ret;
}
/**
* Creates the specified directory as the bash command "mkdir -p", i.e. there is no error
* if the directory exists and makes parent directories as needed.
*/
int mkdir_p(const char* path, mode_t mode) {
if (strlen(path) >= PATH_MAX) {
fprintf(stderr, "cannot mkdir %s. Specified path is too long\n", path);
return 1;
}
char path_copy[PATH_MAX];
strncpy(path_copy, path, PATH_MAX);
char* begin = path_copy;
char* pos = begin;
if (*begin == 0 || *begin != '/') {
fprintf(stderr, "mkdir_p: specified a non valid absulute path\n");
}
// iterate through each subfolder and create them as needed
while(1) {
++pos;
if (*pos == '/' || *pos == '\0') {
int is_last_subfolder = (*pos == '\0');
*pos = '\0';
if (!is_existing_file(begin)) {
if (mkdir(begin, mode) != 0) {
fprintf(stderr, "cannot mkdir %s\n", begin);
return 1;
}
}
if(is_last_subfolder) {
break;
}
else {
*pos = '/';
}
}
}
return 0;
}
/**
* Returns 1 if the specified file exists (could be either a file or a directory), otherwise 0.
*/
int is_existing_file(const char* path) {
struct stat sb;
return stat(path, &sb) == 0;
}
/**
* Returns 1 if the specified directory exists, otherwise 0.
*/
int is_existing_directory(const char* path) {
struct stat sb;
return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode);
}
/**
* Returns 1 if the specified directory is empty.
*/
int is_empty_directory(const char* path) {
DIR *dir = opendir(path);
if(dir == NULL) {
return 1;
}
struct dirent *entry = NULL;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
{
continue;
}
closedir(dir);
return 0;
}
closedir(dir);
return 1;
}