Whamcloud - gitweb
LU-6142 libcfs: discard cfs_strrstr()
[fs/lustre-release.git] / libcfs / libcfs / libcfs_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  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * String manipulation functions.
33  *
34  * libcfs/libcfs/libcfs_string.c
35  *
36  * Author: Nathan Rutman <nathan.rutman@sun.com>
37  */
38
39 #include <linux/ctype.h>
40 #include <libcfs/libcfs.h>
41 #include <libcfs/libcfs_string.h>
42
43 /* Convert a text string to a bitmask */
44 int cfs_str2mask(const char *str, const char *(*bit2str)(int bit),
45                  int *oldmask, int minmask, int allmask)
46 {
47         const char *debugstr;
48         char op = 0;
49         int newmask = minmask, i, len, found = 0;
50
51         ENTRY;
52         /* <str> must be a list of tokens separated by whitespace
53          * and optionally an operator ('+' or '-').  If an operator
54          * appears first in <str>, '*oldmask' is used as the starting point
55          * (relative), otherwise minmask is used (absolute).  An operator
56          * applies to all following tokens up to the next operator.
57          */
58         while (*str != 0) {
59                 while (isspace(*str))
60                         str++;
61                 if (*str == 0)
62                         break;
63                 if (*str == '+' || *str == '-') {
64                         op = *str++;
65                         if (!found)
66                                 /* only if first token is relative */
67                                 newmask = *oldmask;
68                         while (isspace(*str))
69                                 str++;
70                         if (*str == 0)          /* trailing op */
71                                 return -EINVAL;
72                 }
73
74                 /* find token length */
75                 for (len = 0; str[len] != 0 && !isspace(str[len]) &&
76                      str[len] != '+' && str[len] != '-'; len++);
77
78                 /* match token */
79                 found = 0;
80                 for (i = 0; i < 32; i++) {
81                         debugstr = bit2str(i);
82                         if (debugstr != NULL &&
83                             strlen(debugstr) == len &&
84                             strncasecmp(str, debugstr, len) == 0) {
85                                 if (op == '-')
86                                         newmask &= ~BIT(i);
87                                 else
88                                         newmask |= BIT(i);
89                                 found = 1;
90                                 break;
91                         }
92                 }
93                 if (!found && len == 3 &&
94                     (strncasecmp(str, "ALL", len) == 0)) {
95                         if (op == '-')
96                                 newmask = minmask;
97                         else
98                                 newmask = allmask;
99                         found = 1;
100                 }
101                 if (!found) {
102                         CWARN("unknown mask '%.*s'.\n"
103                               "mask usage: [+|-]<all|type> ...\n", len, str);
104                         return -EINVAL;
105                 }
106                 str += len;
107         }
108
109         *oldmask = newmask;
110         return 0;
111 }
112 EXPORT_SYMBOL(cfs_str2mask);
113
114 /**
115  * Extracts tokens from strings.
116  *
117  * Looks for \a delim in string \a next, sets \a res to point to
118  * substring before the delimiter, sets \a next right after the found
119  * delimiter.
120  *
121  * \retval 1 if \a res points to a string of non-whitespace characters
122  * \retval 0 otherwise
123  */
124 int
125 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
126 {
127         char *end;
128
129         if (next->ls_str == NULL)
130                 return 0;
131
132         /* skip leading white spaces */
133         while (next->ls_len) {
134                 if (!isspace(*next->ls_str))
135                         break;
136                 next->ls_str++;
137                 next->ls_len--;
138         }
139
140         if (next->ls_len == 0) /* whitespaces only */
141                 return 0;
142
143         if (*next->ls_str == delim) {
144                 /* first non-writespace is the delimiter */
145                 return 0;
146         }
147
148         res->ls_str = next->ls_str;
149         end = memchr(next->ls_str, delim, next->ls_len);
150         if (end == NULL) {
151                 /* there is no the delimeter in the string */
152                 end = next->ls_str + next->ls_len;
153                 next->ls_str = NULL;
154         } else {
155                 next->ls_str = end + 1;
156                 next->ls_len -= (end - res->ls_str + 1);
157         }
158
159         /* skip ending whitespaces */
160         while (--end != res->ls_str) {
161                 if (!isspace(*end))
162                         break;
163         }
164
165         res->ls_len = end - res->ls_str + 1;
166         return 1;
167 }
168 EXPORT_SYMBOL(cfs_gettok);
169
170 /**
171  * Converts string to integer.
172  *
173  * Accepts decimal and hexadecimal number recordings.
174  *
175  * \retval 1 if first \a nob chars of \a str convert to decimal or
176  * hexadecimal integer in the range [\a min, \a max]
177  * \retval 0 otherwise
178  */
179 int
180 cfs_str2num_check(char *str, int nob, unsigned *num,
181                   unsigned min, unsigned max)
182 {
183         bool all_numbers = true;
184         char *endp, cache;
185         int len;
186         int rc;
187
188         endp = strim(str);
189         /**
190          * kstrouint can only handle strings composed
191          * of only numbers. We need to scan the string
192          * passed in for the first non-digit character
193          * and end the string at that location. If we
194          * don't find any non-digit character we still
195          * need to place a '\0' at position len since
196          * we are not interested in the rest of the
197          * string which is longer than len in size.
198          * After we are done the character at the
199          * position we placed '\0' must be restored.
200          */
201         len = min((int)strlen(endp), nob);
202         for (; endp < str + len; endp++) {
203                 if (!isxdigit(*endp) && *endp != '-' &&
204                     *endp != '+') {
205                         all_numbers = false;
206                         break;
207                 }
208         }
209
210         /* Eat trailing space */
211         if (!all_numbers && isspace(*endp)) {
212                 all_numbers = true;
213                 endp--;
214         }
215
216         cache = *endp;
217         *endp = '\0';
218
219         rc = kstrtouint(str, 0, num);
220         *endp = cache;
221         if (rc || !all_numbers)
222                 return 0;
223
224         return (*num >= min && *num <= max);
225 }
226 EXPORT_SYMBOL(cfs_str2num_check);
227
228 /**
229  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
230  * \a src should only have a single token which can be \<number\> or  \*
231  *
232  * \retval pointer to allocated range_expr and initialized
233  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
234  `* src parses to
235  * \<number\> |
236  * \<number\> '-' \<number\> |
237  * \<number\> '-' \<number\> '/' \<number\>
238  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
239  * -ENOMEM will be returned.
240  */
241 static int
242 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
243                      int bracketed, struct cfs_range_expr **expr)
244 {
245         struct cfs_range_expr *re;
246         struct cfs_lstr tok;
247
248         LIBCFS_ALLOC(re, sizeof(*re));
249         if (re == NULL)
250                 return -ENOMEM;
251
252         if (src->ls_len == 1 && src->ls_str[0] == '*') {
253                 re->re_lo = min;
254                 re->re_hi = max;
255                 re->re_stride = 1;
256                 goto out;
257         }
258
259         if (cfs_str2num_check(src->ls_str, src->ls_len,
260                               &re->re_lo, min, max)) {
261                 /* <number> is parsed */
262                 re->re_hi = re->re_lo;
263                 re->re_stride = 1;
264                 goto out;
265         }
266
267         if (!bracketed || !cfs_gettok(src, '-', &tok))
268                 goto failed;
269
270         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
271                                &re->re_lo, min, max))
272                 goto failed;
273
274         /* <number> - */
275         if (cfs_str2num_check(src->ls_str, src->ls_len,
276                               &re->re_hi, min, max)) {
277                 /* <number> - <number> is parsed */
278                 re->re_stride = 1;
279                 goto out;
280         }
281
282         /* go to check <number> '-' <number> '/' <number> */
283         if (cfs_gettok(src, '/', &tok)) {
284                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
285                                        &re->re_hi, min, max))
286                         goto failed;
287
288                 /* <number> - <number> / ... */
289                 if (cfs_str2num_check(src->ls_str, src->ls_len,
290                                       &re->re_stride, min, max)) {
291                         /* <number> - <number> / <number> is parsed */
292                         goto out;
293                 }
294         }
295
296 out:
297         *expr = re;
298         return 0;
299
300 failed:
301         LIBCFS_FREE(re, sizeof(*re));
302         return -EINVAL;
303 }
304
305 /**
306  * Print the range expression \a re into specified \a buffer.
307  * If \a bracketed is true, expression does not need additional
308  * brackets.
309  *
310  * \retval number of characters written
311  */
312 static int
313 cfs_range_expr_print(char *buffer, int count, struct cfs_range_expr *expr,
314                      bool bracketed)
315 {
316         int i;
317         char s[] = "[";
318         char e[] = "]";
319
320         if (bracketed)
321                 s[0] = e[0] = '\0';
322
323         if (expr->re_lo == expr->re_hi)
324                 i = scnprintf(buffer, count, "%u", expr->re_lo);
325         else if (expr->re_stride == 1)
326                 i = scnprintf(buffer, count, "%s%u-%u%s",
327                               s, expr->re_lo, expr->re_hi, e);
328         else
329                 i = scnprintf(buffer, count, "%s%u-%u/%u%s",
330                               s, expr->re_lo, expr->re_hi,
331                               expr->re_stride, e);
332         return i;
333 }
334
335 /**
336  * Print a list of range expressions (\a expr_list) into specified \a buffer.
337  * If the list contains several expressions, separate them with comma
338  * and surround the list with brackets.
339  *
340  * \retval number of characters written
341  */
342 int
343 cfs_expr_list_print(char *buffer, int count, struct cfs_expr_list *expr_list)
344 {
345         struct cfs_range_expr *expr;
346         int i = 0, j = 0;
347         int numexprs = 0;
348
349         if (count <= 0)
350                 return 0;
351
352         list_for_each_entry(expr, &expr_list->el_exprs, re_link)
353                 numexprs++;
354
355         if (numexprs > 1)
356                 i += scnprintf(buffer + i, count - i, "[");
357
358         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
359                 if (j++ != 0)
360                         i += scnprintf(buffer + i, count - i, ",");
361                 i += cfs_range_expr_print(buffer + i, count - i, expr,
362                                           numexprs > 1);
363         }
364
365         if (numexprs > 1)
366                 i += scnprintf(buffer + i, count - i, "]");
367
368         return i;
369 }
370 EXPORT_SYMBOL(cfs_expr_list_print);
371
372 /**
373  * Matches value (\a value) against ranges expression list \a expr_list.
374  *
375  * \retval 1 if \a value matches
376  * \retval 0 otherwise
377  */
378 int
379 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
380 {
381         struct cfs_range_expr *expr;
382
383         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
384                 if (value >= expr->re_lo && value <= expr->re_hi &&
385                     ((value - expr->re_lo) % expr->re_stride) == 0)
386                         return 1;
387         }
388
389         return 0;
390 }
391 EXPORT_SYMBOL(cfs_expr_list_match);
392
393 /**
394  * Convert express list (\a expr_list) to an array of all matched values
395  *
396  * \retval N N is total number of all matched values
397  * \retval 0 if expression list is empty
398  * \retval < 0 for failure
399  */
400 int
401 cfs_expr_list_values(struct cfs_expr_list *expr_list, int max, __u32 **valpp)
402 {
403         struct cfs_range_expr *expr;
404         __u32 *val;
405         int count = 0;
406         int i;
407
408         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
409                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
410                         if (((i - expr->re_lo) % expr->re_stride) == 0)
411                                 count++;
412                 }
413         }
414
415         if (count == 0) /* empty expression list */
416                 return 0;
417
418         if (count > max) {
419                 CERROR("Number of values %d exceeds max allowed %d\n",
420                        max, count);
421                 return -EINVAL;
422         }
423
424         CFS_ALLOC_PTR_ARRAY(val, count);
425         if (val == NULL)
426                 return -ENOMEM;
427
428         count = 0;
429         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
430                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
431                         if (((i - expr->re_lo) % expr->re_stride) == 0)
432                                 val[count++] = i;
433                 }
434         }
435
436         *valpp = val;
437         return count;
438 }
439 EXPORT_SYMBOL(cfs_expr_list_values);
440
441 void
442 cfs_expr_list_values_free(__u32 *values, int num)
443 {
444         /* This array is allocated by LIBCFS_ALLOC(), so it shouldn't be freed
445          * by OBD_FREE() if it's called by module other than libcfs & LNet,
446          * otherwise we will see fake memory leak */
447         CFS_FREE_PTR_ARRAY(values, num);
448 }
449 EXPORT_SYMBOL(cfs_expr_list_values_free);
450
451 /**
452  * Frees cfs_range_expr structures of \a expr_list.
453  *
454  * \retval none
455  */
456 void
457 cfs_expr_list_free(struct cfs_expr_list *expr_list)
458 {
459         while (!list_empty(&expr_list->el_exprs)) {
460                 struct cfs_range_expr *expr;
461
462                 expr = list_entry(expr_list->el_exprs.next,
463                                       struct cfs_range_expr, re_link);
464                 list_del(&expr->re_link);
465                 LIBCFS_FREE(expr, sizeof(*expr));
466         }
467
468         LIBCFS_FREE(expr_list, sizeof(*expr_list));
469 }
470 EXPORT_SYMBOL(cfs_expr_list_free);
471
472 /**
473  * Parses \<cfs_expr_list\> token of the syntax.
474  *
475  * \retval 0 if \a str parses to \<number\> | \<expr_list\>
476  * \retval -errno otherwise
477  */
478 int
479 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
480                     struct cfs_expr_list **elpp)
481 {
482         struct cfs_expr_list *expr_list;
483         struct cfs_range_expr *expr;
484         struct cfs_lstr src;
485         int rc;
486
487         LIBCFS_ALLOC(expr_list, sizeof(*expr_list));
488         if (expr_list == NULL)
489                 return -ENOMEM;
490
491         src.ls_str = str;
492         src.ls_len = len;
493
494         INIT_LIST_HEAD(&expr_list->el_exprs);
495
496         if (src.ls_str[0] == '[' &&
497             src.ls_str[src.ls_len - 1] == ']') {
498                 src.ls_str++;
499                 src.ls_len -= 2;
500
501                 rc = -EINVAL;
502                 while (src.ls_str != NULL) {
503                         struct cfs_lstr tok;
504
505                         if (!cfs_gettok(&src, ',', &tok)) {
506                                 rc = -EINVAL;
507                                 break;
508                         }
509
510                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
511                         if (rc != 0)
512                                 break;
513
514                         list_add_tail(&expr->re_link, &expr_list->el_exprs);
515                 }
516         } else {
517                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
518                 if (rc == 0)
519                         list_add_tail(&expr->re_link, &expr_list->el_exprs);
520         }
521
522         if (rc != 0)
523                 cfs_expr_list_free(expr_list);
524         else
525                 *elpp = expr_list;
526
527         return rc;
528 }
529 EXPORT_SYMBOL(cfs_expr_list_parse);
530
531 /**
532  * Frees cfs_expr_list structures of \a list.
533  *
534  * For each struct cfs_expr_list structure found on \a list it frees
535  * range_expr list attached to it and frees the cfs_expr_list itself.
536  *
537  * \retval none
538  */
539 void
540 cfs_expr_list_free_list(struct list_head *list)
541 {
542         struct cfs_expr_list *el;
543
544         while (!list_empty(list)) {
545                 el = list_entry(list->next,
546                                     struct cfs_expr_list, el_link);
547                 list_del(&el->el_link);
548                 cfs_expr_list_free(el);
549         }
550 }
551 EXPORT_SYMBOL(cfs_expr_list_free_list);