xref: /csrg-svn/lib/libc/net/getservent.c (revision 21383)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.  The Berkeley software License Agreement
4  * specifies the terms and conditions for redistribution.
5  */
6 
7 #ifndef lint
8 static char sccsid[] = "@(#)getservent.c	5.1 (Berkeley) 05/30/85";
9 #endif not lint
10 
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <netdb.h>
15 #include <ctype.h>
16 
17 #define	MAXALIASES	35
18 
19 static char SERVDB[] = "/etc/services";
20 static FILE *servf = NULL;
21 static char line[BUFSIZ+1];
22 static struct servent serv;
23 static char *serv_aliases[MAXALIASES];
24 static int stayopen = 0;
25 static char *any();
26 
27 setservent(f)
28 	int f;
29 {
30 	if (servf == NULL)
31 		servf = fopen(SERVDB, "r" );
32 	else
33 		rewind(servf);
34 	stayopen |= f;
35 }
36 
37 endservent()
38 {
39 	if (servf && !stayopen) {
40 		fclose(servf);
41 		servf = NULL;
42 	}
43 }
44 
45 struct servent *
46 getservent()
47 {
48 	char *p;
49 	register char *cp, **q;
50 
51 	if (servf == NULL && (servf = fopen(SERVDB, "r" )) == NULL)
52 		return (NULL);
53 again:
54 	if ((p = fgets(line, BUFSIZ, servf)) == NULL)
55 		return (NULL);
56 	if (*p == '#')
57 		goto again;
58 	cp = any(p, "#\n");
59 	if (cp == NULL)
60 		goto again;
61 	*cp = '\0';
62 	serv.s_name = p;
63 	p = any(p, " \t");
64 	if (p == NULL)
65 		goto again;
66 	*p++ = '\0';
67 	while (*p == ' ' || *p == '\t')
68 		p++;
69 	cp = any(p, ",/");
70 	if (cp == NULL)
71 		goto again;
72 	*cp++ = '\0';
73 	serv.s_port = htons((u_short)atoi(p));
74 	serv.s_proto = cp;
75 	q = serv.s_aliases = serv_aliases;
76 	cp = any(cp, " \t");
77 	if (cp != NULL)
78 		*cp++ = '\0';
79 	while (cp && *cp) {
80 		if (*cp == ' ' || *cp == '\t') {
81 			cp++;
82 			continue;
83 		}
84 		if (q < &serv_aliases[MAXALIASES - 1])
85 			*q++ = cp;
86 		cp = any(cp, " \t");
87 		if (cp != NULL)
88 			*cp++ = '\0';
89 	}
90 	*q = NULL;
91 	return (&serv);
92 }
93 
94 static char *
95 any(cp, match)
96 	register char *cp;
97 	char *match;
98 {
99 	register char *mp, c;
100 
101 	while (c = *cp) {
102 		for (mp = match; *mp; mp++)
103 			if (*mp == c)
104 				return (cp);
105 		cp++;
106 	}
107 	return ((char *)0);
108 }
109