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