Whamcloud - gitweb
LU-4629 libcfs: fix buffer overflow of string buffer
[fs/lustre-release.git] / lnet / lnet / config.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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, 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
37 #define DEBUG_SUBSYSTEM S_LNET
38 #include <lnet/lib-lnet.h>
39
40 /* tmp struct for parsing routes */
41 struct lnet_text_buf {
42         struct list_head        ltb_list;       /* stash on lists */
43         int                     ltb_size;       /* allocated size */
44         char                    ltb_text[0];    /* text buffer */
45 };
46
47 static int lnet_tbnob = 0;                      /* track text buf allocation */
48 #define LNET_MAX_TEXTBUF_NOB     (64<<10)       /* bound allocation */
49 #define LNET_SINGLE_TEXTBUF_NOB  (4<<10)
50
51 void
52 lnet_syntax(char *name, char *str, int offset, int width)
53 {
54         static char dots[LNET_SINGLE_TEXTBUF_NOB];
55         static char dashes[LNET_SINGLE_TEXTBUF_NOB];
56
57         memset(dots, '.', sizeof(dots));
58         dots[sizeof(dots)-1] = 0;
59         memset(dashes, '-', sizeof(dashes));
60         dashes[sizeof(dashes)-1] = 0;
61
62         LCONSOLE_ERROR_MSG(0x10f, "Error parsing '%s=\"%s\"'\n", name, str);
63         LCONSOLE_ERROR_MSG(0x110, "here...........%.*s..%.*s|%.*s|\n",
64                            (int)strlen(name), dots, offset, dots,
65                             (width < 1) ? 0 : width - 1, dashes);
66 }
67
68 int
69 lnet_issep (char c)
70 {
71         switch (c) {
72         case '\n':
73         case '\r':
74         case ';':
75                 return 1;
76         default:
77                 return 0;
78         }
79 }
80
81 int
82 lnet_net_unique(__u32 net, struct list_head *nilist)
83 {
84         struct list_head *tmp;
85         lnet_ni_t        *ni;
86
87         list_for_each(tmp, nilist) {
88                 ni = list_entry(tmp, lnet_ni_t, ni_list);
89
90                 if (LNET_NIDNET(ni->ni_nid) == net)
91                         return 0;
92         }
93
94         return 1;
95 }
96
97 void
98 lnet_ni_free(struct lnet_ni *ni)
99 {
100         if (ni->ni_refs != NULL)
101                 cfs_percpt_free(ni->ni_refs);
102
103         if (ni->ni_tx_queues != NULL)
104                 cfs_percpt_free(ni->ni_tx_queues);
105
106         if (ni->ni_cpts != NULL)
107                 cfs_expr_list_values_free(ni->ni_cpts, ni->ni_ncpts);
108
109 #ifndef __KERNEL__
110 # ifdef HAVE_LIBPTHREAD
111         pthread_mutex_destroy(&ni->ni_lock);
112 # endif
113 #endif
114         LIBCFS_FREE(ni, sizeof(*ni));
115 }
116
117 lnet_ni_t *
118 lnet_ni_alloc(__u32 net, struct cfs_expr_list *el, struct list_head *nilist)
119 {
120         struct lnet_tx_queue    *tq;
121         struct lnet_ni          *ni;
122         int                     rc;
123         int                     i;
124
125         if (!lnet_net_unique(net, nilist)) {
126                 LCONSOLE_ERROR_MSG(0x111, "Duplicate network specified: %s\n",
127                                    libcfs_net2str(net));
128                 return NULL;
129         }
130
131         LIBCFS_ALLOC(ni, sizeof(*ni));
132         if (ni == NULL) {
133                 CERROR("Out of memory creating network %s\n",
134                        libcfs_net2str(net));
135                 return NULL;
136         }
137
138 #ifdef __KERNEL__
139         spin_lock_init(&ni->ni_lock);
140 #else
141 # ifdef HAVE_LIBPTHREAD
142         pthread_mutex_init(&ni->ni_lock, NULL);
143 # endif
144 #endif
145         INIT_LIST_HEAD(&ni->ni_cptlist);
146         ni->ni_refs = cfs_percpt_alloc(lnet_cpt_table(),
147                                        sizeof(*ni->ni_refs[0]));
148         if (ni->ni_refs == NULL)
149                 goto failed;
150
151         ni->ni_tx_queues = cfs_percpt_alloc(lnet_cpt_table(),
152                                             sizeof(*ni->ni_tx_queues[0]));
153         if (ni->ni_tx_queues == NULL)
154                 goto failed;
155
156         cfs_percpt_for_each(tq, i, ni->ni_tx_queues)
157                 INIT_LIST_HEAD(&tq->tq_delayed);
158
159         if (el == NULL) {
160                 ni->ni_cpts  = NULL;
161                 ni->ni_ncpts = LNET_CPT_NUMBER;
162         } else {
163                 rc = cfs_expr_list_values(el, LNET_CPT_NUMBER, &ni->ni_cpts);
164                 if (rc <= 0) {
165                         CERROR("Failed to set CPTs for NI %s: %d\n",
166                                libcfs_net2str(net), rc);
167                         goto failed;
168                 }
169
170                 LASSERT(rc <= LNET_CPT_NUMBER);
171                 if (rc == LNET_CPT_NUMBER) {
172                         LIBCFS_FREE(ni->ni_cpts, rc * sizeof(ni->ni_cpts[0]));
173                         ni->ni_cpts = NULL;
174                 }
175
176                 ni->ni_ncpts = rc;
177         }
178
179         /* LND will fill in the address part of the NID */
180         ni->ni_nid = LNET_MKNID(net, 0);
181         ni->ni_last_alive = cfs_time_current_sec();
182         list_add_tail(&ni->ni_list, nilist);
183         return ni;
184  failed:
185         lnet_ni_free(ni);
186         return NULL;
187 }
188
189 int
190 lnet_parse_networks(struct list_head *nilist, char *networks)
191 {
192         struct cfs_expr_list *el = NULL;
193         int             tokensize = strlen(networks) + 1;
194         char            *tokens;
195         char            *str;
196         char            *tmp;
197         struct lnet_ni  *ni;
198         __u32           net;
199         int             nnets = 0;
200
201         if (strlen(networks) > LNET_SINGLE_TEXTBUF_NOB) {
202                 /* _WAY_ conservative */
203                 LCONSOLE_ERROR_MSG(0x112, "Can't parse networks: string too "
204                                    "long\n");
205                 return -EINVAL;
206         }
207
208         LIBCFS_ALLOC(tokens, tokensize);
209         if (tokens == NULL) {
210                 CERROR("Can't allocate net tokens\n");
211                 return -ENOMEM;
212         }
213
214         the_lnet.ln_network_tokens = tokens;
215         the_lnet.ln_network_tokens_nob = tokensize;
216         memcpy (tokens, networks, tokensize);
217         str = tmp = tokens;
218
219         /* Add in the loopback network */
220         ni = lnet_ni_alloc(LNET_MKNET(LOLND, 0), NULL, nilist);
221         if (ni == NULL)
222                 goto failed;
223
224         while (str != NULL && *str != 0) {
225                 char    *comma = strchr(str, ',');
226                 char    *bracket = strchr(str, '(');
227                 char    *square = strchr(str, '[');
228                 char    *iface;
229                 int     niface;
230                 int     rc;
231
232                 /* NB we don't check interface conflicts here; it's the LNDs
233                  * responsibility (if it cares at all) */
234
235                 if (square != NULL && (comma == NULL || square < comma)) {
236                         /* i.e: o2ib0(ib0)[1,2], number between square
237                          * brackets are CPTs this NI needs to be bond */
238                         if (bracket != NULL && bracket > square) {
239                                 tmp = square;
240                                 goto failed_syntax;
241                         }
242
243                         tmp = strchr(square, ']');
244                         if (tmp == NULL) {
245                                 tmp = square;
246                                 goto failed_syntax;
247                         }
248
249                         rc = cfs_expr_list_parse(square, tmp - square + 1,
250                                                  0, LNET_CPT_NUMBER - 1, &el);
251                         if (rc != 0) {
252                                 tmp = square;
253                                 goto failed_syntax;
254                         }
255
256                         while (square <= tmp)
257                                 *square++ = ' ';
258                 }
259
260                 if (bracket == NULL ||
261                     (comma != NULL && comma < bracket)) {
262
263                         /* no interface list specified */
264
265                         if (comma != NULL)
266                                 *comma++ = 0;
267                         net = libcfs_str2net(cfs_trimwhite(str));
268
269                         if (net == LNET_NIDNET(LNET_NID_ANY)) {
270                                 LCONSOLE_ERROR_MSG(0x113, "Unrecognised network"
271                                                    " type\n");
272                                 tmp = str;
273                                 goto failed_syntax;
274                         }
275
276                         if (LNET_NETTYP(net) != LOLND && /* LO is implicit */
277                             lnet_ni_alloc(net, el, nilist) == NULL)
278                                 goto failed;
279
280                         if (el != NULL) {
281                                 cfs_expr_list_free(el);
282                                 el = NULL;
283                         }
284
285                         str = comma;
286                         continue;
287                 }
288
289                 *bracket = 0;
290                 net = libcfs_str2net(cfs_trimwhite(str));
291                 if (net == LNET_NIDNET(LNET_NID_ANY)) {
292                         tmp = str;
293                         goto failed_syntax;
294                 }
295
296                 nnets++;
297                 ni = lnet_ni_alloc(net, el, nilist);
298                 if (ni == NULL)
299                         goto failed;
300
301                 if (el != NULL) {
302                         cfs_expr_list_free(el);
303                         el = NULL;
304                 }
305
306                 niface = 0;
307                 iface = bracket + 1;
308
309                 bracket = strchr(iface, ')');
310                 if (bracket == NULL) {
311                         tmp = iface;
312                         goto failed_syntax;
313                 }
314
315                 *bracket = 0;
316                 do {
317                         comma = strchr(iface, ',');
318                         if (comma != NULL)
319                                 *comma++ = 0;
320
321                         iface = cfs_trimwhite(iface);
322                         if (*iface == 0) {
323                                 tmp = iface;
324                                 goto failed_syntax;
325                         }
326
327                         if (niface == LNET_MAX_INTERFACES) {
328                                 LCONSOLE_ERROR_MSG(0x115, "Too many interfaces "
329                                                    "for net %s\n",
330                                                    libcfs_net2str(net));
331                                 goto failed;
332                         }
333
334                         ni->ni_interfaces[niface++] = iface;
335                         iface = comma;
336                 } while (iface != NULL);
337
338                 str = bracket + 1;
339                 comma = strchr(bracket + 1, ',');
340                 if (comma != NULL) {
341                         *comma = 0;
342                         str = cfs_trimwhite(str);
343                         if (*str != 0) {
344                                 tmp = str;
345                                 goto failed_syntax;
346                         }
347                         str = comma + 1;
348                         continue;
349                 }
350
351                 str = cfs_trimwhite(str);
352                 if (*str != 0) {
353                         tmp = str;
354                         goto failed_syntax;
355                 }
356         }
357
358         LASSERT(!list_empty(nilist));
359         return 0;
360
361  failed_syntax:
362         lnet_syntax("networks", networks, (int)(tmp - tokens), strlen(tmp));
363  failed:
364         while (!list_empty(nilist)) {
365                 ni = list_entry(nilist->next, lnet_ni_t, ni_list);
366
367                 list_del(&ni->ni_list);
368                 lnet_ni_free(ni);
369         }
370
371         if (el != NULL)
372                 cfs_expr_list_free(el);
373
374         LIBCFS_FREE(tokens, tokensize);
375         the_lnet.ln_network_tokens = NULL;
376
377         return -EINVAL;
378 }
379
380 struct lnet_text_buf *lnet_new_text_buf(int str_len)
381 {
382         struct lnet_text_buf *ltb;
383         int nob;
384
385         /* NB allocate space for the terminating 0 */
386         nob = offsetof(struct lnet_text_buf, ltb_text[str_len + 1]);
387         if (nob > LNET_SINGLE_TEXTBUF_NOB) {
388                 /* _way_ conservative for "route net gateway..." */
389                 CERROR("text buffer too big\n");
390                 return NULL;
391         }
392
393         if (lnet_tbnob + nob > LNET_MAX_TEXTBUF_NOB) {
394                 CERROR("Too many text buffers\n");
395                 return NULL;
396         }
397
398         LIBCFS_ALLOC(ltb, nob);
399         if (ltb == NULL)
400                 return NULL;
401
402         ltb->ltb_size = nob;
403         ltb->ltb_text[0] = 0;
404         lnet_tbnob += nob;
405         return ltb;
406 }
407
408 void
409 lnet_free_text_buf(struct lnet_text_buf *ltb)
410 {
411         lnet_tbnob -= ltb->ltb_size;
412         LIBCFS_FREE(ltb, ltb->ltb_size);
413 }
414
415 void
416 lnet_free_text_bufs(struct list_head *tbs)
417 {
418         struct lnet_text_buf  *ltb;
419
420         while (!list_empty(tbs)) {
421                 ltb = list_entry(tbs->next, struct lnet_text_buf, ltb_list);
422
423                 list_del(&ltb->ltb_list);
424                 lnet_free_text_buf(ltb);
425         }
426 }
427
428 void
429 lnet_print_text_bufs(struct list_head *tbs)
430 {
431         struct list_head *tmp;
432         struct lnet_text_buf  *ltb;
433
434         list_for_each(tmp, tbs) {
435                 ltb = list_entry(tmp, struct lnet_text_buf, ltb_list);
436
437                 CDEBUG(D_WARNING, "%s\n", ltb->ltb_text);
438         }
439
440         CDEBUG(D_WARNING, "%d allocated\n", lnet_tbnob);
441 }
442
443 int
444 lnet_str2tbs_sep(struct list_head *tbs, char *str)
445 {
446         struct list_head  pending;
447         char             *sep;
448         int               nob;
449         int               i;
450         struct lnet_text_buf  *ltb;
451
452         INIT_LIST_HEAD(&pending);
453
454         /* Split 'str' into separate commands */
455         for (;;) {
456                 /* skip leading whitespace */
457                 while (cfs_iswhite(*str))
458                         str++;
459
460                 /* scan for separator or comment */
461                 for (sep = str; *sep != 0; sep++)
462                         if (lnet_issep(*sep) || *sep == '#')
463                                 break;
464
465                 nob = (int)(sep - str);
466                 if (nob > 0) {
467                         ltb = lnet_new_text_buf(nob);
468                         if (ltb == NULL) {
469                                 lnet_free_text_bufs(&pending);
470                                 return -1;
471                         }
472
473                         for (i = 0; i < nob; i++)
474                                 if (cfs_iswhite(str[i]))
475                                         ltb->ltb_text[i] = ' ';
476                                 else
477                                         ltb->ltb_text[i] = str[i];
478
479                         ltb->ltb_text[nob] = 0;
480
481                         list_add_tail(&ltb->ltb_list, &pending);
482                 }
483
484                 if (*sep == '#') {
485                         /* scan for separator */
486                         do {
487                                 sep++;
488                         } while (*sep != 0 && !lnet_issep(*sep));
489                 }
490
491                 if (*sep == 0)
492                         break;
493
494                 str = sep + 1;
495         }
496
497         list_splice(&pending, tbs->prev);
498         return 0;
499 }
500
501 int
502 lnet_expand1tb(struct list_head *list,
503                char *str, char *sep1, char *sep2,
504                char *item, int itemlen)
505 {
506         int              len1 = (int)(sep1 - str);
507         int              len2 = strlen(sep2 + 1);
508         struct lnet_text_buf *ltb;
509
510         LASSERT (*sep1 == '[');
511         LASSERT (*sep2 == ']');
512
513         ltb = lnet_new_text_buf(len1 + itemlen + len2);
514         if (ltb == NULL)
515                 return -ENOMEM;
516
517         memcpy(ltb->ltb_text, str, len1);
518         memcpy(&ltb->ltb_text[len1], item, itemlen);
519         memcpy(&ltb->ltb_text[len1+itemlen], sep2 + 1, len2);
520         ltb->ltb_text[len1 + itemlen + len2] = 0;
521
522         list_add_tail(&ltb->ltb_list, list);
523         return 0;
524 }
525
526 int
527 lnet_str2tbs_expand(struct list_head *tbs, char *str)
528 {
529         char              num[16];
530         struct list_head  pending;
531         char             *sep;
532         char             *sep2;
533         char             *parsed;
534         char             *enditem;
535         int               lo;
536         int               hi;
537         int               stride;
538         int               i;
539         int               nob;
540         int               scanned;
541
542         INIT_LIST_HEAD(&pending);
543
544         sep = strchr(str, '[');
545         if (sep == NULL)                        /* nothing to expand */
546                 return 0;
547
548         sep2 = strchr(sep, ']');
549         if (sep2 == NULL)
550                 goto failed;
551
552         for (parsed = sep; parsed < sep2; parsed = enditem) {
553
554                 enditem = ++parsed;
555                 while (enditem < sep2 && *enditem != ',')
556                         enditem++;
557
558                 if (enditem == parsed)          /* no empty items */
559                         goto failed;
560
561                 if (sscanf(parsed, "%d-%d/%d%n", &lo, &hi, &stride, &scanned) < 3) {
562
563                         if (sscanf(parsed, "%d-%d%n", &lo, &hi, &scanned) < 2) {
564
565                                 /* simple string enumeration */
566                                 if (lnet_expand1tb(&pending, str, sep, sep2,
567                                                    parsed, (int)(enditem - parsed)) != 0)
568                                         goto failed;
569
570                                 continue;
571                         }
572
573                         stride = 1;
574                 }
575
576                 /* range expansion */
577
578                 if (enditem != parsed + scanned) /* no trailing junk */
579                         goto failed;
580
581                 if (hi < 0 || lo < 0 || stride < 0 || hi < lo ||
582                     (hi - lo) % stride != 0)
583                         goto failed;
584
585                 for (i = lo; i <= hi; i += stride) {
586
587                         snprintf(num, sizeof(num), "%d", i);
588                         nob = strlen(num);
589                         if (nob + 1 == sizeof(num))
590                                 goto failed;
591
592                         if (lnet_expand1tb(&pending, str, sep, sep2,
593                                            num, nob) != 0)
594                                 goto failed;
595                 }
596         }
597
598         list_splice(&pending, tbs->prev);
599         return 1;
600
601  failed:
602         lnet_free_text_bufs(&pending);
603         return -1;
604 }
605
606 int
607 lnet_parse_hops (char *str, unsigned int *hops)
608 {
609         int     len = strlen(str);
610         int     nob = len;
611
612         return (sscanf(str, "%u%n", hops, &nob) >= 1 &&
613                 nob == len &&
614                 *hops > 0 && *hops < 256);
615 }
616
617 #define LNET_PRIORITY_SEPARATOR (':')
618
619 int
620 lnet_parse_priority(char *str, unsigned int *priority, char **token)
621 {
622         int   nob;
623         char *sep;
624         int   len;
625
626         sep = strchr(str, LNET_PRIORITY_SEPARATOR);
627         if (sep == NULL) {
628                 *priority = 0;
629                 return 0;
630         }
631         len = strlen(sep + 1);
632
633         if ((sscanf((sep+1), "%u%n", priority, &nob) < 1) || (len != nob)) {
634                 /* Update the caller's token pointer so it treats the found
635                    priority as the token to report in the error message. */
636                 *token += sep - str + 1;
637                 return -1;
638         }
639
640         CDEBUG(D_NET, "gateway %s, priority %d, nob %d\n", str, *priority, nob);
641
642         /*
643          * Change priority separator to \0 to be able to parse NID
644          */
645         *sep = '\0';
646         return 0;
647 }
648
649 int
650 lnet_parse_route (char *str, int *im_a_router)
651 {
652         /* static scratch buffer OK (single threaded) */
653         static char       cmd[LNET_SINGLE_TEXTBUF_NOB];
654
655         struct list_head  nets;
656         struct list_head  gateways;
657         struct list_head *tmp1;
658         struct list_head *tmp2;
659         __u32             net;
660         lnet_nid_t        nid;
661         struct lnet_text_buf  *ltb;
662         int               rc;
663         char             *sep;
664         char             *token = str;
665         int               ntokens = 0;
666         int               myrc = -1;
667         unsigned int      hops;
668         int               got_hops = 0;
669         unsigned int      priority = 0;
670
671         INIT_LIST_HEAD(&gateways);
672         INIT_LIST_HEAD(&nets);
673
674         /* save a copy of the string for error messages */
675         strncpy(cmd, str, sizeof(cmd));
676         cmd[sizeof(cmd) - 1] = '\0';
677
678         sep = str;
679         for (;;) {
680                 /* scan for token start */
681                 while (cfs_iswhite(*sep))
682                         sep++;
683                 if (*sep == 0) {
684                         if (ntokens < (got_hops ? 3 : 2))
685                                 goto token_error;
686                         break;
687                 }
688
689                 ntokens++;
690                 token = sep++;
691
692                 /* scan for token end */
693                 while (*sep != 0 && !cfs_iswhite(*sep))
694                         sep++;
695                 if (*sep != 0)
696                         *sep++ = 0;
697
698                 if (ntokens == 1) {
699                         tmp2 = &nets;           /* expanding nets */
700                 } else if (ntokens == 2 &&
701                            lnet_parse_hops(token, &hops)) {
702                         got_hops = 1;           /* got a hop count */
703                         continue;
704                 } else {
705                         tmp2 = &gateways;       /* expanding gateways */
706                 }
707
708                 ltb = lnet_new_text_buf(strlen(token));
709                 if (ltb == NULL)
710                         goto out;
711
712                 strcpy(ltb->ltb_text, token);
713                 tmp1 = &ltb->ltb_list;
714                 list_add_tail(tmp1, tmp2);
715
716                 while (tmp1 != tmp2) {
717                         ltb = list_entry(tmp1, struct lnet_text_buf, ltb_list);
718
719                         rc = lnet_str2tbs_expand(tmp1->next, ltb->ltb_text);
720                         if (rc < 0)
721                                 goto token_error;
722
723                         tmp1 = tmp1->next;
724
725                         if (rc > 0) {           /* expanded! */
726                                 list_del(&ltb->ltb_list);
727                                 lnet_free_text_buf(ltb);
728                                 continue;
729                         }
730
731                         if (ntokens == 1) {
732                                 net = libcfs_str2net(ltb->ltb_text);
733                                 if (net == LNET_NIDNET(LNET_NID_ANY) ||
734                                     LNET_NETTYP(net) == LOLND)
735                                         goto token_error;
736                         } else {
737                                 rc = lnet_parse_priority(ltb->ltb_text,
738                                                          &priority, &token);
739                                 if (rc < 0)
740                                         goto token_error;
741
742                                 nid = libcfs_str2nid(ltb->ltb_text);
743                                 if (nid == LNET_NID_ANY ||
744                                     LNET_NETTYP(LNET_NIDNET(nid)) == LOLND)
745                                         goto token_error;
746                         }
747                 }
748         }
749
750         if (!got_hops)
751                 hops = 1;
752
753         LASSERT(!list_empty(&nets));
754         LASSERT(!list_empty(&gateways));
755
756         list_for_each(tmp1, &nets) {
757                 ltb = list_entry(tmp1, struct lnet_text_buf, ltb_list);
758                 net = libcfs_str2net(ltb->ltb_text);
759                 LASSERT (net != LNET_NIDNET(LNET_NID_ANY));
760
761                 list_for_each(tmp2, &gateways) {
762                         ltb = list_entry(tmp2, struct lnet_text_buf, ltb_list);
763                         nid = libcfs_str2nid(ltb->ltb_text);
764                         LASSERT(nid != LNET_NID_ANY);
765
766                         if (lnet_islocalnid(nid)) {
767                                 *im_a_router = 1;
768                                 continue;
769                         }
770
771                         rc = lnet_add_route(net, hops, nid, priority);
772                         if (rc != 0) {
773                                 CERROR("Can't create route "
774                                        "to %s via %s\n",
775                                        libcfs_net2str(net),
776                                        libcfs_nid2str(nid));
777                                 goto out;
778                         }
779                 }
780         }
781
782         myrc = 0;
783         goto out;
784
785  token_error:
786         lnet_syntax("routes", cmd, (int)(token - str), strlen(token));
787  out:
788         lnet_free_text_bufs(&nets);
789         lnet_free_text_bufs(&gateways);
790         return myrc;
791 }
792
793 int
794 lnet_parse_route_tbs(struct list_head *tbs, int *im_a_router)
795 {
796         struct lnet_text_buf   *ltb;
797
798         while (!list_empty(tbs)) {
799                 ltb = list_entry(tbs->next, struct lnet_text_buf, ltb_list);
800
801                 if (lnet_parse_route(ltb->ltb_text, im_a_router) < 0) {
802                         lnet_free_text_bufs(tbs);
803                         return -EINVAL;
804                 }
805
806                 list_del(&ltb->ltb_list);
807                 lnet_free_text_buf(ltb);
808         }
809
810         return 0;
811 }
812
813 int
814 lnet_parse_routes (char *routes, int *im_a_router)
815 {
816         struct list_head tbs;
817         int              rc = 0;
818
819         *im_a_router = 0;
820
821         INIT_LIST_HEAD(&tbs);
822
823         if (lnet_str2tbs_sep(&tbs, routes) < 0) {
824                 CERROR("Error parsing routes\n");
825                 rc = -EINVAL;
826         } else {
827                 rc = lnet_parse_route_tbs(&tbs, im_a_router);
828         }
829
830         LASSERT (lnet_tbnob == 0);
831         return rc;
832 }
833
834 int
835 lnet_match_network_token(char *token, int len, __u32 *ipaddrs, int nip)
836 {
837         struct list_head list = LIST_HEAD_INIT(list);
838         int             rc;
839         int             i;
840
841         rc = cfs_ip_addr_parse(token, len, &list);
842         if (rc != 0)
843                 return rc;
844
845         for (rc = i = 0; !rc && i < nip; i++)
846                 rc = cfs_ip_addr_match(ipaddrs[i], &list);
847
848         cfs_ip_addr_free(&list);
849
850         return rc;
851 }
852
853 int
854 lnet_match_network_tokens(char *net_entry, __u32 *ipaddrs, int nip)
855 {
856         static char tokens[LNET_SINGLE_TEXTBUF_NOB];
857
858         int   matched = 0;
859         int   ntokens = 0;
860         int   len;
861         char *net = NULL;
862         char *sep;
863         char *token;
864         int   rc;
865
866         LASSERT (strlen(net_entry) < sizeof(tokens));
867
868         /* work on a copy of the string */
869         strcpy(tokens, net_entry);
870         sep = tokens;
871         for (;;) {
872                 /* scan for token start */
873                 while (cfs_iswhite(*sep))
874                         sep++;
875                 if (*sep == 0)
876                         break;
877
878                 token = sep++;
879
880                 /* scan for token end */
881                 while (*sep != 0 && !cfs_iswhite(*sep))
882                         sep++;
883                 if (*sep != 0)
884                         *sep++ = 0;
885
886                 if (ntokens++ == 0) {
887                         net = token;
888                         continue;
889                 }
890
891                 len = strlen(token);
892
893                 rc = lnet_match_network_token(token, len, ipaddrs, nip);
894                 if (rc < 0) {
895                         lnet_syntax("ip2nets", net_entry,
896                                     (int)(token - tokens), len);
897                         return rc;
898                 }
899
900                 matched |= (rc != 0);
901         }
902
903         if (!matched)
904                 return 0;
905
906         strcpy(net_entry, net);                 /* replace with matched net */
907         return 1;
908 }
909
910 __u32
911 lnet_netspec2net(char *netspec)
912 {
913         char   *bracket = strchr(netspec, '(');
914         __u32   net;
915
916         if (bracket != NULL)
917                 *bracket = 0;
918
919         net = libcfs_str2net(netspec);
920
921         if (bracket != NULL)
922                 *bracket = '(';
923
924         return net;
925 }
926
927 int
928 lnet_splitnets(char *source, struct list_head *nets)
929 {
930         int               offset = 0;
931         int               offset2;
932         int               len;
933         struct lnet_text_buf  *tb;
934         struct lnet_text_buf  *tb2;
935         struct list_head *t;
936         char             *sep;
937         char             *bracket;
938         __u32             net;
939
940         LASSERT(!list_empty(nets));
941         LASSERT(nets->next == nets->prev);      /* single entry */
942
943         tb = list_entry(nets->next, struct lnet_text_buf, ltb_list);
944
945         for (;;) {
946                 sep = strchr(tb->ltb_text, ',');
947                 bracket = strchr(tb->ltb_text, '(');
948
949                 if (sep != NULL &&
950                     bracket != NULL &&
951                     bracket < sep) {
952                         /* netspec lists interfaces... */
953
954                         offset2 = offset + (int)(bracket - tb->ltb_text);
955                         len = strlen(bracket);
956
957                         bracket = strchr(bracket + 1, ')');
958
959                         if (bracket == NULL ||
960                             !(bracket[1] == ',' || bracket[1] == 0)) {
961                                 lnet_syntax("ip2nets", source, offset2, len);
962                                 return -EINVAL;
963                         }
964
965                         sep = (bracket[1] == 0) ? NULL : bracket + 1;
966                 }
967
968                 if (sep != NULL)
969                         *sep++ = 0;
970
971                 net = lnet_netspec2net(tb->ltb_text);
972                 if (net == LNET_NIDNET(LNET_NID_ANY)) {
973                         lnet_syntax("ip2nets", source, offset,
974                                     strlen(tb->ltb_text));
975                         return -EINVAL;
976                 }
977
978                 list_for_each(t, nets) {
979                         tb2 = list_entry(t, struct lnet_text_buf, ltb_list);
980
981                         if (tb2 == tb)
982                                 continue;
983
984                         if (net == lnet_netspec2net(tb2->ltb_text)) {
985                                 /* duplicate network */
986                                 lnet_syntax("ip2nets", source, offset,
987                                             strlen(tb->ltb_text));
988                                 return -EINVAL;
989                         }
990                 }
991
992                 if (sep == NULL)
993                         return 0;
994
995                 offset += (int)(sep - tb->ltb_text);
996                 len = strlen(sep);
997                 tb2 = lnet_new_text_buf(len);
998                 if (tb2 == NULL)
999                         return -ENOMEM;
1000
1001                 strncpy(tb2->ltb_text, sep, len);
1002                 tb2->ltb_text[len] = '\0';
1003                 list_add_tail(&tb2->ltb_list, nets);
1004
1005                 tb = tb2;
1006         }
1007 }
1008
1009 int
1010 lnet_match_networks (char **networksp, char *ip2nets, __u32 *ipaddrs, int nip)
1011 {
1012         static char       networks[LNET_SINGLE_TEXTBUF_NOB];
1013         static char       source[LNET_SINGLE_TEXTBUF_NOB];
1014
1015         struct list_head  raw_entries;
1016         struct list_head  matched_nets;
1017         struct list_head  current_nets;
1018         struct list_head *t;
1019         struct list_head *t2;
1020         struct lnet_text_buf  *tb;
1021         struct lnet_text_buf  *tb2;
1022         __u32             net1;
1023         __u32             net2;
1024         int               len;
1025         int               count;
1026         int               dup;
1027         int               rc;
1028
1029         INIT_LIST_HEAD(&raw_entries);
1030         if (lnet_str2tbs_sep(&raw_entries, ip2nets) < 0) {
1031                 CERROR("Error parsing ip2nets\n");
1032                 LASSERT (lnet_tbnob == 0);
1033                 return -EINVAL;
1034         }
1035
1036         INIT_LIST_HEAD(&matched_nets);
1037         INIT_LIST_HEAD(&current_nets);
1038         networks[0] = 0;
1039         count = 0;
1040         len = 0;
1041         rc = 0;
1042
1043         while (!list_empty(&raw_entries)) {
1044                 tb = list_entry(raw_entries.next, struct lnet_text_buf,
1045                                 ltb_list);
1046
1047                 strncpy(source, tb->ltb_text, sizeof(source));
1048                 source[sizeof(source) - 1] = '\0';
1049
1050                 /* replace ltb_text with the network(s) add on match */
1051                 rc = lnet_match_network_tokens(tb->ltb_text, ipaddrs, nip);
1052                 if (rc < 0)
1053                         break;
1054
1055                 list_del(&tb->ltb_list);
1056
1057                 if (rc == 0) {                  /* no match */
1058                         lnet_free_text_buf(tb);
1059                         continue;
1060                 }
1061
1062                 /* split into separate networks */
1063                 INIT_LIST_HEAD(&current_nets);
1064                 list_add(&tb->ltb_list, &current_nets);
1065                 rc = lnet_splitnets(source, &current_nets);
1066                 if (rc < 0)
1067                         break;
1068
1069                 dup = 0;
1070                 list_for_each(t, &current_nets) {
1071                         tb = list_entry(t, struct lnet_text_buf, ltb_list);
1072                         net1 = lnet_netspec2net(tb->ltb_text);
1073                         LASSERT(net1 != LNET_NIDNET(LNET_NID_ANY));
1074
1075                         list_for_each(t2, &matched_nets) {
1076                                 tb2 = list_entry(t2, struct lnet_text_buf,
1077                                                  ltb_list);
1078                                 net2 = lnet_netspec2net(tb2->ltb_text);
1079                                 LASSERT(net2 != LNET_NIDNET(LNET_NID_ANY));
1080
1081                                 if (net1 == net2) {
1082                                         dup = 1;
1083                                         break;
1084                                 }
1085                         }
1086
1087                         if (dup)
1088                                 break;
1089                 }
1090
1091                 if (dup) {
1092                         lnet_free_text_bufs(&current_nets);
1093                         continue;
1094                 }
1095
1096                 list_for_each_safe(t, t2, &current_nets) {
1097                         tb = list_entry(t, struct lnet_text_buf, ltb_list);
1098
1099                         list_del(&tb->ltb_list);
1100                         list_add_tail(&tb->ltb_list, &matched_nets);
1101
1102                         len += snprintf(networks + len, sizeof(networks) - len,
1103                                         "%s%s", (len == 0) ? "" : ",",
1104                                         tb->ltb_text);
1105
1106                         if (len >= sizeof(networks)) {
1107                                 CERROR("Too many matched networks\n");
1108                                 rc = -E2BIG;
1109                                 goto out;
1110                         }
1111                 }
1112
1113                 count++;
1114         }
1115
1116  out:
1117         lnet_free_text_bufs(&raw_entries);
1118         lnet_free_text_bufs(&matched_nets);
1119         lnet_free_text_bufs(&current_nets);
1120         LASSERT (lnet_tbnob == 0);
1121
1122         if (rc < 0)
1123                 return rc;
1124
1125         *networksp = networks;
1126         return count;
1127 }
1128
1129 #ifdef __KERNEL__
1130 void
1131 lnet_ipaddr_free_enumeration(__u32 *ipaddrs, int nip)
1132 {
1133         LIBCFS_FREE(ipaddrs, nip * sizeof(*ipaddrs));
1134 }
1135
1136 int
1137 lnet_ipaddr_enumerate (__u32 **ipaddrsp)
1138 {
1139         int        up;
1140         __u32      netmask;
1141         __u32     *ipaddrs;
1142         __u32     *ipaddrs2;
1143         int        nip;
1144         char     **ifnames;
1145         int        nif = libcfs_ipif_enumerate(&ifnames);
1146         int        i;
1147         int        rc;
1148
1149         if (nif <= 0)
1150                 return nif;
1151
1152         LIBCFS_ALLOC(ipaddrs, nif * sizeof(*ipaddrs));
1153         if (ipaddrs == NULL) {
1154                 CERROR("Can't allocate ipaddrs[%d]\n", nif);
1155                 libcfs_ipif_free_enumeration(ifnames, nif);
1156                 return -ENOMEM;
1157         }
1158
1159         for (i = nip = 0; i < nif; i++) {
1160                 if (!strcmp(ifnames[i], "lo"))
1161                         continue;
1162
1163                 rc = libcfs_ipif_query(ifnames[i], &up,
1164                                        &ipaddrs[nip], &netmask);
1165                 if (rc != 0) {
1166                         CWARN("Can't query interface %s: %d\n",
1167                               ifnames[i], rc);
1168                         continue;
1169                 }
1170
1171                 if (!up) {
1172                         CWARN("Ignoring interface %s: it's down\n",
1173                               ifnames[i]);
1174                         continue;
1175                 }
1176
1177                 nip++;
1178         }
1179
1180         libcfs_ipif_free_enumeration(ifnames, nif);
1181
1182         if (nip == nif) {
1183                 *ipaddrsp = ipaddrs;
1184         } else {
1185                 if (nip > 0) {
1186                         LIBCFS_ALLOC(ipaddrs2, nip * sizeof(*ipaddrs2));
1187                         if (ipaddrs2 == NULL) {
1188                                 CERROR("Can't allocate ipaddrs[%d]\n", nip);
1189                                 nip = -ENOMEM;
1190                         } else {
1191                                 memcpy(ipaddrs2, ipaddrs,
1192                                         nip * sizeof(*ipaddrs));
1193                                 *ipaddrsp = ipaddrs2;
1194                                 rc = nip;
1195                         }
1196                 }
1197                 lnet_ipaddr_free_enumeration(ipaddrs, nif);
1198         }
1199         return nip;
1200 }
1201
1202 int
1203 lnet_parse_ip2nets (char **networksp, char *ip2nets)
1204 {
1205         __u32     *ipaddrs;
1206         int        nip = lnet_ipaddr_enumerate(&ipaddrs);
1207         int        rc;
1208
1209         if (nip < 0) {
1210                 LCONSOLE_ERROR_MSG(0x117, "Error %d enumerating local IP "
1211                                    "interfaces for ip2nets to match\n", nip);
1212                 return nip;
1213         }
1214
1215         if (nip == 0) {
1216                 LCONSOLE_ERROR_MSG(0x118, "No local IP interfaces "
1217                                    "for ip2nets to match\n");
1218                 return -ENOENT;
1219         }
1220
1221         rc = lnet_match_networks(networksp, ip2nets, ipaddrs, nip);
1222         lnet_ipaddr_free_enumeration(ipaddrs, nip);
1223
1224         if (rc < 0) {
1225                 LCONSOLE_ERROR_MSG(0x119, "Error %d parsing ip2nets\n", rc);
1226                 return rc;
1227         }
1228
1229         if (rc == 0) {
1230                 LCONSOLE_ERROR_MSG(0x11a, "ip2nets does not match "
1231                                    "any local IP interfaces\n");
1232                 return -ENOENT;
1233         }
1234
1235         return 0;
1236 }
1237
1238 int
1239 lnet_set_ip_niaddr (lnet_ni_t *ni)
1240 {
1241         __u32  net = LNET_NIDNET(ni->ni_nid);
1242         char **names;
1243         int    n;
1244         __u32  ip;
1245         __u32  netmask;
1246         int    up;
1247         int    i;
1248         int    rc;
1249
1250         /* Convenience for LNDs that use the IP address of a local interface as
1251          * the local address part of their NID */
1252
1253         if (ni->ni_interfaces[0] != NULL) {
1254
1255                 CLASSERT (LNET_MAX_INTERFACES > 1);
1256
1257                 if (ni->ni_interfaces[1] != NULL) {
1258                         CERROR("Net %s doesn't support multiple interfaces\n",
1259                                libcfs_net2str(net));
1260                         return -EPERM;
1261                 }
1262
1263                 rc = libcfs_ipif_query(ni->ni_interfaces[0],
1264                                        &up, &ip, &netmask);
1265                 if (rc != 0) {
1266                         CERROR("Net %s can't query interface %s: %d\n",
1267                                libcfs_net2str(net), ni->ni_interfaces[0], rc);
1268                         return -EPERM;
1269                 }
1270
1271                 if (!up) {
1272                         CERROR("Net %s can't use interface %s: it's down\n",
1273                                libcfs_net2str(net), ni->ni_interfaces[0]);
1274                         return -ENETDOWN;
1275                 }
1276
1277                 ni->ni_nid = LNET_MKNID(net, ip);
1278                 return 0;
1279         }
1280
1281         n = libcfs_ipif_enumerate(&names);
1282         if (n <= 0) {
1283                 CERROR("Net %s can't enumerate interfaces: %d\n",
1284                        libcfs_net2str(net), n);
1285                 return 0;
1286         }
1287
1288         for (i = 0; i < n; i++) {
1289                 if (!strcmp(names[i], "lo")) /* skip the loopback IF */
1290                         continue;
1291
1292                 rc = libcfs_ipif_query(names[i], &up, &ip, &netmask);
1293
1294                 if (rc != 0) {
1295                         CWARN("Net %s can't query interface %s: %d\n",
1296                               libcfs_net2str(net), names[i], rc);
1297                         continue;
1298                 }
1299
1300                 if (!up) {
1301                         CWARN("Net %s ignoring interface %s (down)\n",
1302                               libcfs_net2str(net), names[i]);
1303                         continue;
1304                 }
1305
1306                 libcfs_ipif_free_enumeration(names, n);
1307                 ni->ni_nid = LNET_MKNID(net, ip);
1308                 return 0;
1309         }
1310
1311         CERROR("Net %s can't find any interfaces\n", libcfs_net2str(net));
1312         libcfs_ipif_free_enumeration(names, n);
1313         return -ENOENT;
1314 }
1315 EXPORT_SYMBOL(lnet_set_ip_niaddr);
1316
1317 #endif