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