1 #include <sys/socket.h>
2 #include <netinet/in.h>
3 #include <netdb.h>
4 #include <ctype.h>
5 #include <string.h>
6 #include <stdlib.h>
7 #include <fcntl.h>
8 #include <errno.h>
9 #include "lookup.h"
10 #include "stdio_impl.h"
11 #include "network_conf_function.h"
12
__lookup_serv(struct service buf[static MAXSERVS],const char * name,int proto,int socktype,int flags)13 int __lookup_serv(struct service buf[static MAXSERVS], const char *name, int proto, int socktype, int flags)
14 {
15 char line[128];
16 int cnt = 0;
17 char *p, *z = "";
18 unsigned long port = 0;
19
20 switch (socktype) {
21 case SOCK_STREAM:
22 switch (proto) {
23 case 0:
24 proto = IPPROTO_TCP;
25 case IPPROTO_TCP:
26 break;
27 default:
28 return EAI_SERVICE;
29 }
30 break;
31 case SOCK_DGRAM:
32 switch (proto) {
33 case 0:
34 proto = IPPROTO_UDP;
35 case IPPROTO_UDP:
36 break;
37 default:
38 return EAI_SERVICE;
39 }
40 case 0:
41 break;
42 default:
43 if (name) return EAI_SERVICE;
44 buf[0].port = 0;
45 buf[0].proto = proto;
46 buf[0].socktype = socktype;
47 return 1;
48 }
49
50 if (name) {
51 if (!*name) return EAI_SERVICE;
52 port = strtoul(name, &z, 10);
53 }
54 if (!*z) {
55 if (port > 65535) return EAI_SERVICE;
56 if (proto != IPPROTO_UDP) {
57 buf[cnt].port = port;
58 buf[cnt].socktype = SOCK_STREAM;
59 buf[cnt++].proto = IPPROTO_TCP;
60 }
61 if (proto != IPPROTO_TCP) {
62 buf[cnt].port = port;
63 buf[cnt].socktype = SOCK_DGRAM;
64 buf[cnt++].proto = IPPROTO_UDP;
65 }
66 return cnt;
67 }
68
69 if (flags & AI_NUMERICSERV) return EAI_NONAME;
70
71 size_t l = strlen(name);
72
73 unsigned char _buf[1032];
74 FILE _f, *f = __fopen_rb_ca("/etc/services", &_f, _buf, sizeof _buf);
75 int indexPtr = 0;
76 while (get_services_str(line, f, &indexPtr)) {
77 if ((p=strchr(line, '#'))) *p++='\n', *p=0;
78
79 /* Find service name */
80 for(p=line; (p=strstr(p, name)); p++) {
81 if (p>line && !isspace(p[-1])) continue;
82 if (p[l] && !isspace(p[l])) continue;
83 break;
84 }
85 if (!p) continue;
86
87 /* Skip past canonical name at beginning of line */
88 for (p=line; *p && !isspace(*p); p++);
89
90 port = strtoul(p, &z, 10);
91 if (port > 65535 || z==p) continue;
92 if (!strncmp(z, "/udp", 4)) {
93 if (proto == IPPROTO_TCP) continue;
94 buf[cnt].port = port;
95 buf[cnt].socktype = SOCK_DGRAM;
96 buf[cnt++].proto = IPPROTO_UDP;
97 }
98 if (!strncmp(z, "/tcp", 4)) {
99 if (proto == IPPROTO_UDP) continue;
100 buf[cnt].port = port;
101 buf[cnt].socktype = SOCK_STREAM;
102 buf[cnt++].proto = IPPROTO_TCP;
103 }
104 }
105 if (f) {
106 __fclose_ca(f);
107 }
108 return cnt > 0 ? cnt : EAI_SERVICE;
109 }
110
111