1*0Sstevel@tonic-gate /*
2*0Sstevel@tonic-gate  * Copyright (C) 1993-2001 by Darren Reed.
3*0Sstevel@tonic-gate  *
4*0Sstevel@tonic-gate  * See the IPFILTER.LICENCE file for details on licencing.
5*0Sstevel@tonic-gate  *
6*0Sstevel@tonic-gate  *
7*0Sstevel@tonic-gate  * $Id: portnum.c,v 1.6 2001/06/09 17:09:24 darrenr Exp $
8*0Sstevel@tonic-gate  */
9*0Sstevel@tonic-gate 
10*0Sstevel@tonic-gate #include <ctype.h>
11*0Sstevel@tonic-gate 
12*0Sstevel@tonic-gate #include "ipf.h"
13*0Sstevel@tonic-gate 
14*0Sstevel@tonic-gate 
15*0Sstevel@tonic-gate /*
16*0Sstevel@tonic-gate  * find the port number given by the name, either from getservbyname() or
17*0Sstevel@tonic-gate  * straight atoi(). Return 1 on success, 0 on failure
18*0Sstevel@tonic-gate  */
19*0Sstevel@tonic-gate int	portnum(name, proto, port, linenum)
20*0Sstevel@tonic-gate char	*name, *proto;
21*0Sstevel@tonic-gate u_short	*port;
22*0Sstevel@tonic-gate int     linenum;
23*0Sstevel@tonic-gate {
24*0Sstevel@tonic-gate 	struct	servent	*sp, *sp2;
25*0Sstevel@tonic-gate 	u_short	p1 = 0;
26*0Sstevel@tonic-gate 	int i;
27*0Sstevel@tonic-gate 
28*0Sstevel@tonic-gate 	if (isdigit(*name)) {
29*0Sstevel@tonic-gate 		if (ratoi(name, &i, 0, USHRT_MAX)) {
30*0Sstevel@tonic-gate 			*port = (u_short)i;
31*0Sstevel@tonic-gate 			return 1;
32*0Sstevel@tonic-gate 		}
33*0Sstevel@tonic-gate 		fprintf(stderr, "%d: unknown port \"%s\"\n", linenum, name);
34*0Sstevel@tonic-gate 		return 0;
35*0Sstevel@tonic-gate 	}
36*0Sstevel@tonic-gate 	if (proto != NULL && strcasecmp(proto, "tcp/udp") != 0) {
37*0Sstevel@tonic-gate 		sp = getservbyname(name, proto);
38*0Sstevel@tonic-gate 		if (sp) {
39*0Sstevel@tonic-gate 			*port = ntohs(sp->s_port);
40*0Sstevel@tonic-gate 			return 1;
41*0Sstevel@tonic-gate 		}
42*0Sstevel@tonic-gate 		fprintf(stderr, "%d: unknown service \"%s\".\n", linenum, name);
43*0Sstevel@tonic-gate 		return 0;
44*0Sstevel@tonic-gate 	}
45*0Sstevel@tonic-gate 	sp = getservbyname(name, "tcp");
46*0Sstevel@tonic-gate 	if (sp)
47*0Sstevel@tonic-gate 		p1 = sp->s_port;
48*0Sstevel@tonic-gate 	sp2 = getservbyname(name, "udp");
49*0Sstevel@tonic-gate 	if (!sp || !sp2) {
50*0Sstevel@tonic-gate 		fprintf(stderr, "%d: unknown tcp/udp service \"%s\".\n",
51*0Sstevel@tonic-gate 			linenum, name);
52*0Sstevel@tonic-gate 		return 0;
53*0Sstevel@tonic-gate 	}
54*0Sstevel@tonic-gate 	if (p1 != sp2->s_port) {
55*0Sstevel@tonic-gate 		fprintf(stderr, "%d: %s %d/tcp is a different port to ",
56*0Sstevel@tonic-gate 			linenum, name, p1);
57*0Sstevel@tonic-gate 		fprintf(stderr, "%d: %s %d/udp\n", linenum, name, sp->s_port);
58*0Sstevel@tonic-gate 		return 0;
59*0Sstevel@tonic-gate 	}
60*0Sstevel@tonic-gate 	*port = ntohs(p1);
61*0Sstevel@tonic-gate 	return 1;
62*0Sstevel@tonic-gate }
63