]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/socket.c
Use function from 2-1 for local uuid generation
[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 = 0;
84     ssize_t len = 0;
85     struct timeval now, end, tv;
86     fd_set rfds;
87     int ret;
88
89     if (setnonblocking) {
90         if (setnonblock(socket, 1) != 0)
91             return -1;
92     }
93
94     /* Calculate end time */
95     (void)gettimeofday(&now, NULL);
96     end = now;
97     end.tv_sec += timeout;
98
99     while (stored < length) {
100         len = read(socket, (char *) data + stored, length - stored);
101         if (len == -1) {
102             switch (errno) {
103             case EINTR:
104                 continue;
105             case EAGAIN:
106                 FD_ZERO(&rfds);
107                 FD_SET(socket, &rfds);
108                 tv.tv_usec = 0;
109                 tv.tv_sec  = timeout;
110                         
111                 while ((ret = select(socket + 1, &rfds, NULL, NULL, &tv)) < 1) {
112                     switch (ret) {
113                     case 0:
114                         LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
115                         goto exit;
116
117                     default: /* -1 */
118                         if (errno == EINTR) {
119                             (void)gettimeofday(&now, NULL);
120                             if (now.tv_sec >= end.tv_sec && now.tv_usec >= end.tv_usec) {
121                                 LOG(log_warning, logtype_afpd, "select timeout %d s", timeout);
122                                 goto exit;
123                             }
124                             if (now.tv_usec > end.tv_usec) {
125                                 tv.tv_usec = 1000000 + end.tv_usec - now.tv_usec;
126                                 tv.tv_sec  = end.tv_sec - now.tv_sec - 1;
127                             } else {
128                                 tv.tv_usec = end.tv_usec - now.tv_usec;
129                                 tv.tv_sec  = end.tv_sec - now.tv_sec;
130                             }
131                             FD_ZERO(&rfds);
132                             FD_SET(socket, &rfds);
133                             continue;
134                         }
135                         LOG(log_error, logtype_afpd, "select: %s", strerror(errno));
136                         stored = -1;
137                         goto exit;
138                     }
139                 } /* while (select) */
140                 continue;
141             } /* switch (errno) */
142             LOG(log_error, logtype_afpd, "read: %s", strerror(errno));
143             stored = -1;
144             goto exit;
145         } /* (len == -1) */
146         else if (len > 0)
147             stored += len;
148         else
149             break;
150     } /* while (stored < length) */
151
152 exit:
153     if (setnonblocking) {
154         if (setnonblock(socket, 0) != 0)
155             return -1;
156     }
157
158     if (len == -1 && stored == 0)
159         /* last read or select got an error and we haven't got yet anything => return -1*/
160         return -1;
161     return stored;
162 }
163
164 /*!
165  * @brief convert an IPv4 or IPv6 address to a static string using inet_ntop
166  *
167  * IPv6 mapped IPv4 addresses are returned as IPv4 addreses eg
168  * ::ffff:10.0.0.0 is returned as "10.0.0.0".
169  *
170  * @param  sa        (r) pointer to an struct sockaddr
171  *
172  * @returns pointer to a static string cotaining the converted address as string.\n
173  *          On error pointers to "0.0.0.0" or "::0" are returned.
174  */
175 const char *getip_string(const struct sockaddr *sa)
176 {
177     static char ip4[INET_ADDRSTRLEN];
178     static char ip6[INET6_ADDRSTRLEN];
179
180     switch (sa->sa_family) {
181
182     case AF_INET: {
183         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
184         if ((inet_ntop(AF_INET, &(sai4->sin_addr), ip4, INET_ADDRSTRLEN)) == NULL)
185             return "0.0.0.0";
186         return ip4;
187     }
188     case AF_INET6: {
189         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
190         if ((inet_ntop(AF_INET6, &(sai6->sin6_addr), ip6, INET6_ADDRSTRLEN)) == NULL)
191             return "::0";
192
193         /* Deal with IPv6 mapped IPv4 addresses*/
194         if ((memcmp(sai6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0)
195             return (strrchr(ip6, ':') + 1);
196         return ip6;
197     }
198     default:
199         return "getip_string ERROR";
200     }
201
202     /* We never get here */
203 }
204
205 /*!
206  * @brief return port number from struct sockaddr
207  *
208  * @param  sa        (r) pointer to an struct sockaddr
209  *
210  * @returns port as unsigned int
211  */
212 unsigned int getip_port(const struct sockaddr  *sa)
213 {
214     if (sa->sa_family == AF_INET) { /* IPv4 */
215         const struct sockaddr_in *sai4 = (const struct sockaddr_in *)sa;
216         return ntohs(sai4->sin_port);
217     } else {                       /* IPv6 */
218         const struct sockaddr_in6 *sai6 = (const struct sockaddr_in6 *)sa;
219         return ntohs(sai6->sin6_port);
220     }
221
222     /* We never get here */
223 }
224
225 /*!
226  * @brief apply netmask to IP (v4 or v6)
227  *
228  * Modifies IP address in sa->sin[6]_addr-s[6]_addr. The caller is responsible
229  * for passing a value for mask that is sensible to the passed address,
230  * eg 0 <= mask <= 32 for IPv4 or 0<= mask <= 128 for IPv6. mask > 32 for
231  * IPv4 is treated as mask = 32, mask > 128 is set to 128 for IPv6.
232  *
233  * @param  ai        (rw) pointer to an struct sockaddr
234  * @parma  mask      (r) number of maskbits
235  */
236 void apply_ip_mask(struct sockaddr *sa, uint32_t mask)
237 {
238
239     switch (sa->sa_family) {
240     case AF_INET: {
241         if (mask >= 32)
242             return;
243
244         struct sockaddr_in *si = (struct sockaddr_in *)sa;
245         uint32_t nmask = mask ? ~((1 << (32 - mask)) - 1) : 0;
246         si->sin_addr.s_addr &= htonl(nmask);
247         break;
248     }
249     case AF_INET6: {
250         if (mask >= 128)
251             return;
252
253         int i, maskbytes, maskbits;
254         struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)sa;
255
256         /* Deal with IPv6 mapped IPv4 addresses*/
257         if ((memcmp(si6->sin6_addr.s6_addr, ipv4mapprefix, sizeof(ipv4mapprefix))) == 0) {
258             mask += 96;
259             if (mask >= 128)
260                 return;
261         }
262
263         maskbytes = (128 - mask) / 8; /* maskbytes really are those that will be 0'ed */
264         maskbits = mask % 8;
265
266         for (i = maskbytes - 1; i >= 0; i--)
267             si6->sin6_addr.s6_addr[15 - i] = 0;
268         if (maskbits)
269             si6->sin6_addr.s6_addr[15 - maskbytes] &= ~((1 << (8 - maskbits)) - 1);
270         break;
271     }
272     default:
273         break;
274     }
275 }
276
277 /*!
278  * @brief compare IP addresses for equality
279  *
280  * @param  sa1       (r) pointer to an struct sockaddr
281  * @param  sa2       (r) pointer to an struct sockaddr
282  *
283  * @returns Addresses are converted to strings and compared with strcmp and
284  *          the result of strcmp is returned.
285  *
286  * @note IPv6 mapped IPv4 addresses are treated as IPv4 addresses.
287  */
288 int compare_ip(const struct sockaddr *sa1, const struct sockaddr *sa2)
289 {
290     int ret;
291     char *ip1;
292     const char *ip2;
293
294     ip1 = strdup(getip_string(sa1));
295     ip2 = getip_string(sa2);
296
297     ret = strcmp(ip1, ip2);
298
299     free(ip1);
300
301     return ret;
302 }