summaryrefslogtreecommitdiff
path: root/src/shared.c
blob: 9a147eb0e562d8197cb45d433d1f496d80d509ac (plain)
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
/**
 * @file shared.c
 * @author syxhe (https://t.me/syxhe)
 * @brief A collection of functions and macros shared between files, or without a better place
 * @version 0.1
 * @date 2025-06-09
 *
 * @copyright Copyright (c) 2025
 *
 */

#ifndef __VXGG_REWRITE___SHARED_C___3880294315821___
#define __VXGG_REWRITE___SHARED_C___3880294315821___ 1

#define STATIC_ARRAY_LEN(arr) (sizeof((arr))/sizeof((arr)[0]))

#define ERRRET(errval, retval) do {\
    errno = (errval);\
    return (retval);\
} while (0)

/// Determines how `vx__alloc()` functions exit. `> 0` calls `error()`, otherwise calls `abort()`. `vx__alloc()` type functions will
/// always halt execution
#define ___VXGG___VXALLOC_EXIT_ON_ERROR___ 1

/// Determines whether vxgg functions that can error print out a short warning of the error when one is encountered.
/// `> 0` will print diagnostic error messages, and will do nothing otherwise
#define ___VXGG___VERBOSE_ERRORS___ 1

//! Macro to exit on an alloc error instead of doing the terrible nested if statement that was being used previously
#define XALLOC_EXIT(msg, ...) do {\
    if(!___VXGG___VXALLOC_EXIT_ON_ERROR___)\
        abort();\
    if(!___VXGG___VERBOSE_ERRORS___)\
        exit(EXIT_FAILURE);\
    error(EXIT_FAILURE, errno, (msg)__VA_ARGS__);\
    exit(EXIT_FAILURE); /* Makes gcc happy */\
} while (0)

//! Error macro that gcc will not complain about
#define ERROR(status, errnum, format, ...) do {error((status), (errnum), (format)__VA_ARGS__); exit((status));} while (0)
//! Spit out a warning using `error`
#define WARN(errnum, format, ...) do {error(0, (errnum), (format)__VA_ARGS__);} while (0)


typedef int (*gcallback)(void*);    //!< Generic callback signature
typedef void (*fcallback)(void*);   //!< free()-like callback signature

/**
 * @brief A locally defined structure designed for easier function cleanup
 *
 */
typedef struct cl {
    fcallback *callbacks;   //!< An array of free()-like callbacks. Actual Type: fcallback callbacks[]
    void * *arguments;      //!< An array of void pointers. Actual Type: void *arguments[]
    int size;               //!< The size of each array
    int used;               //!< The current number of used elements in each array
} cleanup;
// While the cleanup thing is useful, it's also a complete fucking mess. Swtich to error gotos asap

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <error.h>

#include <threads.h>

/**
 * @brief Read the entire contents of a file descriptor into a malloc()'ed buffer
 *
 * @param str Pointer to a string. Will be replaced with the malloc()'ed string
 * @param initsize The initial size of the malloc()'ed string
 * @param fd A file descriptor to read from
 * @retval (int)[-1, strlen(str)] Returns the size of the array on success, or -1 on error
 * @note The allocated buffer will expand and contract as necessary, but it's recommended to set `initsize` to some value close to or equal to the size of the file being read to reduce the number of resizes
 */
int rwbuf(char **str, unsigned long int initsize, int fd) {
	// Try to read bytes from fd into str
		// Bytes read == 0, return 0
		// Bytes read < 0, free string, return -1;
	// When string hits capacity, double the capacity, and reallocate the string

	if(!str || initsize < 1 || fd < 0) ERRRET(EINVAL, -1);

    char *lstr = NULL, *tmp = NULL;
	ssize_t bytesread = -1;
	int csize = initsize, ccap = initsize, eflag = 0;

	lstr = calloc(initsize, sizeof(char));
	if(!lstr) return -1;

	while((bytesread = read(fd, lstr + (csize - ccap), ccap)) > 0) {
		ccap -= bytesread;
		if(ccap <= 0) {
			csize *= 2;
			ccap = csize / 2;

			tmp = realloc(lstr, csize * sizeof(char));
			if(!tmp) {eflag = 1; goto ERR_rwbuf;}
			lstr = tmp;
		}
	}
	if(bytesread < 0) {eflag = 2; goto ERR_rwbuf;}

	if(lstr) {
		tmp = realloc(lstr, csize - ccap + 1);
		if(!tmp) {eflag = 3; goto ERR_rwbuf;}
		lstr = tmp;
	}

    if(lstr && fd == STDIN_FILENO) {
        lstr[csize - ccap - 1] = '\0'; // Don't include the newline
    }

	*str = lstr;
	return csize - ccap;

ERR_rwbuf:
    if(___VXGG___VERBOSE_ERRORS___) {
        switch (eflag) {
            case 1: WARN(errno, "Could not reallocate enough space for lstr",);
            case 2: WARN(errno, "Ran into a read() error",);
            case 3: WARN(errno, "Could not shrink lstr after reading buffer",);
            default: WARN(errno, "Ran into some error",);
        }
    }
    free(lstr);

    return -1;
}


/**
 * @brief Write the entire contents of a buffer into a file descriptor
 *
 * @param fd The file descriptor to write to
 * @param buf The buffer to write from
 * @param len The length of the buffer
 * @retval (int)[-1, 0] Returns 0 on success, -1 on error
 */

int wwbuf(int fd, const unsigned char *buf, int len) {
	if(!buf || len <= 0 || fd < 0) ERRRET(EINVAL, -1);

    int total = 0;
    int left = len;
    int n = -1;

    while(total < len) {
        if((n = write(fd, buf + total, left)) < 0)
            break;

        total += n;
        left -= n;
    }

    return (n < 0) ? -1 : 0;
}
// Adapted from Beej's `sendall()` function
// https://beej.us/guide/bgnet/html/split/slightly-advanced-techniques.html#sendall
    // Thanks Beej!

/**
 * @brief `dirname()` reimplementation that returns a malloc()'ed string
 *
 * @param path The filepath to be inspected
 * @retval (char*)[NULL, char*] Returns a null-terminated string on success, or `null` on error
 */
char * vxdirname(const char * const path) {
	char *tmp = NULL;
	if(!path) { // Path being null is a special case which should return early, before anything else (as to avoid null dereference)
		tmp = strdup(".");
		if(!tmp && ___VXGG___VERBOSE_ERRORS___) WARN(errno, "<vxdirname> could not strdup \".\" for set path result \"NULL\"", );
		return tmp;
	}

    const char * const special[] = {"..", ".", "/"};
    for(int i = 0; i < STATIC_ARRAY_LEN(special); i++) {
        if(strncmp(path, special[i], strlen(special[i])) == 0) {
            tmp = strdup(special[i]);
            if(!tmp && ___VXGG___VERBOSE_ERRORS___) WARN(errno, "<vxdirname> could not strdup a set path result", );
            return tmp;
        }
    }

	/* From the manpages: (man 3 dirname)
	//		+=======================================+
	//		|	path		dirname		basename	|
	//		+=======================================+
	//		|	/usr/lib   	/usr      	lib			|
	//		|	/usr/      	/         	usr			|
	//		|	usr        	.         	usr			|
	//		+=======================================+
	*/

	// Get a temp copy of the path for manipulation purposes
	tmp = strdup(path);
	if(!tmp) {
		if(___VXGG___VERBOSE_ERRORS___) WARN(errno, "<vxdirname> could not strdup the given path \"%s\" for internal manipulation", , path);
		return NULL;
	}

	// If there's a trailing '/', delete it
	size_t pathlen = strlen(path);
	if(tmp[pathlen - 1] == '/') {
		tmp[pathlen - 1] = '\0';
		pathlen--;
	}

	// Ok, I think the easiest way to do this (if maybe a bit slow) is to count the number of '/'s in the string
		// If there's only one, return '/'
		// If there are 2 or more, find the last one in the list and set it to '\0'

	size_t count = 0;
	for(size_t i = 0; i < pathlen; i++) {
		if(tmp[i] == '/')
			count++;
	}

    if(count < 2) {
        free(tmp);
        if(count == 1) tmp = strdup("/");
        else tmp = strdup(".");

        if(!tmp && ___VXGG___VERBOSE_ERRORS___) WARN(errno, "<vxdirname> Error: Could not strdup \"%s\" for set path result", , ((count == 0) ? "." : "/"));
        return tmp;
    }

	for(size_t i = 0, c2 = 0; i < pathlen; i++) {
		if(tmp[i] == '/')
			c2++;
		if(c2 == count)
			tmp[i] = '\0';
	}

	char * const actual = strdup(tmp);
	free(tmp);
	if(!actual && ___VXGG___VERBOSE_ERRORS___) WARN(errno, "<xdirname> could not strdup tmp string to make a shorter end string", );

	return actual;
}


/**
 * @brief Initialize a cleanup object
 *
 * @param loc The cleanup object to be initialized
 * @param callbacks An array of free()-like callbacks. Must be `size` elements long
 * @param arguments An array of void pointers. Must be `size` elements long
 * @param size The number of elements the callbacks and arguments array are long
 * @retval (int)[-1, 0] Returns 0 on success, -1 on error
 */
int cleanup_init(cleanup *loc, fcallback callbacks[], void *arguments[], int size) {
    if(!loc || !callbacks || !arguments || size <= 0) ERRRET(EINVAL, -1);

    loc->callbacks = callbacks;
    loc->arguments = arguments;
    loc->size = size;
    loc->used = 0;

    return 0;
}

/**
 * @brief Register a new callback and argument onto a cleanup stack
 *
 * @param loc The cleanup object to modify
 * @param cb A free()-like callback to run
 * @param arg A piece of data for the callback to run
 * @retval (int)[-1, 0] Returns 0 on success, -1 on error
 */
int cleanup_register(cleanup *loc, fcallback cb, void *arg) {
    if(!loc || !cb) ERRRET(EINVAL, -1);
    if(loc->used >= loc->size || loc->used < 0) ERRRET(ENOMEM, -1);

    loc->callbacks[loc->used] = cb;
    loc->arguments[loc->used] = arg;
    loc->used++;

    return 0;
}

/**
 * @brief Conditionally register a callback and argument
 *
 * @param loc The cleanup object to modify
 * @param cb A free()-like callback to run
 * @param arg A piece of data for the callback to run
 * @param flag Whether or not the register should take place. Will not run if `flag` is non-zero
 * @retval (int)[-1, 0] Returns 0 on success or skip, -1 on error
 */
int cleanup_cndregister(cleanup *loc, fcallback cb, void *arg, unsigned char flag) {
    if(flag) return 0;
    return cleanup_register(loc, cb, arg);
}

/**
 * @brief Clear a cleanup object
 * @attention Does not free any registered callbacks or arguments, just marks them as available space
 *
 * @param loc The cleanup object to modify
 * @retval (int)[-1, 0] Returns 0 on success, -1 on error
 */
int cleanup_clear(cleanup *loc) {
    if(!loc) ERRRET(EINVAL, -1);
    loc->used = 0;
    return 0;
}

/**
 * @brief Fires all the registered callbacks and arguments in a cleanup object in FIFO (stack) order
 *
 * @param loc The cleanup object to fire
 * @retval (int)[-1, 0] Returns 0 on success, -1 on error
 */
int cleanup_fire(cleanup *loc) {
    if(!loc) ERRRET(EINVAL, -1);

    for(int i = (loc->used - 1); i >= 0; i--) {
        if(loc->callbacks[i] == NULL) {
            error(0, EINVAL, "cleanup_fire: refusing to run null callback...");
            continue;
        }

        loc->callbacks[i](loc->arguments[i]);
    }
    cleanup_clear(loc);

    return 0;
}

/**
 * @brief Conditionally fires a cleanup object
 *
 * @param loc The cleanup object in question
 * @param flag Whether the object should be fired. Will skip firing if non-zero
 * @retval (int)[-1, 0] Returns 0 on success, -1 on error
 */
int cleanup_cndfire(cleanup *loc, unsigned char flag) {
    if(flag)
        return cleanup_fire(loc);
    return 0;
}

/**
 * @brief Initializes a set of variables suitable for use in the cleanup macros
 * @param size The number of elements long each array should be
 */
#define cleanup_CREATE(size) \
cleanup __CLEANUP; \
fcallback __CLEANUP_FUNCS[(size)]; \
void *__CLEANUP_ARGS[(size)]; \
unsigned char __FLAG = 0; \
cleanup_init(&__CLEANUP, __CLEANUP_FUNCS, __CLEANUP_ARGS, (size))

//! Register a callback-argument pair using the local cleanup object
#define cleanup_REGISTER(cb, arg)       cleanup_register(&__CLEANUP, (cb), (arg))
//! Conditionally register a callback-argument pair using the local cleanup object
#define cleanup_CNDREGISTER(cb, arg)    cleanup_cndregister(&__CLEANUP, (cb), (arg), __FLAG)
//! Clean the local cleanup object
#define cleanup_CLEAR()                 cleanup_clear(&__CLEANUP)
//! Fire the local cleanup object
#define cleanup_FIRE()                  cleanup_fire(&__CLEANUP)
//! Conditionally fire the local cleanup object
#define cleanup_CNDFIRE()               cleanup_cndfire(&__CLEANUP, __FLAG)
//! Set the local cleanup flag to a non-zero number
#define cleanup_MARK()                  (__FLAG = 1)
//! Set the local cleanup flag to zero
#define cleanup_UNMARK()                (__FLAG = 0)
//! Check if the local cleanup flag is non-zero
#define cleanup_ERRORFLAGGED            (__FLAG != 0)
//! Conditionally execute some `code` if the local cleanup flag has not been marked
#define cleanup_CNDEXEC(code)           while(!cleanup_ERRORFLAGGED) {code; break;}
//! Conditionally fire the local cleanup object and return `ret`
#define cleanup_CNDFIRERET(ret)         do {cleanup_CNDFIRE(); return ret;} while (0)

#endif