Add configure test for arpa/inet.h
[deb_libnfs.git] / lib / socket.c
1 /*
2 Copyright (C) 2010 by Ronnie Sahlberg <ronniesahlberg@gmail.com>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as published by
6 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program; if not, see <http://www.gnu.org/licenses/>.
16 */
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
20
21 #ifdef AROS
22 #include "aros_compat.h"
23 #endif
24
25 #ifdef WIN32
26 #include "win32_compat.h"
27 #endif
28
29 #ifdef HAVE_ARPA_INET_H
30 #include <arpa/inet.h>
31 #endif
32
33 #ifdef HAVE_POLL_H
34 #include <poll.h>
35 #endif
36
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
43 #endif
44
45 #ifdef HAVE_SYS_SOCKET_H
46 #include <sys/socket.h>
47 #endif
48
49 #ifdef HAVE_NETDB_H
50 #include <netdb.h>
51 #endif
52
53 #ifdef HAVE_SYS_FILIO_H
54 #include <sys/filio.h>
55 #endif
56
57 #ifdef HAVE_SYS_SOCKIO_H
58 #include <sys/sockio.h>
59 #endif
60
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <assert.h>
64 #include <fcntl.h>
65 #include <string.h>
66 #include <errno.h>
67 #include <sys/types.h>
68 #include "libnfs-zdr.h"
69 #include "libnfs.h"
70 #include "libnfs-raw.h"
71 #include "libnfs-private.h"
72 #include "slist.h"
73
74 #ifdef WIN32
75 //has to be included after stdlib!!
76 #include "win32_errnowrapper.h"
77 #endif
78
79
80 static int rpc_reconnect_requeue(struct rpc_context *rpc);
81 static int rpc_connect_sockaddr_async(struct rpc_context *rpc, struct sockaddr_storage *s);
82
83 static void set_nonblocking(int fd)
84 {
85 int v = 0;
86 #if defined(WIN32)
87 long nonblocking=1;
88 v = ioctl(fd, FIONBIO, &nonblocking);
89 #else
90 v = fcntl(fd, F_GETFL, 0);
91 fcntl(fd, F_SETFL, v | O_NONBLOCK);
92 #endif //FIXME
93 }
94
95 int rpc_get_fd(struct rpc_context *rpc)
96 {
97 assert(rpc->magic == RPC_CONTEXT_MAGIC);
98
99 return rpc->fd;
100 }
101
102 int rpc_which_events(struct rpc_context *rpc)
103 {
104 int events;
105
106 assert(rpc->magic == RPC_CONTEXT_MAGIC);
107
108 events = rpc->is_connected ? POLLIN : POLLOUT;
109
110 if (rpc->is_udp != 0) {
111 /* for udp sockets we only wait for pollin */
112 return POLLIN;
113 }
114
115 if (rpc->outqueue) {
116 events |= POLLOUT;
117 }
118 return events;
119 }
120
121 static int rpc_write_to_socket(struct rpc_context *rpc)
122 {
123 int32_t count;
124
125 assert(rpc->magic == RPC_CONTEXT_MAGIC);
126
127 if (rpc->fd == -1) {
128 rpc_set_error(rpc, "trying to write but not connected");
129 return -1;
130 }
131
132 while (rpc->outqueue != NULL) {
133 int64_t total;
134
135 total = rpc->outqueue->outdata.size;
136
137 count = send(rpc->fd, rpc->outqueue->outdata.data + rpc->outqueue->written, total - rpc->outqueue->written, 0);
138 if (count == -1) {
139 if (errno == EAGAIN || errno == EWOULDBLOCK) {
140 return 0;
141 }
142 rpc_set_error(rpc, "Error when writing to socket :%s(%d)", strerror(errno), errno);
143 return -1;
144 }
145
146 rpc->outqueue->written += count;
147 if (rpc->outqueue->written == total) {
148 struct rpc_pdu *pdu = rpc->outqueue;
149
150 SLIST_REMOVE(&rpc->outqueue, pdu);
151 SLIST_ADD_END(&rpc->waitpdu, pdu);
152 }
153 }
154 return 0;
155 }
156
157 static int rpc_read_from_socket(struct rpc_context *rpc)
158 {
159 int available;
160 int size;
161 int pdu_size;
162 int32_t count;
163
164 assert(rpc->magic == RPC_CONTEXT_MAGIC);
165
166 assert(rpc->magic == RPC_CONTEXT_MAGIC);
167
168 if (ioctl(rpc->fd, FIONREAD, &available) != 0) {
169 rpc_set_error(rpc, "Ioctl FIONREAD returned error : %d. Closing socket.", errno);
170 return -1;
171 }
172
173 if (available == 0) {
174 rpc_set_error(rpc, "Socket has been closed");
175 return -1;
176 }
177
178 if (rpc->is_udp) {
179 char *buf;
180 socklen_t socklen = sizeof(rpc->udp_src);
181
182 buf = malloc(available);
183 if (buf == NULL) {
184 rpc_set_error(rpc, "Failed to malloc buffer for recvfrom");
185 return -1;
186 }
187 count = recvfrom(rpc->fd, buf, available, MSG_DONTWAIT, (struct sockaddr *)&rpc->udp_src, &socklen);
188 if (count < 0) {
189 rpc_set_error(rpc, "Failed recvfrom: %s", strerror(errno));
190 free(buf);
191 }
192 if (rpc_process_pdu(rpc, buf, count) != 0) {
193 rpc_set_error(rpc, "Invalid/garbage pdu received from server. Ignoring PDU");
194 free(buf);
195 return -1;
196 }
197 free(buf);
198 return 0;
199 }
200
201 /* read record marker, 4 bytes at the beginning of every pdu */
202 if (rpc->inbuf == NULL) {
203 rpc->insize = 4;
204 rpc->inbuf = malloc(rpc->insize);
205 if (rpc->inbuf == NULL) {
206 rpc_set_error(rpc, "Failed to allocate buffer for record marker, errno:%d. Closing socket.", errno);
207 return -1;
208 }
209 }
210 if (rpc->inpos < 4) {
211 size = 4 - rpc->inpos;
212
213 count = recv(rpc->fd, rpc->inbuf + rpc->inpos, size, 0);
214 if (count == -1) {
215 if (errno == EINTR) {
216 return 0;
217 }
218 rpc_set_error(rpc, "Read from socket failed, errno:%d. Closing socket.", errno);
219 return -1;
220 }
221 available -= count;
222 rpc->inpos += count;
223 }
224
225 if (available == 0) {
226 return 0;
227 }
228
229 pdu_size = rpc_get_pdu_size(rpc->inbuf);
230 if (rpc->insize < pdu_size) {
231 unsigned char *buf;
232
233 buf = malloc(pdu_size);
234 if (buf == NULL) {
235 rpc_set_error(rpc, "Failed to allocate buffer of %d bytes for pdu, errno:%d. Closing socket.", pdu_size, errno);
236 return -1;
237 }
238 memcpy(buf, rpc->inbuf, rpc->insize);
239 free(rpc->inbuf);
240 rpc->inbuf = buf;
241 rpc->insize = rpc_get_pdu_size(rpc->inbuf);
242 }
243
244 size = available;
245 if (size > rpc->insize - rpc->inpos) {
246 size = rpc->insize - rpc->inpos;
247 }
248
249 count = recv(rpc->fd, rpc->inbuf + rpc->inpos, size, 0);
250 if (count == -1) {
251 if (errno == EINTR) {
252 return 0;
253 }
254 rpc_set_error(rpc, "Read from socket failed, errno:%d. Closing socket.", errno);
255 return -1;
256 }
257 available -= count;
258 rpc->inpos += count;
259
260 if (rpc->inpos == rpc->insize) {
261 if (rpc_process_pdu(rpc, rpc->inbuf, pdu_size) != 0) {
262 rpc_set_error(rpc, "Invalid/garbage pdu received from server. Closing socket");
263 return -1;
264 }
265 free(rpc->inbuf);
266 rpc->inbuf = NULL;
267 rpc->insize = 0;
268 rpc->inpos = 0;
269 }
270
271 return 0;
272 }
273
274
275
276 int rpc_service(struct rpc_context *rpc, int revents)
277 {
278 assert(rpc->magic == RPC_CONTEXT_MAGIC);
279
280 if (revents & POLLERR) {
281 #ifdef WIN32
282 char err = 0;
283 #else
284 int err = 0;
285 #endif
286 socklen_t err_size = sizeof(err);
287
288 if (getsockopt(rpc->fd, SOL_SOCKET, SO_ERROR,
289 (char *)&err, &err_size) != 0 || err != 0) {
290 if (err == 0) {
291 err = errno;
292 }
293 rpc_set_error(rpc, "rpc_service: socket error "
294 "%s(%d).",
295 strerror(err), err);
296 } else {
297 rpc_set_error(rpc, "rpc_service: POLLERR, "
298 "Unknown socket error.");
299 }
300 if (rpc->connect_cb != NULL) {
301 rpc->connect_cb(rpc, RPC_STATUS_ERROR, rpc->error_string, rpc->connect_data);
302 }
303 return -1;
304 }
305 if (revents & POLLHUP) {
306 rpc_set_error(rpc, "Socket failed with POLLHUP");
307 if (rpc->connect_cb != NULL) {
308 rpc->connect_cb(rpc, RPC_STATUS_ERROR, rpc->error_string, rpc->connect_data);
309 }
310 return -1;
311 }
312
313 if (rpc->is_connected == 0 && rpc->fd != -1 && revents&POLLOUT) {
314 int err = 0;
315 socklen_t err_size = sizeof(err);
316
317 if (getsockopt(rpc->fd, SOL_SOCKET, SO_ERROR,
318 (char *)&err, &err_size) != 0 || err != 0) {
319 if (err == 0) {
320 err = errno;
321 }
322 rpc_set_error(rpc, "rpc_service: socket error "
323 "%s(%d) while connecting.",
324 strerror(err), err);
325 if (rpc->connect_cb != NULL) {
326 rpc->connect_cb(rpc, RPC_STATUS_ERROR,
327 NULL, rpc->connect_data);
328 }
329 return -1;
330 }
331
332 rpc->is_connected = 1;
333 if (rpc->connect_cb != NULL) {
334 rpc->connect_cb(rpc, RPC_STATUS_SUCCESS, NULL, rpc->connect_data);
335 }
336 return 0;
337 }
338
339 if (revents & POLLIN) {
340 if (rpc_read_from_socket(rpc) != 0) {
341 rpc_reconnect_requeue(rpc);
342 return 0;
343 }
344 }
345
346 if (revents & POLLOUT && rpc->outqueue != NULL) {
347 if (rpc_write_to_socket(rpc) != 0) {
348 rpc_set_error(rpc, "write to socket failed");
349 return -1;
350 }
351 }
352
353 return 0;
354 }
355
356 void rpc_set_autoreconnect(struct rpc_context *rpc)
357 {
358 assert(rpc->magic == RPC_CONTEXT_MAGIC);
359
360 rpc->auto_reconnect = 1;
361 }
362
363 void rpc_unset_autoreconnect(struct rpc_context *rpc)
364 {
365 assert(rpc->magic == RPC_CONTEXT_MAGIC);
366
367 rpc->auto_reconnect = 0;
368 }
369
370 static int rpc_connect_sockaddr_async(struct rpc_context *rpc, struct sockaddr_storage *s)
371 {
372 int socksize;
373
374 assert(rpc->magic == RPC_CONTEXT_MAGIC);
375
376 switch (s->ss_family) {
377 case AF_INET:
378 socksize = sizeof(struct sockaddr_in);
379 rpc->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
380 break;
381 default:
382 rpc_set_error(rpc, "Can not handle AF_FAMILY:%d", s->ss_family);
383 return -1;
384 }
385
386 if (rpc->fd == -1) {
387 rpc_set_error(rpc, "Failed to open socket");
388 return -1;
389 }
390
391 /* Some systems allow you to set capabilities on an executable
392 * to allow the file to be executed with privilege to bind to
393 * privileged system ports, even if the user is not root.
394 *
395 * Opportunistically try to bind the socket to a low numbered
396 * system port in the hope that the user is either root or the
397 * executable has the CAP_NET_BIND_SERVICE.
398 *
399 * As soon as we fail the bind() with EACCES we know we will never
400 * be able to bind to a system port so we terminate the loop.
401 *
402 * On linux, use
403 * sudo setcap 'cap_net_bind_service=+ep' /path/executable
404 * to make the executable able to bind to a system port.
405 *
406 * On Windows, there is no concept of privileged ports. Thus
407 * binding will usually succeed.
408 */
409 {
410 struct sockaddr_in sin;
411 static int portOfs = 0;
412 const int firstPort = 512; /* >= 512 according to Sun docs */
413 const int portCount = IPPORT_RESERVED - firstPort;
414 int startOfs, port, rc;
415
416 if (portOfs == 0) {
417 portOfs = time(NULL) % 400;
418 }
419 startOfs = portOfs;
420 do {
421 rc = -1;
422 port = htons(firstPort + portOfs);
423 portOfs = (portOfs + 1) % portCount;
424
425 /* skip well-known ports */
426 if (!getservbyport(port, "tcp")) {
427 memset(&sin, 0, sizeof(sin));
428 sin.sin_port = port;
429 sin.sin_family = AF_INET;
430 sin.sin_addr.s_addr = 0;
431
432 rc = bind(rpc->fd, (struct sockaddr *)&sin, sizeof(struct sockaddr_in));
433 #if !defined(WIN32)
434 /* we got EACCES, so don't try again */
435 if (rc != 0 && errno == EACCES)
436 break;
437 #endif
438 }
439 } while (rc != 0 && portOfs != startOfs);
440 }
441
442 set_nonblocking(rpc->fd);
443
444 if (connect(rpc->fd, (struct sockaddr *)s, socksize) != 0 && errno != EINPROGRESS) {
445 rpc_set_error(rpc, "connect() to server failed. %s(%d)", strerror(errno), errno);
446 return -1;
447 }
448
449 return 0;
450 }
451
452 int rpc_connect_async(struct rpc_context *rpc, const char *server, int port, rpc_cb cb, void *private_data)
453 {
454 struct sockaddr_in *sin = (struct sockaddr_in *)&rpc->s;
455
456 assert(rpc->magic == RPC_CONTEXT_MAGIC);
457
458 if (rpc->fd != -1) {
459 rpc_set_error(rpc, "Trying to connect while already connected");
460 return -1;
461 }
462
463 if (rpc->is_udp != 0) {
464 rpc_set_error(rpc, "Trying to connect on UDP socket");
465 return -1;
466 }
467
468 rpc->auto_reconnect = 0;
469
470 sin->sin_family = AF_INET;
471 sin->sin_port = htons(port);
472 if (inet_pton(AF_INET, server, &sin->sin_addr) != 1) {
473 rpc_set_error(rpc, "Not a valid server ip address");
474 return -1;
475 }
476
477
478 switch (rpc->s.ss_family) {
479 case AF_INET:
480 #ifdef HAVE_SOCKADDR_LEN
481 sin->sin_len = sizeof(struct sockaddr_in);
482 #endif
483 break;
484 }
485
486 rpc->connect_cb = cb;
487 rpc->connect_data = private_data;
488
489 if (rpc_connect_sockaddr_async(rpc, &rpc->s) != 0) {
490 return -1;
491 }
492
493 return 0;
494 }
495
496 int rpc_disconnect(struct rpc_context *rpc, char *error)
497 {
498 assert(rpc->magic == RPC_CONTEXT_MAGIC);
499
500 rpc_unset_autoreconnect(rpc);
501
502 if (rpc->fd != -1) {
503 close(rpc->fd);
504 }
505 rpc->fd = -1;
506
507 rpc->is_connected = 0;
508
509 rpc_error_all_pdus(rpc, error);
510
511 return 0;
512 }
513
514 static void reconnect_cb(struct rpc_context *rpc, int status, void *data _U_, void *private_data)
515 {
516 assert(rpc->magic == RPC_CONTEXT_MAGIC);
517
518 if (status != RPC_STATUS_SUCCESS) {
519 rpc_error_all_pdus(rpc, "RPC ERROR: Failed to reconnect async");
520 return;
521 }
522
523 rpc->is_connected = 1;
524 rpc->connect_cb = NULL;
525 }
526
527 /* disconnect but do not error all PDUs, just move pdus in-flight back to the outqueue and reconnect */
528 static int rpc_reconnect_requeue(struct rpc_context *rpc)
529 {
530 struct rpc_pdu *pdu;
531
532 assert(rpc->magic == RPC_CONTEXT_MAGIC);
533
534 if (rpc->fd != -1) {
535 close(rpc->fd);
536 }
537 rpc->fd = -1;
538
539 rpc->is_connected = 0;
540
541 /* socket is closed so we will not get any replies to any commands
542 * in flight. Move them all over from the waitpdu queue back to the out queue
543 */
544 for (pdu=rpc->waitpdu; pdu; pdu=pdu->next) {
545 SLIST_REMOVE(&rpc->waitpdu, pdu);
546 SLIST_ADD(&rpc->outqueue, pdu);
547 /* we have to re-send the whole pdu again */
548 pdu->written = 0;
549 }
550
551 if (rpc->auto_reconnect != 0) {
552 rpc->connect_cb = reconnect_cb;
553
554 if (rpc_connect_sockaddr_async(rpc, &rpc->s) != 0) {
555 rpc_error_all_pdus(rpc, "RPC ERROR: Failed to reconnect async");
556 return -1;
557 }
558 }
559
560 return 0;
561 }
562
563
564 int rpc_bind_udp(struct rpc_context *rpc, char *addr, int port)
565 {
566 struct addrinfo *ai = NULL;
567 char service[6];
568
569 assert(rpc->magic == RPC_CONTEXT_MAGIC);
570
571 if (rpc->is_udp == 0) {
572 rpc_set_error(rpc, "Cant not bind UDP. Not UDP context");
573 return -1;
574 }
575
576 sprintf(service, "%d", port);
577 if (getaddrinfo(addr, service, NULL, &ai) != 0) {
578 rpc_set_error(rpc, "Invalid address:%s. "
579 "Can not resolv into IPv4/v6 structure.");
580 return -1;
581 }
582
583 switch(ai->ai_family) {
584 case AF_INET:
585 rpc->fd = socket(ai->ai_family, SOCK_DGRAM, 0);
586 if (rpc->fd == -1) {
587 rpc_set_error(rpc, "Failed to create UDP socket: %s", strerror(errno));
588 freeaddrinfo(ai);
589 return -1;
590 }
591
592 if (bind(rpc->fd, (struct sockaddr *)ai->ai_addr, sizeof(struct sockaddr_in)) != 0) {
593 rpc_set_error(rpc, "Failed to bind to UDP socket: %s",strerror(errno));
594 freeaddrinfo(ai);
595 return -1;
596 }
597 break;
598 default:
599 rpc_set_error(rpc, "Can not handle UPD sockets of family %d yet", ai->ai_family);
600 freeaddrinfo(ai);
601 return -1;
602 }
603
604 freeaddrinfo(ai);
605
606 return 0;
607 }
608
609 int rpc_set_udp_destination(struct rpc_context *rpc, char *addr, int port, int is_broadcast)
610 {
611 struct addrinfo *ai = NULL;
612 char service[6];
613
614 assert(rpc->magic == RPC_CONTEXT_MAGIC);
615
616 if (rpc->is_udp == 0) {
617 rpc_set_error(rpc, "Can not set destination sockaddr. Not UDP context");
618 return -1;
619 }
620
621 sprintf(service, "%d", port);
622 if (getaddrinfo(addr, service, NULL, &ai) != 0) {
623 rpc_set_error(rpc, "Invalid address:%s. "
624 "Can not resolv into IPv4/v6 structure.");
625 return -1;
626 }
627
628 if (rpc->udp_dest) {
629 free(rpc->udp_dest);
630 rpc->udp_dest = NULL;
631 }
632 rpc->udp_dest = malloc(ai->ai_addrlen);
633 if (rpc->udp_dest == NULL) {
634 rpc_set_error(rpc, "Out of memory. Failed to allocate sockaddr structure");
635 freeaddrinfo(ai);
636 return -1;
637 }
638 memcpy(rpc->udp_dest, ai->ai_addr, ai->ai_addrlen);
639 freeaddrinfo(ai);
640
641 rpc->is_broadcast = is_broadcast;
642 setsockopt(rpc->fd, SOL_SOCKET, SO_BROADCAST, (char *)&is_broadcast, sizeof(is_broadcast));
643
644 return 0;
645 }
646
647 struct sockaddr *rpc_get_recv_sockaddr(struct rpc_context *rpc)
648 {
649 assert(rpc->magic == RPC_CONTEXT_MAGIC);
650
651 return (struct sockaddr *)&rpc->udp_src;
652 }
653
654 int rpc_queue_length(struct rpc_context *rpc)
655 {
656 int i=0;
657 struct rpc_pdu *pdu;
658
659 assert(rpc->magic == RPC_CONTEXT_MAGIC);
660
661 for(pdu = rpc->outqueue; pdu; pdu = pdu->next) {
662 i++;
663 }
664 for(pdu = rpc->waitpdu; pdu; pdu = pdu->next) {
665 i++;
666 }
667 return i;
668 }