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