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