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