1 /* 2 * Copyright (c) 1983 Regents of the University of California. 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms are permitted 6 * provided that this notice is preserved and that due credit is given 7 * to the University of California at Berkeley. The name of the University 8 * may not be used to endorse or promote products derived from this 9 * software without specific prior written permission. This software 10 * is provided ``as is'' without express or implied warranty. 11 */ 12 13 #if defined(LIBC_SCCS) && !defined(lint) 14 static char sccsid[] = "@(#)getservent.c 5.5 (Berkeley) 03/07/88"; 15 #endif /* LIBC_SCCS and not lint */ 16 17 #include <stdio.h> 18 #include <sys/param.h> 19 #include <sys/types.h> 20 #include <sys/socket.h> 21 #include <netdb.h> 22 #include <ctype.h> 23 24 #define MAXALIASES 35 25 26 static char SERVDB[] = "/etc/services"; 27 static FILE *servf = NULL; 28 static char line[BUFSIZ+1]; 29 static struct servent serv; 30 static char *serv_aliases[MAXALIASES]; 31 static char *any(); 32 int _serv_stayopen; 33 34 setservent(f) 35 int f; 36 { 37 if (servf == NULL) 38 servf = fopen(SERVDB, "r" ); 39 else 40 rewind(servf); 41 _serv_stayopen |= f; 42 } 43 44 endservent() 45 { 46 if (servf) { 47 fclose(servf); 48 servf = NULL; 49 } 50 _serv_stayopen = 0; 51 } 52 53 struct servent * 54 getservent() 55 { 56 char *p; 57 register char *cp, **q; 58 59 if (servf == NULL && (servf = fopen(SERVDB, "r" )) == NULL) 60 return (NULL); 61 again: 62 if ((p = fgets(line, BUFSIZ, servf)) == NULL) 63 return (NULL); 64 if (*p == '#') 65 goto again; 66 cp = any(p, "#\n"); 67 if (cp == NULL) 68 goto again; 69 *cp = '\0'; 70 serv.s_name = p; 71 p = any(p, " \t"); 72 if (p == NULL) 73 goto again; 74 *p++ = '\0'; 75 while (*p == ' ' || *p == '\t') 76 p++; 77 cp = any(p, ",/"); 78 if (cp == NULL) 79 goto again; 80 *cp++ = '\0'; 81 serv.s_port = htons((u_short)atoi(p)); 82 serv.s_proto = cp; 83 q = serv.s_aliases = serv_aliases; 84 cp = any(cp, " \t"); 85 if (cp != NULL) 86 *cp++ = '\0'; 87 while (cp && *cp) { 88 if (*cp == ' ' || *cp == '\t') { 89 cp++; 90 continue; 91 } 92 if (q < &serv_aliases[MAXALIASES - 1]) 93 *q++ = cp; 94 cp = any(cp, " \t"); 95 if (cp != NULL) 96 *cp++ = '\0'; 97 } 98 *q = NULL; 99 return (&serv); 100 } 101 102 static char * 103 any(cp, match) 104 register char *cp; 105 char *match; 106 { 107 register char *mp, c; 108 109 while (c = *cp) { 110 for (mp = match; *mp; mp++) 111 if (*mp == c) 112 return (cp); 113 cp++; 114 } 115 return ((char *)0); 116 } 117