Simplify split_args().
[dss.git] / str.c
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #include <string.h>
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <stdarg.h>
6 #include <assert.h>
7 #include <limits.h>
8 #include <errno.h>
9 #include <pwd.h>
10 #include <sys/types.h>
11 #include <unistd.h>
12
13
14 #include "gcc-compat.h"
15 #include "log.h"
16 #include "err.h"
17 #include "str.h"
18
19 /**
20  * dss' version of realloc().
21  *
22  * \param p Pointer to the memory block, may be \p NULL.
23  * \param size The desired new size.
24  *
25  * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
26  * i.e. there is no need to check the return value in the caller.
27  *
28  * \return A pointer to  the newly allocated memory, which is suitably aligned
29  * for any kind of variable and may be different from \a p.
30  *
31  * \sa realloc(3).
32  */
33 __must_check __malloc void *dss_realloc(void *p, size_t size)
34 {
35         /*
36          * No need to check for NULL pointers: If p is NULL, the  call
37          * to realloc is equivalent to malloc(size)
38          */
39         assert(size);
40         if (!(p = realloc(p, size))) {
41                 DSS_EMERG_LOG(("realloc failed (size = %zu), aborting\n",
42                         size));
43                 exit(EXIT_FAILURE);
44         }
45         return p;
46 }
47
48 /**
49  * dss' version of malloc().
50  *
51  * \param size The desired new size.
52  *
53  * A wrapper for malloc(3) which exits on errors.
54  *
55  * \return A pointer to the allocated memory, which is suitably aligned for any
56  * kind of variable.
57  *
58  * \sa malloc(3).
59  */
60 __must_check __malloc void *dss_malloc(size_t size)
61 {
62         void *p;
63         assert(size);
64         p = malloc(size);
65
66         if (!p) {
67                 DSS_EMERG_LOG(("malloc failed (size = %zu),  aborting\n",
68                         size));
69                 exit(EXIT_FAILURE);
70         }
71         return p;
72 }
73
74 /**
75  * dss' version of calloc().
76  *
77  * \param size The desired new size.
78  *
79  * A wrapper for calloc(3) which exits on errors.
80  *
81  * \return A pointer to the allocated and zeroed-out memory, which is suitably
82  * aligned for any kind of variable.
83  *
84  * \sa calloc(3)
85  */
86 __must_check __malloc void *dss_calloc(size_t size)
87 {
88         void *ret = dss_malloc(size);
89
90         memset(ret, 0, size);
91         return ret;
92 }
93
94 /**
95  * dss' version of strdup().
96  *
97  * \param s The string to be duplicated.
98  *
99  * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
100  * there is no need to check the return value in the caller.
101  *
102  * \return A pointer to the duplicated string. If \p s was the NULL pointer,
103  * an pointer to an empty string is returned.
104  *
105  * \sa strdup(3)
106  */
107
108 __must_check __malloc char *dss_strdup(const char *s)
109 {
110         char *ret;
111
112         if ((ret = strdup(s? s: "")))
113                 return ret;
114         DSS_EMERG_LOG(("strdup failed, aborting\n"));
115         exit(EXIT_FAILURE);
116 }
117
118 /**
119  * Allocate a sufficiently large string and print into it.
120  *
121  * \param fmt A usual format string.
122  *
123  * Produce output according to \p fmt. No artificial bound on the length of the
124  * resulting string is imposed.
125  *
126  * \return This function either returns a pointer to a string that must be
127  * freed by the caller or aborts without returning.
128  *
129  * \sa printf(3).
130  */
131 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
132 {
133         char *msg;
134         size_t size = 100;
135
136         msg = dss_malloc(size);
137         while (1) {
138                 int n;
139                 va_list ap;
140
141                 /* Try to print in the allocated space. */
142                 va_start(ap, fmt);
143                 n = vsnprintf(msg, size, fmt, ap);
144                 va_end(ap);
145                 /* If that worked, return the string. */
146                 if (n < size)
147                         return msg;
148                 /* Else try again with more space. */
149                 size = n + 1; /* precisely what is needed */
150                 msg = dss_realloc(msg, size);
151         }
152 }
153
154 /**
155  * Get the home directory of the current user.
156  *
157  * \return A dynamically allocated string that must be freed by the caller. If
158  * the home directory could not be found, this function returns "/tmp".
159  */
160 __must_check __malloc char *get_homedir(void)
161 {
162         struct passwd *pw = getpwuid(getuid());
163         return dss_strdup(pw? pw->pw_dir : "/tmp");
164 }
165
166 /**
167  * Convert a string to a 64-bit signed integer value.
168  *
169  * \param str The string to be converted.
170  * \param value Result pointer.
171  *
172  * \return Standard.
173  *
174  * \sa strtol(3), atoi(3).
175  */
176 int dss_atoi64(const char *str, int64_t *value)
177 {
178         char *endptr;
179         long long tmp;
180
181         errno = 0; /* To distinguish success/failure after call */
182         tmp = strtoll(str, &endptr, 10);
183         if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
184                 return -E_ATOI_OVERFLOW;
185         if (errno != 0 && tmp == 0) /* other error */
186                 return -E_STRTOLL;
187         if (endptr == str)
188                 return -E_ATOI_NO_DIGITS;
189         if (*endptr != '\0') /* Further characters after number */
190                 return -E_ATOI_JUNK_AT_END;
191         *value = tmp;
192         return 1;
193 }
194
195 /**
196  * Get the logname of the current user.
197  *
198  * \return A dynamically allocated string that must be freed by the caller. On
199  * errors, the string "unknown user" is returned, i.e. this function never
200  * returns \p NULL.
201  *
202  * \sa getpwuid(3).
203  */
204 __must_check __malloc char *dss_logname(void)
205 {
206         struct passwd *pw = getpwuid(getuid());
207         return dss_strdup(pw? pw->pw_name : "unknown_user");
208 }
209
210 /**
211  * Split string and return pointers to its parts.
212  *
213  * \param args The string to be split.
214  * \param argv_ptr Pointer to the list of substrings.
215  *
216  * This function modifies the string given by the first argument by replacing
217  * all occurrences of space and '\t' characters by '\0'. A NULL-terminated
218  * array of pointers to char * is allocated dynamically, and these pointers are
219  * initialized to point to the broken-up substrings.  A pointer to this array
220  * is returned via the last argument.
221  *
222  * \return The number of substrings found.
223  */
224 unsigned split_args(char *args, char *** const argv_ptr)
225 {
226         char *p;
227         char **argv;
228         size_t n = 0, i, j;
229         const char delim[] = " \t";
230
231         p = args + strspn(args, delim);
232         for (;;) {
233                 i = strcspn(p, delim);
234                 if (!i)
235                         break;
236                 p += i;
237                 n++;
238                 p += strspn(p, delim);
239         }
240         *argv_ptr = dss_malloc((n + 1) * sizeof(char *));
241         argv = *argv_ptr;
242         i = 0;
243         p = args + strspn(args, delim);
244         while (p) {
245                 argv[i] = p;
246                 j = strcspn(p, delim);
247                 if (!j)
248                         break;
249                 p += strcspn(p, delim);
250                 if (*p) {
251                         *p = '\0';
252                         p++;
253                         p += strspn(p, delim);
254                 }
255                 i++;
256         }
257         argv[n] = NULL;
258         return n;
259 }