Whamcloud - gitweb
LU-14487 libcfs: remove references to Sun Trademark.
[fs/lustre-release.git] / libcfs / libcfs / util / string.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * String manipulation functions.
32  *
33  * libcfs/libcfs/util/string.c
34  *
35  * Author: Nathan Rutman <nathan.rutman@sun.com>
36  */
37 #include <ctype.h>
38 #include <errno.h>
39 #include <stdbool.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <limits.h>
44 #include <unistd.h>
45 #include <libcfs/util/string.h>
46
47 /**
48  * Extracts tokens from strings.
49  *
50  * Looks for \a delim in string \a next, sets \a res to point to
51  * substring before the delimiter, sets \a next right after the found
52  * delimiter.
53  *
54  * \retval 1 if \a res points to a string of non-whitespace characters
55  * \retval 0 otherwise
56  */
57 int
58 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
59 {
60         char *end;
61
62         if (next->ls_str == NULL)
63                 return 0;
64
65         /* skip leading white spaces */
66         while (next->ls_len) {
67                 if (!isspace(*next->ls_str))
68                         break;
69                 next->ls_str++;
70                 next->ls_len--;
71         }
72
73         if (next->ls_len == 0) /* whitespaces only */
74                 return 0;
75
76         if (*next->ls_str == delim) {
77                 /* first non-writespace is the delimiter */
78                 return 0;
79         }
80
81         res->ls_str = next->ls_str;
82         end = memchr(next->ls_str, delim, next->ls_len);
83         if (end == NULL) {
84                 /* there is no the delimeter in the string */
85                 end = next->ls_str + next->ls_len;
86                 next->ls_str = NULL;
87         } else {
88                 next->ls_str = end + 1;
89                 next->ls_len -= (end - res->ls_str + 1);
90         }
91
92         /* skip ending whitespaces */
93         while (--end != res->ls_str) {
94                 if (!isspace(*end))
95                         break;
96         }
97
98         res->ls_len = end - res->ls_str + 1;
99         return 1;
100 }
101
102 /**
103  * Converts string to integer.
104  *
105  * Accepts decimal and hexadecimal number recordings.
106  *
107  * \retval 1 if first \a nob chars of \a str convert to decimal or
108  * hexadecimal integer in the range [\a min, \a max]
109  * \retval 0 otherwise
110  */
111 int
112 cfs_str2num_check(char *str, int nob, unsigned *num,
113                   unsigned min, unsigned max)
114 {
115         char    *endp;
116
117         *num = strtoul(str, &endp, 0);
118         if (endp == str)
119                 return 0;
120
121         for (; endp < str + nob; endp++) {
122                 if (!isspace(*endp))
123                         return 0;
124         }
125
126         return (*num >= min && *num <= max);
127 }
128
129 /**
130  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
131  * \a src should only have a single token which can be \<number\> or  \*
132  *
133  * \retval pointer to allocated range_expr and initialized
134  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
135  * src parses to
136  * \<number\> |
137  * \<number\> '-' \<number\> |
138  * \<number\> '-' \<number\> '/' \<number\>
139  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
140  * -ENOMEM will be returned.
141  */
142 static int
143 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
144                      int bracketed, struct cfs_range_expr **expr)
145 {
146         struct cfs_range_expr   *re;
147         struct cfs_lstr         tok;
148
149         re = calloc(1, sizeof(*re));
150         if (re == NULL)
151                 return -ENOMEM;
152
153         if (src->ls_len == 1 && src->ls_str[0] == '*') {
154                 re->re_lo = min;
155                 re->re_hi = max;
156                 re->re_stride = 1;
157                 goto out;
158         }
159
160         if (cfs_str2num_check(src->ls_str, src->ls_len,
161                               &re->re_lo, min, max)) {
162                 /* <number> is parsed */
163                 re->re_hi = re->re_lo;
164                 re->re_stride = 1;
165                 goto out;
166         }
167
168         if (!bracketed || !cfs_gettok(src, '-', &tok))
169                 goto failed;
170
171         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
172                                &re->re_lo, min, max))
173                 goto failed;
174
175         /* <number> - */
176         if (cfs_str2num_check(src->ls_str, src->ls_len,
177                               &re->re_hi, min, max)) {
178                 /* <number> - <number> is parsed */
179                 re->re_stride = 1;
180                 goto out;
181         }
182
183         /* go to check <number> '-' <number> '/' <number> */
184         if (cfs_gettok(src, '/', &tok)) {
185                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
186                                        &re->re_hi, min, max))
187                         goto failed;
188
189                 /* <number> - <number> / ... */
190                 if (cfs_str2num_check(src->ls_str, src->ls_len,
191                                       &re->re_stride, min, max)) {
192                         /* <number> - <number> / <number> is parsed */
193                         goto out;
194                 }
195         }
196
197  out:
198         *expr = re;
199         return 0;
200
201  failed:
202         free(re);
203         return -EINVAL;
204 }
205
206 /**
207  * Print the range expression \a re into specified \a buffer.
208  * If \a bracketed is true, expression does not need additional
209  * brackets.
210  *
211  * \retval number of characters written
212  */
213 static int
214 cfs_range_expr_print(char *buffer, int count, struct cfs_range_expr *expr,
215                      bool bracketed)
216 {
217         int i;
218         char s[] = "[";
219         char e[] = "]";
220
221         if (bracketed)
222                 s[0] = e[0] = '\0';
223
224         if (expr->re_lo == expr->re_hi)
225                 i = snprintf(buffer, count, "%u", expr->re_lo);
226         else if (expr->re_stride == 1)
227                 i = snprintf(buffer, count, "%s%u-%u%s",
228                                   s, expr->re_lo, expr->re_hi, e);
229         else
230                 i = snprintf(buffer, count, "%s%u-%u/%u%s",
231                                   s, expr->re_lo, expr->re_hi,
232                                   expr->re_stride, e);
233         return i;
234 }
235
236 /**
237  * Print a list of range expressions (\a expr_list) into specified \a buffer.
238  * If the list contains several expressions, separate them with comma
239  * and surround the list with brackets.
240  *
241  * \retval number of characters written
242  */
243 int
244 cfs_expr_list_print(char *buffer, int count, struct cfs_expr_list *expr_list)
245 {
246         struct cfs_range_expr *expr;
247         int i = 0, j = 0;
248         int numexprs = 0;
249
250         if (count <= 0)
251                 return 0;
252
253         list_for_each_entry(expr, &expr_list->el_exprs, re_link)
254                 numexprs++;
255
256         if (numexprs > 1)
257                 i += scnprintf(buffer + i, count - i, "[");
258
259         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
260                 if (j++ != 0)
261                         i += scnprintf(buffer + i, count - i, ",");
262                 i += cfs_range_expr_print(buffer + i, count - i, expr,
263                                           numexprs > 1);
264         }
265
266         if (numexprs > 1)
267                 i += scnprintf(buffer + i, count - i, "]");
268
269         return i;
270 }
271
272 /**
273  * Matches value (\a value) against ranges expression list \a expr_list.
274  *
275  * \retval 1 if \a value matches
276  * \retval 0 otherwise
277  */
278 int
279 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
280 {
281         struct cfs_range_expr   *expr;
282
283         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
284                 if (value >= expr->re_lo && value <= expr->re_hi &&
285                     ((value - expr->re_lo) % expr->re_stride) == 0)
286                         return 1;
287         }
288
289         return 0;
290 }
291
292 /**
293  * Convert express list (\a expr_list) to an array of all matched values
294  *
295  * \retval N N is total number of all matched values
296  * \retval 0 if expression list is empty
297  * \retval < 0 for failure
298  */
299 int
300 cfs_expr_list_values(struct cfs_expr_list *expr_list, int max, __u32 **valpp)
301 {
302         struct cfs_range_expr   *expr;
303         __u32                   *val;
304         int                     count = 0;
305         int                     i;
306
307         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
308                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
309                         if (((i - expr->re_lo) % expr->re_stride) == 0)
310                                 count++;
311                 }
312         }
313
314         if (count == 0) /* empty expression list */
315                 return 0;
316
317         if (count > max)
318                 return -EINVAL;
319
320         val = calloc(sizeof(val[0]), count);
321         if (val == NULL)
322                 return -ENOMEM;
323
324         count = 0;
325         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
326                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
327                         if (((i - expr->re_lo) % expr->re_stride) == 0)
328                                 val[count++] = i;
329                 }
330         }
331
332         *valpp = val;
333         return count;
334 }
335
336 void
337 cfs_expr_list_values_free(__u32 *values, int num)
338 {
339         /* This array is allocated by LIBCFS_ALLOC(), so it shouldn't be freed
340          * by OBD_FREE() if it's called by module other than libcfs & LNet,
341          * otherwise we will see fake memory leak */
342         free(values);
343 }
344
345 /**
346  * Frees cfs_range_expr structures of \a expr_list.
347  *
348  * \retval none
349  */
350 void
351 cfs_expr_list_free(struct cfs_expr_list *expr_list)
352 {
353         while (!list_empty(&expr_list->el_exprs)) {
354                 struct cfs_range_expr *expr;
355
356                 expr = list_entry(expr_list->el_exprs.next,
357                                   struct cfs_range_expr, re_link);
358                 list_del(&expr->re_link);
359                 free(expr);
360         }
361
362         free(expr_list);
363 }
364
365 /**
366  * Parses \<cfs_expr_list\> token of the syntax.
367  *
368  * \retval 0 if \a str parses to \<number\> | \<expr_list\>
369  * \retval -errno otherwise
370  */
371 int
372 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
373                     struct cfs_expr_list **elpp)
374 {
375         struct cfs_expr_list    *expr_list;
376         struct cfs_range_expr   *expr;
377         struct cfs_lstr         src;
378         int                     rc;
379
380         expr_list = calloc(1, sizeof(*expr_list));
381         if (expr_list == NULL)
382                 return -ENOMEM;
383
384         src.ls_str = str;
385         src.ls_len = len;
386
387         INIT_LIST_HEAD(&expr_list->el_exprs);
388
389         if (src.ls_str[0] == '[' &&
390             src.ls_str[src.ls_len - 1] == ']') {
391                 src.ls_str++;
392                 src.ls_len -= 2;
393
394                 rc = -EINVAL;
395                 while (src.ls_str != NULL) {
396                         struct cfs_lstr tok;
397
398                         if (!cfs_gettok(&src, ',', &tok)) {
399                                 rc = -EINVAL;
400                                 break;
401                         }
402
403                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
404                         if (rc != 0)
405                                 break;
406
407                         list_add_tail(&expr->re_link,
408                                           &expr_list->el_exprs);
409                 }
410         } else {
411                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
412                 if (rc == 0) {
413                         list_add_tail(&expr->re_link,
414                                           &expr_list->el_exprs);
415                 }
416         }
417
418         if (rc != 0)
419                 cfs_expr_list_free(expr_list);
420         else
421                 *elpp = expr_list;
422
423         return rc;
424 }
425
426 /**
427  * Frees cfs_expr_list structures of \a list.
428  *
429  * For each struct cfs_expr_list structure found on \a list it frees
430  * range_expr list attached to it and frees the cfs_expr_list itself.
431  *
432  * \retval none
433  */
434 void
435 cfs_expr_list_free_list(struct list_head *list)
436 {
437         struct cfs_expr_list *el;
438
439         while (!list_empty(list)) {
440                 el = list_entry(list->next,
441                                     struct cfs_expr_list, el_link);
442                 list_del(&el->el_link);
443                 cfs_expr_list_free(el);
444         }
445 }
446
447 /**
448  * cfs_abs_path() - Get the absolute path of a relative path
449  * @request_path:       The relative path to be resolved
450  * @resolved_path:      Set to the resolved absolute path
451  *
452  * Returns the canonicalized absolute pathname.  This function is a wrapper to
453  * realpath, but will work even if the target file does not exist.  All
454  * directories in the path must exist.
455  *
456  * Return: On success, 0 is returned and resolved_path points to an allocated
457  * string containing the absolute pathname.  On error, errno is set
458  * appropriately, -errno is returned, and resolved_path points to NULL.
459  */
460 int cfs_abs_path(const char *request_path, char **resolved_path)
461 {
462         char  buf[PATH_MAX + 1] = "";
463         char *path;
464         char *ptr;
465         int len;
466         int rc = 0;
467         const char *fmt;
468
469         path = malloc(sizeof(buf));
470         if (path == NULL)
471                 return -ENOMEM;
472
473         if (request_path[0] != '/') {
474                 if (getcwd(path, sizeof(buf) - 1) == NULL) {
475                         rc = -errno;
476                         goto out;
477                 }
478                 len = snprintf(buf, sizeof(buf), "%s/%s", path, request_path);
479                 if (len >= sizeof(buf)) {
480                         rc = -ENAMETOOLONG;
481                         goto out;
482                 }
483         } else {
484                 /* skip duplicate leading '/' */
485                 len = snprintf(buf, sizeof(buf), "%s",
486                                request_path + strspn(request_path, "/") - 1);
487                 if (len >= sizeof(buf)) {
488                         rc = -ENAMETOOLONG;
489                         goto out;
490                 }
491         }
492
493         /* if filename not in root directory, call realpath for parent path */
494         ptr = strrchr(buf, '/');
495         if (ptr != buf) {
496                 *ptr = '\0';
497                 if (path != realpath(buf, path)) {
498                         rc = -errno;
499                         goto out;
500                 }
501                 /* add the filename back */
502                 len = strlen(path);
503                 fmt = (path[len - 1] == '/') ? "%s" : "/%s";
504                 len = snprintf(path + len, sizeof(buf) - len, fmt, ptr + 1);
505                 if (len >= sizeof(buf) - len) {
506                         rc = -ENAMETOOLONG;
507                         goto out;
508                 }
509         } else {
510                 len = snprintf(path, sizeof(buf), "%s", buf);
511                 if (len >= sizeof(buf)) {
512                         rc = -ENAMETOOLONG;
513                         goto out;
514                 }
515         }
516
517 out:
518         if (rc == 0) {
519                 *resolved_path = path;
520         } else {
521                 *resolved_path = NULL;
522                 free(path);
523         }
524         return rc;
525 }