fix getservby*() with null pointer for protocol argument
[musl] / src / network / getservbyport_r.c
1 #define _GNU_SOURCE
2 #include <sys/socket.h>
3 #include <netinet/in.h>
4 #include <netdb.h>
5 #include <inttypes.h>
6 #include <errno.h>
7 #include <string.h>
8
9 int getservbyport_r(int port, const char *prots,
10         struct servent *se, char *buf, size_t buflen, struct servent **res)
11 {
12         int i;
13         struct sockaddr_in sin = {
14                 .sin_family = AF_INET,
15                 .sin_port = port,
16         };
17
18         if (!prots) return -(
19                 getservbyport_r(port, "tcp", se, buf, buflen, res)
20                 && getservbyport_r(port, "udp", se, buf, buflen, res) );
21
22         /* Align buffer */
23         i = (uintptr_t)buf & sizeof(char *)-1;
24         if (!i) i = sizeof(char *);
25         if (buflen < 3*sizeof(char *)-i) {
26                 errno = ERANGE;
27                 return -1;
28         }
29         buf += sizeof(char *)-i;
30         buflen -= sizeof(char *)-i;
31
32         if (strcmp(prots, "tcp") && strcmp(prots, "udp")) return -1;
33
34         se->s_port = port;
35         se->s_proto = (char *)prots;
36         se->s_aliases = (void *)buf;
37         buf += 2*sizeof(char *);
38         buflen -= 2*sizeof(char *);
39         se->s_aliases[1] = 0;
40         se->s_aliases[0] = se->s_name = buf;
41
42         if (getnameinfo((void *)&sin, sizeof sin, 0, 0, buf, buflen,
43                 strcmp(prots, "udp") ? 0 : NI_DGRAM) < 0) return -1;
44
45         *res = se;
46         return 0;
47 }