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