/* $NetBSD: getnetconfig.c,v 1.3 2000/07/06 03:10:34 christos Exp $ */12/*-3* SPDX-License-Identifier: BSD-3-Clause4*5* Copyright (c) 2009, Sun Microsystems, Inc.6* All rights reserved.7*8* Redistribution and use in source and binary forms, with or without9* modification, are permitted provided that the following conditions are met:10* - Redistributions of source code must retain the above copyright notice,11* this list of conditions and the following disclaimer.12* - Redistributions in binary form must reproduce the above copyright notice,13* this list of conditions and the following disclaimer in the documentation14* and/or other materials provided with the distribution.15* - Neither the name of Sun Microsystems, Inc. nor the names of its16* contributors may be used to endorse or promote products derived17* from this software without specific prior written permission.18*19* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"20* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE21* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE22* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE23* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR24* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF25* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS26* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN27* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)28* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE29* POSSIBILITY OF SUCH DAMAGE.30*/3132/*33* Copyright (c) 1989 by Sun Microsystems, Inc.34*/3536#include "namespace.h"37#include "reentrant.h"38#include <stdio.h>39#include <errno.h>40#include <netconfig.h>41#include <stddef.h>42#include <stdlib.h>43#include <string.h>44#include <rpc/rpc.h>45#include <unistd.h>46#include "un-namespace.h"47#include "rpc_com.h"4849/*50* The five library routines in this file provide application access to the51* system network configuration database, /etc/netconfig. In addition to the52* netconfig database and the routines for accessing it, the environment53* variable NETPATH and its corresponding routines in getnetpath.c may also be54* used to specify the network transport to be used.55*/565758/*59* netconfig errors60*/6162#define NC_NONETCONFIG ENOENT63#define NC_NOMEM ENOMEM64#define NC_NOTINIT EINVAL /* setnetconfig was not called first */65#define NC_BADFILE EBADF /* format for netconfig file is bad */66#define NC_NOTFOUND ENOPROTOOPT /* specified netid was not found */6768/*69* semantics as strings (should be in netconfig.h)70*/71#define NC_TPI_CLTS_S "tpi_clts"72#define NC_TPI_COTS_S "tpi_cots"73#define NC_TPI_COTS_ORD_S "tpi_cots_ord"74#define NC_TPI_RAW_S "tpi_raw"7576/*77* flags as characters (also should be in netconfig.h)78*/79#define NC_NOFLAG_C '-'80#define NC_VISIBLE_C 'v'81#define NC_BROADCAST_C 'b'8283/*84* Character used to indicate there is no name-to-address lookup library85*/86#define NC_NOLOOKUP "-"8788static const char * const _nc_errors[] = {89"Netconfig database not found",90"Not enough memory",91"Not initialized",92"Netconfig database has invalid format",93"Netid not found in netconfig database"94};9596struct netconfig_info {97int eof; /* all entries has been read */98int ref; /* # of times setnetconfig() has been called */99struct netconfig_list *head; /* head of the list */100struct netconfig_list *tail; /* last of the list */101};102103struct netconfig_list {104char *linep; /* hold line read from netconfig */105struct netconfig *ncp;106struct netconfig_list *next;107};108109struct netconfig_vars {110int valid; /* token that indicates a valid netconfig_vars */111int flag; /* first time flag */112struct netconfig_list *nc_configs; /* pointer to the current netconfig entry */113};114115#define NC_VALID 0xfeed116#define NC_STORAGE 0xf00d117#define NC_INVALID 0118119120static int *__nc_error(void);121static int parse_ncp(char *, struct netconfig *);122static struct netconfig *dup_ncp(struct netconfig *);123124125static FILE *nc_file; /* for netconfig db */126static mutex_t nc_file_lock = MUTEX_INITIALIZER;127128static struct netconfig_info ni = { 0, 0, NULL, NULL};129static mutex_t ni_lock = MUTEX_INITIALIZER;130131static thread_key_t nc_key;132static once_t nc_once = ONCE_INITIALIZER;133static int nc_key_error;134135static void136nc_key_init(void)137{138139nc_key_error = thr_keycreate(&nc_key, free);140}141142#define MAXNETCONFIGLINE 1000143144static int *145__nc_error(void)146{147static int nc_error = 0;148int *nc_addr;149150/*151* Use the static `nc_error' if we are the main thread152* (including non-threaded programs), or if an allocation153* fails.154*/155if (thr_main())156return (&nc_error);157if (thr_once(&nc_once, nc_key_init) != 0 || nc_key_error != 0)158return (&nc_error);159if ((nc_addr = (int *)thr_getspecific(nc_key)) == NULL) {160nc_addr = (int *)malloc(sizeof (int));161if (thr_setspecific(nc_key, (void *) nc_addr) != 0) {162free(nc_addr);163return (&nc_error);164}165*nc_addr = 0;166}167return (nc_addr);168}169170#define nc_error (*(__nc_error()))171/*172* A call to setnetconfig() establishes a /etc/netconfig "session". A session173* "handle" is returned on a successful call. At the start of a session (after174* a call to setnetconfig()) searches through the /etc/netconfig database will175* proceed from the start of the file. The session handle must be passed to176* getnetconfig() to parse the file. Each call to getnetconfig() using the177* current handle will process one subsequent entry in /etc/netconfig.178* setnetconfig() must be called before the first call to getnetconfig().179* (Handles are used to allow for nested calls to setnetpath()).180*181* A new session is established with each call to setnetconfig(), with a new182* handle being returned on each call. Previously established sessions remain183* active until endnetconfig() is called with that session's handle as an184* argument.185*186* setnetconfig() need *not* be called before a call to getnetconfigent().187* setnetconfig() returns a NULL pointer on failure (for example, if188* the netconfig database is not present).189*/190void *191setnetconfig(void)192{193struct netconfig_vars *nc_vars;194195if ((nc_vars = (struct netconfig_vars *)malloc(sizeof196(struct netconfig_vars))) == NULL) {197return(NULL);198}199200/*201* For multiple calls, i.e. nc_file is not NULL, we just return the202* handle without reopening the netconfig db.203*/204mutex_lock(&ni_lock);205ni.ref++;206mutex_unlock(&ni_lock);207208mutex_lock(&nc_file_lock);209if ((nc_file != NULL) || (nc_file = fopen(NETCONFIG, "r")) != NULL) {210nc_vars->valid = NC_VALID;211nc_vars->flag = 0;212nc_vars->nc_configs = ni.head;213mutex_unlock(&nc_file_lock);214return ((void *)nc_vars);215}216mutex_unlock(&nc_file_lock);217218mutex_lock(&ni_lock);219ni.ref--;220mutex_unlock(&ni_lock);221222nc_error = NC_NONETCONFIG;223free(nc_vars);224return (NULL);225}226227228/*229* When first called, getnetconfig() returns a pointer to the first entry in230* the netconfig database, formatted as a struct netconfig. On each subsequent231* call, getnetconfig() returns a pointer to the next entry in the database.232* getnetconfig() can thus be used to search the entire netconfig file.233* getnetconfig() returns NULL at end of file.234*/235236struct netconfig *237getnetconfig(void *handlep)238{239struct netconfig_vars *ncp = (struct netconfig_vars *)handlep;240char *stringp; /* tmp string pointer */241struct netconfig_list *list;242struct netconfig *np;243struct netconfig *result;244245/*246* Verify that handle is valid247*/248mutex_lock(&nc_file_lock);249if (ncp == NULL || nc_file == NULL) {250nc_error = NC_NOTINIT;251mutex_unlock(&nc_file_lock);252return (NULL);253}254mutex_unlock(&nc_file_lock);255256switch (ncp->valid) {257case NC_VALID:258/*259* If entry has already been read into the list,260* we return the entry in the linked list.261* If this is the first time call, check if there are any entries in262* linked list. If no entries, we need to read the netconfig db.263* If we have been here and the next entry is there, we just return264* it.265*/266if (ncp->flag == 0) { /* first time */267ncp->flag = 1;268mutex_lock(&ni_lock);269ncp->nc_configs = ni.head;270mutex_unlock(&ni_lock);271if (ncp->nc_configs != NULL) /* entry already exist */272return(ncp->nc_configs->ncp);273}274else if (ncp->nc_configs != NULL && ncp->nc_configs->next != NULL) {275ncp->nc_configs = ncp->nc_configs->next;276return(ncp->nc_configs->ncp);277}278279/*280* If we cannot find the entry in the list and is end of file,281* we give up.282*/283mutex_lock(&ni_lock);284if (ni.eof == 1) {285mutex_unlock(&ni_lock);286return(NULL);287}288mutex_unlock(&ni_lock);289290break;291default:292nc_error = NC_NOTINIT;293return (NULL);294}295296stringp = (char *) malloc(MAXNETCONFIGLINE);297if (stringp == NULL)298return (NULL);299300#ifdef MEM_CHK301if (malloc_verify() == 0) {302fprintf(stderr, "memory heap corrupted in getnetconfig\n");303exit(1);304}305#endif306307/*308* Read a line from netconfig file.309*/310mutex_lock(&nc_file_lock);311do {312if (fgets(stringp, MAXNETCONFIGLINE, nc_file) == NULL) {313free(stringp);314mutex_lock(&ni_lock);315ni.eof = 1;316mutex_unlock(&ni_lock);317mutex_unlock(&nc_file_lock);318return (NULL);319}320} while (*stringp == '#');321mutex_unlock(&nc_file_lock);322323list = (struct netconfig_list *) malloc(sizeof (struct netconfig_list));324if (list == NULL) {325free(stringp);326return(NULL);327}328np = (struct netconfig *) malloc(sizeof (struct netconfig));329if (np == NULL) {330free(stringp);331free(list);332return(NULL);333}334list->ncp = np;335list->next = NULL;336list->ncp->nc_lookups = NULL;337list->linep = stringp;338if (parse_ncp(stringp, list->ncp) == -1) {339free(stringp);340free(np);341free(list);342return (NULL);343}344else {345/*346* If this is the first entry that's been read, it is the head of347* the list. If not, put the entry at the end of the list.348* Reposition the current pointer of the handle to the last entry349* in the list.350*/351mutex_lock(&ni_lock);352if (ni.head == NULL) { /* first entry */353ni.head = ni.tail = list;354}355else {356ni.tail->next = list;357ni.tail = ni.tail->next;358}359ncp->nc_configs = ni.tail;360result = ni.tail->ncp;361mutex_unlock(&ni_lock);362return(result);363}364}365366/*367* endnetconfig() may be called to "unbind" or "close" the netconfig database368* when processing is complete, releasing resources for reuse. endnetconfig()369* may not be called before setnetconfig(). endnetconfig() returns 0 on370* success and -1 on failure (for example, if setnetconfig() was not called371* previously).372*/373int374endnetconfig(void *handlep)375{376struct netconfig_vars *nc_handlep = (struct netconfig_vars *)handlep;377378struct netconfig_list *q, *p;379380/*381* Verify that handle is valid382*/383if (nc_handlep == NULL || (nc_handlep->valid != NC_VALID &&384nc_handlep->valid != NC_STORAGE)) {385nc_error = NC_NOTINIT;386return (-1);387}388389/*390* Return 0 if anyone still needs it.391*/392nc_handlep->valid = NC_INVALID;393nc_handlep->flag = 0;394nc_handlep->nc_configs = NULL;395mutex_lock(&ni_lock);396if (--ni.ref > 0) {397mutex_unlock(&ni_lock);398free(nc_handlep);399return(0);400}401402/*403* No one needs these entries anymore, then frees them.404* Make sure all info in netconfig_info structure has been reinitialized.405*/406q = ni.head;407ni.eof = ni.ref = 0;408ni.head = NULL;409ni.tail = NULL;410mutex_unlock(&ni_lock);411412while (q != NULL) {413p = q->next;414free(q->ncp->nc_lookups);415free(q->ncp);416free(q->linep);417free(q);418q = p;419}420free(nc_handlep);421422mutex_lock(&nc_file_lock);423fclose(nc_file);424nc_file = NULL;425mutex_unlock(&nc_file_lock);426427return (0);428}429430/*431* getnetconfigent(netid) returns a pointer to the struct netconfig structure432* corresponding to netid. It returns NULL if netid is invalid (that is, does433* not name an entry in the netconfig database). It returns NULL and sets434* errno in case of failure (for example, if the netconfig database cannot be435* opened).436*/437438struct netconfig *439getnetconfigent(const char *netid)440{441FILE *file; /* NETCONFIG db's file pointer */442char *linep; /* holds current netconfig line */443char *stringp; /* temporary string pointer */444struct netconfig *ncp = NULL; /* returned value */445struct netconfig_list *list; /* pointer to cache list */446447nc_error = NC_NOTFOUND; /* default error. */448if (netid == NULL || strlen(netid) == 0) {449return (NULL);450}451452/*453* Look up table if the entries have already been read and parsed in454* getnetconfig(), then copy this entry into a buffer and return it.455* If we cannot find the entry in the current list and there are more456* entries in the netconfig db that has not been read, we then read the457* db and try find the match netid.458* If all the netconfig db has been read and placed into the list and459* there is no match for the netid, return NULL.460*/461mutex_lock(&ni_lock);462if (ni.head != NULL) {463for (list = ni.head; list; list = list->next) {464if (strcmp(list->ncp->nc_netid, netid) == 0) {465mutex_unlock(&ni_lock);466return(dup_ncp(list->ncp));467}468}469if (ni.eof == 1) { /* that's all the entries */470mutex_unlock(&ni_lock);471return(NULL);472}473}474mutex_unlock(&ni_lock);475476477if ((file = fopen(NETCONFIG, "r")) == NULL) {478nc_error = NC_NONETCONFIG;479return (NULL);480}481482if ((linep = malloc(MAXNETCONFIGLINE)) == NULL) {483fclose(file);484nc_error = NC_NOMEM;485return (NULL);486}487do {488ptrdiff_t len;489char *tmpp; /* tmp string pointer */490491do {492if ((stringp = fgets(linep, MAXNETCONFIGLINE, file)) == NULL) {493break;494}495} while (*stringp == '#');496if (stringp == NULL) { /* eof */497break;498}499if ((tmpp = strpbrk(stringp, "\t ")) == NULL) { /* can't parse file */500nc_error = NC_BADFILE;501break;502}503if (strlen(netid) == (size_t) (len = tmpp - stringp) && /* a match */504strncmp(stringp, netid, (size_t)len) == 0) {505if ((ncp = (struct netconfig *)506malloc(sizeof (struct netconfig))) == NULL) {507break;508}509ncp->nc_lookups = NULL;510if (parse_ncp(linep, ncp) == -1) {511free(ncp);512ncp = NULL;513}514break;515}516} while (stringp != NULL);517if (ncp == NULL) {518free(linep);519}520fclose(file);521return(ncp);522}523524/*525* freenetconfigent(netconfigp) frees the netconfig structure pointed to by526* netconfigp (previously returned by getnetconfigent()).527*/528529void530freenetconfigent(struct netconfig *netconfigp)531{532if (netconfigp != NULL) {533free(netconfigp->nc_netid); /* holds all netconfigp's strings */534free(netconfigp->nc_lookups);535free(netconfigp);536}537return;538}539540/*541* Parse line and stuff it in a struct netconfig542* Typical line might look like:543* udp tpi_cots vb inet udp /dev/udp /usr/lib/ip.so,/usr/local/ip.so544*545* We return -1 if any of the tokens don't parse, or malloc fails.546*547* Note that we modify stringp (putting NULLs after tokens) and548* we set the ncp's string field pointers to point to these tokens within549* stringp.550*551* stringp - string to parse552* ncp - where to put results553*/554555static int556parse_ncp(char *stringp, struct netconfig *ncp)557{558char *tokenp; /* for processing tokens */559char *lasts;560char **nc_lookups;561562nc_error = NC_BADFILE; /* nearly anything that breaks is for this reason */563stringp[strlen(stringp)-1] = '\0'; /* get rid of newline */564/* netid */565if ((ncp->nc_netid = strtok_r(stringp, "\t ", &lasts)) == NULL) {566return (-1);567}568569/* semantics */570if ((tokenp = strtok_r(NULL, "\t ", &lasts)) == NULL) {571return (-1);572}573if (strcmp(tokenp, NC_TPI_COTS_ORD_S) == 0)574ncp->nc_semantics = NC_TPI_COTS_ORD;575else if (strcmp(tokenp, NC_TPI_COTS_S) == 0)576ncp->nc_semantics = NC_TPI_COTS;577else if (strcmp(tokenp, NC_TPI_CLTS_S) == 0)578ncp->nc_semantics = NC_TPI_CLTS;579else if (strcmp(tokenp, NC_TPI_RAW_S) == 0)580ncp->nc_semantics = NC_TPI_RAW;581else582return (-1);583584/* flags */585if ((tokenp = strtok_r(NULL, "\t ", &lasts)) == NULL) {586return (-1);587}588for (ncp->nc_flag = NC_NOFLAG; *tokenp != '\0';589tokenp++) {590switch (*tokenp) {591case NC_NOFLAG_C:592break;593case NC_VISIBLE_C:594ncp->nc_flag |= NC_VISIBLE;595break;596case NC_BROADCAST_C:597ncp->nc_flag |= NC_BROADCAST;598break;599default:600return (-1);601}602}603/* protocol family */604if ((ncp->nc_protofmly = strtok_r(NULL, "\t ", &lasts)) == NULL) {605return (-1);606}607/* protocol name */608if ((ncp->nc_proto = strtok_r(NULL, "\t ", &lasts)) == NULL) {609return (-1);610}611/* network device */612if ((ncp->nc_device = strtok_r(NULL, "\t ", &lasts)) == NULL) {613return (-1);614}615if ((tokenp = strtok_r(NULL, "\t ", &lasts)) == NULL) {616return (-1);617}618if (strcmp(tokenp, NC_NOLOOKUP) == 0) {619ncp->nc_nlookups = 0;620ncp->nc_lookups = NULL;621} else {622char *cp; /* tmp string */623624free(ncp->nc_lookups); /* from last visit */625ncp->nc_lookups = NULL;626ncp->nc_nlookups = 0;627while ((cp = tokenp) != NULL) {628if ((nc_lookups = reallocarray(ncp->nc_lookups,629ncp->nc_nlookups + 1, sizeof(*ncp->nc_lookups))) == NULL) {630free(ncp->nc_lookups);631ncp->nc_lookups = NULL;632return (-1);633}634tokenp = _get_next_token(cp, ',');635ncp->nc_lookups = nc_lookups;636ncp->nc_lookups[ncp->nc_nlookups++] = cp;637}638}639return (0);640}641642643/*644* Returns a string describing the reason for failure.645*/646char *647nc_sperror(void)648{649const char *message;650651switch(nc_error) {652case NC_NONETCONFIG:653message = _nc_errors[0];654break;655case NC_NOMEM:656message = _nc_errors[1];657break;658case NC_NOTINIT:659message = _nc_errors[2];660break;661case NC_BADFILE:662message = _nc_errors[3];663break;664case NC_NOTFOUND:665message = _nc_errors[4];666break;667default:668message = "Unknown network selection error";669}670/* LINTED const castaway */671return ((char *)message);672}673674/*675* Prints a message onto standard error describing the reason for failure.676*/677void678nc_perror(const char *s)679{680fprintf(stderr, "%s: %s\n", s, nc_sperror());681}682683/*684* Duplicates the matched netconfig buffer.685*/686static struct netconfig *687dup_ncp(struct netconfig *ncp)688{689struct netconfig *p;690char *tmp;691u_int i;692693if ((tmp=malloc(MAXNETCONFIGLINE)) == NULL)694return(NULL);695if ((p=(struct netconfig *)malloc(sizeof(struct netconfig))) == NULL) {696free(tmp);697return(NULL);698}699/*700* First we dup all the data from matched netconfig buffer. Then we701* adjust some of the member pointer to a pre-allocated buffer where702* contains part of the data.703* To follow the convention used in parse_ncp(), we store all the704* necessary information in the pre-allocated buffer and let each705* of the netconfig char pointer member point to the right address706* in the buffer.707*/708*p = *ncp;709p->nc_netid = (char *)strcpy(tmp,ncp->nc_netid);710tmp = strchr(tmp, '\0') + 1;711p->nc_protofmly = (char *)strcpy(tmp,ncp->nc_protofmly);712tmp = strchr(tmp, '\0') + 1;713p->nc_proto = (char *)strcpy(tmp,ncp->nc_proto);714tmp = strchr(tmp, '\0') + 1;715p->nc_device = (char *)strcpy(tmp,ncp->nc_device);716p->nc_lookups = (char **)malloc((size_t)(p->nc_nlookups+1) * sizeof(char *));717if (p->nc_lookups == NULL) {718free(p->nc_netid);719free(p);720return(NULL);721}722for (i=0; i < p->nc_nlookups; i++) {723tmp = strchr(tmp, '\0') + 1;724p->nc_lookups[i] = (char *)strcpy(tmp,ncp->nc_lookups[i]);725}726return(p);727}728729730