separate reading of file into its own routine, lpd needed it
[unix-history] / usr / src / lib / libc / net / getservent.c
CommitLineData
8ea4199d
DF
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
2ce81398
DS
7#if defined(LIBC_SCCS) && !defined(lint)
8static char sccsid[] = "@(#)getservent.c 5.2 (Berkeley) %G%";
9#endif LIBC_SCCS and not lint
229225cd
SL
10
11#include <stdio.h>
62fc8b9c 12#include <sys/types.h>
229225cd
SL
13#include <sys/socket.h>
14#include <netdb.h>
15#include <ctype.h>
16
17#define MAXALIASES 35
18
62fc8b9c 19static char SERVDB[] = "/etc/services";
229225cd
SL
20static FILE *servf = NULL;
21static char line[BUFSIZ+1];
22static struct servent serv;
23static char *serv_aliases[MAXALIASES];
24static int stayopen = 0;
229225cd
SL
25static char *any();
26
27setservent(f)
28 int f;
29{
30 if (servf == NULL)
31 servf = fopen(SERVDB, "r" );
32 else
33 rewind(servf);
34 stayopen |= f;
35}
36
37endservent()
38{
39 if (servf && !stayopen) {
40 fclose(servf);
41 servf = NULL;
42 }
43}
44
45struct servent *
46getservent()
47{
48 char *p;
49 register char *cp, **q;
50
51 if (servf == NULL && (servf = fopen(SERVDB, "r" )) == NULL)
52 return (NULL);
53again:
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';
62fc8b9c 73 serv.s_port = htons((u_short)atoi(p));
229225cd 74 serv.s_proto = cp;
9243aabf 75 q = serv.s_aliases = serv_aliases;
229225cd 76 cp = any(cp, " \t");
463dee20 77 if (cp != NULL)
229225cd 78 *cp++ = '\0';
463dee20
SL
79 while (cp && *cp) {
80 if (*cp == ' ' || *cp == '\t') {
81 cp++;
82 continue;
229225cd 83 }
463dee20
SL
84 if (q < &serv_aliases[MAXALIASES - 1])
85 *q++ = cp;
86 cp = any(cp, " \t");
87 if (cp != NULL)
88 *cp++ = '\0';
229225cd
SL
89 }
90 *q = NULL;
91 return (&serv);
92}
93
94static char *
95any(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}