af4a48449dbf8c67219f816de95577128417af4e
[platform/upstream/libtirpc.git] / src / getnetconfig.c
1 /*
2  * Copyright (c) 2009, Sun Microsystems, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  * - Redistributions of source code must retain the above copyright notice,
8  *   this list of conditions and the following disclaimer.
9  * - Redistributions in binary form must reproduce the above copyright notice,
10  *   this list of conditions and the following disclaimer in the documentation
11  *   and/or other materials provided with the distribution.
12  * - Neither the name of Sun Microsystems, Inc. nor the names of its
13  *   contributors may be used to endorse or promote products derived
14  *   from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 /*
30  * Copyright (c) 1989 by Sun Microsystems, Inc.
31  */
32  
33 #include <pthread.h>
34 #include <reentrant.h>
35 #include <sys/cdefs.h>
36 #include <stdio.h>
37 #include <errno.h>
38 #include <netconfig.h>
39 #include <stddef.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <rpc/rpc.h>
43 #include <unistd.h>
44 #include "rpc_com.h"
45
46 /*
47  * The five library routines in this file provide application access to the
48  * system network configuration database, /etc/netconfig.  In addition to the
49  * netconfig database and the routines for accessing it, the environment
50  * variable NETPATH and its corresponding routines in getnetpath.c may also be
51  * used to specify the network transport to be used.
52  */
53
54 /*
55  * netconfig errors
56  */
57
58 #define NC_NONETCONFIG  ENOENT
59 #define NC_NOMEM        ENOMEM
60 #define NC_NOTINIT      EINVAL      /* setnetconfig was not called first */
61 #define NC_BADFILE      EBADF       /* format for netconfig file is bad */
62 #define NC_NOTFOUND     ENOPROTOOPT /* specified netid was not found */
63
64 /*
65  * semantics as strings (should be in netconfig.h)
66  */
67 #define NC_TPI_CLTS_S       "tpi_clts"
68 #define NC_TPI_COTS_S       "tpi_cots"
69 #define NC_TPI_COTS_ORD_S   "tpi_cots_ord"
70 #define NC_TPI_RAW_S        "tpi_raw"
71
72 /*
73  * flags as characters (also should be in netconfig.h)
74  */
75 #define NC_NOFLAG_C     '-'
76 #define NC_VISIBLE_C    'v'
77 #define NC_BROADCAST_C  'b'
78
79 /*
80  * Character used to indicate there is no name-to-address lookup library
81  */
82 #define NC_NOLOOKUP     "-"
83
84 static const char * const _nc_errors[] = {
85     "Netconfig database not found",
86     "Not enough memory",
87     "Not initialized",
88     "Netconfig database has invalid format",
89     "Netid not found in netconfig database"
90 };
91
92 struct netconfig_info {
93     int         eof;    /* all entries has been read */
94     int         ref;    /* # of times setnetconfig() has been called */
95     struct netconfig_list       *head;  /* head of the list */
96     struct netconfig_list       *tail;  /* last of the list */
97 };
98
99 struct netconfig_list {
100     char                        *linep; /* hold line read from netconfig */
101     struct netconfig            *ncp;
102     struct netconfig_list       *next;
103 };
104
105 struct netconfig_vars {
106     int   valid;        /* token that indicates a valid netconfig_vars */
107     int   flag;         /* first time flag */
108     struct netconfig_list *nc_configs;  /* pointer to the current netconfig entry */
109 };
110
111 #define NC_VALID        0xfeed
112 #define NC_STORAGE      0xf00d
113 #define NC_INVALID      0
114
115
116 static int *__nc_error(void);
117 static int parse_ncp(char *, struct netconfig *);
118 static struct netconfig *dup_ncp(struct netconfig *);
119
120
121 static FILE *nc_file;           /* for netconfig db */
122 static struct netconfig_info    ni = { 0, 0, NULL, NULL};
123
124 #define MAXNETCONFIGLINE    1000
125
126 static int *
127 __nc_error()
128 {
129         static pthread_mutex_t nc_lock = PTHREAD_MUTEX_INITIALIZER;
130         extern thread_key_t nc_key;
131         static int nc_error = 0;
132         int error, *nc_addr;
133
134         /*
135          * Use the static `nc_error' if we are the main thread
136          * (including non-threaded programs), or if an allocation
137          * fails.
138          */
139         if (nc_key == -1) {
140                 error = 0;
141                 mutex_lock(&nc_lock);
142                 if (nc_key == -1)
143                         error = thr_keycreate(&nc_key, free);
144                 mutex_unlock(&nc_lock);
145                 if (error)
146                         return (&nc_error);
147         }
148         if ((nc_addr = (int *)thr_getspecific(nc_key)) == NULL) {
149                 nc_addr = (int *)malloc(sizeof (int));
150                 if (thr_setspecific(nc_key, (void *) nc_addr) != 0) {
151                         if (nc_addr)
152                                 free(nc_addr);
153                         return (&nc_error);
154                 }
155                 *nc_addr = 0;
156         }
157         return (nc_addr);
158 }
159
160 #define nc_error        (*(__nc_error()))
161 /*
162  * A call to setnetconfig() establishes a /etc/netconfig "session".  A session
163  * "handle" is returned on a successful call.  At the start of a session (after
164  * a call to setnetconfig()) searches through the /etc/netconfig database will
165  * proceed from the start of the file.  The session handle must be passed to
166  * getnetconfig() to parse the file.  Each call to getnetconfig() using the
167  * current handle will process one subsequent entry in /etc/netconfig.
168  * setnetconfig() must be called before the first call to getnetconfig().
169  * (Handles are used to allow for nested calls to setnetpath()).
170  *
171  * A new session is established with each call to setnetconfig(), with a new
172  * handle being returned on each call.  Previously established sessions remain
173  * active until endnetconfig() is called with that session's handle as an
174  * argument.
175  *
176  * setnetconfig() need *not* be called before a call to getnetconfigent().
177  * setnetconfig() returns a NULL pointer on failure (for example, if
178  * the netconfig database is not present).
179  */
180 void *
181 setnetconfig()
182 {
183     struct netconfig_vars *nc_vars;
184
185     if ((nc_vars = (struct netconfig_vars *)malloc(sizeof
186                 (struct netconfig_vars))) == NULL) {
187         return(NULL);
188     }
189
190     /*
191      * For multiple calls, i.e. nc_file is not NULL, we just return the
192      * handle without reopening the netconfig db.
193      */
194     ni.ref++;
195     if ((nc_file != NULL) || (nc_file = fopen(NETCONFIG, "r")) != NULL) {
196         nc_vars->valid = NC_VALID;
197         nc_vars->flag = 0;
198         nc_vars->nc_configs = ni.head;
199         return ((void *)nc_vars);
200     }
201     ni.ref--;
202     nc_error = NC_NONETCONFIG;
203     free(nc_vars);
204     return (NULL);
205 }
206
207
208 /*
209  * When first called, getnetconfig() returns a pointer to the first entry in
210  * the netconfig database, formatted as a struct netconfig.  On each subsequent
211  * call, getnetconfig() returns a pointer to the next entry in the database.
212  * getnetconfig() can thus be used to search the entire netconfig file.
213  * getnetconfig() returns NULL at end of file.
214  */
215
216 struct netconfig *
217 getnetconfig(handlep)
218 void *handlep;
219 {
220     struct netconfig_vars *ncp = (struct netconfig_vars *)handlep;
221     char *stringp;              /* tmp string pointer */
222     struct netconfig_list       *list;
223     struct netconfig *np;
224
225     /*
226      * Verify that handle is valid
227      */
228     if (ncp == NULL || nc_file == NULL) {
229         nc_error = NC_NOTINIT;
230         return (NULL);
231     }
232
233     switch (ncp->valid) {
234     case NC_VALID:
235         /*
236          * If entry has already been read into the list,
237          * we return the entry in the linked list.
238          * If this is the first time call, check if there are any entries in
239          * linked list.  If no entries, we need to read the netconfig db.
240          * If we have been here and the next entry is there, we just return
241          * it.
242          */
243         if (ncp->flag == 0) {   /* first time */
244             ncp->flag = 1;
245             ncp->nc_configs = ni.head;
246             if (ncp->nc_configs != NULL)        /* entry already exist */
247                 return(ncp->nc_configs->ncp);
248         }
249         else if (ncp->nc_configs != NULL && ncp->nc_configs->next != NULL) {
250             ncp->nc_configs = ncp->nc_configs->next;
251             return(ncp->nc_configs->ncp);
252         }
253
254         /*
255          * If we cannot find the entry in the list and is end of file,
256          * we give up.
257          */
258         if (ni.eof == 1)        return(NULL);
259         break;
260     default:
261         nc_error = NC_NOTINIT;
262         return (NULL);
263     }
264
265     stringp = (char *) malloc(MAXNETCONFIGLINE);
266     if (stringp == NULL)
267         return (NULL);
268
269 #ifdef MEM_CHK
270     if (malloc_verify() == 0) {
271         fprintf(stderr, "memory heap corrupted in getnetconfig\n");
272         exit(1);
273     }
274 #endif
275
276     /*
277      * Read a line from netconfig file.
278      */
279     do {
280         if (fgets(stringp, MAXNETCONFIGLINE, nc_file) == NULL) {
281             free(stringp);
282             ni.eof = 1;
283             return (NULL);
284         }
285     } while (*stringp == '#');
286
287     list = (struct netconfig_list *) malloc(sizeof (struct netconfig_list));
288     if (list == NULL) {
289         free(stringp);
290         return(NULL);
291     }
292     np = (struct netconfig *) malloc(sizeof (struct netconfig));
293     if (np == NULL) {
294         free(stringp);
295         free(list);
296         return(NULL);
297     }
298     list->ncp = np;
299     list->next = NULL;
300     list->ncp->nc_lookups = NULL;
301     list->linep = stringp;
302     if (parse_ncp(stringp, list->ncp) == -1) {
303         free(stringp);
304         free(np);
305         free(list);
306         return (NULL);
307     }
308     else {
309         /*
310          * If this is the first entry that's been read, it is the head of
311          * the list.  If not, put the entry at the end of the list.
312          * Reposition the current pointer of the handle to the last entry
313          * in the list.
314          */
315         if (ni.head == NULL) {  /* first entry */
316             ni.head = ni.tail = list;
317         }
318         else {
319             ni.tail->next = list;
320             ni.tail = ni.tail->next;
321         }
322         ncp->nc_configs = ni.tail;
323         return(ni.tail->ncp);
324     }
325 }
326
327 /*
328  * endnetconfig() may be called to "unbind" or "close" the netconfig database
329  * when processing is complete, releasing resources for reuse.  endnetconfig()
330  * may not be called before setnetconfig().  endnetconfig() returns 0 on
331  * success and -1 on failure (for example, if setnetconfig() was not called
332  * previously).
333  */
334 int
335 endnetconfig(handlep)
336 void *handlep;
337 {
338     struct netconfig_vars *nc_handlep = (struct netconfig_vars *)handlep;
339
340     struct netconfig_list *q, *p;
341
342     /*
343      * Verify that handle is valid
344      */
345     if (nc_handlep == NULL || (nc_handlep->valid != NC_VALID &&
346             nc_handlep->valid != NC_STORAGE)) {
347         nc_error = NC_NOTINIT;
348         return (-1);
349     }
350
351     /*
352      * Return 0 if anyone still needs it.
353      */
354     nc_handlep->valid = NC_INVALID;
355     nc_handlep->flag = 0;
356     nc_handlep->nc_configs = NULL;
357     if (--ni.ref > 0) {
358         free(nc_handlep);
359         return(0);
360     }
361
362     /*
363      * Noone needs these entries anymore, then frees them.
364      * Make sure all info in netconfig_info structure has been reinitialized.
365      */
366     q = p = ni.head;
367     ni.eof = ni.ref = 0;
368     ni.head = NULL;
369     ni.tail = NULL;
370     while (q) {
371         p = q->next;
372         if (q->ncp->nc_lookups != NULL) free(q->ncp->nc_lookups);
373         free(q->ncp);
374         free(q->linep);
375         free(q);
376         q = p;
377     }
378     free(nc_handlep);
379
380     fclose(nc_file);
381     nc_file = NULL;
382     return (0);
383 }
384
385 /*
386  * getnetconfigent(netid) returns a pointer to the struct netconfig structure
387  * corresponding to netid.  It returns NULL if netid is invalid (that is, does
388  * not name an entry in the netconfig database).  It returns NULL and sets
389  * errno in case of failure (for example, if the netconfig database cannot be
390  * opened).
391  */
392
393 struct netconfig *
394 getnetconfigent(netid)
395         const char *netid;
396 {
397     FILE *file;         /* NETCONFIG db's file pointer */
398     char *linep;        /* holds current netconfig line */
399     char *stringp;      /* temporary string pointer */
400     struct netconfig *ncp = NULL;   /* returned value */
401     struct netconfig_list *list;        /* pointer to cache list */
402
403     nc_error = NC_NOTFOUND;     /* default error. */
404     if (netid == NULL || strlen(netid) == 0) {
405         return (NULL);
406     }
407
408     if (strcmp(netid, "unix") == 0) {
409         fprintf(stderr, "The local transport is called \"unix\" ");
410         fprintf(stderr, "in /etc/netconfig.\n");
411         fprintf(stderr, "Please change this to \"local\" manually ");
412         fprintf(stderr, "or run mergemaster(8).\n");
413         fprintf(stderr, "See UPDATING entry 20021216 for details.\n");
414         fprintf(stderr, "Continuing in 10 seconds\n\n");
415         fprintf(stderr, "This warning will be removed 20030301\n");
416         sleep(10);
417
418     }
419
420     /*
421      * Look up table if the entries have already been read and parsed in
422      * getnetconfig(), then copy this entry into a buffer and return it.
423      * If we cannot find the entry in the current list and there are more
424      * entries in the netconfig db that has not been read, we then read the
425      * db and try find the match netid.
426      * If all the netconfig db has been read and placed into the list and
427      * there is no match for the netid, return NULL.
428      */
429     if (ni.head != NULL) {
430         for (list = ni.head; list; list = list->next) {
431             if (strcmp(list->ncp->nc_netid, netid) == 0) {
432                 return(dup_ncp(list->ncp));
433             }
434         }
435         if (ni.eof == 1)        /* that's all the entries */
436                 return(NULL);
437     }
438
439
440     if ((file = fopen(NETCONFIG, "r")) == NULL) {
441         nc_error = NC_NONETCONFIG;
442         return (NULL);
443     }
444
445     if ((linep = malloc(MAXNETCONFIGLINE)) == NULL) {
446         fclose(file);
447         nc_error = NC_NOMEM;
448         return (NULL);
449     }
450     do {
451         ptrdiff_t len;
452         char *tmpp;     /* tmp string pointer */
453
454         do {
455             if ((stringp = fgets(linep, MAXNETCONFIGLINE, file)) == NULL) {
456                 break;
457             }
458         } while (*stringp == '#');
459         if (stringp == NULL) {      /* eof */
460             break;
461         }
462         if ((tmpp = strpbrk(stringp, "\t ")) == NULL) { /* can't parse file */
463             nc_error = NC_BADFILE;
464             break;
465         }
466         if (strlen(netid) == (size_t) (len = tmpp - stringp) && /* a match */
467                 strncmp(stringp, netid, (size_t)len) == 0) {
468             if ((ncp = (struct netconfig *)
469                     malloc(sizeof (struct netconfig))) == NULL) {
470                 break;
471             }
472             ncp->nc_lookups = NULL;
473             if (parse_ncp(linep, ncp) == -1) {
474                 free(ncp);
475                 ncp = NULL;
476             }
477             break;
478         }
479     } while (stringp != NULL);
480     if (ncp == NULL) {
481         free(linep);
482     }
483     fclose(file);
484     return(ncp);
485 }
486
487 /*
488  * freenetconfigent(netconfigp) frees the netconfig structure pointed to by
489  * netconfigp (previously returned by getnetconfigent()).
490  */
491
492 void
493 freenetconfigent(netconfigp)
494         struct netconfig *netconfigp;
495 {
496     if (netconfigp != NULL) {
497         free(netconfigp->nc_netid);     /* holds all netconfigp's strings */
498         if (netconfigp->nc_lookups != NULL)
499             free(netconfigp->nc_lookups);
500         free(netconfigp);
501     }
502     return;
503 }
504
505 /*
506  * Parse line and stuff it in a struct netconfig
507  * Typical line might look like:
508  *      udp tpi_cots vb inet udp /dev/udp /usr/lib/ip.so,/usr/local/ip.so
509  *
510  * We return -1 if any of the tokens don't parse, or malloc fails.
511  *
512  * Note that we modify stringp (putting NULLs after tokens) and
513  * we set the ncp's string field pointers to point to these tokens within
514  * stringp.
515  */
516
517 static int
518 parse_ncp(stringp, ncp)
519 char *stringp;          /* string to parse */
520 struct netconfig *ncp;  /* where to put results */
521 {
522     char    *tokenp;    /* for processing tokens */
523     char    *lasts;
524
525     nc_error = NC_BADFILE;      /* nearly anything that breaks is for this reason */
526     stringp[strlen(stringp)-1] = '\0';  /* get rid of newline */
527     /* netid */
528     if ((ncp->nc_netid = strtok_r(stringp, "\t ", &lasts)) == NULL) {
529         return (-1);
530     }
531
532     /* semantics */
533     if ((tokenp = strtok_r(NULL, "\t ", &lasts)) == NULL) {
534         return (-1);
535     }
536     if (strcmp(tokenp, NC_TPI_COTS_ORD_S) == 0)
537         ncp->nc_semantics = NC_TPI_COTS_ORD;
538     else if (strcmp(tokenp, NC_TPI_COTS_S) == 0)
539         ncp->nc_semantics = NC_TPI_COTS;
540     else if (strcmp(tokenp, NC_TPI_CLTS_S) == 0)
541         ncp->nc_semantics = NC_TPI_CLTS;
542     else if (strcmp(tokenp, NC_TPI_RAW_S) == 0)
543         ncp->nc_semantics = NC_TPI_RAW;
544     else
545         return (-1);
546
547     /* flags */
548     if ((tokenp = strtok_r(NULL, "\t ", &lasts)) == NULL) {
549         return (-1);
550     }
551     for (ncp->nc_flag = NC_NOFLAG; *tokenp != '\0';
552             tokenp++) {
553         switch (*tokenp) {
554         case NC_NOFLAG_C:
555             break;
556         case NC_VISIBLE_C:
557             ncp->nc_flag |= NC_VISIBLE;
558             break;
559         case NC_BROADCAST_C:
560             ncp->nc_flag |= NC_BROADCAST;
561             break;
562         default:
563             return (-1);
564         }
565     }
566     /* protocol family */
567     if ((ncp->nc_protofmly = strtok_r(NULL, "\t ", &lasts)) == NULL) {
568         return (-1);
569     }
570     /* protocol name */
571     if ((ncp->nc_proto = strtok_r(NULL, "\t ", &lasts)) == NULL) {
572         return (-1);
573     }
574     /* network device */
575     if ((ncp->nc_device = strtok_r(NULL, "\t ", &lasts)) == NULL) {
576         return (-1);
577     }
578     if ((tokenp = strtok_r(NULL, "\t ", &lasts)) == NULL) {
579         return (-1);
580     }
581     if (strcmp(tokenp, NC_NOLOOKUP) == 0) {
582         ncp->nc_nlookups = 0;
583         ncp->nc_lookups = NULL;
584     } else {
585         char *cp;           /* tmp string */
586
587         if (ncp->nc_lookups != NULL)    /* from last visit */
588             free(ncp->nc_lookups);
589         /* preallocate one string pointer */
590         ncp->nc_lookups = (char **)malloc(sizeof (char *));
591         ncp->nc_nlookups = 0;
592         while ((cp = tokenp) != NULL) {
593             tokenp = _get_next_token(cp, ',');
594             ncp->nc_lookups[(size_t)ncp->nc_nlookups++] = cp;
595             ncp->nc_lookups = (char **)realloc(ncp->nc_lookups,
596                 (size_t)(ncp->nc_nlookups+1) *sizeof(char *));  /* for next loop */
597         }
598     }
599     return (0);
600 }
601
602
603 /*
604  * Returns a string describing the reason for failure.
605  */
606 char *
607 nc_sperror()
608 {
609     const char *message;
610
611     switch(nc_error) {
612     case NC_NONETCONFIG:
613         message = _nc_errors[0];
614         break;
615     case NC_NOMEM:
616         message = _nc_errors[1];
617         break;
618     case NC_NOTINIT:
619         message = _nc_errors[2];
620         break;
621     case NC_BADFILE:
622         message = _nc_errors[3];
623         break;
624     case NC_NOTFOUND:
625         message = _nc_errors[4];
626         break;
627     default:
628         message = "Unknown network selection error";
629     }
630     /* LINTED const castaway */
631     return ((char *)message);
632 }
633
634 /*
635  * Prints a message onto standard error describing the reason for failure.
636  */
637 void
638 nc_perror(s)
639         const char *s;
640 {
641     fprintf(stderr, "%s: %s\n", s, nc_sperror());
642 }
643
644 /*
645  * Duplicates the matched netconfig buffer.
646  */
647 static struct netconfig *
648 dup_ncp(ncp)
649 struct netconfig        *ncp;
650 {
651     struct netconfig    *p;
652     char        *tmp;
653     u_int       i;
654
655     if ((tmp=malloc(MAXNETCONFIGLINE)) == NULL)
656         return(NULL);
657     if ((p=(struct netconfig *)malloc(sizeof(struct netconfig))) == NULL) {
658         free(tmp);
659         return(NULL);
660     }
661     /*
662      * First we dup all the data from matched netconfig buffer.  Then we
663      * adjust some of the member pointer to a pre-allocated buffer where
664      * contains part of the data.
665      * To follow the convention used in parse_ncp(), we store all the
666      * necessary information in the pre-allocated buffer and let each
667      * of the netconfig char pointer member point to the right address
668      * in the buffer.
669      */
670     *p = *ncp;
671     p->nc_netid = (char *)strcpy(tmp,ncp->nc_netid);
672     tmp = strchr(tmp, 0) + 1;
673     p->nc_protofmly = (char *)strcpy(tmp,ncp->nc_protofmly);
674     tmp = strchr(tmp, 0) + 1;
675     p->nc_proto = (char *)strcpy(tmp,ncp->nc_proto);
676     tmp = strchr(tmp, 0) + 1;
677     p->nc_device = (char *)strcpy(tmp,ncp->nc_device);
678     p->nc_lookups = (char **)malloc((size_t)(p->nc_nlookups+1) * sizeof(char *));
679     if (p->nc_lookups == NULL) {
680         free(p->nc_netid);
681         return(NULL);
682     }
683     for (i=0; i < p->nc_nlookups; i++) {
684         tmp = strchr(tmp, 0) + 1;
685         p->nc_lookups[i] = (char *)strcpy(tmp,ncp->nc_lookups[i]);
686     }
687     return(p);
688 }