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