xref: /titanic_52/usr/src/cmd/getent/dogetserv.c (revision fa9e4066f08beec538e775443c5be79dd423fcab)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 #ident	"%Z%%M%	%I%	%E% SMI"
23 
24 /*
25  * Copyright (c) 1994, by Sun Microsystems, Inc.
26  */
27 
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <string.h>
34 
35 #include <netdb.h>
36 #include "getent.h"
37 
38 static int
39 putservent(const struct servent *sp, FILE *fp)
40 {
41 	char **p;
42 	int rc = 0;
43 
44 	if (sp == NULL) {
45 		return (1);
46 	}
47 
48 	if (fprintf(fp, "%-20s %d/%s",
49 		    sp->s_name, ntohs(sp->s_port), sp->s_proto) == EOF)
50 		rc = 1;
51 	for (p = sp->s_aliases; *p != 0; p++) {
52 		if (fprintf(fp, " %s", *p) == EOF)
53 			rc = 1;
54 	}
55 	if (putc('\n', fp) == EOF)
56 		rc = 1;
57 	return (rc);
58 }
59 
60 /*
61  * getservbyname/addr - get entries from service database
62  * Accepts arguments as:
63  *	port/protocol
64  *	port
65  *	name/protocol
66  *	name
67  */
68 int
69 dogetserv(const char **list)
70 {
71 	struct servent *sp;
72 	int rc = EXC_SUCCESS;
73 
74 	if (list == NULL || *list == NULL) {
75 		while ((sp = getservent()) != NULL)
76 			(void) putservent(sp, stdout);
77 	} else {
78 		for (; *list != NULL; list++) {
79 			int port;
80 			char key[BUFSIZ];
81 			const char *protocol = NULL;
82 			char *cp;
83 
84 			/* Copy string to avoiding modifying the argument */
85 			(void) strncpy(key, *list, sizeof (key));
86 			key[sizeof (key) - 1] = NULL;
87 			/* Split at a '/' to extract protocol number */
88 			if ((cp = strchr(key, '/')) != NULL) {
89 				*cp = NULL;
90 				protocol = cp + 1;
91 			}
92 			port = htons(atoi(key));
93 			if (port != 0)
94 				sp = getservbyport(port, protocol);
95 			else
96 				sp = getservbyname(key, protocol);
97 			if (sp == NULL)
98 				rc = EXC_NAME_NOT_FOUND;
99 			else
100 				(void) putservent(sp, stdout);
101 		}
102 	}
103 
104 	return (rc);
105 }
106