]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/socket.c
Merge branch-2-1
[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 #include <sys/time.h>
34 #include <time.h>
35
36 #include <atalk/logger.h>
37
38 static char ipv4mapprefix[] = {0,0,0,0,0,0,0,0,0,0,0xff,0xff};
39
40 /*!
41  * @brief set or unset non-blocking IO on a fd
42  *
43  * @param     fd         (r) File descriptor
44  * @param     cmd        (r) 0: disable non-blocking IO, ie block\n
45  *                           <>0: enable non-blocking IO
46  *
47  * @returns   0 on success, -1 on failure
48  */
49 int setnonblock(int fd, int cmd)
50 {
51     int ofdflags;
52     int fdflags;
53
54     if ((fdflags = ofdflags = fcntl(fd, F_GETFL, 0)) == -1)
55         return -1;
56
57     if (cmd)
58         fdflags |= O_NONBLOCK;
59     else
60         fdflags &= ~O_NONBLOCK;
61
62     if (fdflags != ofdflags)
63         if (fcntl(fd, F_SETFL, fdflags) == -1)
64             return -1;
65
66     return 0;
67 }
68
69 /*!
70  * non-blocking drop-in replacement for read with timeout using select
71  *
72  * @param socket          (r)  socket, if in blocking mode, pass "setnonblocking" arg as 1
73  * @param data            (rw) buffer for the read data
74  * @param lenght          (r)  how many bytes to read
75  * @param setnonblocking  (r)  when non-zero this func will enable and disable non blocking
76  *                             io mode for the socket
77  * @param timeout         (r)  number of seconds to try reading
78  *
79  * @returns number of bytes actually read or -1 on fatal error
80  */
81 ssize_t readt(int socket, void *data, const size_t length, int setnonblocking, int timeout)
82 {
83     size_t stored;
84     ssize_t len;
85     struct timeval now, end, tv;
86     fd_set rfds;
87     int ret;
88
89     stored = 0;
90
91     if (setnonblocking) {
92         if (setnonblock(socket, 1) != 0)
93             return -1;
94     }
95
96     /* Calculate end time */
97     (void)gettimeofday(&now, NULL);
98     end = now;
99     end.tv_sec += timeout;
100
101     while (stored < length) {
102         len = read(socket, (char *) data + stored, length - stored);
103         if (len == -1) {
104             switch (errno) {
105             case EINTR:
106                 continue;
107             case EAGAIN:
108                 FD_ZERO(&rfds);
109                 FD_SET(socket, &rfds);
110                 tv.tv_usec = 0;
111                 tv.tv_sec  = timeout;
112                         
113                 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
114                     switch (ret) {
115                     case 0:
116                         LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
117                         goto exit;
118
119                     default: /* -1 */
120                         if (errno == EINTR) {
121                             (void)gettimeofday(&now, NULL);
122                             if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
123                                 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
124                                 goto exit;
125                             }
126                             if (now.tv_usec > end.tv_usec) {
127                                 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
128                                 tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
129                             } else {
130                                 tv.tv_usec = end.tv_usec - now.tv_usec;
131                                 tv.tv_sec  = end.tv_sec - now.tv_sec;
132                             }
133                             FD_ZERO(&rfds);
134                             FD_SET(socket, &rfds);
135                             continue;
136                         }
137                         LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
138                         stored = -1;
139                         goto exit;
140                     }
141                 } /* while (select) */
142                 continue;
143             } /* switch (errno) */
144             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
145             stored = -1;
146             goto exit;
147         } /* (len == -1) */
148         else if (len > 0)
149             stored += len;
150         else
151             break;
152     } /* while (stored < length) */
153
154 exit:
155     if (setnonblocking) {
156         if (setnonblock(socket, 0) != 0)
157             return -1;
158     }
159
160     return stored;
161 }
162
163 /*!
164  * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
165  *
166  * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
167  * ::ffff:10.0.0.0 is returned as "10.0.0.0".
168  *
169  * @param  sa        (r) pointer to an struct sockaddr
170  *
171  * @returns pointer to a static string cotaining the converted address as string.\n
172  *          On error pointers to "0.0.0.0" or "::0" are returned.
173  */
174 const char *getip_string(const struct sockaddr *sa)
175 {
176     static char ip4[INET_ADDRSTRLEN];
177     static char ip6[INET6_ADDRSTRLEN];
178
179     switch (sa->sa_family) {
180
181     case AF_INET: {
182         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
183         if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
184             return "0.0.0.0";
185         return ip4;
186     }
187     case AF_INET6: {
188         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
189         if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
190             return "::0";
191
192         /* Deal with IPv6 mapped IPv4 addresses*/
193         if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
194             return (strrchr(ip6, ':') + 1);
195         return ip6;
196     }
197     default:
198         return "getip_string ERROR";
199     }
200
201     /* We never get here */
202 }
203
204 /*!
205  * @brief return port number from struct sockaddr
206  *
207  * @param  sa        (r) pointer to an struct sockaddr
208  *
209  * @returns port as unsigned int
210  */
211 unsigned int getip_port(const struct sockaddr  *sa)
212 {
213     if (sa->sa_family == AF_INET) { /* IPv4 */
214         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
215         return ntohs(sai4->sin_port);
216     } else {                       /* IPv6 */
217         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
218         return ntohs(sai6->sin6_port);
219     }
220
221     /* We never get here */
222 }
223
224 /*!
225  * @brief apply netmask to IP (v4 or v6)
226  *
227  * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
228  * for passing a value for mask that is sensible to the passed address,
229  * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
230  * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
231  *
232  * @param  ai        (rw) pointer to an struct sockaddr
233  * @parma  mask      (r) number of maskbits
234  */
235 void apply_ip_mask(struct sockaddr *sa, uint32_t mask)
236 {
237
238     switch (sa->sa_family) {
239     case AF_INET: {
240         if (mask >= 32)
241             return;
242
243         struct sockaddr_in *si = (struct sockaddr_in *)sa;
244         uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
245         si->sin_addr.s_addr &= htonl(nmask);
246         break;
247     }
248     case AF_INET6: {
249         if (mask >= 128)
250             return;
251
252         int i, maskbytes, maskbits;
253         struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
254
255         /* Deal with IPv6 mapped IPv4 addresses*/
256         if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
257             mask += 96;
258             if (mask >= 128)
259                 return;
260         }
261
262         maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
263         maskbits = mask % 8;
264
265         for (i = maskbytes - 1; i >= 0; i--)
266             si6->sin6_addr.s6_addr[15 - i] = 0;
267         if (maskbits)
268             si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
269         break;
270     }
271     default:
272         break;
273     }
274 }
275
276 /*!
277  * @brief compare IP addresses for equality
278  *
279  * @param  sa1       (r) pointer to an struct sockaddr
280  * @param  sa2       (r) pointer to an struct sockaddr
281  *
282  * @returns Addresses are converted to strings and compared with strcmp and
283  *          the result of strcmp is returned.
284  *
285  * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
286  */
287 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
288 {
289     int ret;
290     char *ip1;
291     const char *ip2;
292
293     ip1 = strdup(getip_string(sa1));
294     ip2 = getip_string(sa2);
295
296     ret = strcmp(ip1, ip2);
297
298     free(ip1);
299
300     return ret;
301 }