]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/socket.c
4f8445929b6f0f3f915633e1bcdb16b7510a3484
[netatalk.git] / libatalk / util / socket.c
1 /*
2    Copyright (c) 2009 Frank Lahm <franklahm@gmail.com>
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2 of the License, or
7    (at your option) any later version.
8  
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 */
14
15 /*!
16  * @file
17  * Netatalk utility functions
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif /* HAVE_CONFIG_H */
23
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <arpa/inet.h>
29 #include <netinet/in.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <errno.h>
33
34 #include <atalk/logger.h>
35
36 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
37
38 /*!
39  * @brief set or unset non-blocking IO on a fd
40  *
41  * @param     fd         (r) File descriptor
42  * @param     cmd        (r) 0: disable non-blocking IO, ie block\n
43  *                           <>0: enable non-blocking IO
44  *
45  * @returns   0 on success, -1 on failure
46  */
47 int setnonblock(int fd, int cmd)
48 {
49     int ofdflags;
50     int fdflags;
51
52     if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
53         return -1;
54
55     if (cmd)
56         fdflags |= O_NONBLOCK;
57     else
58         fdflags &= ~O_NONBLOCK;
59
60     if (fdflags != ofdflags)
61         if (fcntl(fd, F_SETFL, fdflags) == -1)
62             return -1;
63
64     return 0;
65 }
66
67 /*!
68  * non-blocking drop-in replacement for read with timeout using select
69  *
70  * @param socket   (r)  must be nonblocking !
71  * @param data     (rw) buffer for the read data
72  * @param lenght   (r)  how many bytes to read
73  * @param timeout  (r)  number of seconds to try reading
74  *
75  * @returns number of bytes actually read or -1 on fatal error
76  */
77 ssize_t readt(int socket, void *data, const size_t length, int timeout)
78 {
79     size_t stored;
80     ssize_t len;
81     struct timeval tv;
82     fd_set rfds;
83     int ret;
84
85     stored = 0;
86
87     while (stored < length) {
88         len = read(socket, (char *) data + stored, length - stored);
89         if (len == -1) {
90             switch (errno) {
91             case EINTR:
92                 continue;
93             case EAGAIN:
94                 tv.tv_usec = 0;
95                 tv.tv_sec  = timeout;
96
97                 FD_ZERO(&rfds);
98                 FD_SET(socket, &rfds);
99                 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
100                     switch (ret) {
101                     case 0:
102                         LOG(log_warning, logtype_cnid, "select timeout 1s");
103                         return stored;
104                     default: /* -1 */
105                         LOG(log_error, logtype_cnid, "select: %s", strerror(errno));
106                         return -1;
107                     }
108                 }
109                 continue;
110             }
111             LOG(log_error, logtype_cnid, "read: %s", strerror(errno));
112             return -1;
113         }
114         else if (len > 0)
115             stored += len;
116         else
117             break;
118     }
119     return stored;
120 }
121
122 /*!
123  * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
124  *
125  * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
126  * ::ffff:10.0.0.0 is returned as "10.0.0.0".
127  *
128  * @param  sa        (r) pointer to an struct sockaddr
129  *
130  * @returns pointer to a static string cotaining the converted address as string.\n
131  *          On error pointers to "0.0.0.0" or "::0" are returned.
132  */
133 const char *getip_string(const struct sockaddr *sa)
134 {
135     static char ip4[INET_ADDRSTRLEN];
136     static char ip6[INET6_ADDRSTRLEN];
137
138     switch (sa->sa_family) {
139
140     case AF_INET: {
141         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
142         if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
143             return "0.0.0.0";
144         return ip4;
145     }
146     case AF_INET6: {
147         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
148         if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
149             return "::0";
150
151         /* Deal with IPv6 mapped IPv4 addresses*/
152         if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
153             return (strrchr(ip6, ':') + 1);
154         return ip6;
155     }
156     default:
157         return "getip_string ERROR";
158     }
159
160     /* We never get here */
161 }
162
163 /*!
164  * @brief return port number from struct sockaddr
165  *
166  * @param  sa        (r) pointer to an struct sockaddr
167  *
168  * @returns port as unsigned int
169  */
170 unsigned int getip_port(const struct sockaddr  *sa)
171 {
172     if (sa->sa_family == AF_INET) { /* IPv4 */
173         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
174         return ntohs(sai4->sin_port);
175     } else {                       /* IPv6 */
176         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
177         return ntohs(sai6->sin6_port);
178     }
179
180     /* We never get here */
181 }
182
183 /*!
184  * @brief apply netmask to IP (v4 or v6)
185  *
186  * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
187  * for passing a value for mask that is sensible to the passed address,
188  * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
189  * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
190  *
191  * @param  ai        (rw) pointer to an struct sockaddr
192  * @parma  mask      (r) number of maskbits
193  */
194 void apply_ip_mask(struct sockaddr *sa, uint32_t mask)
195 {
196
197     switch (sa->sa_family) {
198     case AF_INET: {
199         if (mask >= 32)
200             return;
201
202         struct sockaddr_in *si = (struct sockaddr_in *)sa;
203         uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
204         si->sin_addr.s_addr &= htonl(nmask);
205         break;
206     }
207     case AF_INET6: {
208         if (mask >= 128)
209             return;
210
211         int i, maskbytes, maskbits;
212         struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
213
214         /* Deal with IPv6 mapped IPv4 addresses*/
215         if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
216             mask += 96;
217             if (mask >= 128)
218                 return;
219         }
220
221         maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
222         maskbits = mask % 8;
223
224         for (i = maskbytes - 1; i >= 0; i--)
225             si6->sin6_addr.s6_addr[15 - i] = 0;
226         if (maskbits)
227             si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
228         break;
229     }
230     default:
231         break;
232     }
233 }
234
235 /*!
236  * @brief compare IP addresses for equality
237  *
238  * @param  sa1       (r) pointer to an struct sockaddr
239  * @param  sa2       (r) pointer to an struct sockaddr
240  *
241  * @returns Addresses are converted to strings and compared with strcmp and
242  *          the result of strcmp is returned.
243  *
244  * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
245  */
246 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
247 {
248     int ret;
249     char *ip1;
250     const char *ip2;
251
252     ip1 = strdup(getip_string(sa1));
253     ip2 = getip_string(sa2);
254
255     ret = strcmp(ip1, ip2);
256
257     free(ip1);
258
259     return ret;
260 }