Whamcloud - gitweb
ebe91acb401d8f8096eb5cfd4b59aa8515371830
[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 /**
143  * cfs_{v}snprintf() return the actual size that is printed rather than
144  * the size that would be printed in standard functions.
145  */
146 /* safe vsnprintf */
147 int cfs_vsnprintf(char *buf, size_t size, const char *fmt, va_list args)
148 {
149         int i;
150
151         LASSERT(size > 0);
152         i = vsnprintf(buf, size, fmt, args);
153
154         return  (i >= size ? size - 1 : i);
155 }
156 EXPORT_SYMBOL(cfs_vsnprintf);
157
158 /* safe snprintf */
159 int cfs_snprintf(char *buf, size_t size, const char *fmt, ...)
160 {
161         va_list args;
162         int i;
163
164         va_start(args, fmt);
165         i = cfs_vsnprintf(buf, size, fmt, args);
166         va_end(args);
167
168         return  i;
169 }
170 EXPORT_SYMBOL(cfs_snprintf);
171
172 /* get the first string out of @str */
173 char *cfs_firststr(char *str, size_t size)
174 {
175         size_t i = 0;
176         char  *end;
177
178         /* trim leading spaces */
179         while (i < size && *str && isspace(*str)) {
180                 ++i;
181                 ++str;
182         }
183
184         /* string with all spaces */
185         if (*str == '\0')
186                 goto out;
187
188         end = str;
189         while (i < size && *end != '\0' && !isspace(*end)) {
190                 ++i;
191                 ++end;
192         }
193
194         *end= '\0';
195 out:
196         return str;
197 }
198 EXPORT_SYMBOL(cfs_firststr);
199
200 char *
201 cfs_trimwhite(char *str)
202 {
203         char *end;
204
205         while (isspace(*str))
206                 str++;
207
208         end = str + strlen(str);
209         while (end > str) {
210                 if (!isspace(end[-1]))
211                         break;
212                 end--;
213         }
214
215         *end = 0;
216         return str;
217 }
218 EXPORT_SYMBOL(cfs_trimwhite);
219
220 /**
221  * Extracts tokens from strings.
222  *
223  * Looks for \a delim in string \a next, sets \a res to point to
224  * substring before the delimiter, sets \a next right after the found
225  * delimiter.
226  *
227  * \retval 1 if \a res points to a string of non-whitespace characters
228  * \retval 0 otherwise
229  */
230 int
231 cfs_gettok(struct cfs_lstr *next, char delim, struct cfs_lstr *res)
232 {
233         char *end;
234
235         if (next->ls_str == NULL)
236                 return 0;
237
238         /* skip leading white spaces */
239         while (next->ls_len) {
240                 if (!isspace(*next->ls_str))
241                         break;
242                 next->ls_str++;
243                 next->ls_len--;
244         }
245
246         if (next->ls_len == 0) /* whitespaces only */
247                 return 0;
248
249         if (*next->ls_str == delim) {
250                 /* first non-writespace is the delimiter */
251                 return 0;
252         }
253
254         res->ls_str = next->ls_str;
255         end = memchr(next->ls_str, delim, next->ls_len);
256         if (end == NULL) {
257                 /* there is no the delimeter in the string */
258                 end = next->ls_str + next->ls_len;
259                 next->ls_str = NULL;
260         } else {
261                 next->ls_str = end + 1;
262                 next->ls_len -= (end - res->ls_str + 1);
263         }
264
265         /* skip ending whitespaces */
266         while (--end != res->ls_str) {
267                 if (!isspace(*end))
268                         break;
269         }
270
271         res->ls_len = end - res->ls_str + 1;
272         return 1;
273 }
274 EXPORT_SYMBOL(cfs_gettok);
275
276 /**
277  * Converts string to integer.
278  *
279  * Accepts decimal and hexadecimal number recordings.
280  *
281  * \retval 1 if first \a nob chars of \a str convert to decimal or
282  * hexadecimal integer in the range [\a min, \a max]
283  * \retval 0 otherwise
284  */
285 int
286 cfs_str2num_check(char *str, int nob, unsigned *num,
287                   unsigned min, unsigned max)
288 {
289         char    *endp;
290
291         *num = simple_strtoul(str, &endp, 0);
292         if (endp == str)
293                 return 0;
294
295         for (; endp < str + nob; endp++) {
296                 if (!isspace(*endp))
297                         return 0;
298         }
299
300         return (*num >= min && *num <= max);
301 }
302 EXPORT_SYMBOL(cfs_str2num_check);
303
304 /**
305  * Parses \<range_expr\> token of the syntax. If \a bracketed is false,
306  * \a src should only have a single token which can be \<number\> or  \*
307  *
308  * \retval pointer to allocated range_expr and initialized
309  * range_expr::re_lo, range_expr::re_hi and range_expr:re_stride if \a
310  `* src parses to
311  * \<number\> |
312  * \<number\> '-' \<number\> |
313  * \<number\> '-' \<number\> '/' \<number\>
314  * \retval 0 will be returned if it can be parsed, otherwise -EINVAL or
315  * -ENOMEM will be returned.
316  */
317 int
318 cfs_range_expr_parse(struct cfs_lstr *src, unsigned min, unsigned max,
319                      int bracketed, struct cfs_range_expr **expr)
320 {
321         struct cfs_range_expr   *re;
322         struct cfs_lstr         tok;
323
324         LIBCFS_ALLOC(re, sizeof(*re));
325         if (re == NULL)
326                 return -ENOMEM;
327
328         if (src->ls_len == 1 && src->ls_str[0] == '*') {
329                 re->re_lo = min;
330                 re->re_hi = max;
331                 re->re_stride = 1;
332                 goto out;
333         }
334
335         if (cfs_str2num_check(src->ls_str, src->ls_len,
336                               &re->re_lo, min, max)) {
337                 /* <number> is parsed */
338                 re->re_hi = re->re_lo;
339                 re->re_stride = 1;
340                 goto out;
341         }
342
343         if (!bracketed || !cfs_gettok(src, '-', &tok))
344                 goto failed;
345
346         if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
347                                &re->re_lo, min, max))
348                 goto failed;
349
350         /* <number> - */
351         if (cfs_str2num_check(src->ls_str, src->ls_len,
352                               &re->re_hi, min, max)) {
353                 /* <number> - <number> is parsed */
354                 re->re_stride = 1;
355                 goto out;
356         }
357
358         /* go to check <number> '-' <number> '/' <number> */
359         if (cfs_gettok(src, '/', &tok)) {
360                 if (!cfs_str2num_check(tok.ls_str, tok.ls_len,
361                                        &re->re_hi, min, max))
362                         goto failed;
363
364                 /* <number> - <number> / ... */
365                 if (cfs_str2num_check(src->ls_str, src->ls_len,
366                                       &re->re_stride, min, max)) {
367                         /* <number> - <number> / <number> is parsed */
368                         goto out;
369                 }
370         }
371
372  out:
373         *expr = re;
374         return 0;
375
376  failed:
377         LIBCFS_FREE(re, sizeof(*re));
378         return -EINVAL;
379 }
380 EXPORT_SYMBOL(cfs_range_expr_parse);
381
382 /**
383  * Print the range expression \a re into specified \a buffer.
384  * If \a bracketed is true, expression does not need additional
385  * brackets.
386  *
387  * \retval number of characters written
388  */
389 static int
390 cfs_range_expr_print(char *buffer, int count, struct cfs_range_expr *expr,
391                      bool bracketed)
392 {
393         int i;
394         char s[] = "[";
395         char e[] = "]";
396
397         if (bracketed)
398                 s[0] = e[0] = '\0';
399
400         if (expr->re_lo == expr->re_hi)
401                 i = cfs_snprintf(buffer, count, "%u", expr->re_lo);
402         else if (expr->re_stride == 1)
403                 i = cfs_snprintf(buffer, count, "%s%u-%u%s",
404                                   s, expr->re_lo, expr->re_hi, e);
405         else
406                 i = cfs_snprintf(buffer, count, "%s%u-%u/%u%s",
407                                   s, expr->re_lo, expr->re_hi,
408                                   expr->re_stride, e);
409         return i;
410 }
411
412 /**
413  * Print a list of range expressions (\a expr_list) into specified \a buffer.
414  * If the list contains several expressions, separate them with comma
415  * and surround the list with brackets.
416  *
417  * \retval number of characters written
418  */
419 int
420 cfs_expr_list_print(char *buffer, int count, struct cfs_expr_list *expr_list)
421 {
422         struct cfs_range_expr *expr;
423         int i = 0, j = 0;
424         int numexprs = 0;
425
426         if (count <= 0)
427                 return 0;
428
429         list_for_each_entry(expr, &expr_list->el_exprs, re_link)
430                 numexprs++;
431
432         if (numexprs > 1)
433                 i += cfs_snprintf(buffer + i, count - i, "[");
434
435         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
436                 if (j++ != 0)
437                         i += cfs_snprintf(buffer + i, count - i, ",");
438                 i += cfs_range_expr_print(buffer + i, count - i, expr,
439                                           numexprs > 1);
440         }
441
442         if (numexprs > 1)
443                 i += cfs_snprintf(buffer + i, count - i, "]");
444
445         return i;
446 }
447 EXPORT_SYMBOL(cfs_expr_list_print);
448
449 /**
450  * Matches value (\a value) against ranges expression list \a expr_list.
451  *
452  * \retval 1 if \a value matches
453  * \retval 0 otherwise
454  */
455 int
456 cfs_expr_list_match(__u32 value, struct cfs_expr_list *expr_list)
457 {
458         struct cfs_range_expr   *expr;
459
460         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
461                 if (value >= expr->re_lo && value <= expr->re_hi &&
462                     ((value - expr->re_lo) % expr->re_stride) == 0)
463                         return 1;
464         }
465
466         return 0;
467 }
468 EXPORT_SYMBOL(cfs_expr_list_match);
469
470 /**
471  * Convert express list (\a expr_list) to an array of all matched values
472  *
473  * \retval N N is total number of all matched values
474  * \retval 0 if expression list is empty
475  * \retval < 0 for failure
476  */
477 int
478 cfs_expr_list_values(struct cfs_expr_list *expr_list, int max, __u32 **valpp)
479 {
480         struct cfs_range_expr   *expr;
481         __u32                   *val;
482         int                     count = 0;
483         int                     i;
484
485         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
486                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
487                         if (((i - expr->re_lo) % expr->re_stride) == 0)
488                                 count++;
489                 }
490         }
491
492         if (count == 0) /* empty expression list */
493                 return 0;
494
495         if (count > max) {
496                 CERROR("Number of values %d exceeds max allowed %d\n",
497                        max, count);
498                 return -EINVAL;
499         }
500
501         LIBCFS_ALLOC(val, sizeof(val[0]) * count);
502         if (val == NULL)
503                 return -ENOMEM;
504
505         count = 0;
506         list_for_each_entry(expr, &expr_list->el_exprs, re_link) {
507                 for (i = expr->re_lo; i <= expr->re_hi; i++) {
508                         if (((i - expr->re_lo) % expr->re_stride) == 0)
509                                 val[count++] = i;
510                 }
511         }
512
513         *valpp = val;
514         return count;
515 }
516 EXPORT_SYMBOL(cfs_expr_list_values);
517
518 /**
519  * Frees cfs_range_expr structures of \a expr_list.
520  *
521  * \retval none
522  */
523 void
524 cfs_expr_list_free(struct cfs_expr_list *expr_list)
525 {
526         while (!list_empty(&expr_list->el_exprs)) {
527                 struct cfs_range_expr *expr;
528
529                 expr = list_entry(expr_list->el_exprs.next,
530                                       struct cfs_range_expr, re_link);
531                 list_del(&expr->re_link);
532                 LIBCFS_FREE(expr, sizeof(*expr));
533         }
534
535         LIBCFS_FREE(expr_list, sizeof(*expr_list));
536 }
537 EXPORT_SYMBOL(cfs_expr_list_free);
538
539 /**
540  * Parses \<cfs_expr_list\> token of the syntax.
541  *
542  * \retval 0 if \a str parses to \<number\> | \<expr_list\>
543  * \retval -errno otherwise
544  */
545 int
546 cfs_expr_list_parse(char *str, int len, unsigned min, unsigned max,
547                     struct cfs_expr_list **elpp)
548 {
549         struct cfs_expr_list    *expr_list;
550         struct cfs_range_expr   *expr;
551         struct cfs_lstr         src;
552         int                     rc;
553
554         LIBCFS_ALLOC(expr_list, sizeof(*expr_list));
555         if (expr_list == NULL)
556                 return -ENOMEM;
557
558         src.ls_str = str;
559         src.ls_len = len;
560
561         INIT_LIST_HEAD(&expr_list->el_exprs);
562
563         if (src.ls_str[0] == '[' &&
564             src.ls_str[src.ls_len - 1] == ']') {
565                 src.ls_str++;
566                 src.ls_len -= 2;
567
568                 rc = -EINVAL;
569                 while (src.ls_str != NULL) {
570                         struct cfs_lstr tok;
571
572                         if (!cfs_gettok(&src, ',', &tok)) {
573                                 rc = -EINVAL;
574                                 break;
575                         }
576
577                         rc = cfs_range_expr_parse(&tok, min, max, 1, &expr);
578                         if (rc != 0)
579                                 break;
580
581                         list_add_tail(&expr->re_link,
582                                           &expr_list->el_exprs);
583                 }
584         } else {
585                 rc = cfs_range_expr_parse(&src, min, max, 0, &expr);
586                 if (rc == 0) {
587                         list_add_tail(&expr->re_link,
588                                           &expr_list->el_exprs);
589                 }
590         }
591
592         if (rc != 0)
593                 cfs_expr_list_free(expr_list);
594         else
595                 *elpp = expr_list;
596
597         return rc;
598 }
599 EXPORT_SYMBOL(cfs_expr_list_parse);
600
601 /**
602  * Frees cfs_expr_list structures of \a list.
603  *
604  * For each struct cfs_expr_list structure found on \a list it frees
605  * range_expr list attached to it and frees the cfs_expr_list itself.
606  *
607  * \retval none
608  */
609 void
610 cfs_expr_list_free_list(struct list_head *list)
611 {
612         struct cfs_expr_list *el;
613
614         while (!list_empty(list)) {
615                 el = list_entry(list->next,
616                                     struct cfs_expr_list, el_link);
617                 list_del(&el->el_link);
618                 cfs_expr_list_free(el);
619         }
620 }
621 EXPORT_SYMBOL(cfs_expr_list_free_list);
622
623 int
624 cfs_ip_addr_parse(char *str, int len, struct list_head *list)
625 {
626         struct cfs_expr_list    *el;
627         struct cfs_lstr         src;
628         int                     rc;
629         int                     i;
630
631         src.ls_str = str;
632         src.ls_len = len;
633         i = 0;
634
635         while (src.ls_str != NULL) {
636                 struct cfs_lstr res;
637
638                 if (!cfs_gettok(&src, '.', &res)) {
639                         rc = -EINVAL;
640                         goto out;
641                 }
642
643                 rc = cfs_expr_list_parse(res.ls_str, res.ls_len, 0, 255, &el);
644                 if (rc != 0)
645                         goto out;
646
647                 list_add_tail(&el->el_link, list);
648                 i++;
649         }
650
651         if (i == 4)
652                 return 0;
653
654         rc = -EINVAL;
655  out:
656         cfs_expr_list_free_list(list);
657
658         return rc;
659 }
660 EXPORT_SYMBOL(cfs_ip_addr_parse);
661
662 /**
663  * Matches address (\a addr) against address set encoded in \a list.
664  *
665  * \retval 1 if \a addr matches
666  * \retval 0 otherwise
667  */
668 int
669 cfs_ip_addr_match(__u32 addr, struct list_head *list)
670 {
671         struct cfs_expr_list *el;
672         int i = 0;
673
674         list_for_each_entry_reverse(el, list, el_link) {
675                 if (!cfs_expr_list_match(addr & 0xff, el))
676                         return 0;
677                 addr >>= 8;
678                 i++;
679         }
680
681         return i == 4;
682 }
683 EXPORT_SYMBOL(cfs_ip_addr_match);